diff --git a/desktop/internal/core/git.go b/desktop/internal/core/git.go index 091202688e..60b50c0c52 100644 --- a/desktop/internal/core/git.go +++ b/desktop/internal/core/git.go @@ -20,11 +20,22 @@ type GitChange struct { // CanToggleStaging is false for a parent gitlink whose only change is uncommitted content // inside the submodule, which cannot be staged from the parent. CanToggleStaging bool `json:"canToggleStaging"` + // Submodule is set on a gitlink and tells a new recorded commit from content changes + // inside the submodule. + Submodule *GitSubmoduleStatus `json:"submodule,omitempty"` // UntrackedFileCount is the number of non-ignored files below a summarized untracked // directory, and 0 for every other change. UntrackedFileCount int `json:"untrackedFileCount,omitempty"` } +// GitSubmoduleStatus is what Git porcelain v2 reports about a gitlink. +type GitSubmoduleStatus struct { + // CommitChanged reports that the submodule's HEAD is not the commit the parent records. + CommitChanged bool `json:"commitChanged"` + TrackedChanges bool `json:"trackedChanges"` + UntrackedChanges bool `json:"untrackedChanges"` +} + // GitStatus is the repository identity, branch divergence and file changes of a directory. type GitStatus struct { // RepositoryRoot is the repository's top-level directory, relative to the root that was diff --git a/desktop/internal/core/gitcommit.go b/desktop/internal/core/gitcommit.go index a94f8a5f34..cdd4aaa0c2 100644 --- a/desktop/internal/core/gitcommit.go +++ b/desktop/internal/core/gitcommit.go @@ -232,6 +232,10 @@ type WorkspaceCommitRequest struct { // Reviewed is the session whose plan the user confirmed; the kernel reports // ReviewChanged when the repositories no longer match it. Nil asks for a first plan. Reviewed *WorkspaceCommitSession + // WorkspaceRepositories are the discovery entries of the workspace. Core binds every + // nested one that Repositories does not already bind, under its discovery ID, unless the + // commit is scoped to a ChangeList; it never adds the workspace repository. + WorkspaceRepositories []WorkspaceRepository } // workspaceCommitPrepareRequest is the payload of git.workspaceCommitPrepare. @@ -247,6 +251,7 @@ type workspaceCommitPrepareRequest struct { PathScope *ChangeListScope `json:"pathScope,omitempty"` Previous *WorkspaceCommitSession `json:"previous,omitempty"` Reviewed json.RawMessage `json:"reviewed,omitempty"` + WorkspaceRepositories []WorkspaceRepository `json:"workspaceRepositories,omitempty"` } // WorkspaceCommitStatus is the kernel's stable key for where one repository of a workspace @@ -415,6 +420,7 @@ func (c *Client) WorkspaceCommitPrepare(ctx context.Context, request WorkspaceCo IncludeParentReferences: request.IncludeParentReferences, PathScope: request.PathScope, Previous: request.Previous, + WorkspaceRepositories: request.WorkspaceRepositories, } if request.Reviewed != nil { payload.Reviewed = request.Reviewed.plan diff --git a/desktop/internal/core/repository_discovery_test.go b/desktop/internal/core/repository_discovery_test.go index ab7a2f3deb..37a474748e 100644 --- a/desktop/internal/core/repository_discovery_test.go +++ b/desktop/internal/core/repository_discovery_test.go @@ -26,9 +26,10 @@ func TestWorkspaceRepositoryDiscoveryUsesCoreRules(t *testing.T) { if err != nil { t.Fatal(err) } + serviceA := filepath.ToSlash(filepath.Join(root, "service-a")) want := []WorkspaceRepository{ - {Path: filepath.ToSlash(filepath.Join(root, "service-a"))}, - {Path: filepath.ToSlash(filepath.Join(root, "service-b"))}, + {Path: serviceA, ID: "service-a", Name: "service-a", Role: RepositoryNested}, + {Path: filepath.ToSlash(filepath.Join(root, "service-b")), ID: "service-b", Name: "service-b", Role: RepositoryNested}, } if !reflect.DeepEqual(repositories, want) { t.Fatalf("repositories = %#v, want %#v", repositories, want) @@ -38,8 +39,88 @@ func TestWorkspaceRepositoryDiscoveryUsesCoreRules(t *testing.T) { t.Fatal(err) } repositories, err = NewClient().DiscoverWorkspaceRepositories(testContext(t), nested) - if err != nil || !reflect.DeepEqual(repositories, want[:1]) { - t.Fatalf("nested workspace repositories = %#v, error = %v; want %#v", repositories, err, want[:1]) + containing := []WorkspaceRepository{{Path: serviceA, ID: "..", Name: "service-a", Role: RepositoryWorkspace}} + if err != nil || !reflect.DeepEqual(repositories, containing) { + t.Fatalf("nested workspace repositories = %#v, error = %v; want %#v", repositories, err, containing) + } +} + +// The bridge passes discovery entries through and decodes Core's answer; the rules are the +// fixtures' and Core's. +func TestWorkspaceRepositorySelectionUsesCoreFixtures(t *testing.T) { + data, err := os.ReadFile(contractfixture.CoreFixture("git/workspace-repository-selection-v1.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Cases []struct { + Name string `json:"name"` + Request struct { + Repositories []WorkspaceRepository `json:"repositories"` + Selected string `json:"selected"` + } `json:"request"` + Response struct { + Active *string `json:"active"` + FellBack bool `json:"fellBack"` + Others []string `json:"others"` + } `json:"response"` + } `json:"cases"` + } + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + if len(fixture.Cases) == 0 { + t.Fatal("the selection fixture has no cases") + } + client := NewClient() + for _, item := range fixture.Cases { + t.Run(item.Name, func(t *testing.T) { + want := WorkspaceRepositorySelection{FellBack: item.Response.FellBack, Others: item.Response.Others} + if item.Response.Active != nil { + want.Active = *item.Response.Active + } + got, err := client.SelectWorkspaceRepository(testContext(t), item.Request.Repositories, item.Request.Selected) + if err != nil || !reflect.DeepEqual(got, want) { + t.Fatalf("selection = %#v, error = %v; want %#v", got, err, want) + } + }) + } + duplicate := []WorkspaceRepository{ + {Path: "/w/a", ID: "a", Name: "a", Role: RepositoryNested}, + {Path: "/w/b", ID: "a", Name: "a", Role: RepositoryNested}, + } + _, err = client.SelectWorkspaceRepository(testContext(t), duplicate, "") + requireCode(t, err, CodeInvalidRequest) +} + +func TestWorkspaceChangeGroupsUseCoreFixtures(t *testing.T) { + data, err := os.ReadFile(contractfixture.CoreFixture("git/workspace-change-groups-v1.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Cases []struct { + Name string `json:"name"` + Request struct { + Repositories []WorkspaceRepositoryChanges `json:"repositories"` + } `json:"request"` + Response WorkspaceChangeGroups `json:"response"` + } `json:"cases"` + } + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + if len(fixture.Cases) == 0 { + t.Fatal("the change group fixture has no cases") + } + client := NewClient() + for _, item := range fixture.Cases { + t.Run(item.Name, func(t *testing.T) { + got, err := client.GroupWorkspaceChanges(testContext(t), item.Request.Repositories) + if err != nil || !reflect.DeepEqual(got, item.Response) { + t.Fatalf("groups = %#v, error = %v; want %#v", got, err, item.Response) + } + }) } } diff --git a/desktop/internal/core/workspace.go b/desktop/internal/core/workspace.go index 817e5c6f76..1e1ad80a2b 100644 --- a/desktop/internal/core/workspace.go +++ b/desktop/internal/core/workspace.go @@ -2,12 +2,156 @@ package core import "context" +// WorkspaceRepositoryRole is how a discovered repository relates to the opened folder. +type WorkspaceRepositoryRole string + +const ( + // RepositoryWorkspace is the repository that contains the opened folder. Discovery lists + // at most one, first. + RepositoryWorkspace WorkspaceRepositoryRole = "workspace" + // RepositoryNested is a repository below the opened folder. + RepositoryNested WorkspaceRepositoryRole = "nested" +) + // WorkspaceRepository is a Git root discovered by Core. Path is an absolute // path and can be outside the opened folder when the folder is inside a // containing repository. Core uses forward slashes on Windows too; callers // that compare native paths must normalize separators. Ordering belongs to Core. +// The window hands entries back to Core unchanged, so every field is Core's. type WorkspaceRepository struct { Path string `json:"path"` + // ID is the root relative to the opened folder with "/" separators: "." for the folder + // itself, "a/b" below it and ".." segments for a containing repository. It names the + // repository in commit plans, color assignments and selections. + ID string `json:"id"` + // Name is what views show: the folder name of the workspace repository, the ID of a + // nested one. + Name string `json:"name"` + Role WorkspaceRepositoryRole `json:"role"` +} + +// WorkspaceRepositorySelection is the repository a multi-repository view acts on. +type WorkspaceRepositorySelection struct { + // Active is the ID the view acts on, empty when the workspace has no repository. + Active string + // FellBack reports that the repository the view picked is no longer listed, so the view + // drops what belonged to it. + FellBack bool + // Others are every other ID in discovery order: the repositories the view lists to + // switch to. + Others []string +} + +// SelectWorkspaceRepository asks Core which repository a view acts on, given the discovery +// list and the ID the view picked before, empty when it has not picked one. +func (c *Client) SelectWorkspaceRepository(ctx context.Context, repositories []WorkspaceRepository, selected string) (WorkspaceRepositorySelection, error) { + request := struct { + Repositories []WorkspaceRepository `json:"repositories"` + Selected string `json:"selected,omitempty"` + }{nonNil(repositories), selected} + var response struct { + Active *string `json:"active"` + FellBack bool `json:"fellBack"` + Others []string `json:"others"` + } + if err := c.Execute(ctx, "git.workspaceRepositorySelection", request, &response); err != nil { + return WorkspaceRepositorySelection{}, err + } + selection := WorkspaceRepositorySelection{FellBack: response.FellBack, Others: response.Others} + if response.Active != nil { + selection.Active = *response.Active + } + return selection, nil +} + +// WorkspaceRepositoryChanges is a discovery entry with the changes git.status read for it. +type WorkspaceRepositoryChanges struct { + WorkspaceRepository + Changes []GitChange `json:"changes"` +} + +// StagingOperation is what a checkbox of the Commit tool window writes. +type StagingOperation string + +const ( + StageChanges StagingOperation = "stage" + UnstageChanges StagingOperation = "unstage" +) + +// StagingPlan is the operation one checkbox applies to one repository. +type StagingPlan struct { + Operation StagingOperation `json:"operation"` + // Paths are repository-relative, both sides of a rename, in change order. + Paths []string `json:"paths"` +} + +// ParentReference says whether the listed ancestor that records a nested repository as a +// submodule moved its recorded commit. +type ParentReference string + +const ( + // ParentReferenceMoved is a gitlink the ancestor lists with a new commit. + ParentReferenceMoved ParentReference = "moved" + // ParentReferenceUnchanged is a gitlink the ancestor lists with only content changes: a + // commit here still has to be recorded in the parent. + ParentReferenceUnchanged ParentReference = "unchanged" +) + +// WorkspaceChangeGroup is one repository with changes in the Commit tool window. +type WorkspaceChangeGroup struct { + ID string `json:"id"` + Name string `json:"name"` + Role WorkspaceRepositoryRole `json:"role"` + // FileCount counts each file below a summarized untracked directory. + FileCount int `json:"fileCount"` + StagedCount int `json:"stagedCount"` + // AllStaged reports that every change that can toggle is staged in full. + AllStaged bool `json:"allStaged"` + // Toggleable reports that some change can be staged or unstaged. + Toggleable bool `json:"toggleable"` + // Staging is what the group's checkbox writes, nil when it writes nothing. + Staging *StagingPlan `json:"staging,omitempty"` + // ParentReference is empty when no listed ancestor records the repository as a submodule. + ParentReference ParentReference `json:"parentReference,omitempty"` +} + +// RepositoryStaging is the paths one repository stages or unstages. +type RepositoryStaging struct { + ID string `json:"id"` + Paths []string `json:"paths"` +} + +// WorkspaceStageAll is what the workspace line's checkbox writes: one operation for every +// repository with something to write. +type WorkspaceStageAll struct { + Operation StagingOperation `json:"operation"` + Repositories []RepositoryStaging `json:"repositories"` +} + +// WorkspaceChangeGroups is the Commit tool window of a workspace with several repositories: +// one line for all changes and a group per repository that has changes, in discovery order. +type WorkspaceChangeGroups struct { + Groups []WorkspaceChangeGroup `json:"groups"` + FileCount int `json:"fileCount"` + StagedCount int `json:"stagedCount"` + AllStaged bool `json:"allStaged"` + // StageAll is nil when the workspace line writes nothing. + StageAll *WorkspaceStageAll `json:"stageAll,omitempty"` +} + +// GroupWorkspaceChanges asks Core to group the changes of every repository and plan what +// each checkbox writes. It reads nothing from disk. +func (c *Client) GroupWorkspaceChanges(ctx context.Context, repositories []WorkspaceRepositoryChanges) (WorkspaceChangeGroups, error) { + request := make([]WorkspaceRepositoryChanges, len(repositories)) + for i, repository := range repositories { + repository.Changes = nonNil(repository.Changes) + request[i] = repository + } + var groups WorkspaceChangeGroups + err := c.Execute(ctx, "git.workspaceChangeGroups", struct { + Repositories []WorkspaceRepositoryChanges `json:"repositories"` + }{request}, &groups) + return groups, err } // DiscoverWorkspaceRepositories returns Core's ordered repository roots. Core diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 6d4306cd78..f5ff62433e 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -55,20 +55,25 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.branch.forceCheckout": "Force Checkout", "desktop.branch.loadFailed": "Failed to load branches: {reason}", "desktop.branch.loading": "Loading branches…", + "desktop.branch.localIn": "Local Branches in {repository}", "desktop.branch.newBranchFrom": "New Branch from '{name}'…", "desktop.branch.recent": "Recent", + "desktop.branch.recentIn": "Recent Branches in {repository}", + "desktop.branch.remoteIn": "Remote Branches in {repository}", "desktop.branch.rename": "Rename…", "desktop.branch.renameButton": "Rename", "desktop.branch.renameFailed": "Failed to rename branch: {reason}", "desktop.branch.renameFrom": "Rename '{name}'.", "desktop.branch.renameTitle": "Rename Branch", "desktop.branch.renamed": "Renamed the branch to '{name}'", + "desktop.branch.repositoryPanel": "{repository} on {branch}", "desktop.branch.revision": "Tag or revision", "desktop.branch.revisionPrompt": "Enter a tag name, branch name, commit hash, or other Git revision.", "desktop.branch.revisionTitle": "Checkout Tag or Revision", "desktop.branch.rowMenu": "{name} actions", "desktop.branch.search": "Search for branches and actions", "desktop.branch.smartCheckout": "Smart Checkout", + "desktop.branch.tagsIn": "Tags in {repository}", "desktop.build.argumentsRequired": "This task asks for arguments, which this window cannot collect yet.", "desktop.build.cancelled": "Build cancelled", "desktop.build.chooseTask": "Choose a build task first.", @@ -1018,6 +1023,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.nested.commit": "Commit Repository", "desktop.nested.expand": "Expand Repository", "desktop.nested.refUnchanged": "The parent repository's reference to this submodule is unchanged. Commit here, then update the parent to record it.", + "desktop.nested.roots": "Roots", "desktop.newProject.advanced": "Advanced Settings", "desktop.newProject.archiveInvalid": "The downloaded archive is not a valid project.", "desktop.newProject.cancel": "Cancel", @@ -1972,6 +1978,7 @@ var sharedCatalogs = map[string]map[string]string{ "git.log.retry": "Retry", "git.log.selectCommit": "Select a commit", "git.log.tags": "Tags", + "git.log.toolbar.moreActions": "More Actions", "git.log.toolbar.newBranch": "New Branch", "git.log.updateBranch": "Update", "git.log.workingTreeComparisonFailed": "Failed to compare '{branch}' with the working tree:\n{error}", @@ -2784,20 +2791,25 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.branch.forceCheckout": "强制检出", "desktop.branch.loadFailed": "加载分支失败:{reason}", "desktop.branch.loading": "正在加载分支…", + "desktop.branch.localIn": "{repository} 中的本地分支", "desktop.branch.newBranchFrom": "从“{name}”新建分支…", "desktop.branch.recent": "最近", + "desktop.branch.recentIn": "{repository} 中的最近分支", + "desktop.branch.remoteIn": "{repository} 中的远程分支", "desktop.branch.rename": "重命名…", "desktop.branch.renameButton": "重命名", "desktop.branch.renameFailed": "重命名分支失败:{reason}", "desktop.branch.renameFrom": "重命名“{name}”。", "desktop.branch.renameTitle": "重命名分支", "desktop.branch.renamed": "分支已重命名为“{name}”", + "desktop.branch.repositoryPanel": "{repository},位于 {branch}", "desktop.branch.revision": "标签或修订版本", "desktop.branch.revisionPrompt": "输入标签名、分支名、提交 Hash 或其他 Git 修订版本。", "desktop.branch.revisionTitle": "检出标签或修订版本", "desktop.branch.rowMenu": "{name} 的操作", "desktop.branch.search": "搜索分支和操作", "desktop.branch.smartCheckout": "智能检出", + "desktop.branch.tagsIn": "{repository} 中的标签", "desktop.build.argumentsRequired": "此任务需要额外参数,当前窗口尚不能收集。", "desktop.build.cancelled": "构建已取消", "desktop.build.chooseTask": "请先选择一个构建任务。", @@ -3747,6 +3759,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.nested.commit": "提交此仓库", "desktop.nested.expand": "展开仓库", "desktop.nested.refUnchanged": "父仓库中该子模块的引用没有变化。在此提交后需要在父仓库中更新引用。", + "desktop.nested.roots": "仓库根目录", "desktop.newProject.advanced": "高级设置", "desktop.newProject.archiveInvalid": "下载的压缩包不是有效的项目。", "desktop.newProject.cancel": "取消", @@ -4701,6 +4714,7 @@ var sharedCatalogs = map[string]map[string]string{ "git.log.retry": "重试", "git.log.selectCommit": "选择一个提交", "git.log.tags": "标签", + "git.log.toolbar.moreActions": "更多操作", "git.log.toolbar.newBranch": "新建分支", "git.log.updateBranch": "更新", "git.log.workingTreeComparisonFailed": "无法比较“{branch}”与工作树:\n{error}", diff --git a/desktop/internal/workbench/branch.go b/desktop/internal/workbench/branch.go index 05529a909a..989cbf033d 100644 --- a/desktop/internal/workbench/branch.go +++ b/desktop/internal/workbench/branch.go @@ -51,7 +51,8 @@ type branchSession struct { // one the log walks when the popup opened, or one the user picked in the popup. Empty for the // project's own repository (branchRoot). repo string - // repoOpen says the repository picker of the popup lists the repositories to pick from. + // repoOpen says the panel of the repository repo is open beside its row, in the popup of a + // project folder with several repositories (drawWorkspaceBranchPanel). repoOpen bool // gen counts the loads of the references; the answer of an older load is dropped. gen int @@ -99,7 +100,7 @@ var headReference = core.GitReference{FullName: "HEAD", ShortName: "HEAD"} // references of the open project. func (a *App) openBranches() { p := a.project - if p == nil || !p.git.isRepository() { + if p == nil || !p.hasRepository() { return } a.title.projectOpen = false @@ -108,7 +109,6 @@ func (a *App) openBranches() { b := &a.branch b.open, b.menu, b.dialog = true, "", branchDialogNone b.repo, b.repoOpen = p.logBranchRepo(), false - a.loadNestedReferences(p) b.search.SetText("") if b.collapsed == nil { b.collapsed, b.expanded = map[string]bool{}, map[string]bool{} @@ -118,7 +118,7 @@ func (a *App) openBranches() { // closeBranches closes the popup and the row menu in it. func (a *App) closeBranches() { - a.branch.open, a.branch.menu = false, "" + a.branch.open, a.branch.repoOpen, a.branch.menu = false, false, "" } // leaveBranches closes the popup before a write or a dialog starts and records whether the @@ -169,12 +169,13 @@ func (a *App) branchRoot(p *project) string { return p.git.repositoryRoot(p.root) } -// selectBranchRepo makes the repository at root the one the popup lists and its dialogs act on, -// "" or the project's own root for the project's own repository, and reads its references. +// selectBranchRepo makes the repository at root the one the popup's repository panel lists and its +// dialogs act on, "" or the project's own root for the project's own repository, and reads its +// references. func (a *App) selectBranchRepo(p *project, root string) { b := &a.branch - b.repoOpen, b.menu = false, "" - if root == p.git.repositoryRoot(p.root) { + b.menu = "" + if p.git.isRepository() && root == p.git.repositoryRoot(p.root) { root = "" } if b.repo == root { @@ -183,10 +184,21 @@ func (a *App) selectBranchRepo(p *project, root string) { b.repo = root b.refs, b.sections = core.GitReferences{}, [3]logSection{} b.loaded, b.err = false, nil - a.loadNestedReferences(p) a.loadBranches(p) } +// toggleBranchRepo opens the panel of the repository at root beside its row, or closes it when it +// is the one open. +func (a *App) toggleBranchRepo(p *project, root string) { + b := &a.branch + if b.repoOpen && a.branchRoot(p) == root { + b.repoOpen, b.menu = false, "" + return + } + a.selectBranchRepo(p, root) + b.repoOpen = true +} + // runBranchWrite runs write against the repository of p in the background and reads the // status after it. operation names the write for the log, failed words its failure for the // user, and done reports its success once the status is in place. @@ -212,9 +224,12 @@ func (a *App) runBranchWrite(p *project, operation string, failed func(reason st a.operationFailed(operation, err) return } - // The project's status describes its own repository only. - if root == p.git.repositoryRoot(p.root) { + // The project's status describes its own repository only; a nested one's branch is read + // again with the repositories of the folder. + if p.git.isRepository() && root == p.git.repositoryRoot(p.root) { a.setGit(p, gitState{loaded: true, status: status}) + } else { + a.loadNestedRepos(p) } if p.log.started { a.loadLog(p) diff --git a/desktop/internal/workbench/branch_view.go b/desktop/internal/workbench/branch_view.go index 728ae32399..54592da3db 100644 --- a/desktop/internal/workbench/branch_view.go +++ b/desktop/internal/workbench/branch_view.go @@ -7,6 +7,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -56,82 +57,182 @@ func (a *App) drawBranchPopup(c ui.C, p *project, anchor ui.Box) { }) }) if !b.open { - // The press outside or Escape closed it; a closed popup has no row menu. - b.menu = "" + // The press outside or Escape closed it; a closed popup has no repository panel or row menu. + b.repoOpen, b.menu = false, "" } } -// drawBranchPanel declares the popup's contents: the search field, the repository picker of a -// project with nested repositories, the actions, and the references. Without a search the -// sections show Core's folder trees; a search lists every match by its full name. +// drawBranchPanel declares the popup's contents: the search field, the actions, and the +// references. Without a search the sections show Core's folder trees; a search lists every match +// by its full name. A project folder with several repositories lists them instead, as IDEA does +// (drawWorkspaceBranchPanel). func (a *App) drawBranchPanel(c ui.C, p *project, t i18n.BranchMessages) { + if p.workspaceMode() { + a.drawWorkspaceBranchPanel(c, p, t) + return + } b := &a.branch current := b.currentReference() - query := strings.ToLower(strings.TrimSpace(b.search.Text())) + query := branchQuery(b) ui.TextField(c, &b.search, t.Search, t.Search).FillWidth().AutoFocus() - if len(p.nested.repos) > 0 { - a.drawBranchRepoPicker(c, p) - } - if a.drawBranchActions(c, p, current, query) { + if a.drawBranchActions(c, p, current, query, true) { ui.Divider(c) } ui.Scroll(c).Scrollbars().FillWidth().MaxHeight(branchPopupMaxHeight).Children(func() { - switch { - case b.err != nil && !b.loading: - ui.Paragraph(c, t.LoadFailed(b.err.Error()), 4).Color(a.colors.Subtle).PadX(chromeEdge) - return - case !b.loaded: - a.drawBranchNote(c, t.Loading) - return - } - labels := [4]string{t.Recent, t.Local, t.Remote, t.Tags} - listed := 0 - for i, key := range branchSectionKeys { - refs := b.refs.RecentReferences - if i > 0 { - refs = b.sections[i-1].refs - } - if query != "" { - refs = matchingReferences(refs, query) - if i == 0 { - // The recent branches are in Local as well; a search lists each once. - refs = nil - } - } - if len(refs) == 0 { - continue - } - listed += len(refs) - collapsed := query == "" && b.collapsed[key] - if a.drawBranchSection(c, key, labels[i], collapsed, query == "") { - c.After(func() { b.collapsed[key] = !b.collapsed[key] }) + a.drawBranchReferences(c, p, t, query, [4]string{t.Recent, t.Local, t.Remote, t.Tags}) + }) +} + +// branchQuery is the search of the popup, trimmed and in lower case. +func branchQuery(b *branchState) string { + return strings.ToLower(strings.TrimSpace(b.search.Text())) +} + +// drawBranchReferences declares the sections of the references the popup read, under labels in +// the order of branchSectionKeys, filtered by query. +func (a *App) drawBranchReferences(c ui.C, p *project, t i18n.BranchMessages, query string, labels [4]string) { + b := &a.branch + switch { + case b.err != nil && !b.loading: + ui.Paragraph(c, t.LoadFailed(b.err.Error()), 4).Color(a.colors.Subtle).PadX(chromeEdge) + return + case !b.loaded: + a.drawBranchNote(c, t.Loading) + return + } + current := b.currentReference() + listed := 0 + for i, key := range branchSectionKeys { + refs := b.refs.RecentReferences + if i > 0 { + refs = b.sections[i-1].refs + } + if query != "" { + refs = matchingReferences(refs, query) + if i == 0 { + // The recent branches are in Local as well; a search lists each once. + refs = nil } - switch { - case collapsed: - case i == 0 || query != "": - for _, r := range refs { - a.drawBranchRow(c, p, key, r, r.ShortName, 1, r.FullName == current.FullName) - } - default: - s := &b.sections[i-1] - a.drawBranchNodes(c, p, s, key, s.nodes, 1, current) + } + if len(refs) == 0 { + continue + } + listed += len(refs) + collapsed := query == "" && b.collapsed[key] + if a.drawBranchSection(c, key, labels[i], collapsed, query == "") { + c.After(func() { b.collapsed[key] = !b.collapsed[key] }) + } + switch { + case collapsed: + case i == 0 || query != "": + for _, r := range refs { + a.drawBranchRow(c, p, key, r, r.ShortName, 1, r.FullName == current.FullName) } + default: + s := &b.sections[i-1] + a.drawBranchNodes(c, p, s, key, s.nodes, 1, current) } - if listed == 0 { - a.drawBranchNote(c, t.NoMatches) + } + if listed == 0 { + a.drawBranchNote(c, t.NoMatches) + } +} + +// drawWorkspaceBranchPanel declares the popup of a project folder with several repositories, as +// IDEA's: the search field, the commit of the Commit tool window, which spans every repository, and +// a row per repository in Core's order with its color, its name and the branch it is on. A click on +// a row opens the repository's panel beside it with its actions and references; every write there +// acts in that repository alone. +func (a *App) drawWorkspaceBranchPanel(c ui.C, p *project, t i18n.BranchMessages) { + b := &a.branch + query := branchQuery(b) + ui.TextField(c, &b.search, t.Search, t.Search).FillWidth().AutoFocus() + if commit := i18n.Shared(a.language(), "desktop.command.commit"); query == "" || strings.Contains(strings.ToLower(commit), query) { + if a.drawBranchAction(c, "commit", icons.GitCommitHorizontal, commit, false) { + c.After(a.commitFromBranches) } - if query == "" { - a.drawNestedReferences(c, p, t) + ui.Divider(c) + } + ui.Scroll(c).Scrollbars().FillWidth().MaxHeight(branchPopupMaxHeight).Children(func() { + for _, repo := range p.workspaceRepositories() { + a.drawWorkspaceBranchRepo(c, p, t, repo, query) + } + }) +} + +// drawWorkspaceBranchRepo declares the row of one repository of the folder's popup and, while it is +// open, its panel beside it: the actions of drawBranchActions and the sections of its references, +// each named after the repository. +func (a *App) drawWorkspaceBranchRepo(c ui.C, p *project, t i18n.BranchMessages, repo workspaceRepository, query string) { + b := &a.branch + open := b.repoOpen && a.branchRoot(p) == repo.root + branch := p.branchOf(repo.id) + label := repo.name + if branch != "" { + label = i18n.SharedFormat(a.language(), "desktop.branch.repositoryPanel", map[string]string{"repository": repo.name, "branch": branch}) + } + row := ui.Row(c.Key("repo/"+repo.id)).Height(branchRowHeight).Shrink(0).FillWidth().Items(ui.Center).Gap(chromeMenuGap).PadX(chromeEdge). + Radius(a.theme.Metrics.RadiusItem()).HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleMenuItem, Cursor: gfx.PointerCursorHand, Expandable: true, Expanded: open}) + if open { + row = row.Background(a.colors.Selection) + } else { + row = a.chromeHover(row) + } + row.Children(func() { + a.drawRepositorySwatch(c, p, repo.id) + ui.Text(c, repo.name).Color(a.colors.Text).LineHeight(chromeLineHeight).Ellipsis().Shrink(1) + ui.Spacer(c) + if branch != "" { + ui.Text(c, branch).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).LineHeight(chromeLineHeight). + Ellipsis().MaxWidth(branchPopupWidth / 2) } + ui.Icon(c, icons.ChevronRight).Size(chromeMarkSize, chromeMarkSize).Shrink(0).Color(a.colors.Subtle) }) + if row.Clicked() { + c.After(func() { a.toggleBranchRepo(p, repo.root) }) + } + if !open { + return + } + // The press that closes the panel goes on to the popup, so a click on another repository opens + // that one's panel at once. + spec := ui.PopoverSpec{Side: components.PopoverRight, Align: ui.Start, Offset: chromeMenuOffset, Width: branchPopupWidth} + ui.PopoverWith(c, row, spec, &b.repoOpen, func() { + ui.Column(c).FillWidth().MaxHeight(branchPopupMaxHeight).Gap(chromeMenuItems).Children(func() { + if a.drawBranchActions(c, p, b.currentReference(), query, false) { + ui.Divider(c) + } + ui.Scroll(c).Scrollbars().FillWidth().MaxHeight(branchPopupMaxHeight).Children(func() { + lang := a.language() + a.drawBranchReferences(c, p, t, query, [4]string{ + i18n.SharedFormat(lang, "desktop.branch.recentIn", map[string]string{"repository": repo.name}), + i18n.SharedFormat(lang, "desktop.branch.localIn", map[string]string{"repository": repo.name}), + i18n.SharedFormat(lang, "desktop.branch.remoteIn", map[string]string{"repository": repo.name}), + i18n.SharedFormat(lang, "desktop.branch.tagsIn", map[string]string{"repository": repo.name}), + }) + }) + }) + }) + if !b.repoOpen { + // A closed panel has no row menu. + b.menu = "" + } +} + +// commitFromBranches opens the Commit tool window's changes from the branch popup. +func (a *App) commitFromBranches() { + a.performed("git.showChanges", surfaceButton) + a.closeBranches() + a.layout.commitTab = commitTabChanges + a.showChanges() } // drawBranchActions declares the actions at the top of the popup in IDEA's order and reports // whether it showed any: Fetch, which shows only while the search names it, then updating, -// committing and pushing the current branch, then creating a branch, checking out a revision -// and creating a tag. A search keeps the actions whose names contain it. Every action works -// in the repository the popup lists. -func (a *App) drawBranchActions(c ui.C, p *project, current core.GitReference, query string) bool { +// committing, unless commit is false, and pushing the current branch, then creating a branch, +// checking out a revision and creating a tag. A search keeps the actions whose names contain it. +// Every action works in the repository the popup lists. +func (a *App) drawBranchActions(c ui.C, p *project, current core.GitReference, query string, commit bool) bool { b, t, g := &a.branch, a.text.Branch, a.text.Git lang := a.language() root := a.branchRoot(p) @@ -157,15 +258,10 @@ func (a *App) drawBranchActions(c ui.C, p *project, current core.GitReference, q }) } } - if commit := i18n.Shared(lang, "desktop.command.commit"); named(commit) { + if label := i18n.Shared(lang, "desktop.command.commit"); commit && named(label) { shown++ - if a.drawBranchAction(c, "commit", icons.GitCommitHorizontal, commit, false) { - c.After(func() { - a.performed("git.showChanges", surfaceButton) - a.closeBranches() - a.layout.commitTab = commitTabChanges - a.showChanges() - }) + if a.drawBranchAction(c, "commit", icons.GitCommitHorizontal, label, false) { + c.After(a.commitFromBranches) } } if push := i18n.Shared(lang, "git.contextMenu.push"); named(push) { @@ -202,42 +298,6 @@ func (a *App) drawBranchActions(c ui.C, p *project, current core.GitReference, q return shown > 0 } -// drawBranchRepoPicker declares the repository the popup lists, when the project has nested -// repositories: a row that names the picked one, which opens the list of every repository. -func (a *App) drawBranchRepoPicker(c ui.C, p *project) { - b, pull := &a.branch, a.text.Sync.Pull - picked := a.branchRoot(p) - repos := a.pullRepos(p) - name := "" - for _, r := range repos { - if r.root == picked { - name = r.name - } - } - chevron := icons.ChevronRight - if b.repoOpen { - chevron = icons.ChevronDown - } - row := ui.Row(c.Part("repo")).Height(branchRowHeight).Shrink(0).FillWidth().Items(ui.Center).Gap(chromeGap).PadX(chromeEdge). - Radius(a.theme.Metrics.RadiusItem()).HitWith(ui.ID(c), pull.Repository, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand, Expandable: true, Expanded: b.repoOpen}) - a.chromeHover(row).Children(func() { - ui.Text(c, pull.Repository).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).LineHeight(chromeLineHeight) - ui.Text(c, name).Color(a.colors.Text).LineHeight(chromeLineHeight).Ellipsis().Grow(1) - ui.Icon(c, chevron).Size(chromeMarkSize, chromeMarkSize).Shrink(0).Color(a.colors.Subtle) - }) - if row.Clicked() { - c.After(func() { b.repoOpen = !b.repoOpen }) - } - if !b.repoOpen { - return - } - for _, r := range repos { - if a.logMenuItem(c, "repo/"+r.root, r.name, r.root == picked, false) { - c.After(func() { a.selectBranchRepo(p, r.root) }) - } - } -} - // matchingReferences returns the references of refs whose short name contains query, which // is already lower case. func matchingReferences(refs []core.GitReference, query string) []core.GitReference { diff --git a/desktop/internal/workbench/changelists.go b/desktop/internal/workbench/changelists.go index b8a1fd838f..a0e56188bd 100644 --- a/desktop/internal/workbench/changelists.go +++ b/desktop/internal/workbench/changelists.go @@ -268,8 +268,10 @@ func (a *App) nextChangeListJob(p *project) { kernel, ok := a.kernel.(changeListKernel) if !ok || !p.git.isRepository() { l.members, l.scope, l.projected = nil, nil, l.statusGen - if !ok { - l.read, l.state = true, defaultChangeLists() + if !ok || p.git.loaded && p.git.err == nil { + // A folder that is no repository has only the default list; its nested repositories + // commit without one. + l.read, l.failed, l.state = true, nil, defaultChangeLists() } if job.then != nil { job.then(a, nil) diff --git a/desktop/internal/workbench/changelists_view.go b/desktop/internal/workbench/changelists_view.go index b210df5912..5045387de9 100644 --- a/desktop/internal/workbench/changelists_view.go +++ b/desktop/internal/workbench/changelists_view.go @@ -102,7 +102,7 @@ func (a *App) drawChangeListSections(c ui.C, p *project) { ui.Text(sc, t.Files(fileCount(changes))).Muted().Shrink(0) }) for _, change := range changes { - a.drawCommitChange(c, p, change) + a.drawCommitChange(c, p, change, changeRowIndent) } } }) diff --git a/desktop/internal/workbench/chrome.go b/desktop/internal/workbench/chrome.go index d1ddfce0af..13e2af19b8 100644 --- a/desktop/internal/workbench/chrome.go +++ b/desktop/internal/workbench/chrome.go @@ -164,7 +164,7 @@ func (a *App) chromeStatusText(i int) string { return strconv.Itoa(a.sessions.frameRate()) case itemChanges: if a.project != nil { - if count, ok := a.project.git.changeCount(); ok && count > 0 { + if count := a.project.changedFiles(); count > 0 { return a.text.Status.Changes(count) } } diff --git a/desktop/internal/workbench/chrome_view.go b/desktop/internal/workbench/chrome_view.go index 855bc7fb0d..9bb26cb3c5 100644 --- a/desktop/internal/workbench/chrome_view.go +++ b/desktop/internal/workbench/chrome_view.go @@ -547,7 +547,7 @@ func (a *App) chromeStatusLabel(c ui.C, text string) { // chromeBranch declares the checked-out branch as the button that opens the branch popup, and // shows nothing when the project is not a repository. The popup hangs off the button. func (a *App) chromeBranch(c ui.C) { - name := a.project.git.branch() + name := a.project.titleBranch() if name == "" { if a.branch.open { // The project stopped being a repository, so the popup has no branch to hang off. diff --git a/desktop/internal/workbench/commands.go b/desktop/internal/workbench/commands.go index 0bc5f15566..64b52173bf 100644 --- a/desktop/internal/workbench/commands.go +++ b/desktop/internal/workbench/commands.go @@ -197,7 +197,7 @@ func (a *App) commands() []command { addFrom("git.commit", t.GroupGit, t.Commit, true, func(surface actionSurface) { a.startCommit(p, false, surface) }) addFrom("git.commitPush", t.GroupGit, t.CommitAndPush, true, func(surface actionSurface) { a.startCommit(p, true, surface) }) add("git.branches", t.GroupGit, t.Branches, "", true, a.openBranches) - add("git.pull", t.GroupGit, a.text.Sync.Pull.MenuItem, "", p.git.isRepository(), func() { a.openPullDialog(p) }) + add("git.pull", t.GroupGit, a.text.Sync.Pull.MenuItem, "", p.hasRepository(), func() { a.openPullDialog(p) }) if d := p.selectedDocument(p.docs.group); d != nil && !d.virtual { addFrom("git.lineHistory", t.GroupGit, i18n.Shared(a.language(), "desktop.editorMenu.lineHistory"), p.git.isRepository(), func(surface actionSurface) { a.startLineHistory(p, d, surface) }) } diff --git a/desktop/internal/workbench/commit.go b/desktop/internal/workbench/commit.go index 74ee7967cb..6c061c0aff 100644 --- a/desktop/internal/workbench/commit.go +++ b/desktop/internal/workbench/commit.go @@ -209,7 +209,7 @@ func countStaged(changes []core.GitChange) int { // under way or waiting for the user. func (p *project) canCommit() bool { c := &p.commit - return p.git.isRepository() && p.listsReady() && c.idle() && + return p.hasRepository() && p.listsReady() && c.idle() && (p.activeStagedCount() > 0 || p.nestedStagedCount() > 0) && !p.otherStaged() && c.message() != "" } @@ -269,8 +269,9 @@ func (a *App) prepareCommit(p *project, t commitTarget, request core.WorkspaceCo c := t.state c.busy = true kernel := a.kernel + request = p.withWorkspaceRepositories(t, request) a.background(p, gitTimeout, func(ctx context.Context) func(*App) { - prep, err := kernel.WorkspaceCommitPrepare(ctx, includeNestedRepositories(ctx, kernel, p, t, request)) + prep, err := kernel.WorkspaceCommitPrepare(ctx, request) return func(a *App) { c.busy = false if err != nil { @@ -316,8 +317,9 @@ func (a *App) confirmReview(p *project, t commitTarget) { } c.busy = true kernel := a.kernel + request = p.withWorkspaceRepositories(t, request) a.background(p, gitTimeout, func(ctx context.Context) func(*App) { - prep, err := kernel.WorkspaceCommitPrepare(ctx, includeNestedRepositories(ctx, kernel, p, t, request)) + prep, err := kernel.WorkspaceCommitPrepare(ctx, request) return func(a *App) { c.busy = false switch { diff --git a/desktop/internal/workbench/commit_nested.go b/desktop/internal/workbench/commit_nested.go index 0d34888fb6..a0ed21d2b9 100644 --- a/desktop/internal/workbench/commit_nested.go +++ b/desktop/internal/workbench/commit_nested.go @@ -1,59 +1,25 @@ package workbench -import ( - "context" - "path/filepath" - "strings" - - "github.com/1lck/Lithe-IDEA/desktop/internal/core" -) +import "github.com/1lck/Lithe-IDEA/desktop/internal/core" // This file adds the repositories nested in the project folder to a commit of the project's -// staged changes (matrix id git-workspace-staged-commit). Core discovers them; each one with -// staged changes is planned and committed with the project's repository, and each keeps its -// own result. A first plan takes every nested repository unless a ChangeList scope holds the -// commit to the project's repository; a retry takes only the repositories its failed attempt -// planned, so the continued plan matches the one the attempt recorded. - -// repositoryDiscoverer is the part of the kernel the nested repositories use. Core's client -// implements it. -type repositoryDiscoverer interface { - DiscoverWorkspaceRepositories(ctx context.Context, root string) ([]core.WorkspaceRepository, error) -} +// staged changes (matrix id git-workspace-staged-commit). The window hands Core's discovery list +// back with the request, and Core binds the nested repositories to the plan: every one on a first +// plan, none when a ChangeList scope holds the commit to the project's repository, and on a retry +// only the ones its failed attempt planned, so the continued plan matches the one the attempt +// recorded. A folder that is no repository itself commits its nested repositories alone. -// includeNestedRepositories adds the repositories below the project folder, other than the -// project's own, to request. It keeps request unchanged for the project's own checkouts other -// than the Commit tool window, for a commit held to a ChangeList scope, and when Core cannot -// discover the repositories; the project's repository is committed in every case. -func includeNestedRepositories(ctx context.Context, kernel Kernel, p *project, t commitTarget, request core.WorkspaceCommitRequest) core.WorkspaceCommitRequest { - discoverer, ok := kernel.(repositoryDiscoverer) - if !ok || !t.console || request.PathScope != nil { - return request - } - repos, err := discoverer.DiscoverWorkspaceRepositories(ctx, p.root) - if err != nil { +// withWorkspaceRepositories hands the repositories of the project folder to request, for a commit +// of the Commit tool window. The project's own checkouts other than that window commit their +// repository alone. +func (p *project) withWorkspaceRepositories(t commitTarget, request core.WorkspaceCommitRequest) core.WorkspaceCommitRequest { + if !t.console || len(p.nested.discovered) == 0 { return request } - own := filepath.Clean(t.root) - for _, repo := range repos { - path := filepath.Clean(filepath.FromSlash(repo.Path)) - if path == own { - continue - } - rel, err := filepath.Rel(p.root, path) - if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { - continue - } - id := filepath.ToSlash(rel) - if request.Previous != nil { - if _, planned := request.Previous.States[id]; !planned { - continue - } - } - request.Repositories = append(request.Repositories, core.WorkspaceCommitRepository{ - ID: id, - Root: path, - }) + request.WorkspaceRepositories = append([]core.WorkspaceRepository(nil), p.nested.discovered...) + if !p.git.isRepository() { + // The project folder is no repository, so only the nested ones Core binds are planned. + request.Repositories = nil } return request } diff --git a/desktop/internal/workbench/commit_view.go b/desktop/internal/workbench/commit_view.go index ae19cec2c4..5e596316ef 100644 --- a/desktop/internal/workbench/commit_view.go +++ b/desktop/internal/workbench/commit_view.go @@ -26,6 +26,15 @@ const ( // commitReviewHeight is the most the steps of a review take before they scroll. const commitReviewHeight = 320 +// The left padding of a change row, so its checkbox sits one logIndent right of its parent's, as +// the levels of IDEA's change tree do. changeRowIndent is for a change right under the change +// list, whose checkbox is at 8; repositoryChangeIndent for a change under a repository's group, +// whose checkbox follows the group's fold button (drawRepositoryGroup). +const ( + changeRowIndent = 8 + logIndent + repositoryChangeIndent = 8 + shellHideSize + repositoryGroupGap + logIndent +) + // commitPageView declares the body of the Commit tool window. func (a *App) commitPageView(c ui.C) { v := &a.commitView @@ -94,7 +103,7 @@ func (a *App) drawCommitStatus(c ui.C, p *project) bool { c.After(func() { a.refreshChanges(p) }) } }) - case !p.git.isRepository(): + case !p.hasRepository(): a.gitEmpty(c, g.NotRepository) default: return true @@ -114,7 +123,7 @@ func (a *App) drawCommitChanges(c ui.C, p *project) ui.Box { a.drawChangeListSections(c, p) return } - if len(p.nested.repos) > 0 { + if p.workspaceMode() { a.drawRepositoryChanges(c, p) return } @@ -126,14 +135,15 @@ func (a *App) drawCommitChanges(c ui.C, p *project) ui.Box { return } a.drawChangeRows(c, t.ChangeList, t.Files(fileCount(changes)), changes, cs.busy, - func() { a.stageAllAcrossRepositories(p) }, - func(change core.GitChange) { a.drawCommitChange(c, p, change) }) + func() { a.stageAll(p, surfaceButton) }, + func(change core.GitChange) { a.drawCommitChange(c, p, change, changeRowIndent) }) }) } -// drawCommitChange declares the row of one change of the project's repository. -func (a *App) drawCommitChange(c ui.C, p *project, change core.GitChange) { - toggled, opened, clicked, mods := a.drawChangeRow(c, change, p.commit.busy, p.lists.selected[change.Path], func(rowC ui.C) func(*ui.MenuItems) { +// drawCommitChange declares the row of one change of the project's repository, indent from the +// left. +func (a *App) drawCommitChange(c ui.C, p *project, change core.GitChange, indent float32) { + toggled, opened, clicked, mods := a.drawChangeRow(c, change, p.commit.busy, p.lists.selected[change.Path], indent, func(rowC ui.C) func(*ui.MenuItems) { return a.changeMenuItems(rowC, p, change) }) if clicked && !toggled { @@ -151,7 +161,7 @@ func (a *App) drawCommitChange(c ui.C, p *project, change core.GitChange) { // unstages them all, with the list's title and size, over a row per change. func (a *App) drawChangeRows(c ui.C, title, size string, changes []core.GitChange, busy bool, toggleAll func(), row func(core.GitChange)) { ui.Scroll(c).Scrollbars().Grow(1).FillWidth().PadY(4).Children(func() { - a.drawChangeListHeader(c, title, size, changes, busy, toggleAll) + a.drawChangeListHeader(c, title, size, allStaged(changes), hasToggleable(changes), busy, toggleAll) for _, change := range changes { row(change) } @@ -159,11 +169,11 @@ func (a *App) drawChangeRows(c ui.C, title, size string, changes []core.GitChang } // drawChangeListHeader declares the line over a change list: the checkbox that stages or unstages -// all of its changes, with the list's title and size. -func (a *App) drawChangeListHeader(c ui.C, title, size string, changes []core.GitChange, busy bool, toggleAll func()) { +// all of its changes, checked when all is set and enabled when toggleable is, with the list's title +// and size. +func (a *App) drawChangeListHeader(c ui.C, title, size string, all, toggleable, busy bool, toggleAll func()) { ui.Row(c).Height(logItemHeight).FillWidth().Shrink(0).Items(ui.Center).Gap(6).PadX(8).Children(func() { - all := allStaged(changes) - if ui.Checkbox(c, &all, "").Label(title).Disabled(busy || !hasToggleable(changes)).Clicked() { + if ui.Checkbox(c, &all, "").Label(title).Disabled(busy || !toggleable).Clicked() { c.After(toggleAll) } ui.Text(c, title).Weight(gfx.WeightMedium).Ellipsis().Shrink(1) @@ -172,9 +182,9 @@ func (a *App) drawChangeListHeader(c ui.C, title, size string, changes []core.Gi } // drawChangeRow declares the row of one change: its checkbox, its icon, its name and folder, -// and whether it is staged, with the context menu menu builds. It reports a click on the -// checkbox and a double click on the row. -func (a *App) drawChangeRow(c ui.C, change core.GitChange, busy, selected bool, menu func(ui.C) func(*ui.MenuItems)) (toggled, opened, clicked bool, mods gfx.Modifiers) { +// and whether it is staged, indent from the left, with the context menu menu builds. It reports a +// click on the checkbox and a double click on the row. +func (a *App) drawChangeRow(c ui.C, change core.GitChange, busy, selected bool, indent float32, menu func(ui.C) func(*ui.MenuItems)) (toggled, opened, clicked bool, mods gfx.Modifiers) { t := a.text.Commit state, label := t.UnstagedState, t.StageFile(change.Path) switch { @@ -191,7 +201,7 @@ func (a *App) drawChangeRow(c ui.C, change core.GitChange, busy, selected bool, } rowC := c.Key(change.Path) row := ui.Row(rowC).Height(logItemHeight).FillWidth().Shrink(0).Items(ui.Center).Gap(6). - PadSides(0, 8, 0, float32(8+logIndent)).Hover(ui.Look{}.Background(a.colors.Hover)). + PadSides(0, 8, 0, indent).Hover(ui.Look{}.Background(a.colors.Hover)). HitWith(ui.ID(rowC), change.Path, gfx.HitOptions{Cursor: gfx.PointerCursorHand}) if selected { row = row.Background(a.colors.Selection) diff --git a/desktop/internal/workbench/filetree_menu.go b/desktop/internal/workbench/filetree_menu.go index d1413f88ba..9840aff072 100644 --- a/desktop/internal/workbench/filetree_menu.go +++ b/desktop/internal/workbench/filetree_menu.go @@ -158,7 +158,7 @@ func (a *App) projectTreeMenu(c ui.C, p *project, row gfx.ID, n *treeNode, targe } } if n.dir { - if p.git.isRepository() && menu.Item(i18n.Shared(language, "desktop.files.showRepositoryChanges")).Clicked() { + if p.hasRepository() && menu.Item(i18n.Shared(language, "desktop.files.showRepositoryChanges")).Clicked() { c.After(func() { a.performed("git.contextMenu.showRepositoryChanges", surfaceContextMenu) a.showRepositoryChangesOf(p, filepath.Join(p.root, filepath.FromSlash(n.path))) diff --git a/desktop/internal/workbench/git_log_repo.go b/desktop/internal/workbench/git_log_repo.go index a1094410d2..4df09e42ea 100644 --- a/desktop/internal/workbench/git_log_repo.go +++ b/desktop/internal/workbench/git_log_repo.go @@ -1,13 +1,19 @@ package workbench -import "path/filepath" +import ( + "context" + "path/filepath" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) // This file keeps which repository the Git log walks (matrix id git-multi-repository-references). -// The log starts on the project's own repository. A click on a group or a reference of a nested -// repository in the reference pane makes that repository the one the log walks: its history, -// commit details, comparisons, fetches and branch writes then act on it, and the log's header -// names it and offers the way back. A nested repository that leaves the workspace falls back to the -// project's own (nested_repos.go). The nested repositories' references are read in nested_refs.go. +// Core picks it from the repositories of the folder: the one the user picked while it is listed, +// otherwise the project's own, otherwise the first nested one, so a folder that is no repository +// itself walks its first nested repository. A click on a root of the Paths filter, or on a group or +// a reference of another repository in the reference pane, picks that repository: its history, +// commit details, comparisons, fetches and branch writes then act on it, and the log's header names +// it. The other repositories' references are read in nested_refs.go. // logRepo is the nested repository the log walks, nil while it walks the project's own. func (p *project) logRepo() *nestedRepo { @@ -18,6 +24,14 @@ func (p *project) logRepo() *nestedRepo { return repo } +// logRepoID is Core's ID of the repository the log walks. +func (p *project) logRepoID() string { + if repo := p.logRepo(); repo != nil { + return repo.id + } + return p.ownID() +} + // logRoot is the root the log reads the repository it walks from: the project folder for the // project's own repository, as the log always read it, and the nested repository's root otherwise. func (p *project) logRoot() string { @@ -44,37 +58,57 @@ func (p *project) logBranchRepo() string { return "" } -// repositoryName is the name a repository's group shows: the folder name of the project's own -// repository, or the nested repository's path in the project folder. The empty ID is the own one. +// repositoryName is the name a repository shows, Core's name for it: the folder name of the +// project's own repository and the path in the project folder of a nested one. The empty ID and +// commitRepositoryID are the own one. func (p *project) repositoryName(id string) string { - if id == "" || id == commitRepositoryID { + if p.isOwnID(id) { + if own, ok := p.nested.own(); ok { + return own.Name + } return filepath.Base(p.git.repositoryRoot(p.root)) } + if repo, ok := p.nested.repo(id); ok && repo.name != "" { + return repo.name + } return id } -// referenceGroups are the repositories the reference pane lists below its own sections: every -// nested repository but the one the log walks. While a nested repository is walked, the project's -// own repository is listed too, read-only, so the user can walk back to it by a click. -func (p *project) referenceGroups() []nestedRepo { - active := p.nested.logRepo - var groups []nestedRepo - if active != "" { - groups = append(groups, nestedRepo{id: commitRepositoryID, root: p.root}) - } - for _, repo := range p.nested.repos { - if repo.id != active { - groups = append(groups, repo) +// selectLogRepo asks Core which repository the log walks now that the repositories were read +// again, and the ones its reference pane lists besides. When Core falls back from the one walked, +// or picks a nested one because the folder is no repository, the log walks that one from its start. +func (a *App) selectLogRepo(p *project) { + n := &p.nested + selection, ok := a.workspaceSelection(p, n.logRepo) + if !ok { + return + } + n.others = selection.Others + active := selection.Active + if _, nested := n.repo(active); !nested { + active = "" + } + if active != n.logRepo { + a.releaseLogCursor(p) + n.logRepo = active + p.log.reference, p.log.referenceLabel, p.log.refSelected = "", "", "" + if p.log.started { + a.loadLog(p) + return } } - return groups + // The reference pane lists the other repositories' references, so they are read again once the + // repositories are. + if p.log.started { + a.loadNestedReferences(p) + } } // setLogRepo makes the repository with ID the one the log walks, "" or the project's own ID for the // project's own repository, and reads its log once. full, when given, is the reference the log then // walks in it, short its name. func (a *App) setLogRepo(p *project, id, full, short string) { - if id == commitRepositoryID { + if p.isOwnID(id) { id = "" } if p.nested.logRepo == id && full == "" { @@ -83,11 +117,37 @@ func (a *App) setLogRepo(p *project, id, full, short string) { // The history walk belongs to the repository it was opened in, so it is closed before the switch. a.releaseLogCursor(p) p.nested.logRepo = id + if selection, ok := a.workspaceSelection(p, id); ok { + p.nested.others = selection.Others + } l := &p.log l.reference, l.referenceLabel, l.refSelected = full, short, full a.loadLog(p) } +// workspaceSelection asks Core which repository a view acts on, given the ID of the one the log +// walks, "" for the project's own. It reports false, after logging why, when Core cannot answer. +func (a *App) workspaceSelection(p *project, picked string) (core.WorkspaceRepositorySelection, bool) { + discoverer, ok := a.kernel.(repositoryDiscoverer) + if !ok { + return core.WorkspaceRepositorySelection{}, false + } + n := &p.nested + if picked == "" { + if own, ok := n.own(); ok { + picked = own.ID + } + } + ctx, cancel := context.WithTimeout(context.Background(), kernelCallTimeout) + defer cancel() + selection, err := discoverer.SelectWorkspaceRepository(ctx, n.discovered, picked) + if err != nil { + a.backgroundFailed("workspace_repository_selection", err) + return core.WorkspaceRepositorySelection{}, false + } + return selection, true +} + // releaseLogCursor closes the history walk of the log, when one is open, in the repository it // was opened in. func (a *App) releaseLogCursor(p *project) { @@ -96,27 +156,3 @@ func (a *App) releaseLogCursor(p *project) { p.log.cursor = "" } } - -// logFallsBack reports that the log walked a nested repository that is no longer in the workspace, -// and makes the project's own repository the one it walks again. It reports whether it did. -func (a *App) logFallsBack(p *project) bool { - if p.nested.logRepo == "" || p.logRepo() != nil { - return false - } - a.releaseLogCursor(p) - p.nested.logRepo = "" - p.log.reference, p.log.referenceLabel, p.log.refSelected = "", "", "" - return true -} - -// workspaceRepositoryIDs are the IDs of every repository of the workspace, the project's own first -// and the nested ones in discovery order, for the color assignments. Core's list is unfiltered, so -// worktrees stay in it; the views drop the hidden ones. -func (p *project) workspaceRepositoryIDs() []string { - ids := make([]string, 0, len(p.nested.repos)+1) - ids = append(ids, commitRepositoryID) - for _, repo := range p.nested.repos { - ids = append(ids, repo.id) - } - return ids -} diff --git a/desktop/internal/workbench/gitcompare.go b/desktop/internal/workbench/gitcompare.go index 0fa6ad3ef4..a7454d786e 100644 --- a/desktop/internal/workbench/gitcompare.go +++ b/desktop/internal/workbench/gitcompare.go @@ -41,7 +41,7 @@ func (a *App) compareReferences(p *project, base core.GitReference, target *core func (a *App) compareReferencesAt(p *project, root string, base core.GitReference, target *core.GitReference) { kernel, ok := a.reviewKernel() l := &p.log - if !ok || !p.git.isRepository() || l.comparing || base.FullName == "" { + if !ok || !p.hasRepository() || l.comparing || base.FullName == "" { return } l.comparing = true diff --git a/desktop/internal/workbench/gitgraph.go b/desktop/internal/workbench/gitgraph.go index 2f2d1460a3..f6641db6f1 100644 --- a/desktop/internal/workbench/gitgraph.go +++ b/desktop/internal/workbench/gitgraph.go @@ -32,6 +32,9 @@ const ( logDatePad = 8 logDateFormat = "2006/1/2 15:04" logDateSample = "0000/00/00 00:00" + // logRootStripWidth is the strip at a row's left edge in the color of its repository, in a + // folder with several; the first lane's node starts past it. + logRootStripWidth = 3 ) // The logical grid of the graph, scaled from the 22 point rows of IntelliJ's log. @@ -395,6 +398,11 @@ func (a *App) paintLogRow(canvas *gfx.Canvas, rect gfx.Rect, index int) { commit, _ := l.commit(row.CommitHash) selected := row.CommitHash == l.selected a.paintGraphRow(canvas, m, rect, row, color) + if slot, ok := a.project.repositorySlot(a.project.logRepoID()); ok && a.project.workspaceMode() { + // As IDEA marks each commit with the color of its root, the strip at the left edge says which + // repository of the folder the log walks. + canvas.Fill(gfx.Rect{X: rect.X, Y: rect.Y, Width: logRootStripWidth, Height: rect.Height}, repositoryColor(slot, dark)) + } foreground := a.colors.Text if len(commit.ParentHashes) > 1 && !selected { diff --git a/desktop/internal/workbench/gitlog.go b/desktop/internal/workbench/gitlog.go index 5cec68f66e..69d6106ee0 100644 --- a/desktop/internal/workbench/gitlog.go +++ b/desktop/internal/workbench/gitlog.go @@ -70,6 +70,9 @@ const ( logPopoverPath // logPopoverBranchSettings is the menu of the reference pane's settings. logPopoverBranchSettings + // logPopoverViewMore is the overflow menu of the filter bar: the view buttons it has no room + // for. + logPopoverViewMore ) // logSection is one section of the reference pane: the local branches, the remote ones diff --git a/desktop/internal/workbench/gitlog_page.go b/desktop/internal/workbench/gitlog_page.go index 4b0eea653c..317037a311 100644 --- a/desktop/internal/workbench/gitlog_page.go +++ b/desktop/internal/workbench/gitlog_page.go @@ -42,6 +42,15 @@ const ( logPopoverWidth = 240 logPathWidth = 320 logListMaxHeight = 320 + // logBarPad is the padding at the ends of the commit list's filter bar and logBarGap the gap + // between its parts. logSearchMin is the least width of its text filter while view buttons are + // left in the bar: they go into the bar's overflow menu before the field gets narrower + // (logViewFit). Once they are all there, the field gives up room down to logSearchFloor before + // the filters' end is cut (logSearchWidth). + logBarPad = 6 + logBarGap = 4 + logSearchMin = 120 + logSearchFloor = 72 // logRowSlots is how many rows of the commit list can be on screen at once, and so how // many draw callbacks the list keeps: a row uses the one of its index modulo the slots. logRowSlots = 256 @@ -105,6 +114,13 @@ type logView struct { hasBody bool details bool + // barWidth is the width of the commit list's filter bar and filtersWidth that of its filters + // at their own width, as the last paint laid them out, read from the draw callbacks barDraw + // and filtersDraw gave their boxes. The view buttons that do not fit beside them go into the + // bar's overflow menu (logViewFit). + barWidth, filtersWidth float32 + barDraw, filtersDraw func(*ui.DrawContext) + // refs is the tree of the reference pane, refItems what its visible rows are and refSel // the reference selected in it, as the paint being drawn has it. refs ui.TreeState diff --git a/desktop/internal/workbench/gitlog_page_test.go b/desktop/internal/workbench/gitlog_page_test.go index 22f8d20d1f..2c2c62a4ff 100644 --- a/desktop/internal/workbench/gitlog_page_test.go +++ b/desktop/internal/workbench/gitlog_page_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/vivaui/viva/gfx" ) @@ -69,6 +70,124 @@ func TestLogDateChipFiltersThroughItsPopover(t *testing.T) { } } +// The filter bar shows every view button that fits beside the text filter at its least width and +// the filters, and, when not all of them fit, as many as fit with the overflow menu's button. +func TestLogViewFitKeepsTheButtonsThatFitBesideTheFilters(t *testing.T) { + // The filter bar's fixed parts: its padding, the text filter and the gaps around the filters. + const fixed = 2*logBarPad + logSearchMin + 3*logBarGap + const slot = shellHideSize + logBarGap + for _, tc := range []struct { + name string + bar, filters float32 + count, wantShow int + }{ + {"a bar not laid out yet shows every button", 0, 300, logViewCount, logViewCount}, + {"a bar with room for every button", fixed + 300 + logViewCount*slot - logBarGap, 300, logViewCount, logViewCount}, + {"one button short moves two to make room for the menu", fixed + 300 + logViewCount*slot - logBarGap - 1, 300, logViewCount, logViewCount - 2}, + {"room for three buttons shows two and the menu", fixed + 300 + 3*slot - logBarGap, 300, logViewCount, 2}, + {"a bar narrower than its filters shows only the menu", 340, 300, logViewCount, 0}, + } { + if got := logViewFit(tc.bar, tc.filters, tc.count); got != tc.wantShow { + t.Errorf("%s: logViewFit(%v, %v, %d) = %d, want %d", tc.name, tc.bar, tc.filters, tc.count, got, tc.wantShow) + } + } +} + +// A bar with every view button in its overflow menu gives the text filter the room the filters and +// the menu's button leave, between logSearchFloor and logSearchMin. +func TestLogSearchWidthGivesTheTextFilterTheRoomTheFiltersLeave(t *testing.T) { + // The filter bar's fixed parts: its padding, the menu's button and the gaps around the filters. + const fixed = 2*logBarPad + shellHideSize + 3*logBarGap + for _, tc := range []struct { + name string + bar, filters float32 + want float32 + }{ + {"room for the whole field keeps it at its least width", fixed + 300 + 200, 300, logSearchMin}, + {"less room narrows the field to it", fixed + 300 + 90, 300, 90}, + {"no room stops at the floor", fixed + 300 + 10, 300, logSearchFloor}, + } { + if got := logSearchWidth(tc.bar, tc.filters); got != tc.want { + t.Errorf("%s: logSearchWidth(%v, %v) = %v, want %v", tc.name, tc.bar, tc.filters, got, tc.want) + } + } +} + +// A commit list too narrow for the filter bar's view buttons keeps the filters whole, moves the +// last buttons into the bar's overflow menu, and the menu does what the button it stands for does. +func TestLogToolbarMovesTheViewButtonsItHasNoRoomForIntoItsMenu(t *testing.T) { + dir := newTestRepository(t) + h := newHarness(t, gitKernel{core.NewClient()}) + p := h.openLog(t, dir) + v, g := &h.app.logView, h.app.text.Git + more := i18n.Shared(h.app.language(), "git.log.toolbar.moreActions") + if more == "" { + t.Fatal("the overflow menu's button has no name in the desktop catalog") + } + if _, ok := h.findPageHit(more); ok { + t.Fatalf("a filter bar %v wide shows the overflow menu though every view button fits", v.barWidth) + } + + // Narrow the commit list to room for three view buttons, and half of one more, beside the + // text filter at its least width and the filters: two buttons and the menu's. + const slot = shellHideSize + logBarGap + target := 2*logBarPad + logSearchMin + v.filtersWidth + 3*logBarGap + 3*slot - logBarGap + slot/2 + v.detailWidth += v.barWidth - target + h.relayLogBar() + if _, ok := h.findPageHit(more); !ok { + t.Fatalf("a filter bar %v wide with filters %v wide shows no overflow menu", v.barWidth, v.filtersWidth) + } + for _, name := range []string{g.FilterPaths, g.CompareBranch, g.ShowDetails} { + if _, ok := h.findPageHit(name); !ok { + t.Fatalf("a filter bar %v wide with filters %v wide does not show %q", v.barWidth, v.filtersWidth, name) + } + } + if _, ok := h.findPageHit(g.LongEdges); ok { + t.Fatalf("a filter bar %v wide still shows the last view button %q", v.barWidth, g.LongEdges) + } + + h.clickNamed(more) + if p.log.popover != logPopoverViewMore { + t.Fatalf("popover %v after clicking %q, want the overflow menu", p.log.popover, more) + } + h.clickNamed(g.LongEdges) + h.settle() + if !p.log.expanded || p.log.popover != logPopoverNone { + t.Fatalf("long edges %v popover %v after choosing %q in the menu, want them shown and the menu closed", p.log.expanded, p.log.popover, g.LongEdges) + } +} + +// At the commit list's least width every view button is in the overflow menu and the text filter +// gives up room, no narrower than logSearchFloor, for the filters. +func TestLogToolbarNarrowsTheTextFilterOnceEveryViewButtonIsInItsMenu(t *testing.T) { + dir := newTestRepository(t) + h := newHarness(t, gitKernel{core.NewClient()}) + h.openLog(t, dir) + v, g := &h.app.logView, h.app.text.Git + + v.detailWidth = 10_000 // the details take all but the commit list's least width + h.relayLogBar() + if _, ok := h.findPageHit(g.CompareBranch); ok { + t.Fatalf("a filter bar %v wide with filters %v wide still shows %q", v.barWidth, v.filtersWidth, g.CompareBranch) + } + h.pageHit(i18n.Shared(h.app.language(), "git.log.toolbar.moreActions")) + if width := h.pageHit(g.TextOrHash).Bounds.Width; width >= logSearchMin || width < logSearchFloor { + t.Fatalf("the text filter of a filter bar %v wide is %v wide, want narrower than %v and no narrower than %v", + v.barWidth, width, float32(logSearchMin), float32(logSearchFloor)) + } +} + +// relayLogBar paints the window twice after the log's filter bar changed width: the first paint +// lays the bar out and measures it, the second lays out the view buttons by that measure. The +// headless driver paints only when woken, so the paint the measurement asks for is made here. +func (h *harness) relayLogBar() { + h.t.Helper() + for range 2 { + h.app.post(func(*App) {}) + h.settle() + } +} + func TestLogMenuOpensTheFetchOptionsDialogAndEscapeClosesIt(t *testing.T) { dir := newTestRepository(t) h := newHarness(t, gitKernel{core.NewClient()}) diff --git a/desktop/internal/workbench/gitlog_popover_view.go b/desktop/internal/workbench/gitlog_popover_view.go index bde2dc973e..91414d98be 100644 --- a/desktop/internal/workbench/gitlog_popover_view.go +++ b/desktop/internal/workbench/gitlog_popover_view.go @@ -211,7 +211,9 @@ func (a *App) drawLogDateFilter(c ui.C, p *project) { } } -// drawLogPathFilter declares the path filter: a field and the buttons that apply it. +// drawLogPathFilter declares the path filter: a field and the buttons that apply it. The popover +// already keeps its content off its edges, so the field and the roots take no padding of their +// own, as the other filters' rows do not. func (a *App) drawLogPathFilter(c ui.C, p *project) { l, v, g := &p.log, &a.logView, a.text.Git apply := func(value string) { @@ -225,7 +227,7 @@ func (a *App) drawLogPathFilter(c ui.C, p *project) { a.reproject(p, 0) } } - ui.Column(c).FillWidth().Pad(8).Gap(8).Children(func() { + ui.Column(c).FillWidth().Gap(8).Children(func() { ui.Text(c, g.PathTitle).Weight(gfx.WeightMedium) if ui.TextFieldID(c, logPathID, &v.pathField, g.PathTitle, g.PathPlaceholder).FillWidth().Submitted() { c.After(func() { apply(v.pathField.Text()) }) @@ -246,6 +248,44 @@ func (a *App) drawLogPathFilter(c ui.C, p *project) { } }) }) + if p.workspaceMode() { + a.drawLogRoots(c, p) + } +} + +// drawLogRoots declares the repositories of the project folder under the Paths filter, as IDEA's +// filter lists the roots of a project with several: each in its color, the one the log walks +// checked. A click walks that repository's history. +func (a *App) drawLogRoots(c ui.C, p *project) { + l := &p.log + walked := p.logRepoID() + ui.Divider(c) + ui.Column(c).FillWidth().Gap(2).Children(func() { + ui.Text(c, i18n.Shared(a.language(), "desktop.nested.roots")).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + for _, repo := range p.workspaceRepositories() { + checked := repo.id == walked + item := ui.Row(c.Key("root/"+repo.id)).Height(logItemHeight+2).FillWidth().Shrink(0).Items(ui.Center).Gap(8).PadX(8). + Radius(a.theme.Metrics.RadiusItem()). + HitWith(ui.ID(c), repo.name, gfx.HitOptions{Role: gfx.RoleMenuItem, Selected: checked}). + Hover(ui.Look{}.Background(a.colors.Hover)).Pressed(ui.Look{}.Background(a.colors.Active)) + item.Children(func() { + if checked { + ui.Icon(c, icons.Check).Size(14, 14).Color(a.colors.Accent) + } else { + ui.Row(c).Size(14, 14).Shrink(0) + } + a.drawRepositorySwatch(c, p, repo.id) + ui.Text(c, repo.name).Color(a.colors.Text).Ellipsis().Grow(1) + }) + if item.Clicked() { + id := repo.id + c.After(func() { + l.popover = logPopoverNone + a.setLogRepo(p, id, "", "") + }) + } + } + }) } // logMenuItem declares one item of a popover, named key among its siblings, with a check mark diff --git a/desktop/internal/workbench/gitlog_view.go b/desktop/internal/workbench/gitlog_view.go index af2b9e7091..e618a53d37 100644 --- a/desktop/internal/workbench/gitlog_view.go +++ b/desktop/internal/workbench/gitlog_view.go @@ -6,6 +6,7 @@ import ( "strings" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" @@ -22,6 +23,8 @@ func (a *App) logPageView(c ui.C) { v := &a.logView if v.bodyDraw == nil { v.bodyDraw = func(d *ui.DrawContext) { v.bodyRect = d.Rect } + v.barDraw = func(d *ui.DrawContext) { measureLogBar(&v.barWidth, d) } + v.filtersDraw = func(d *ui.DrawContext) { measureLogBar(&v.filtersWidth, d) } v.refs.Node, v.refLabel = v.refNode, v.refRowLabel v.commits.Label = a.logCommitLabel } @@ -349,7 +352,6 @@ func (a *App) chooseLogRef(p *project, r logRefRow, query string) { // drawLogCommits declares the commit pane: the filter bar over the list. func (a *App) drawLogCommits(c ui.C, p *project) ui.Box { return ui.Column(c).FillHeight().MinWidth(logCommitsMin).Clip().Children(func() { - a.drawLogRepoBar(c, p) a.drawLogToolbar(c, p) ui.Divider(c) a.drawSyncStatus(c, p) @@ -371,99 +373,244 @@ func (a *App) drawGitActions(c ui.C, p *project) { a.drawLogMenu(c, p, menu) } -// drawLogToolbar declares the filter bar: the text filter, the filter chips and the -// view buttons. The menu of the Git actions is in the tool window's header (drawGitActions). +// drawLogToolbar declares the filter bar: the text filter, the filters (the filter chips, the +// repository the log walks and the button that shows every reference again), and the view +// buttons, as IDEA's log toolbar lays them out. The filters keep their width; a bar short of room +// moves the view buttons, the last first, into its overflow menu, then narrows the text filter to +// logSearchFloor, and only a bar too narrow for that cuts the filters' end. The menu of the Git +// actions is in the tool window's header (drawGitActions). func (a *App) drawLogToolbar(c ui.C, p *project) { l, v, g := &p.log, &a.logView, a.text.Git - ui.Row(c).Height(logToolbarHeight).Shrink(0).Items(ui.Center).Gap(4).PadX(6).Children(func() { - ui.TextFieldID(c, logSearchID, &v.search, g.TextOrHash, g.TextOrHash).MinWidth(150).Grow(1).MaxWidth(320) - dates := [logDateCount]string{g.AnyTime, g.Today, g.Yesterday, g.Last7Days, g.Last30Days} - chips := [logChipCount]struct { - label, value string - popover logPopover - }{ - {g.FilterBranch, l.referenceLabel, logPopoverBranch}, - {g.FilterUser, l.user, logPopoverUser}, - {g.FilterDate, "", logPopoverDate}, - {g.FilterPaths, l.path, logPopoverPath}, - } - if l.date != logAnyTime { - chips[logChipDate].value = dates[l.date] - } - for i, chip := range chips { - box := a.drawLogChip(c, i, chip.label, chip.value, l.popover == chip.popover) - if box.Clicked() { - c.After(func() { a.toggleLogPopover(p, chip.popover) }) + shown := logViewFit(v.barWidth, v.filtersWidth, logViewCount) + if shown == logViewCount && l.popover == logPopoverViewMore { + l.popover = logPopoverNone // the bar has room for every button again + } + searchMin := float32(logSearchMin) + if shown == 0 { + searchMin = logSearchWidth(v.barWidth, v.filtersWidth) + } + ui.Row(c).Height(logToolbarHeight).FillWidth().Shrink(0).Items(ui.Center).Gap(logBarGap).PadX(logBarPad).Draw(v.barDraw).Children(func() { + ui.TextFieldID(c, logSearchID, &v.search, g.TextOrHash, g.TextOrHash).MinWidth(searchMin).Grow(1).MaxWidth(320) + ui.Row(c).Shrink(1).MinWidth(0).Clip().Items(ui.Center).Children(func() { + ui.Row(c).Shrink(0).Items(ui.Center).Gap(logBarGap).Draw(v.filtersDraw).Children(func() { + a.drawLogFilters(c, p) + }) + }) + ui.Spacer(c) + ui.Row(c).Shrink(0).Items(ui.Center).Gap(logBarGap).Children(func() { + for i := range shown { + b := a.logViewButton(p, i) + if a.gitIconButton(c, b.label, b.icon, b.lit, b.disabled) { + c.After(func() { a.runLogView(p, i) }) + } } - a.drawLogPopover(c, p, chip.popover, box) - } - if l.reference != "" { - // The log walks one reference: this shows every reference again. - if a.gitIconButton(c, g.ShowAll, icons.Plus, false, false) { - c.After(func() { - l.refSelected = "" - a.setLogReference(p, "", "") - }) + if shown < logViewCount { + a.drawLogViewMore(c, p, shown) } + }) + }) +} + +// drawLogFilters declares the filters of the filter bar: the filter chips with their popovers, the +// repository the log walks, and, while the log walks one reference, the button that shows every +// reference again. +func (a *App) drawLogFilters(c ui.C, p *project) { + l, g := &p.log, a.text.Git + dates := [logDateCount]string{g.AnyTime, g.Today, g.Yesterday, g.Last7Days, g.Last30Days} + chips := [logChipCount]struct { + label, value string + popover logPopover + }{ + {g.FilterBranch, l.referenceLabel, logPopoverBranch}, + {g.FilterUser, l.user, logPopoverUser}, + {g.FilterDate, "", logPopoverDate}, + {g.FilterPaths, l.path, logPopoverPath}, + } + if l.date != logAnyTime { + chips[logChipDate].value = dates[l.date] + } + for i, chip := range chips { + box := a.drawLogChip(c, i, chip.label, chip.value, l.popover == chip.popover) + if box.Clicked() { + c.After(func() { a.toggleLogPopover(p, chip.popover) }) } - ui.Spacer(c) - if a.gitIconButton(c, g.CompareBranch, icons.ArrowLeftRight, false, l.comparing) { - c.After(func() { a.compareReferences(p, l.currentReference(), nil) }) - } - if a.gitIconButton(c, g.ShowDetails, icons.PanelRight, l.showDetails, false) { - c.After(func() { l.showDetails = !l.showDetails }) - } - if a.gitIconButton(c, g.RefreshLog, icons.RefreshCw, false, false) { - c.After(func() { a.loadLog(p) }) + a.drawLogPopover(c, p, chip.popover, box) + } + a.drawLogRepoLabel(c, p) + if l.reference != "" { + if a.gitIconButton(c, g.ShowAll, icons.Plus, false, false) { + c.After(func() { + l.refSelected = "" + a.setLogReference(p, "", "") + }) } - decorations := icons.EyeOff + } +} + +// The view buttons at the end of the filter bar, in the order the bar shows them. A bar short of +// room moves the last ones into its overflow menu first. +const ( + logViewCompare = iota + logViewDetails + logViewRefresh + logViewDecorations + logViewFind + logViewEdges + logViewCount +) + +// logViewButtonSpec is what a view button of the filter bar shows: its label and icon, whether it +// is drawn pressed (lit) and whether it is disabled. toggle says it switches a setting, on or off +// as state says, which the overflow menu shows as a check mark. +type logViewButtonSpec struct { + label string + icon gfx.Icon + lit, disabled bool + toggle, state bool +} + +// logViewButton is what view button i of the filter bar shows. +func (a *App) logViewButton(p *project, i int) logViewButtonSpec { + l, g := &p.log, a.text.Git + switch i { + case logViewCompare: + return logViewButtonSpec{label: g.CompareBranch, icon: icons.ArrowLeftRight, disabled: l.comparing} + case logViewDetails: + return logViewButtonSpec{label: g.ShowDetails, icon: icons.PanelRight, lit: l.showDetails, toggle: true, state: l.showDetails} + case logViewRefresh: + return logViewButtonSpec{label: g.RefreshLog, icon: icons.RefreshCw} + case logViewDecorations: + icon := icons.EyeOff if l.decorations { - decorations = icons.Eye - } - if a.gitIconButton(c, g.Decorations, decorations, false, false) { - c.After(func() { l.decorations = !l.decorations }) - } - if a.gitIconButton(c, g.FindInLog, icons.Search, false, false) { - v.focus = logSearchID + icon = icons.Eye } - edges := icons.ArrowDownToLine + return logViewButtonSpec{label: g.Decorations, icon: icon, toggle: true, state: l.decorations} + case logViewFind: + return logViewButtonSpec{label: g.FindInLog, icon: icons.Search} + default: + icon := icons.ArrowDownToLine if l.expanded { - edges = icons.ArrowUpDown + icon = icons.ArrowUpDown } - if a.gitIconButton(c, g.LongEdges, edges, l.expanded, false) { - c.After(func() { - l.expanded = !l.expanded - if !l.loading { - a.reproject(p, 0) - } - }) + return logViewButtonSpec{label: g.LongEdges, icon: icon, lit: l.expanded, toggle: true, state: l.expanded} + } +} + +// runLogView does what view button i of the filter bar does, pressed in the bar or chosen in its +// overflow menu. +func (a *App) runLogView(p *project, i int) { + l := &p.log + switch i { + case logViewCompare: + a.compareReferences(p, l.currentReference(), nil) + case logViewDetails: + l.showDetails = !l.showDetails + case logViewRefresh: + a.loadLog(p) + case logViewDecorations: + l.decorations = !l.decorations + case logViewFind: + a.logView.focus = logSearchID + case logViewEdges: + l.expanded = !l.expanded + if !l.loading { + a.reproject(p, 0) + } + } +} + +// logViewFit is how many of count view buttons the filter bar shows: all of them when they fit in +// a bar barWidth wide beside the text filter at its least width and filters filtersWidth wide, +// otherwise as many as fit with the button of the overflow menu after them. A bar not laid out +// yet shows them all. +func logViewFit(barWidth, filtersWidth float32, count int) int { + if barWidth <= 0 { + return count + } + // The text filter, the filters, the spacer and the buttons stand logBarGap apart. + room := barWidth - 2*logBarPad - logSearchMin - filtersWidth - 3*logBarGap + fits := int((room + logBarGap) / (shellHideSize + logBarGap)) + if fits >= count { + return count + } + return max(fits-1, 0) +} + +// logSearchWidth is the least width of the text filter of a bar barWidth wide that has moved every +// view button into its overflow menu: the room the filters filtersWidth wide and the menu's button +// leave it, no more than logSearchMin and no less than logSearchFloor. +func logSearchWidth(barWidth, filtersWidth float32) float32 { + room := barWidth - 2*logBarPad - filtersWidth - shellHideSize - 3*logBarGap + return min(max(room, logSearchFloor), logSearchMin) +} + +// measureLogBar records in width the width d laid its box out at and, when it changed, asks for +// one more paint: which view buttons the filter bar shows is worked out from it. +func measureLogBar(width *float32, d *ui.DrawContext) { + if d.Rect.Width != *width { + *width = d.Rect.Width + d.Canvas.RequestFrame() + } +} + +// drawLogViewMore declares the button of the filter bar's overflow menu and, while it is open, the +// menu: the view buttons from first on, which the bar has no room for, each with its icon, and a +// setting one switches checked when it is on. +func (a *App) drawLogViewMore(c ui.C, p *project, first int) { + l := &p.log + label := i18n.Shared(a.language(), "git.log.toolbar.moreActions") + button, clicked := a.gitToolButton(c, label, icons.Ellipsis, l.popover == logPopoverViewMore, false) + if clicked { + c.After(func() { a.toggleLogPopover(p, logPopoverViewMore) }) + } + if l.popover != logPopoverViewMore { + return + } + open := true + ui.Menu(c, button, &open, func(menu *ui.MenuItems) { + for i := first; i < logViewCount; i++ { + b := a.logViewButton(p, i) + item := menu.Item(b.label).Icon(b.icon).Disabled(b.disabled) + if b.toggle { + item = item.Checked(b.state) + } + if item.Clicked() { + c.After(func() { a.runLogView(p, i) }) + } } }) + if !open { + l.popover = logPopoverNone + } } -// drawLogRepoBar declares the header of the commit list that names the repository the log walks, -// and, while a nested repository is walked, the way back to the project's own. It shows only in a -// workspace with nested repositories. -func (a *App) drawLogRepoBar(c ui.C, p *project) { - if len(p.nested.repos) == 0 && p.nested.logRepo == "" { +// drawLogRepoLabel declares, in the filter bar after the Paths chip, the repository the log walks, +// and, while a nested repository is walked in a folder that is a repository itself, the way back to +// the project's own. It shows only in a workspace with nested repositories; the Paths filter lists +// the roots to walk another one (drawLogRoots). The bar is short of room, so the label shows the +// repository's folder in its color and its name, keeps that width, and says it is the repository +// the log walks in its tip. +func (a *App) drawLogRepoLabel(c ui.C, p *project) { + if !p.workspaceMode() && p.nested.logRepo == "" { return } g := a.text.Git.Repositories - id := commitRepositoryID - if repo := p.logRepo(); repo != nil { - id = repo.id - } + id := p.logRepoID() + name := p.repositoryName(id) tint := a.repositoryTint(p, id) - ui.Row(c).Height(logToolbarHeight).Shrink(0).Items(ui.Center).Gap(6).PadX(6).Children(func() { - ui.Icon(c, icons.Folder).Size(14, 14).Shrink(0).Color(tint) - ui.Text(c, g.Current(p.repositoryName(id))).Weight(gfx.WeightMedium).Color(tint).Ellipsis().Grow(1) - if p.nested.logRepo != "" { - if ui.Button(c.Part("repo-back"), g.Back(p.repositoryName(commitRepositoryID))).Ghost().Clicked() { - c.After(func() { a.setLogRepo(p, commitRepositoryID, "", "") }) - } + rc := c.Part("repo") + ui.Row(rc).Shrink(0).Items(ui.Center).Gap(4).PadX(4). + HitWith(ui.ID(rc), g.Current(name), gfx.HitOptions{Role: gfx.RoleStatus}).Tooltip(g.Current(name)). + Children(func() { + ui.Icon(rc, icons.Folder).Size(14, 14).Shrink(0).Color(tint) + ui.Text(rc, name).Weight(gfx.WeightMedium).Color(tint).Ellipsis().MaxWidth(160) + }) + if p.nested.logRepo != "" && p.git.isRepository() { + own := p.ownID() + if ui.Button(c.Part("repo-back"), g.Back(p.repositoryName(own))).Ghost().Shrink(0).Clicked() { + c.After(func() { a.setLogRepo(p, own, "", "") }) } - }) - ui.Divider(c) + } } // drawLogChip declares a filter chip: its name, or the filter it applies, and a chevron. @@ -503,9 +650,13 @@ func (a *App) drawLogList(c ui.C, p *project) { case !p.git.loaded || l.loading && len(l.commits) == 0: a.gitEmpty(c, g.Loading) return - case !p.git.isRepository(): + case !p.hasRepository(): a.gitEmpty(c, g.NotRepository) return + case !p.git.isRepository() && p.logRepo() == nil: + // The folder is no repository; the log walks a nested one once Core picked it. + a.gitEmpty(c, g.Loading) + return case l.err != nil: a.gitEmpty(c, g.Failed(l.err.Error())) return diff --git a/desktop/internal/workbench/gitpull.go b/desktop/internal/workbench/gitpull.go index 2e021adc59..e01affdb80 100644 --- a/desktop/internal/workbench/gitpull.go +++ b/desktop/internal/workbench/gitpull.go @@ -111,12 +111,12 @@ func (s *pullState) preselectUpstream(root string) { } } -// pullRepos are the repositories the Pull dialog can pull into: the project's own, then each -// nested repository, in the order the workspace lists them. +// pullRepos are the repositories the Pull dialog can pull into: the project's own while the folder +// is in one, then each nested repository, in the order the workspace lists them. func (a *App) pullRepos(p *project) []pullRepo { - repos := []pullRepo{{root: p.git.repositoryRoot(p.root), name: p.repositoryName("")}} - for _, repo := range p.nested.repos { - repos = append(repos, pullRepo{root: repo.root, name: p.repositoryName(repo.id)}) + var repos []pullRepo + for _, repo := range p.workspaceRepositories() { + repos = append(repos, pullRepo{root: repo.root, name: repo.name}) } return repos } @@ -126,7 +126,7 @@ func (a *App) pullRepos(p *project) []pullRepo { // dialog starts on that repository, with the branch it tracks picked. func (a *App) openPullDialog(p *project) { s := &p.log.sync - if s.busy || !p.git.isRepository() { + if s.busy || !p.hasRepository() { return } repos := a.pullRepos(p) diff --git a/desktop/internal/workbench/gitreview_tools.go b/desktop/internal/workbench/gitreview_tools.go index 5c4deb8d01..fe1aaa7cf0 100644 --- a/desktop/internal/workbench/gitreview_tools.go +++ b/desktop/internal/workbench/gitreview_tools.go @@ -46,7 +46,7 @@ func (a *App) openPush(p *project, surface actionSurface) { // checked-out one when branch is empty, and reads Core's preview. surface is where the user // asked. func (a *App) openPushOf(p *project, root string, branch core.GitReference, surface actionSurface) { - if _, ok := a.reviewKernel(); !ok || !p.git.isRepository() { + if _, ok := a.reviewKernel(); !ok || !p.hasRepository() { return } s := &p.review.push diff --git a/desktop/internal/workbench/gitreview_tools_view.go b/desktop/internal/workbench/gitreview_tools_view.go index 0cb19434a2..3b8ef92377 100644 --- a/desktop/internal/workbench/gitreview_tools_view.go +++ b/desktop/internal/workbench/gitreview_tools_view.go @@ -21,7 +21,7 @@ var pushTagIndexes = []int{0, 1, 2} // repositories. func (a *App) drawGitReviewMenu(c ui.C, p *project) { r := &a.reviewMenu - button, clicked := a.gitToolButton(c, i18n.Shared(a.language(), "desktop.gitReview.menuLabel"), icons.Ellipsis, r.open, !p.git.isRepository()) + button, clicked := a.gitToolButton(c, i18n.Shared(a.language(), "desktop.gitReview.menuLabel"), icons.Ellipsis, r.open, !p.hasRepository()) if clicked { r.open = !r.open } diff --git a/desktop/internal/workbench/gitworktree_view.go b/desktop/internal/workbench/gitworktree_view.go index fbbb57d6bb..c38e656c1b 100644 --- a/desktop/internal/workbench/gitworktree_view.go +++ b/desktop/internal/workbench/gitworktree_view.go @@ -484,7 +484,7 @@ func (a *App) drawWorktreeChanges(c ui.C, p *project, w core.GitWorktree) { // drawWorktreeChange declares the row of one local change of the worktree at root, with the // commit panel's checkbox; a double click shows its diff. func (a *App) drawWorktreeChange(c ui.C, p *project, root string, busy bool, change core.GitChange) { - toggled, opened, _, _ := a.drawChangeRow(c, change, busy, false, func(rowC ui.C) func(*ui.MenuItems) { + toggled, opened, _, _ := a.drawChangeRow(c, change, busy, false, changeRowIndent, func(rowC ui.C) func(*ui.MenuItems) { return a.worktreeChangeMenuItems(rowC, p, root, change) }) if toggled { diff --git a/desktop/internal/workbench/nested_refs.go b/desktop/internal/workbench/nested_refs.go index fae9c99170..5f5cfe6ba5 100644 --- a/desktop/internal/workbench/nested_refs.go +++ b/desktop/internal/workbench/nested_refs.go @@ -5,21 +5,19 @@ import ( "strings" "github.com/1lck/Lithe-IDEA/desktop/internal/core" - "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" - "github.com/1lck/Lithe-IDEA/desktop/internal/icons" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) -// This file is the references of the nested repositories (matrix id -// git-multi-repository-references). The branch popup lists, under the project's own references, -// the local branches and tags of each repository nested in the project folder, each repository in -// its own group, read-only. The Git Log's reference pane lists the repository groups below its own -// sections, with each repository's color from Core; a click on a group or one of its references makes -// that repository the one the log walks (git_log_repo.go). The references are read when the popup -// opens, and again with the log and the nested repositories. +// This file is the references and the colors of the repositories of the project folder (matrix id +// git-multi-repository-references). The Git Log's reference pane lists, below its own sections, a +// group per repository the log does not walk, in Core's order and in each repository's color from +// Core; a click on a group or one of its references makes that repository the one the log walks +// (git_log_repo.go). The references are read with the log and again with the repositories; the +// colors are assigned with the repositories (nested_repos.go) and mark each repository in the branch +// popup, the change list, the Paths filter and the log rows. -// nestedReferences are the references of one nested repository as the panel last read them. +// nestedReferences are the references of one repository as the pane last read them. type nestedReferences struct { refs core.GitReferences err error @@ -34,35 +32,36 @@ type repositoryColorer interface { // repositoryColorPage is the most identities one color request carries, as Core bounds it. const repositoryColorPage = 128 -// loadNestedReferences reads the references of the repository groups the reference pane lists in -// the background, and the color slot of every repository of the workspace with them. The answer of -// a reading that a newer one overtook is dropped. +// repositorySwatchSize is the side of the square that marks a repository in its color. +const repositorySwatchSize = 10 + +// loadNestedReferences reads in the background the references of the repositories the log does not +// walk, the groups of the reference pane. The answer of a reading that a newer one overtook is +// dropped. func (a *App) loadNestedReferences(p *project) { kernel := a.kernel n := &p.nested n.refGen++ gen := n.refGen - // The branch popup lists every nested repository, so all of them are read; the project's own is - // read too while the log walks or the popup lists a nested repository, to list it as a group. - reads := append([]nestedRepo(nil), n.repos...) - if n.logRepo != "" || a.branch.repo != "" { - reads = append([]nestedRepo{{id: commitRepositoryID, root: p.root}}, reads...) + type read struct{ id, root string } + var reads []read + for _, id := range n.others { + if root := p.rootOf(id); root != "" { + reads = append(reads, read{id: id, root: root}) + } } - ids := p.workspaceRepositoryIDs() a.background(p, gitTimeout, func(ctx context.Context) func(*App) { // The references are read again whenever a repository changes, so the console records // these reads only when it shows background branch reads. ctx = core.WithQueryCategory(ctx, core.GitQueryReferences) out := make(map[string]nestedReferences, len(reads)) - for _, repo := range reads { - refs, err := kernel.GitReferences(ctx, repo.root) - out[repo.id] = nestedReferences{refs: refs, err: err} + for _, r := range reads { + refs, err := kernel.GitReferences(ctx, r.root) + out[r.id] = nestedReferences{refs: refs, err: err} } - slots, showColors := assignRepositoryColors(ctx, kernel, ids) return func(a *App) { if p.nested.refGen == gen { p.nested.references = out - p.nested.slots, p.nested.showColors = slots, showColors } } }) @@ -94,16 +93,40 @@ func assignRepositoryColors(ctx context.Context, kernel Kernel, ids []string) (m return slots, showColors } -// repositoryTint is the color a repository's group is drawn in: its Core slot in the palette when -// the view shows colors, the text color otherwise. +// repositoryTint is the color a repository is drawn in: its Core slot in the palette when the view +// shows colors, the text color otherwise. func (a *App) repositoryTint(p *project, id string) gfx.Color { - slot, ok := p.nested.slots[id] - if !ok || !p.nested.showColors { + slot, ok := p.repositorySlot(id) + if !ok { return a.colors.Text } return repositoryColor(slot, a.colors.Dark) } +// repositorySlot is the Core color slot of the repository with ID, "" for the project's own, and +// whether the view shows it in a color. +func (p *project) repositorySlot(id string) (int, bool) { + if !p.nested.showColors { + return 0, false + } + if p.isOwnID(id) { + if own, ok := p.nested.own(); ok { + id = own.ID + } + } + slot, ok := p.nested.slots[id] + return slot, ok +} + +// drawRepositorySwatch declares the square that marks a repository in its color, as IDEA marks the +// roots of a project with several. Nothing is drawn while the view shows no colors. +func (a *App) drawRepositorySwatch(c ui.C, p *project, id string) { + if _, ok := p.repositorySlot(id); !ok { + return + } + ui.Row(c).Size(repositorySwatchSize, repositorySwatchSize).Shrink(0).Radius(2).Background(a.repositoryTint(p, id)) +} + // repositoryPalette is the pair of colors of each slot: the color on a dark surface, then on a // light one. Slots past the palette repeat. var repositoryPalette = [...][2]uint32{ @@ -124,73 +147,14 @@ func repositoryColor(slot int, dark bool) gfx.Color { return pick(dark, pair[0], pair[1]) } -// branchGroups are the repositories the popup lists below the picked one's references: the project's -// own repository when the popup lists a nested one, then every nested repository but the picked one. -func (a *App) branchGroups(p *project) []nestedRepo { - picked := a.branchRoot(p) - var groups []nestedRepo - if picked != p.git.repositoryRoot(p.root) { - groups = append(groups, nestedRepo{id: commitRepositoryID, root: p.root}) - } - for _, repo := range p.nested.repos { - if repo.root != picked { - groups = append(groups, repo) - } - } - return groups -} - -// drawNestedReferences declares the groups of the repositories the branch popup does not list -// itself: one foldable group per repository, with its local branches and its tags. -func (a *App) drawNestedReferences(c ui.C, p *project, t i18n.BranchMessages) { - b := &a.branch - for _, repo := range a.branchGroups(p) { - key := "nested/" + repo.id - refs, loaded := p.nested.references[repo.id] - collapsed := b.collapsed[key] - if a.drawBranchSection(c, key, p.repositoryName(repo.id), collapsed, true) { - c.After(func() { b.collapsed[key] = !b.collapsed[key] }) - } - if collapsed { - continue - } - switch { - case !loaded: - a.drawBranchNote(c, t.Loading) - case refs.err != nil: - a.drawBranchNote(c, t.LoadFailed(refs.err.Error())) - default: - for _, r := range refs.refs.References { - if r.Kind != "local" && r.Kind != "tag" { - continue - } - a.drawNestedReferenceRow(c, r) - } - } - } -} - -// drawNestedReferenceRow declares one reference of a nested repository: its icon in the color of -// its kind and its name. -func (a *App) drawNestedReferenceRow(c ui.C, r core.GitReference) { - icon := icons.GitBranch - if r.Kind == "tag" { - icon = icons.Tag - } - ui.Row(c.Key("nestedref/" + r.FullName)).Height(branchRowHeight).Shrink(0).FillWidth().Items(ui.Center).Gap(chromeMenuGap).PadX(chromeEdge + 12).Children(func() { - ui.Icon(c, icon).Size(chromeIconSize, chromeIconSize).Shrink(0).Color(referenceColor(r.Kind, a.colors.Dark)) - ui.Text(c, r.ShortName).Color(a.colors.Text).LineHeight(chromeLineHeight).Ellipsis().Grow(1) - }) -} - // appendNestedLogRows appends the groups of the other repositories to the reference pane: one row // per repository with local branches or tags, then those references. A click on a group or a // reference makes its repository the one the log walks. While the filter has text only the matching // references show, and every group opens. It returns how many references the groups list. func (a *App) appendNestedLogRows(rows []logRefRow, p *project, query string) ([]logRefRow, int) { shown := 0 - for _, repo := range p.referenceGroups() { - refs, loaded := p.nested.references[repo.id] + for _, id := range p.nested.others { + refs, loaded := p.nested.references[id] if !loaded || refs.err != nil { continue } @@ -208,18 +172,18 @@ func (a *App) appendNestedLogRows(rows []logRefRow, p *project, query string) ([ continue } shown += len(matches) - key := "nested/" + repo.id + key := "nested/" + id open := query != "" || !p.log.collapsed[key] rows = append(rows, logRefRow{ - kind: logRefRepository, label: p.repositoryName(repo.id), short: repo.id, repo: repo.id, key: key, open: open, - tint: a.repositoryTint(p, repo.id), + kind: logRefRepository, label: p.repositoryName(id), short: id, repo: id, key: key, open: open, + tint: a.repositoryTint(p, id), }) if !open { continue } for i := range matches { ref := &matches[i] - rows = append(rows, logRefRow{kind: logRefForeign, depth: 1, label: ref.ShortName, key: ref.FullName, short: ref.ShortName, ref: ref, repo: repo.id}) + rows = append(rows, logRefRow{kind: logRefForeign, depth: 1, label: ref.ShortName, key: ref.FullName, short: ref.ShortName, ref: ref, repo: id}) } } return rows, shown diff --git a/desktop/internal/workbench/nested_repos.go b/desktop/internal/workbench/nested_repos.go index a17b62126b..098b92f81c 100644 --- a/desktop/internal/workbench/nested_repos.go +++ b/desktop/internal/workbench/nested_repos.go @@ -8,27 +8,49 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" ) -// This file keeps the repositories nested in the project folder with their own changes -// (matrix ids git-multi-repository-change-groups, git-workspace-staged-commit). Core discovers -// them; the project reads each one's status in the background after every project status, so the -// Commit tool window can group their changes under the project's and count their staged changes -// toward the commit. The commit itself is planned by commit_nested.go. The window is declared in -// nested_repos_view.go. +// This file keeps the repositories of the project folder (matrix ids +// git-multi-repository-change-groups, git-workspace-staged-commit, git-multi-repository-references). +// Core discovers them, picks the one a view acts on and groups their changes; the project reads the +// status of each nested one in the background after every project status. A folder that is no +// repository itself but holds repositories is a workspace too: its views then act on the nested +// ones. The Commit tool window shows Core's groups (nested_repos_view.go), a commit binds Core's list +// (commit_nested.go), and the Git Log and the branch popup act on the repository Core picks +// (git_log_repo.go). -// nestedRepo is one repository nested in the project folder: its ID as a workspace commit names -// it, where it is on disk, and the changes its status lists. +// repositoryDiscoverer is the part of the kernel the workspace's repositories use. Core's client +// implements it; a kernel that does not lists no nested repositories. +type repositoryDiscoverer interface { + DiscoverWorkspaceRepositories(ctx context.Context, root string) ([]core.WorkspaceRepository, error) + SelectWorkspaceRepository(ctx context.Context, repositories []core.WorkspaceRepository, selected string) (core.WorkspaceRepositorySelection, error) + GroupWorkspaceChanges(ctx context.Context, repositories []core.WorkspaceRepositoryChanges) (core.WorkspaceChangeGroups, error) +} + +// nestedRepo is one repository nested in the project folder: its ID and name as Core lists them, +// where it is on disk, and the branch and changes its status reads. type nestedRepo struct { - id string - root string - changes []core.GitChange - err error + id, name string + root string + branch string + changes []core.GitChange + err error } -// nestedState is what a project keeps of its nested repositories. +// nestedState is what a project keeps of the repositories of its folder. type nestedState struct { // gen counts the readings started; an answer of an older reading is dropped. - gen int - repos []nestedRepo + gen int + // discovered is Core's list as it answered, the repository that contains the folder first; + // requests hand it back to Core unchanged. repos are its nested entries with their status. + discovered []core.WorkspaceRepository + repos []nestedRepo + // others are the IDs of the repositories the Git Log does not walk, in Core's order: the + // groups its reference pane lists (nested_refs.go). + others []string + // groupGen counts the groupings asked for; groups is Core's last answer, and grouped says + // one arrived for the repositories listed. + groupGen int + grouped bool + groups core.WorkspaceChangeGroups // focus is the ID of the nested repository a folder of the project tree asked for; empty // when the project's own repository is meant. focus string @@ -48,62 +70,51 @@ type nestedState struct { folded map[string]bool } -// nestedRepositoryID is the ID of the repository at path in a workspace commit of projectRoot: its -// path relative to the project folder with "/" separators. It reports false for a repository -// outside the project folder or the project folder itself. -func nestedRepositoryID(projectRoot, path string) (string, bool) { - rel, err := filepath.Rel(projectRoot, path) - if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { - return "", false - } - return filepath.ToSlash(rel), true -} - -// loadNestedRepos reads the nested repositories of the project and the status of each in the -// background. It does nothing outside a repository or without a kernel that discovers them. +// loadNestedRepos reads the repositories of the project folder, the status of each nested one and +// their colors in the background. It does nothing with a kernel that does not discover them. func (a *App) loadNestedRepos(p *project) { discoverer, ok := a.kernel.(repositoryDiscoverer) - if !ok || !p.git.isRepository() { + if !ok { return } n := &p.nested n.gen++ gen := n.gen kernel, root := a.kernel, p.root - own := filepath.Clean(p.git.repositoryRoot(p.root)) a.background(p, gitTimeout, func(ctx context.Context) func(*App) { found, err := discoverer.DiscoverWorkspaceRepositories(ctx, root) var repos []nestedRepo + var slots map[string]int + showColors := false if err == nil { + ids := make([]string, 0, len(found)) for _, repo := range found { - path := filepath.Clean(filepath.FromSlash(repo.Path)) - id, inside := nestedRepositoryID(root, path) - if !inside || path == own { + ids = append(ids, repo.ID) + if repo.Role != core.RepositoryNested { continue } + path := filepath.FromSlash(repo.Path) status, serr := kernel.GitStatus(core.AutomaticRefresh(ctx), path) - repos = append(repos, nestedRepo{id: id, root: path, changes: status.Changes, err: serr}) + repos = append(repos, nestedRepo{id: repo.ID, name: repo.Name, root: path, branch: status.Branch, changes: status.Changes, err: serr}) } + slots, showColors = assignRepositoryColors(ctx, kernel, ids) } return func(a *App) { - if p.nested.gen != gen || err != nil { + if p.nested.gen != gen { return } - p.nested.repos = repos - if _, ok := p.nested.repo(p.nested.focus); !ok { - p.nested.focus = "" - } - // A repository the log walks that left the workspace hands the log back to the project's own, - // which loads the references too. - if a.logFallsBack(p) { - a.loadLog(p) + if err != nil { + a.backgroundFailed("workspace_repositories", err) return } - // The Git Log's reference pane lists the nested repositories' references too, so they - // are read again once the repositories are. - if p.log.started { - a.loadNestedReferences(p) + n := &p.nested + n.discovered, n.repos = found, repos + n.slots, n.showColors = slots, showColors + if _, ok := n.repo(n.focus); !ok { + n.focus = "" } + a.selectLogRepo(p) + a.groupChanges(p) } }) } @@ -118,6 +129,157 @@ func (n *nestedState) repo(id string) (*nestedRepo, bool) { return nil, false } +// own is Core's entry of the repository that contains the project folder, which it lists first. +func (n *nestedState) own() (core.WorkspaceRepository, bool) { + if len(n.discovered) > 0 && n.discovered[0].Role == core.RepositoryWorkspace { + return n.discovered[0], true + } + return core.WorkspaceRepository{}, false +} + +// ownID is the ID Core gives the project's own repository: "." for the project folder, ".." +// segments for a repository that contains it. It is commitRepositoryID before Core listed it. +func (p *project) ownID() string { + if own, ok := p.nested.own(); ok { + return own.ID + } + return commitRepositoryID +} + +// isOwnID reports that id names the project's own repository: empty, commitRepositoryID or Core's ID. +func (p *project) isOwnID(id string) bool { + return id == "" || id == commitRepositoryID || id == p.ownID() +} + +// rootOf is where the repository with Core's ID id is on disk. +func (p *project) rootOf(id string) string { + if p.isOwnID(id) { + if !p.git.isRepository() { + return "" + } + return p.git.repositoryRoot(p.root) + } + if repo, ok := p.nested.repo(id); ok { + return repo.root + } + return "" +} + +// hasRepository reports that the project has a repository to act on: its own, or one nested in +// its folder. +func (p *project) hasRepository() bool { + return p.git.isRepository() || len(p.nested.repos) > 0 +} + +// workspaceMode reports that the views list the repositories of the folder one by one: the folder +// holds nested repositories. +func (p *project) workspaceMode() bool { return len(p.nested.repos) > 0 } + +// workspaceRepository is one repository of the project folder as the branch popup, the Pull dialog +// and the Git Log's Paths filter list it. +type workspaceRepository struct { + id, name, root string + own bool +} + +// workspaceRepositories are the repositories of the project folder in Core's order: the project's +// own while the folder is in one, then each nested one. +func (p *project) workspaceRepositories() []workspaceRepository { + var out []workspaceRepository + if p.git.isRepository() { + out = append(out, workspaceRepository{id: p.ownID(), name: p.repositoryName(""), root: p.git.repositoryRoot(p.root), own: true}) + } + for _, repo := range p.nested.repos { + out = append(out, workspaceRepository{id: repo.id, name: p.repositoryName(repo.id), root: repo.root}) + } + return out +} + +// branchOf is the branch the repository with ID id is on, empty before its status arrived. +func (p *project) branchOf(id string) string { + if p.isOwnID(id) { + return p.git.branch() + } + if repo, ok := p.nested.repo(id); ok && repo.err == nil { + return repo.branch + } + return "" +} + +// titleBranch is the branch the title bar shows: the project's own, or the one of the nested +// repository the log walks when the folder is no repository itself. +func (p *project) titleBranch() string { + if branch := p.git.branch(); branch != "" { + return branch + } + if repo := p.logRepo(); repo != nil && repo.err == nil { + return repo.branch + } + return "" +} + +// groupChanges asks Core in the background to group the changes of every repository of the folder +// and to plan what each checkbox writes. The answer of a grouping a newer one overtook is dropped. +func (a *App) groupChanges(p *project) { + n := &p.nested + discoverer, ok := a.kernel.(repositoryDiscoverer) + if !ok || !p.workspaceMode() { + n.grouped, n.groups = false, core.WorkspaceChangeGroups{} + return + } + n.groupGen++ + gen := n.groupGen + input := make([]core.WorkspaceRepositoryChanges, 0, len(n.discovered)) + for _, entry := range n.discovered { + var changes []core.GitChange + if entry.Role == core.RepositoryWorkspace { + if !p.git.isRepository() { + continue + } + changes = p.git.status.Changes + } else if repo, ok := n.repo(entry.ID); ok { + changes = repo.changes + } + input = append(input, core.WorkspaceRepositoryChanges{WorkspaceRepository: entry, Changes: changes}) + } + a.background(p, kernelCallTimeout, func(ctx context.Context) func(*App) { + groups, err := discoverer.GroupWorkspaceChanges(ctx, input) + return func(a *App) { + if p.nested.groupGen != gen { + return + } + if err != nil { + a.backgroundFailed("workspace_change_groups", err) + return + } + p.nested.groups, p.nested.grouped = groups, true + } + }) +} + +// changedFiles is the number of changed files the status bar counts: Core's count over every +// repository of the folder, the one the Commit window's list shows, while the folder holds nested +// ones, and the project's own status otherwise. +func (p *project) changedFiles() int { + if p.workspaceMode() && p.nested.grouped { + return p.nested.groups.FileCount + } + count, _ := p.git.changeCount() + return count +} + +// changesOf is the changes the group with Core's ID id lists: the project's status for its own +// repository, the nested repository's status otherwise. +func (p *project) changesOf(id string) []core.GitChange { + if p.isOwnID(id) { + return p.git.status.Changes + } + if repo, ok := p.nested.repo(id); ok { + return repo.changes + } + return nil +} + // nestedStagedCount is the number of changes staged in the nested repositories. func (p *project) nestedStagedCount() int { if p.lists.inUse() { @@ -150,30 +312,14 @@ func (a *App) showRepositoryChangesOf(p *project, full string) { a.showChanges() } -// stageNestedChanges stages or unstages changes of the nested repository repo, as a click on -// their checkboxes asks: a click on the repository's checkbox stages everything it can, or -// unstages everything when it is all staged. Then the nested repositories are read again. -func (a *App) stageNestedChanges(p *project, repo nestedRepo, changes []core.GitChange, all bool) { - if p.commit.busy { +// applyStaging writes Core's staging plan of the repository with ID id, as a click on the +// checkbox of its group asks. +func (a *App) applyStaging(p *project, id string, plan core.StagingPlan) { + root := p.rootOf(id) + if p.commit.busy || root == "" || len(plan.Paths) == 0 { return } - var paths []string - stage := !all - for _, change := range changes { - if !change.CanToggleStaging { - continue - } - if all && change.Staged { - paths = append(paths, change.StagingPaths()...) - } - if !all && stagesChange(change) { - paths = append(paths, change.StagingPaths()...) - } - } - if len(paths) == 0 { - return - } - a.writeNestedStaging(p, repo.root, stage, paths) + a.writeNestedStaging(p, root, plan.Operation == core.StageChanges, plan.Paths) } // stageNestedChange stages or unstages one change of the nested repository repo, as the @@ -185,7 +331,7 @@ func (a *App) stageNestedChange(p *project, repo nestedRepo, change core.GitChan a.writeNestedStaging(p, repo.root, stagesChange(change), change.StagingPaths()) } -// writeNestedStaging stages or unstages paths of the repository at root, then reads the nested +// writeNestedStaging stages or unstages paths of the repository at root, then reads the // repositories again. func (a *App) writeNestedStaging(p *project, root string, stage bool, paths []string) { if stage { @@ -214,6 +360,46 @@ func (a *App) writeNestedStaging(p *project, root string, stage bool, paths []st }) } +// stageWorkspace writes Core's plan of the change list's checkbox: it stages, or unstages, the +// paths of every repository it names, one repository after another, then reads them again. +func (a *App) stageWorkspace(p *project, plan core.WorkspaceStageAll) { + if p.commit.busy || len(plan.Repositories) == 0 { + return + } + stage := plan.Operation == core.StageChanges + type write struct { + root string + paths []string + } + var writes []write + for _, repo := range plan.Repositories { + if root := p.rootOf(repo.ID); root != "" && len(repo.Paths) > 0 { + writes = append(writes, write{root: root, paths: repo.Paths}) + } + } + if stage { + a.performed("git.stageAll", surfaceButton) + } else { + a.performed("git.unstageAll", surfaceButton) + } + p.commit.busy = true + kernel := a.kernel + a.background(p, gitTimeout, func(ctx context.Context) func(*App) { + var err error + for _, w := range writes { + if stage { + err = kernel.GitStage(ctx, w.root, w.paths) + } else { + err = kernel.GitUnstage(ctx, w.root, w.paths) + } + if err != nil { + break + } + } + return func(a *App) { a.stagingDone(p, stage, err) } + }) +} + // nestedCommitTarget is the commit of one nested repository: it commits the staged changes of // that repository alone, with the message the Commit tool window holds. func (a *App) nestedCommitTarget(p *project, repo nestedRepo) commitTarget { @@ -232,68 +418,3 @@ func (p *project) canCommitNested(repo nestedRepo) bool { return !p.lists.inUse() && p.listsReady() && p.commit.idle() && !p.commit.busy && countStaged(repo.changes) > 0 && p.commit.message() != "" } - -// stageAllRepositories stages every change of the project and of its nested repositories, or -// unstages every staged one when stage is false: the checkbox of the project's change list acts -// on all repositories it lists. The repositories are written one after another, then read again. -func (a *App) stageAllRepositories(p *project, stage bool) { - if p.commit.busy { - return - } - a.performed("git.stageAll", surfaceButton) - p.commit.busy = true - kernel, root := a.kernel, p.git.repositoryRoot(p.root) - projectChanges := p.git.status.Changes - repos := append([]nestedRepo(nil), p.nested.repos...) - a.background(p, gitTimeout, func(ctx context.Context) func(*App) { - var err error - if stage { - err = kernel.GitStageAll(ctx, root) - } else if paths := stagedPaths(projectChanges); len(paths) > 0 { - err = kernel.GitUnstage(ctx, root, paths) - } - for _, repo := range repos { - if err != nil { - break - } - var paths []string - for _, change := range repo.changes { - if !change.CanToggleStaging { - continue - } - if stage && stagesChange(change) || !stage && change.Staged { - paths = append(paths, change.StagingPaths()...) - } - } - if len(paths) == 0 { - continue - } - if stage { - err = kernel.GitStage(ctx, repo.root, paths) - } else { - err = kernel.GitUnstage(ctx, repo.root, paths) - } - } - return func(a *App) { - p.commit.busy = false - a.reloadGit(p) - a.loadNestedRepos(p) - if err != nil { - a.stagingFailed(stage, err) - } - } - }) -} - -// submoduleReferenceChanged reports that the project's own status lists the nested repository with -// the given ID as changed: the reference the parent records for it has moved. A nested repository -// that has changes of its own but no moved reference shows the hint that the parent does not -// record them yet. -func (p *project) submoduleReferenceChanged(id string) bool { - for _, change := range p.git.status.Changes { - if strings.TrimSuffix(change.Path, "/") == id { - return true - } - } - return false -} diff --git a/desktop/internal/workbench/nested_repos_view.go b/desktop/internal/workbench/nested_repos_view.go index 09024b45c9..5f3ec981d2 100644 --- a/desktop/internal/workbench/nested_repos_view.go +++ b/desktop/internal/workbench/nested_repos_view.go @@ -8,15 +8,24 @@ import ( "github.com/vivaui/viva/ui" ) -// drawRepositoryChanges declares the change list of a workspace with nested repositories: one line -// for all the changes, then a foldable group per repository with changes, the project's own first. -// A group is named after its repository, so a workspace where only one repository has changes still -// shows its name. State and staging are in nested_repos.go. +// repositoryGroupGap is the space between the parts of a repository group's line; the rows of the +// group's changes are indented after it (repositoryChangeIndent). +const repositoryGroupGap = 6 + +// drawRepositoryChanges declares the change list of a workspace with nested repositories as Core +// groups it: one line for all the changes, then a foldable group per repository with changes, in +// Core's order. A group is named after its repository, so a workspace where only one repository has +// changes still shows its name. What each checkbox writes is Core's plan; state and staging are in +// nested_repos.go. func (a *App) drawRepositoryChanges(c ui.C, p *project) { t := a.text.Commit - changes := p.git.status.Changes - all := append(append([]core.GitChange(nil), changes...), nestedChanges(p)...) - if len(all) == 0 { + n := &p.nested + if !n.grouped { + a.gitEmpty(c, a.text.Git.Loading) + return + } + g := n.groups + if len(g.Groups) == 0 { ui.Column(c).Fill().Center().Gap(8).Children(func() { ui.Icon(c, icons.Check).Size(20, 20).Color(a.colors.Success) ui.Text(c, t.Clean).Color(a.colors.Subtle) @@ -24,41 +33,36 @@ func (a *App) drawRepositoryChanges(c ui.C, p *project) { return } ui.Scroll(c).Scrollbars().Grow(1).FillWidth().PadY(4).Children(func() { - a.drawChangeListHeader(c, t.ChangeList, t.Files(fileCount(all)), all, p.commit.busy, func() { a.stageAllAcrossRepositories(p) }) - if len(changes) > 0 { - a.drawRepositoryGroup(c, p, ownRepositoryGroup(p), true) - } - for _, repo := range p.nested.repos { - if len(repo.changes) > 0 { - a.drawRepositoryGroup(c, p, repo, false) + a.drawChangeListHeader(c, t.ChangeList, t.Files(g.FileCount), g.AllStaged, g.StageAll != nil, p.commit.busy, func() { + if g.StageAll != nil { + a.stageWorkspace(p, *g.StageAll) } + }) + for _, group := range g.Groups { + a.drawRepositoryGroup(c, p, group) } }) } -// ownRepositoryGroup is the project's own repository as a group of the change list: the ID the -// group keys and the repository commit use, and the project's status changes. -func ownRepositoryGroup(p *project) nestedRepo { - return nestedRepo{id: commitRepositoryID, root: p.git.repositoryRoot(p.root), changes: p.git.status.Changes} -} - // drawRepositoryGroup declares the group of one repository of the change list: its fold, its -// checkbox, its name and count, its commit button, and then its changes unless it is folded. A -// nested repository's changes are read-only apart from staging; the project's own are the ones the +// checkbox, its color, name and count, its commit button, and then its changes unless it is folded. +// A nested repository's changes are read-only apart from staging; the project's own are the ones the // Commit tool window's rows act on. -func (a *App) drawRepositoryGroup(c ui.C, p *project, repo nestedRepo, own bool) { +func (a *App) drawRepositoryGroup(c ui.C, p *project, group core.WorkspaceChangeGroup) { t := a.text.Commit lang := a.language() busy := p.commit.busy - rc := c.Key("nested/" + repo.id) - all := allStaged(repo.changes) - name := p.repositoryName(repo.id) + own := group.Role == core.RepositoryWorkspace + id := group.ID + changes := p.changesOf(id) + rc := c.Key("nested/" + id) + all := group.AllStaged color := a.colors.Text - if !own && p.nested.focus == repo.id { + if !own && p.nested.focus == id { color = a.colors.Accent } - folded := p.nested.folded[repo.id] - ui.Row(rc).Height(logItemHeight).FillWidth().Shrink(0).Items(ui.Center).Gap(6).PadX(8).Children(func() { + folded := p.nested.folded[id] + ui.Row(rc).Height(logItemHeight).FillWidth().Shrink(0).Items(ui.Center).Gap(repositoryGroupGap).PadX(8).Children(func() { chevron, foldLabel := icons.ChevronDown, i18n.Shared(lang, "desktop.nested.collapse") if folded { chevron, foldLabel = icons.ChevronRight, i18n.Shared(lang, "desktop.nested.expand") @@ -68,56 +72,47 @@ func (a *App) drawRepositoryGroup(c ui.C, p *project, repo nestedRepo, own bool) if p.nested.folded == nil { p.nested.folded = map[string]bool{} } - p.nested.folded[repo.id] = !folded + p.nested.folded[id] = !folded }) } - if ui.Checkbox(rc, &all, "").Label(name).Disabled(busy || !hasToggleable(repo.changes)).Clicked() { - rc.After(func() { a.stageNestedChanges(p, repo, repo.changes, allStaged(repo.changes)) }) + if ui.Checkbox(rc, &all, "").Label(group.Name).Disabled(busy || group.Staging == nil).Clicked() && group.Staging != nil { + plan := *group.Staging + rc.After(func() { a.applyStaging(p, id, plan) }) } - ui.Text(rc, name).Color(color).Weight(gfx.WeightMedium).Ellipsis().Shrink(1) - ui.Text(rc, t.Files(fileCount(repo.changes))).Muted().Shrink(0) + a.drawRepositorySwatch(rc, p, id) + ui.Text(rc, group.Name).Color(color).Weight(gfx.WeightMedium).Ellipsis().Shrink(1) + ui.Text(rc, t.Files(group.FileCount)).Muted().Shrink(0) if own { if ui.Button(rc, i18n.Shared(lang, "desktop.nested.commit")).Outline().Disabled(!p.canCommit()).Clicked() { rc.After(func() { a.startCommitIn(p, p.projectCommit(), false, surfaceButton) }) } return } - if ui.Button(rc, i18n.Shared(lang, "desktop.nested.commit")).Outline().Disabled(!p.canCommitNested(repo)).Clicked() { - rc.After(func() { a.startCommitIn(p, a.nestedCommitTarget(p, repo), false, surfaceButton) }) + repo, ok := p.nested.repo(id) + if ui.Button(rc, i18n.Shared(lang, "desktop.nested.commit")).Outline().Disabled(!ok || !p.canCommitNested(*repo)).Clicked() && ok { + target := a.nestedCommitTarget(p, *repo) + rc.After(func() { a.startCommitIn(p, target, false, surfaceButton) }) } }) if folded { return } - if !own && !p.submoduleReferenceChanged(repo.id) { - ui.Paragraph(rc, i18n.Shared(lang, "desktop.nested.refUnchanged"), 2).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).PadX(8) + if group.ParentReference == core.ParentReferenceUnchanged { + ui.Paragraph(rc, i18n.Shared(lang, "desktop.nested.refUnchanged"), 2).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle). + PadSides(0, 8, 0, repositoryChangeIndent) } - for _, change := range repo.changes { + repo, _ := p.nested.repo(id) + for _, change := range changes { if own { - a.drawCommitChange(rc, p, change) + a.drawCommitChange(rc, p, change, repositoryChangeIndent) continue } - toggled, _, _, _ := a.drawChangeRow(rc, change, busy, false, func(ui.C) func(*ui.MenuItems) { + toggled, _, _, _ := a.drawChangeRow(rc, change, busy, false, repositoryChangeIndent, func(ui.C) func(*ui.MenuItems) { return func(*ui.MenuItems) {} }) - if toggled { - rc.After(func() { a.stageNestedChange(p, repo, change) }) + if toggled && repo != nil { + r := *repo + rc.After(func() { a.stageNestedChange(p, r, change) }) } } } - -// nestedChanges are the changes of every nested repository, in the order the repositories list. -func nestedChanges(p *project) []core.GitChange { - var out []core.GitChange - for _, repo := range p.nested.repos { - out = append(out, repo.changes...) - } - return out -} - -// stageAllAcrossRepositories is the project's stage-all checkbox: when every change of every -// repository is staged it unstages them all, otherwise it stages them all. -func (a *App) stageAllAcrossRepositories(p *project) { - all := allStaged(append(append([]core.GitChange(nil), p.git.status.Changes...), nestedChanges(p)...)) - a.stageAllRepositories(p, !all) -} diff --git a/desktop/internal/workbench/workspace_repositories_test.go b/desktop/internal/workbench/workspace_repositories_test.go new file mode 100644 index 0000000000..e12e2cc468 --- /dev/null +++ b/desktop/internal/workbench/workspace_repositories_test.go @@ -0,0 +1,206 @@ +package workbench + +import ( + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +// newWorkspaceFolder is a folder that is no repository itself holding one repository per name, +// each on main with the commit "initial " and the modified file .txt, not staged. +func newWorkspaceFolder(t *testing.T, names ...string) string { + t.Helper() + requireTestGit(t) + parent := t.TempDir() + for _, name := range names { + dir := filepath.Join(parent, name) + if err := os.Mkdir(dir, 0o755); err != nil { + t.Fatal(err) + } + gitRun(t, dir, "init") + gitRun(t, dir, "symbolic-ref", "HEAD", "refs/heads/main") + file := filepath.Join(dir, name+".txt") + if err := os.WriteFile(file, []byte("first\n"), 0o600); err != nil { + t.Fatal(err) + } + gitRun(t, dir, "add", name+".txt") + gitRun(t, dir, "commit", "-m", "initial "+name) + if err := os.WriteFile(file, []byte("second\n"), 0o600); err != nil { + t.Fatal(err) + } + } + return parent +} + +// openWorkspaceFolder opens dir, a folder holding repositories, and waits until its repositories +// and their changes were read. +func (h *harness) openWorkspaceFolder(dir string) *project { + h.t.Helper() + h.app.delays = logDelays{} + h.open(dir) + h.settleUntil("reading the nested repositories", func() bool { + p := h.app.project + return p != nil && p.workspaceMode() && p.nested.grouped + }) + p := h.app.project + if p.git.isRepository() { + h.t.Fatalf("the project folder is a repository itself: %+v", p.git.status) + } + return p +} + +// repositoryID is Core's ID of the nested repository named name. +func repositoryID(t *testing.T, p *project, name string) string { + t.Helper() + for _, repo := range p.nested.repos { + if repo.name == name { + return repo.id + } + } + t.Fatalf("no nested repository named %q in %+v", name, p.nested.repos) + return "" +} + +// The branch popup of a folder holding repositories lists them as IDEA does, each with its branch; +// the panel a row opens beside it lists that repository's branches, and a checkout there switches +// that repository alone. +func TestWorkspaceBranchPopupChecksOutInTheRepositoryOfItsPanel(t *testing.T) { + parent := newWorkspaceFolder(t, "alpha", "beta") + alpha, beta := filepath.Join(parent, "alpha"), filepath.Join(parent, "beta") + gitRun(t, beta, "branch", "other") + h := newHarness(t, &gitKernel{Client: core.NewClient()}) + p := h.openWorkspaceFolder(parent) + if got := p.titleBranch(); got != "main" { + t.Fatalf("title bar branch = %q, want the first repository's main", got) + } + + h.click(center(h.hitLabeled(h.app.text.Title.BranchMenu))) + b := &h.app.branch + if !b.open { + t.Fatal("the branch popup did not open for a folder holding repositories") + } + lang := h.app.language() + repoRow := func(name, branch string) string { + return i18n.SharedFormat(lang, "desktop.branch.repositoryPanel", map[string]string{"repository": name, "branch": branch}) + } + for _, name := range []string{"alpha", "beta"} { + if _, ok := h.findPageHit(repoRow(name, "main")); !ok { + t.Fatalf("the popup has no row %q", repoRow(name, "main")) + } + } + if b.repoOpen { + t.Fatal("a repository panel is open before a row was clicked") + } + + row := h.popupHit(repoRow("beta", "main")) + h.click(center(row)) + if !b.repoOpen || filepath.Base(b.repo) != "beta" || !b.loaded || b.err != nil { + t.Fatalf("after clicking beta: panel open %v on %q, loaded %v, err %v", b.repoOpen, b.repo, b.loaded, b.err) + } + if want := i18n.SharedFormat(lang, "desktop.branch.localIn", map[string]string{"repository": "beta"}); !h.shows(want) { + t.Fatalf("the panel does not show %q", want) + } + other := h.branchRow("other") + if other.X < row.X+row.Width { + t.Fatalf("branch row at x %v, repository row ends at %v; want the panel beside the row", other.X, row.X+row.Width) + } + + h.click(center(other)) + if b.menu == "" { + t.Fatal("clicking the branch row did not open its menu") + } + h.clickNamed(h.app.text.Branch.Checkout) + if got := currentBranch(t, beta); got != "other" { + t.Fatalf("beta is on %q, want other", got) + } + if got := currentBranch(t, alpha); got != "main" { + t.Fatalf("alpha is on %q, want it left on main", got) + } + betaID := repositoryID(t, p, "beta") + h.settleUntil("reading beta's new branch", func() bool { return p.branchOf(betaID) == "other" }) +} + +// The Paths filter of a folder holding repositories lists them under Roots; a click walks that +// repository's history, and the writes of the log act on it. +func TestWorkspaceLogRootsWalkTheChosenRepository(t *testing.T) { + parent := newWorkspaceFolder(t, "alpha", "beta") + h := newHarness(t, &gitKernel{Client: core.NewClient()}) + p := h.openWorkspaceFolder(parent) + alphaID, betaID := repositoryID(t, p, "alpha"), repositoryID(t, p, "beta") + h.app.layout.gitTab = gitTabLog + if !h.app.chrome.isOpen(catalogIndex[itemGit]) { + h.click(center(h.button(itemGit))) + } + h.settleUntil("alpha's history", func() bool { return p.logRepoID() == alphaID && !p.log.loading && len(p.log.graph.Rows) == 1 }) + if !h.shows("initial alpha") { + t.Fatal("the log does not show alpha's commit") + } + for _, id := range []string{alphaID, betaID} { + if _, ok := p.repositorySlot(id); !ok { + t.Fatalf("repository %q has no color slot for the log's strip", id) + } + } + + g := h.app.text.Git + // The chip is the first control of that name; the window's path bar below shares it. + h.click(center(h.hitLabeled(g.FilterPaths))) + if p.log.popover != logPopoverPath { + t.Fatalf("popover %v after clicking the Paths chip, want the Paths filter", p.log.popover) + } + if roots := i18n.Shared(h.app.language(), "desktop.nested.roots"); !h.shows(roots) { + t.Fatalf("the Paths filter has no %q section", roots) + } + h.clickNamed("beta") + h.settleUntil("beta's history", func() bool { return p.logRepoID() == betaID && !p.log.loading && len(p.log.graph.Rows) == 1 }) + if p.log.popover != logPopoverNone { + t.Fatalf("popover %v after choosing a root, want it closed", p.log.popover) + } + if !h.shows("initial beta") { + t.Fatal("the log does not show beta's commit") + } + if got := filepath.Base(p.logRepositoryRoot()); got != "beta" { + t.Fatalf("the log's writes act on %q, want beta", got) + } + if got := p.titleBranch(); got != "main" { + t.Fatalf("title bar branch = %q, want beta's main", got) + } +} + +// The Commit tool window of a folder holding repositories groups the changes by repository, and +// its Commit button commits the staged changes of each. +func TestWorkspaceCommitCommitsEveryNestedRepository(t *testing.T) { + parent := newWorkspaceFolder(t, "alpha", "beta") + h := newHarness(t, &gitKernel{Client: core.NewClient()}) + p := h.openWorkspaceFolder(parent) + h.click(center(h.button(itemCommit))) + for _, name := range []string{"alpha", "beta", "alpha.txt", "beta.txt"} { + if !h.shows(name) { + t.Fatalf("the Commit window does not show %q", name) + } + } + if want := h.app.text.Status.Changes(2); !h.shows(want) { + t.Fatalf("the status bar does not count the nested repositories' changes as %q", want) + } + + h.clickNamed(h.app.text.Commit.ChangeList) + h.settleUntil("staging both repositories", func() bool { return p.nestedStagedCount() == 2 }) + h.clickNamed(h.app.text.Commit.MessageLabel) + if err := h.driver.Type("Change both"); err != nil { + t.Fatal(err) + } + h.settle() + if !p.canCommit() { + t.Fatalf("the commit button is disabled with %d staged changes and message %q", p.nestedStagedCount(), p.commit.message()) + } + h.clickNamed(h.app.text.Commit.Commit) + h.settle() + for _, name := range []string{"alpha", "beta"} { + if got := gitRun(t, filepath.Join(parent, name), "log", "-1", "--format=%s"); got != "Change both" { + t.Fatalf("last commit of %s = %q, want the typed message", name, got) + } + } + h.settleUntil("reading the committed repositories", func() bool { return p.nestedStagedCount() == 0 }) +} diff --git a/desktop/internal/workbench/workspace_repositories_visual_test.go b/desktop/internal/workbench/workspace_repositories_visual_test.go new file mode 100644 index 0000000000..efac507c9c --- /dev/null +++ b/desktop/internal/workbench/workspace_repositories_visual_test.go @@ -0,0 +1,85 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +// TestVisualWorkspaceRepositories captures the views of a folder that is no repository itself and +// holds three: the branch popup listing them with one's panel open beside its row, the Git log +// with the color strip of the repository it walks, the Paths filter's Roots, and the Commit +// window's groups. +func TestVisualWorkspaceRepositories(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, look := range []struct{ theme, language string }{{"dark", "zh-Hans"}, {"light", "en"}} { + for _, scene := range []string{"branch-popup", "git-log", "log-roots", "log-more", "commit-groups"} { + t.Run(scene+"-"+look.theme, func(t *testing.T) { + parent := newWorkspaceFolder(t, "backend", "frontend", "shared") + frontend, backend := filepath.Join(parent, "frontend"), filepath.Join(parent, "backend") + for _, message := range []string{"Add the sign-in form", "Validate the email field", "Show the session banner"} { + gitRun(t, backend, "commit", "--allow-empty", "-m", message) + } + gitRun(t, backend, "branch", "feature/login") + gitRun(t, backend, "branch", "release/1.0") + gitRun(t, frontend, "branch", "feature/theme") + gitRun(t, frontend, "switch", "-c", "develop") + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(look.theme), Language: look.language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: gitKernel{core.NewClient()}, Store: prefs, Languages: []string{look.language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1200, 760 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + p := h.openWorkspaceFolder(parent) + switch scene { + case "branch-popup": + h.click(center(h.hitLabeled(h.app.text.Title.BranchMenu))) + label := i18n.SharedFormat(h.app.language(), "desktop.branch.repositoryPanel", map[string]string{"repository": "frontend", "branch": "develop"}) + h.click(center(h.popupHit(label))) + case "git-log", "log-roots", "log-more": + h.app.layout.gitTab = gitTabLog + if !h.app.chrome.isOpen(catalogIndex[itemGit]) { + h.click(center(h.button(itemGit))) + } + backendID := repositoryID(t, p, "backend") + h.settleUntil("backend's history", func() bool { return p.logRepoID() == backendID && !p.log.loading && len(p.log.graph.Rows) == 4 }) + h.relayLogBar() + switch scene { + case "log-roots": + h.click(center(h.hitLabeled(h.app.text.Git.FilterPaths))) + case "log-more": + h.click(center(h.hitLabeled(i18n.Shared(h.app.language(), "git.log.toolbar.moreActions")))) + } + case "commit-groups": + h.click(center(h.button(itemCommit))) + } + h.settleChain() + if err := session.Screenshot(filepath.Join(out, "workspace-"+scene+"-"+look.theme+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/docs/assets/workspace-repositories/README.md b/docs/assets/workspace-repositories/README.md new file mode 100644 index 0000000000..52790519a9 --- /dev/null +++ b/docs/assets/workspace-repositories/README.md @@ -0,0 +1,17 @@ +# 多仓库项目文件夹测试截图 + +来自生产 Viva Page 的无头渲染。项目文件夹本身不是 Git 仓库,里面有三个独立仓库 backend、frontend、shared, +由测试在临时目录中创建;颜色由 Core 按仓库分配。深色使用中文、浅色使用英文。截图不代表 macOS/Windows +原生窗口验收。 + +| 场景 | 深色中文 | 浅色英文 | +| --- | --- | --- | +| 标题栏分支入口:先列出“提交…”,再按 IDEA 的样式逐行列出仓库,每行有颜色方块、仓库名、右侧的当前分支和 ›;点击 frontend 后,面板在这一行旁边展开,列出该仓库的分支操作和“frontend 中的最近分支 / 本地分支 / 远程分支 / 标签”,在面板里新建、检出等操作只作用于 frontend | [截图](workspace-branch-popup-dark.png) | [截图](workspace-branch-popup-light.png) | +| Git 日志:文件夹本身不是仓库,Core 选第一个嵌套仓库 backend;提交行最左侧是 backend 的颜色条,筛选栏在“路径”之后用仓库颜色写明正在查看的仓库,左侧引用面板里其他仓库按各自颜色分组 | [截图](workspace-git-log-dark.png) | [截图](workspace-git-log-light.png) | +| 路径筛选器下方的“仓库根目录”:按颜色列出三个仓库并勾选正在查看的一个,点击即切换日志查看的仓库 | [截图](workspace-log-roots-dark.png) | [截图](workspace-log-roots-light.png) | +| Git 日志筛选栏放不下全部视图按钮时:筛选项和仓库名完整保留,放不下的按钮收进末尾的“更多操作”(…)菜单,每项带图标,“显示提交详情”等开关项开启时打勾;全部收进菜单后文本筛选框再缩窄,最后才裁掉筛选项 | [截图](workspace-log-more-dark.png) | [截图](workspace-log-more-light.png) | +| 提交窗口:按仓库分组,每组有暂存复选框、颜色、文件数和“提交此仓库”;顶部复选框按 Core 的计划暂存全部仓库;状态栏统计所有仓库的更改数 | [截图](workspace-commit-groups-dark.png) | [截图](workspace-commit-groups-light.png) | + +复验:设置 `LITHE_VISUAL_OUTPUT_DIR`,通过 `scripts/desktop/desktop-go.sh test +-tags vivahead,lithevisual ./internal/workbench -run '^TestVisualWorkspaceRepositories$' +-count=1 -timeout 300s` 生成。 diff --git a/docs/assets/workspace-repositories/workspace-branch-popup-dark.png b/docs/assets/workspace-repositories/workspace-branch-popup-dark.png new file mode 100644 index 0000000000..95fc71a469 Binary files /dev/null and b/docs/assets/workspace-repositories/workspace-branch-popup-dark.png differ diff --git a/docs/assets/workspace-repositories/workspace-branch-popup-light.png b/docs/assets/workspace-repositories/workspace-branch-popup-light.png new file mode 100644 index 0000000000..a2e5e74f30 Binary files /dev/null and b/docs/assets/workspace-repositories/workspace-branch-popup-light.png differ diff --git a/docs/assets/workspace-repositories/workspace-commit-groups-dark.png b/docs/assets/workspace-repositories/workspace-commit-groups-dark.png new file mode 100644 index 0000000000..e8aa1bbec3 Binary files /dev/null and b/docs/assets/workspace-repositories/workspace-commit-groups-dark.png differ diff --git a/docs/assets/workspace-repositories/workspace-commit-groups-light.png b/docs/assets/workspace-repositories/workspace-commit-groups-light.png new file mode 100644 index 0000000000..5454f1ffc6 Binary files /dev/null and b/docs/assets/workspace-repositories/workspace-commit-groups-light.png differ diff --git a/docs/assets/workspace-repositories/workspace-git-log-dark.png b/docs/assets/workspace-repositories/workspace-git-log-dark.png new file mode 100644 index 0000000000..0e2e8a1c9d Binary files /dev/null and b/docs/assets/workspace-repositories/workspace-git-log-dark.png differ diff --git a/docs/assets/workspace-repositories/workspace-git-log-light.png b/docs/assets/workspace-repositories/workspace-git-log-light.png new file mode 100644 index 0000000000..d491042c33 Binary files /dev/null and b/docs/assets/workspace-repositories/workspace-git-log-light.png differ diff --git a/docs/assets/workspace-repositories/workspace-log-more-dark.png b/docs/assets/workspace-repositories/workspace-log-more-dark.png new file mode 100644 index 0000000000..1a8512ea21 Binary files /dev/null and b/docs/assets/workspace-repositories/workspace-log-more-dark.png differ diff --git a/docs/assets/workspace-repositories/workspace-log-more-light.png b/docs/assets/workspace-repositories/workspace-log-more-light.png new file mode 100644 index 0000000000..893bd5321b Binary files /dev/null and b/docs/assets/workspace-repositories/workspace-log-more-light.png differ diff --git a/docs/assets/workspace-repositories/workspace-log-roots-dark.png b/docs/assets/workspace-repositories/workspace-log-roots-dark.png new file mode 100644 index 0000000000..d8c4244048 Binary files /dev/null and b/docs/assets/workspace-repositories/workspace-log-roots-dark.png differ diff --git a/docs/assets/workspace-repositories/workspace-log-roots-light.png b/docs/assets/workspace-repositories/workspace-log-roots-light.png new file mode 100644 index 0000000000..87d60991e3 Binary files /dev/null and b/docs/assets/workspace-repositories/workspace-log-roots-light.png differ diff --git a/docs/viva-migration.md b/docs/viva-migration.md index 9297cc4d36..e28b465f87 100644 --- a/docs/viva-migration.md +++ b/docs/viva-migration.md @@ -301,15 +301,15 @@ | `git-line-history` | 行级修改历史 | 必须迁移 | 缺/实现 | 部分 | `core/git_blame.go` | | `git-local-changelists` | 本地 ChangeList | 必须迁移 | 实现/实现 | 部分 | changelists.go、changelists_view.go、core/changelists.go;多选/目录批量移动未做 | | `git-metadata-observation` | Git 元数据变化观察与刷新 | 必须迁移 | 实现/实现 | 部分 | `workbench/git_observation.go` | -| `git-multi-repository-change-groups` | 多仓库变更折叠分组 | 必须迁移 | 实现/实现 | 部分 | `core/changelists.go` | -| `git-multi-repository-references` | 多仓库引用面板 | 必须迁移 | 实现/实现 | 部分 | — | +| `git-multi-repository-change-groups` | 多仓库变更折叠分组 | 必须迁移 | 实现/实现 | 部分 | core/workspace.go、nested_repos.go、nested_repos_view.go:提交窗口按 Core 的 GroupWorkspaceChanges 按仓库折叠分组,顶部复选框按 Core 的 StageAll 计划暂存全部仓库,状态栏统计所有仓库的更改数;文件夹本身不是 Git 仓库时同样分组 | +| `git-multi-repository-references` | 多仓库引用面板 | 必须迁移 | 实现/实现 | 部分 | branch_view.go、gitlog_popover_view.go、gitgraph.go:分支入口按 IDEA 样式逐行列出仓库,点一行在旁边展开该仓库的分支面板,写操作只作用于该仓库;Git Log 行左侧是仓库颜色条,路径筛选器下方“仓库根目录”切换日志的仓库(截图见 `docs/assets/workspace-repositories/`);Common Local / Remote Branches、聚合日志、跨仓库 Update / Push 未做 | | `git-rebase-stash` | Rebase 与 Stash | 必须迁移 | 实现/实现 | 部分 | stash.go、stash_view.go:Commit 工具窗口暂存页可查看、应用、弹出、删除与新建 stash;拉取分叉时可选变基(gitsync.go);独立 Rebase(含交互式)未找到 | | `git-repository-discovery` | 仓库自动发现排除隐藏目录与构建缓存 | 必须迁移 | 实现/实现 | 部分 | core/repository_colors.go、gitmetadata/ | | `git-status-colors-idea-alignment` | Windows 默认主题 Git 状态配色与 IDEA 对齐(修改/… | 必须迁移 | 专属/实现 | 部分 | theme.go 新增 GitModified/GitModifiedStaged/GitRenamed/GitAdded/GitFileDeleted/GitUntracked 与 Gutter* 令牌(IDEA expUI 明暗值);commit_view.go、gitlog_details_view.go 统一走 palette.gitStatusColor,删除文件改灰、未跟踪改暖红、暂存修改用浅蓝;documents.go 的 gutter 改用浅色令牌。未做:项目文件树与 Git Log 文件树尚未按状态着色(filetree 缺少状态字段) | | `git-status-commit` | 状态、暂存与提交 | 必须迁移 | 实现/实现 | 完成 | commit.go、commit_view.go、core/gitcommit.go;“提交选项”可加 Sign-off、指定作者(必须是 `Name `,否则 Core 以 `git_commit_author_invalid` 拒绝,作者在提交成功后清空);Git 控制台(gitconsole.go、core/gitconsole.go)除自动刷新、监听这类后台命令外记录全部 Git 命令,含读取状态的内部查询,查询的答案型非零退出显示为预期;Commit 工具窗口、Diff 标签和分支弹窗发起的写操作会切到控制台页,Log 与工作树页的不切换 | | `git-submodule-commit-plan` | 子模块先提交与推送、自动更新父引用、计划变化再次确认 | 必须迁移 | 实现/实现 | 部分 | `core/gitcommit.go` | -| `git-workspace-commit-retry` | 失败后只重试未完成的提交或推送步骤 | 必须迁移 | 实现/实现 | 部分 | commit.go `retryCommit`:本项目仓库的提交失败后可重试剩余步骤,先显示复核;多仓库批量提交未接(见 `git-workspace-staged-commit`) | -| `git-workspace-staged-commit` | 按文件所属仓库批量提交及推送,保留每仓库结果 | 必须迁移 | 实现/实现 | 部分 | `core/gitcommit.go` | +| `git-workspace-commit-retry` | 失败后只重试未完成的提交或推送步骤 | 必须迁移 | 实现/实现 | 部分 | commit.go `retryCommit`:提交失败后可重试剩余步骤,先显示复核;多仓库批量提交的重试只带失败那次计划过的仓库,由 Core 绑定(见 `git-workspace-staged-commit`) | +| `git-workspace-staged-commit` | 按文件所属仓库批量提交及推送,保留每仓库结果 | 必须迁移 | 实现/实现 | 部分 | core/gitcommit.go、commit_nested.go:提交窗口把 Core 发现的仓库列表随请求交回,由 Core 绑定嵌套仓库,文件夹本身不是 Git 仓库时只提交嵌套仓库,每仓库保留结果;推送与中途停止待实机验证 | | `git-worktrees` | Worktree 管理 | 必须迁移 | 实现/实现 | 部分 | gitworktree.go、gitworktree_view.go、core/gitworktree.go;在新窗口打开、悬停信息、设置页未做 | | `vcs-subversion-and-plugin-providers` | 统一 VCS 模型与插件 VCS Provider | 插件提供 | 部分/缺 | 部分 | C06 扩展点:vcsProviders;vcs.go、vcs_view.go、core/vcs.go:每个 Provider 一个工具窗口,状态、提交、回滚、更新、标记解决、清理、历史、只读 Diff;Annotate、单文件历史、gutter、元数据监听、fileOperations、项目树状态未做 | diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index b94852e8e0..6ff0db1f45 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -32,8 +32,14 @@ native_path() { # apart; git.consolePresentation takes display options, all false by default as in IDEA; output # folds only past ten lines and a deletion never folds; a failed unrecorded query still reports its # command, stderr and exit; a reported query's started event carries its queryCategory (#2025). It -# is on top of #65, squash-merged into main as db54ba0: workspace repository identities, selection -# and change groups in Core. That is on top of #63, squash-merged into main as ad148ec: +# is on top of #65, squash-merged into main as db54ba0: every workspace.repositories entry has an +# id relative to the opened folder, a display name and a role (workspace or nested); +# git.workspaceRepositorySelection keeps the repository a view picked while discovery still lists +# it and otherwise falls back to the workspace repository, then the first one; +# git.workspaceChangeGroups groups status changes per repository with their staged counts, the +# paths a checkbox stages or unstages and whether the parent's gitlink moved; and +# git.workspaceCommitPrepare binds the nested repositories it is given (#2013). That is on top of +# #63, squash-merged into main as ad148ec: # a Unix process group whose members have all exited but are not reaped yet is killed without # error, so disposing a language server or # closing an SSH session on macOS no longer reports EPERM (#2017). It is on top of #62, diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index 6b9af70732..9287224a24 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -761,20 +761,25 @@ "desktop.branch.forceCheckout": "Force Checkout", "desktop.branch.loadFailed": "Failed to load branches: {reason}", "desktop.branch.loading": "Loading branches…", + "desktop.branch.localIn": "Local Branches in {repository}", "desktop.branch.newBranchFrom": "New Branch from '{name}'…", "desktop.branch.recent": "Recent", + "desktop.branch.recentIn": "Recent Branches in {repository}", + "desktop.branch.remoteIn": "Remote Branches in {repository}", "desktop.branch.rename": "Rename…", "desktop.branch.renameButton": "Rename", "desktop.branch.renameFailed": "Failed to rename branch: {reason}", "desktop.branch.renameFrom": "Rename '{name}'.", "desktop.branch.renameTitle": "Rename Branch", "desktop.branch.renamed": "Renamed the branch to '{name}'", + "desktop.branch.repositoryPanel": "{repository} on {branch}", "desktop.branch.revision": "Tag or revision", "desktop.branch.revisionPrompt": "Enter a tag name, branch name, commit hash, or other Git revision.", "desktop.branch.revisionTitle": "Checkout Tag or Revision", "desktop.branch.rowMenu": "{name} actions", "desktop.branch.search": "Search for branches and actions", "desktop.branch.smartCheckout": "Smart Checkout", + "desktop.branch.tagsIn": "Tags in {repository}", "desktop.build.argumentsRequired": "This task asks for arguments, which this window cannot collect yet.", "desktop.build.cancelled": "Build cancelled", "desktop.build.stopping": "Stopping…", @@ -10747,6 +10752,7 @@ "desktop.git.settings.console.repositoryHelp": "Each command line starts with the time alone, without the [repository] name.", "desktop.nested.collapse": "Collapse Repository", "desktop.nested.expand": "Expand Repository", + "desktop.nested.roots": "Roots", "desktop.git.repo.current": "Repository: {name}", "desktop.git.repo.back": "Back to {name}", "desktop.pull.menu": "Pull…", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index d1e0b196b3..2806663b9e 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -761,20 +761,25 @@ "desktop.branch.forceCheckout": "强制检出", "desktop.branch.loadFailed": "加载分支失败:{reason}", "desktop.branch.loading": "正在加载分支…", + "desktop.branch.localIn": "{repository} 中的本地分支", "desktop.branch.newBranchFrom": "从“{name}”新建分支…", "desktop.branch.recent": "最近", + "desktop.branch.recentIn": "{repository} 中的最近分支", + "desktop.branch.remoteIn": "{repository} 中的远程分支", "desktop.branch.rename": "重命名…", "desktop.branch.renameButton": "重命名", "desktop.branch.renameFailed": "重命名分支失败:{reason}", "desktop.branch.renameFrom": "重命名“{name}”。", "desktop.branch.renameTitle": "重命名分支", "desktop.branch.renamed": "分支已重命名为“{name}”", + "desktop.branch.repositoryPanel": "{repository},位于 {branch}", "desktop.branch.revision": "标签或修订版本", "desktop.branch.revisionPrompt": "输入标签名、分支名、提交 Hash 或其他 Git 修订版本。", "desktop.branch.revisionTitle": "检出标签或修订版本", "desktop.branch.rowMenu": "{name} 的操作", "desktop.branch.search": "搜索分支和操作", "desktop.branch.smartCheckout": "智能检出", + "desktop.branch.tagsIn": "{repository} 中的标签", "desktop.build.argumentsRequired": "此任务需要额外参数,当前窗口尚不能收集。", "desktop.build.cancelled": "构建已取消", "desktop.build.stopping": "正在停止…", @@ -10747,6 +10752,7 @@ "desktop.git.settings.console.repositoryHelp": "命令行开头只显示时间,不显示 [仓库名]。", "desktop.nested.collapse": "折叠仓库", "desktop.nested.expand": "展开仓库", + "desktop.nested.roots": "仓库根目录", "desktop.git.repo.current": "仓库:{name}", "desktop.git.repo.back": "切回 {name}", "desktop.pull.menu": "拉取…", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index c4b4fe7f0e..535cec290c 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -6438,6 +6438,16 @@ "desktop" ] }, + { + "id": "desktop.branch.localIn", + "description": "Branch popup of a folder with several repositories: head of the local branches of one repository, in its panel", + "platforms": [ + "desktop" + ], + "parameters": { + "repository": "string" + } + }, { "id": "desktop.branch.newBranchFrom", "description": "Desktop branch: NewBranchFrom", @@ -6455,6 +6465,26 @@ "desktop" ] }, + { + "id": "desktop.branch.recentIn", + "description": "Branch popup of a folder with several repositories: head of the recently checked-out branches of one repository, in its panel", + "platforms": [ + "desktop" + ], + "parameters": { + "repository": "string" + } + }, + { + "id": "desktop.branch.remoteIn", + "description": "Branch popup of a folder with several repositories: head of the remote branches of one repository, in its panel", + "platforms": [ + "desktop" + ], + "parameters": { + "repository": "string" + } + }, { "id": "desktop.branch.rename", "description": "Desktop branch: Rename", @@ -6506,6 +6536,17 @@ "name": "string" } }, + { + "id": "desktop.branch.repositoryPanel", + "description": "Accessible label of a repository row in the branch popup that opens its branches beside it", + "platforms": [ + "desktop" + ], + "parameters": { + "repository": "string", + "branch": "string" + } + }, { "id": "desktop.branch.revision", "description": "Desktop branch: Revision", @@ -6551,6 +6592,16 @@ "desktop" ] }, + { + "id": "desktop.branch.tagsIn", + "description": "Branch popup of a folder with several repositories: head of the tags of one repository, in its panel", + "platforms": [ + "desktop" + ], + "parameters": { + "repository": "string" + } + }, { "id": "desktop.build.argumentsRequired", "description": "This task asks for arguments, which this window cannot collect yet.", @@ -12917,6 +12968,13 @@ "desktop" ] }, + { + "id": "desktop.nested.roots", + "description": "Head of the repositories of the project folder in the Git Log's Paths filter; a click picks the one the log walks", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.newProject.advanced", "description": "Desktop new project: advanced", @@ -27949,9 +28007,10 @@ }, { "id": "git.log.toolbar.moreActions", - "description": "Windows UI: git.log.toolbar.moreActions", + "description": "Windows UI: git.log.toolbar.moreActions; Viva desktop: the overflow menu button of the Git Log filter bar, holding the view buttons it has no room for", "platforms": [ - "windows" + "windows", + "desktop" ] }, { diff --git a/shared/platform-feature-matrix/features/git-multi-repository-change-groups.json b/shared/platform-feature-matrix/features/git-multi-repository-change-groups.json index e777a7aa45..0bbd507ba7 100644 --- a/shared/platform-feature-matrix/features/git-multi-repository-change-groups.json +++ b/shared/platform-feature-matrix/features/git-multi-repository-change-groups.json @@ -9,7 +9,11 @@ "evidence": [ "desktop/internal/core/changelists.go", "desktop/internal/workbench/changelists.go", - "desktop/internal/workbench/changelists_view.go" + "desktop/internal/workbench/changelists_view.go", + "desktop/internal/core/workspace.go", + "desktop/internal/workbench/nested_repos.go", + "desktop/internal/workbench/nested_repos_view.go", + "desktop/internal/workbench/workspace_repositories_test.go" ] }, "windows": { @@ -18,12 +22,16 @@ "evidence": [ "desktop/internal/core/changelists.go", "desktop/internal/workbench/changelists.go", - "desktop/internal/workbench/changelists_view.go" + "desktop/internal/workbench/changelists_view.go", + "desktop/internal/core/workspace.go", + "desktop/internal/workbench/nested_repos.go", + "desktop/internal/workbench/nested_repos_view.go", + "desktop/internal/workbench/workspace_repositories_test.go" ] }, "owner": "Git", "verification": "在同一工作区打开多个 Git 仓库,确认变更按仓库折叠分组;只剩一个仓库有变更时仍显示仓库名。仓库级和文件级勾选与 Git 暂存区同步;子模块只有未提交文件时显示提示,不能勾选未变化的引用。", - "notes": "Viva:Core 的 ChangeList 按仓库根分组并接受多个 Repositories,但 workbench/changelists.go 只用当前项目的仓库根构造列表,变更列表没有按仓库折叠分组,也没有多仓库勾选同步或子模块未变化引用的提示。", + "notes": "Viva:项目文件夹含嵌套仓库时(含文件夹本身不是 Git 仓库),提交窗口按 Core 的 GroupWorkspaceChanges 按仓库折叠分组,每组有颜色、文件数、暂存复选框和“提交此仓库”;顶部复选框按 Core 的 StageAll 计划暂存全部仓库,状态栏统计所有仓库的更改数(Core 的 FileCount)。子模块未变化引用的提示还未在界面中验证。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/git-multi-repository-references.json b/shared/platform-feature-matrix/features/git-multi-repository-references.json index 4648ffe7cd..e816404ef4 100644 --- a/shared/platform-feature-matrix/features/git-multi-repository-references.json +++ b/shared/platform-feature-matrix/features/git-multi-repository-references.json @@ -11,7 +11,13 @@ "desktop/internal/workbench/gitlog.go", "desktop/internal/workbench/nested_refs.go", "desktop/internal/core/repository_colors.go", - "desktop/internal/workbench/nested_repos.go" + "desktop/internal/workbench/nested_repos.go", + "desktop/internal/workbench/branch.go", + "desktop/internal/workbench/branch_view.go", + "desktop/internal/workbench/gitlog_popover_view.go", + "desktop/internal/workbench/gitgraph.go", + "desktop/internal/workbench/workspace_repositories_test.go", + "docs/assets/workspace-repositories/README.md" ] }, "windows": { @@ -22,12 +28,18 @@ "desktop/internal/workbench/gitlog.go", "desktop/internal/workbench/nested_refs.go", "desktop/internal/core/repository_colors.go", - "desktop/internal/workbench/nested_repos.go" + "desktop/internal/workbench/nested_repos.go", + "desktop/internal/workbench/branch.go", + "desktop/internal/workbench/branch_view.go", + "desktop/internal/workbench/gitlog_popover_view.go", + "desktop/internal/workbench/gitgraph.go", + "desktop/internal/workbench/workspace_repositories_test.go", + "docs/assets/workspace-repositories/README.md" ] }, "owner": "Git", - "verification": "在多仓库工作区打开 Git Log:确认按仓库分组、仓库配色、非活动仓库分组只读,点其它仓库的引用会切换活动仓库且只加载一次,Pull 弹窗可选择远程分支与策略。 Windows 无已保存折叠设置时,单仓库与多仓库的 Tags 默认折叠、Local / Remote 默认展开;手动展开 Tags 后重新打开面板仍保留选择,已有折叠设置继续生效。 Windows 明暗主题中普通本地、远程分支均复用顶部分支按钮的空心 VcsIcon,当前分支勾选、收藏星标、标签与文件夹提示保持可辨认。 macOS 在两个分支名不同的仓库间切换时不得查询旧分支;目标历史读取失败也不能保留旧仓库的提交、分页或文件详情。 Windows Git Log 本地和远程分支右键菜单的拷贝分支名称在删除之前,删除是最后一个操作并单独分组;当前分支无删除入口,执行 Git 写操作时删除仍禁用。 Windows Git Log Tags 标签节点右键菜单最后一组提供 Delete,点击后直接删除活动仓库本地标签,不弹二次确认;失败保留引用和选择,成功后清除被删标签的历史筛选并刷新。非活动仓库及写操作期间禁用;旧工作区/仓库的动作回调不得发起删除,迟到结果不得刷新新仓库或释放新请求状态。 Windows Tags 的 Delete 与分支和提交节点删除复用相同 TrashIcon,明暗主题图标与禁用状态一致。 引用树的 `/` 分组与同级排序(引用先于纯分组,再按自然序,收藏分支及其所在分组优先)由 Core `git.referenceTree` 决定,两端只负责展开、缩进与虚拟化;同一组引用在 macOS 与 Windows 的树结构和顺序一致。", - "notes": "Viva:分支弹窗在项目自己的引用下,按仓库分组只读列出嵌套仓库的本地分支与标签;Git Log 引用面板在自己的分区下列出仓库组,颜色来自 Core(repository_colors.go),点组或其中的引用把该仓库设为日志遍历的仓库。跨仓库的检出、合并、删除等引用操作尚未实现。", + "verification": "在多仓库工作区打开 Git Log:确认按仓库分组、仓库配色、非活动仓库分组只读,点其它仓库的引用会切换活动仓库且只加载一次,Pull 弹窗可选择远程分支与策略。 Windows 无已保存折叠设置时,单仓库与多仓库的 Tags 默认折叠、Local / Remote 默认展开;手动展开 Tags 后重新打开面板仍保留选择,已有折叠设置继续生效。 Windows 明暗主题中普通本地、远程分支均复用顶部分支按钮的空心 VcsIcon,当前分支勾选、收藏星标、标签与文件夹提示保持可辨认。 macOS 在两个分支名不同的仓库间切换时不得查询旧分支;目标历史读取失败也不能保留旧仓库的提交、分页或文件详情。 Windows Git Log 本地和远程分支右键菜单的拷贝分支名称在删除之前,删除是最后一个操作并单独分组;当前分支无删除入口,执行 Git 写操作时删除仍禁用。 Windows Git Log Tags 标签节点右键菜单最后一组提供 Delete,点击后直接删除活动仓库本地标签,不弹二次确认;失败保留引用和选择,成功后清除被删标签的历史筛选并刷新。非活动仓库及写操作期间禁用;旧工作区/仓库的动作回调不得发起删除,迟到结果不得刷新新仓库或释放新请求状态。 Windows Tags 的 Delete 与分支和提交节点删除复用相同 TrashIcon,明暗主题图标与禁用状态一致。 引用树的 `/` 分组与同级排序(引用先于纯分组,再按自然序,收藏分支及其所在分组优先)由 Core `git.referenceTree` 决定,两端只负责展开、缩进与虚拟化;同一组引用在 macOS 与 Windows 的树结构和顺序一致。 打开本身不是 Git 仓库、内含多个独立仓库的文件夹:标题栏分支入口按 IDEA 样式逐行列出仓库(颜色方块、仓库名、右侧当前分支、›),点一行在其旁边展开该仓库的分支面板,在面板里检出、新建、合并、删除只改变该仓库,其他仓库分支不变;Git Log 提交行左侧显示正在查看仓库的颜色条,路径筛选器下方“仓库根目录”按颜色列出仓库,点击后日志改看该仓库且写操作作用于该仓库。", + "notes": "Viva:项目文件夹含嵌套仓库时(含文件夹本身不是 Git 仓库),标题栏分支入口按 IDEA 样式逐行列出仓库,颜色来自 Core(repository_colors.go),右侧是 Core 读出的当前分支;点一行在旁边展开该仓库的面板(“<仓库> 中的最近分支 / 本地分支 / 远程分支 / 标签”),面板里的检出、新建、合并、删除等写操作都只作用于该仓库。Git Log 引用面板按仓库分组,提交行左侧有正在查看仓库的颜色条,路径筛选器下方的“仓库根目录”列出各仓库并切换日志遍历的仓库。尚未实现:IDEA 的 Common Local / Remote Branches(多个仓库同名分支一起操作)、多仓库提交混排的聚合日志,以及跨仓库的 Update / Push。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/git-workspace-staged-commit.json b/shared/platform-feature-matrix/features/git-workspace-staged-commit.json index 4515d47fb7..07a8e57923 100644 --- a/shared/platform-feature-matrix/features/git-workspace-staged-commit.json +++ b/shared/platform-feature-matrix/features/git-workspace-staged-commit.json @@ -8,7 +8,9 @@ "verificationStatus": "pending", "evidence": [ "desktop/internal/core/gitcommit.go", - "desktop/internal/workbench/commit.go" + "desktop/internal/workbench/commit.go", + "desktop/internal/workbench/commit_nested.go", + "desktop/internal/workbench/workspace_repositories_test.go" ] }, "windows": { @@ -16,12 +18,14 @@ "verificationStatus": "pending", "evidence": [ "desktop/internal/core/gitcommit.go", - "desktop/internal/workbench/commit.go" + "desktop/internal/workbench/commit.go", + "desktop/internal/workbench/commit_nested.go", + "desktop/internal/workbench/workspace_repositories_test.go" ] }, "owner": "Git", "verification": "勾选两个独立仓库文件,一次提交并推送,验证各自 HEAD 和远程;停止一个操作后其余独立仓库继续,已成功仓库不会回滚。", - "notes": "Viva:Core 的 WorkspaceCommitRequest 支持多个仓库并为每个仓库保留 WorkspaceCommitResult,失败不回滚。workbench 的 commitTarget.request 只提交项目仓库,未按文件所属仓库分组,因此多仓库批量提交与每仓库结果在界面中未接入。", + "notes": "Viva:提交窗口把 Core 发现的仓库列表随请求交回,由 Core 的 WorkspaceCommitRequest.WorkspaceRepositories 绑定嵌套仓库:首次计划带上全部仓库,ChangeList 范围只提交项目仓库,重试只带失败那次计划过的仓库;文件夹本身不是 Git 仓库时只提交嵌套仓库。每个仓库保留自己的 WorkspaceCommitResult,失败不回滚。提交并推送沿用同一计划;推送和中途停止的实机验证还没做。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": {