diff --git a/Docs/DESIGN.md b/Docs/DESIGN.md index 2cd782004..c5b8097ee 100644 --- a/Docs/DESIGN.md +++ b/Docs/DESIGN.md @@ -29,6 +29,8 @@ folder where a subject needs several. A file here is binding, not background. | [design/files/modified-and-branch.md](design/files/modified-and-branch.md) | Modified against Branch, what Changes and file tabs count from, the Branch read and its pace, failures, no base branch, staged marks under Branch, merge base reads, scope switches, costs left. | | [design/files/image-tabs.md](design/files/image-tabs.md) | Which files open as images, Before and After, the 32 MiB cap, decoding, find and keyboard on an image. | | [design/files/review-comments.md](design/files/review-comments.md) | Comments inline in a file tab, Review and its Send, a file then a mention, the picker's default, a file per worktree, anchoring by quote, Outdated and Lines changed, scope, gaps in the row geometry and the split, the composer's draft, the command line. | +| [design/files/all-changes-tab.md](design/files/all-changes-tab.md) | The All changes tab: a third tab kind, its file list and lazy reads, a list of per-file diff views, the Changes list as its index, review cards in it, Split, its row cap | +| [design/files/all-changes-tab-reviewed.md](design/files/all-changes-tab-reviewed.md) | Review findings on the All changes tab settled without a change, and why. | | [design/tabs-and-groups/groups-and-dragging.md](design/tabs-and-groups/groups-and-dragging.md) | Pane trees, groups, the active versus shown tabs, dragging a tab to another worktree or into a group, drop bands, springing back, the drag preview, live reorder, the keyboard following a dropped tab, refused drops, `tabs move`. | | [design/tabs-and-groups/tab-strip.md](design/tabs-and-groups/tab-strip.md) | A strip out of room, scroll arrows, split buttons, sideways wheel scrolling, the New Tab plus menu, renames from the command line, file tabs in the strip, tab titles, the X button, the shown tab's hairlines, the no-tab placeholder. | | [design/terminals/sessions.md](design/terminals/sessions.md) | A session's state and what clears it, Done and Failed, closing a tab and how a shell ends, notification banners, agents launched through the login shell, the captured login environment, auto-start and warming sessions, terminal editor tabs, each pane's PATH, inherited shell state, the helper hand-off. | diff --git a/Docs/design/agents/command-line.md b/Docs/design/agents/command-line.md index 9e061d222..f5de2b591 100644 --- a/Docs/design/agents/command-line.md +++ b/Docs/design/agents/command-line.md @@ -229,6 +229,9 @@ The command line's requests on the reports' socket. Newest at the bottom. first tab starting out of view as a held-back one does after its hook, and the keyboard staying put. Added 2026-11-14 so a script can make several at once without each pulling the view to itself. +- **`tabs open-all-changes` opens or turns to a worktree's All changes tab**, + and `tabs list` reports it as kind `all-changes`; `tabs step` and `tabs find` + reach it as a file tab (files/all-changes-tab.md). ## Reviewed and left as is diff --git a/Docs/design/files/all-changes-tab-reviewed.md b/Docs/design/files/all-changes-tab-reviewed.md new file mode 100644 index 000000000..50bfffca1 --- /dev/null +++ b/Docs/design/files/all-changes-tab-reviewed.md @@ -0,0 +1,87 @@ +# The All changes tab: reviewed and left as is + +Findings from the review rounds on [all-changes-tab.md](all-changes-tab.md) that +were settled without a change, each with why. A review reads this first. + +- **An opened fold is not moved when lines are added above it** (review round + 2): it is kept by the file on disk's line numbers, as the bullet on folds + says, so an edit above shifts which lines show open. Re-anchoring folds as + comments are would cost a quote per fold for a run-only convenience. +- **Find carried twice when a read moves comments** (review round 3, unproven): + setting the comments searches again from the old text, and the read then + carries the result from it once more. A test inserting a line above a repeated + match moved the selection with no comment involved, so this showed nothing of + its own. Round 17 found the cause: the carry went by line number across files. + Round 18 tried a read moving a comment with one row and five above the match, + and the selection held (`aReadMovingCommentsKeepsTheFindSelectionOnItsMatch`). +- **The document's staging marks taken from its first file with rows** (review + round 3, unproven): under Branch a file in an embedded repository counts from + `HEAD` and marks staging while the worktree's own do not. No case has been + shown; each file's own rows carry its marks. +- **A file deleted after the tab read it keeps its last text** (review round 4): + its file tab does the same + (`aFileDeletedUnderAnOpenTabKeepsItsLastTextUnmarked`), and each file reads as + its tab would; read afresh it shows its lines removed. +- **A step's box dropped once the unread file it sat on is read** (review round + 5, unproven): the next step counts from the top of the clip, which can step + back into a short file above. Not shown in a test. +- **"Fold" for unchanged lines hidden in a file** (review round 5): the design, + the mockups and `git` itself say fold; the Files panel's "folded" is case + folding, an adjective in another area, and renaming either is churn for no + reader's gain. +- **A file shown whole keeps its gap items at document rows in its slice** + (review round 6): no such file gets a fold or notice, being all one kind of + line, and rebasing by the document's rows would be wrong for a removed file, + whose Split rows do not count as its Unified ones do. +- **Each update regroups the worktree's comments once per built file** (review + round 7): about ten files and a few hundred comments make it a few thousand + cheap steps; caching the groups would need every comment write to keep them + fresh. +- **A scroll to a row can land short of it where files it builds grow by their + cards** (review round 9, unproven): heights measured a turn later move the + files below. Not shown in a test; the next scroll or step corrects it. +- **Spans shifted into document offsets and back when a file is coloured** + (review round 9): it runs once a parse, the parse kept by path; not measured. +- **Every update lays the list out again, estimating each unbuilt file** (review + round 9, not measured): an estimate is a lookup and a sum, and a layout + already runs on every scroll that builds a file. +- **Unproven in review round 11, each tried or traced and not shown**: a bare + caret scrolling a long line back to its left edge (a test kept the sideways + scroll); a file's wheel axis lock met mid-gesture keeping an old axis (rests + on AppKit sending one gesture to two scroll views); a pending caret rect + scrolling the list during a file's layout (none is pending once laid out). +- **Cmd+Up or Cmd+Down in a focused file scrolling the list twice** (review + round 12, unproven): the caret's move and the list's jump to its end were + counted in a test, and the list reported one scroll. +- **Every read lstats every listed file** (review round 13, not measured): the + signature also drops a submodule's folder from the list, and a few thousand + lstats run off the main thread. +- **A path listed twice merged both here and in `FileTree`** (review round 13): + the two differ on purpose, the tree keeping a nested repository's row that + this list leaves out, and each merge is two lines. +- **A row cap of zero or less makes the reader spin** (review round 16): only + tests pass a cap, and each passes a positive one. +- **The canvas's gutter and gap layers framed at the document's height** (review + round 17, unproven, not measured): a scroll redraws only what shows. +- **File-tab names on code the All changes tab shares** (review round 17): + `rerunFileFind(in: FileTab.ID)`, `FileTabReadLog` and the like take its ids + too; renaming every shared call touches dozens of files for no change in + behaviour, and one per-kind seam for them is a larger refactor than the tab. +- **Each read rebuilds the whole document and resolves its git bases again** + (review round 18, not measured): a scroll that brings unread files near reads + them in one batch, which 2 or more files make cheaper than reading alone. +- **Two git diffs a chunk, twice `runsAtOnce` processes** (review round 18): + measured on 6,000 changed files and 12 cores, 8 chunks took 0.307 s and 4 took + 0.334 s, so the pair stays. +- **A `git check-ignore` refusal on a path inside a submodule drops the batch** + (review round 19, unproven): a scratch repository in round 16 showed the + reader leaves the submodule's folder out, so its paths never reach it. +- **Two bounded task pools, the reader's and the batched patches'** (review + round 19): the reader's also lands files in order against the row cap, so one + shared pool would need both shapes. +- **Find kept in step by each change to the layout** (review round 19): a rerun + inside `allChangesDocument(of:)` would search from a getter; the four callers + share `relayingOutAllChanges` or pass the old layout themselves. +- **`DiffColumn.hasPendingScrolls` read by a test alone** (review round 20): a + file in the list cannot scroll on its own, so no scroll shows a pending one; + the property is the only way to see `forgetShownFile` clear all three. diff --git a/Docs/design/files/all-changes-tab.md b/Docs/design/files/all-changes-tab.md new file mode 100644 index 000000000..810f2cae2 --- /dev/null +++ b/Docs/design/files/all-changes-tab.md @@ -0,0 +1,228 @@ +# The All changes tab + +One scrolling diff of every change in a worktree, with review comments on its +lines (issue #42, owner's picks of 2026-11-14 from the mockups). Newest at the +bottom. + +- **The exception to "no diff tab"** (files/file-tabs.md). A file and its change + read as one thing, but reviewing what an agent did across twenty files meant + twenty tabs stepped through one by one. This tab is that review; the file tab + stays as it was. +- **A third tab kind, not a file tab holding many paths.** A file tab's path, + title, strike and dot each assume one file. `WorkspaceTab` gains a case, so + every switch on the kind is a compile error until it says what the tab does; + the sites that probed one array then another now ask `workspaceTab(_:)` once + and switch. +- **At most one a worktree, closable like any tab.** Opening it again turns to + it. It never leaves its worktree, as a file tab does not. +- **Saved under a key of its own, read lossily**, so an older build drops it as + it drops file tabs. The repair drops one whose worktree went or whose id + another tab holds, and a second in its worktree, the first kept. +- **Opened from a button beside the Changes page's filter**, or + `tabs open-all-changes`. A click on a Changes row shows the tab at that file, + opening it if closed and expanding the file if collapsed (owner's ask), rather + than the file's tab; the Files page, the quick switcher and `tabs open-file` + still open the file's tab. Each file's header has a button that does. +- **The row of the file at the top of the tab is lit in Changes** while the tab + is in front, the view reporting the file at its clip's top as it scrolls. A + clicked row lights at once and stays lit while the view stays where the click + left it: a file near the end cannot reach the top, and the click otherwise + seemed to do nothing (owner's report). The file at the top is the one whose + box's top sits at or above the clip's top; mapped from the row there, a file + with no rows of its own lit the next file with rows (owner's report). +- **The files are the Changes list's, in its order**: the status read's under + Modified, the Branch read's under Branch, folders before files and names as + Finder sorts them. A folder listed as a change, a submodule or a nested + repository, is left out as the list leaves it, found by `lstat` since the + index read that marks submodules is the panel's alone. +- **The Branch read was the panel's only**, made for its worktree while it + showed Changes. A shown All changes tab under Branch now asks for its + worktree's, and forgetting the panel's listings keeps it; there is no second + way of reading git for the tab. +- **Each file is read by the file tab's reader, with its cap**, so a file reads + the same in both. A read asks git once, not once a file, for the merge base, + `HEAD`, the committed sizes (`ls-tree`), the ignored files and the files the + index holds, and diffs files forty a run, several runs at once; a file in no + commit and not in the index is read as new with no diff run. A diff header git + quotes, a name with a tab or quote, sends that run's files to their own runs. + 300 modified files went from 3.3 s to 0.08 s, this repository's 222 branch + files from 0.45 s to 0.19 s. +- **One read log a tab, paced by the files the next read reads**: ten times a + file's share of the last read's cost, times the files owed. Paced by the whole + read, as a file tab is, a first read of 1,802 files held the next for minutes, + so files the status listed since waited that long to show. A read reads only + what moved: a git change in the project reads every file, and one in an + embedded repository the files inside it, as each file tab would; an event in a + listed file's folder reads the files whose `lstat` moved; a status or Branch + read reads the files it lists new or counted otherwise. The rest keep their + rows. +- **A hidden tab lets go of its rows and is owed its read**, as a file tab is; + shown again it reads every file at once. A shown tab's worktree has its status + read in the background too, as the panel's has. +- **The tab holds at most 200,000 rows across its files**; past that a file + shows its header and an Open File button, as the mockup's over-cap file did. A + file past the file tab's 1 MiB cap says so in its place. Measured with the + debug build over a copy of this repository's sources, every one of 1,802 Swift + files changed by a line and 191 more added: 191 MB in all against 78 MB with + the tab shut, 13 MB of it the rows held (82,895 lines). The cap stays as a + guard now that only files near the screen are read. +- **Only the files near the screen are read**, as the owner asked: the list + names the files it builds, and a read leaves the rest unread behind a Reading + notice, read as the list nears them. A file read once keeps its rows: one a + change outdates away from the screen keeps them stale, read again as the list + nears it (review round 3; dropped to Reading, a git commit emptied the tab). +- **Only the files near the clip are built**, each a view of its own, and let go + of as they leave: hosting every header and fold of 1,802 files took the app to + 1.43 GB, a SwiftUI hosting view and its surface each costing a few hundred + kilobytes. A file not built takes its height from its rows, folds and notices; + a built one its own, cards and all, and a height moving holds the file at the + top where it was. A view let go of is kept, a few of each kind, for the next + file: building one a file scrolled to cost 150 MB while scrolling (owner's + report). It starts the next file at its left edge. +- **A list of files, each its own view** (owner's pick, replacing one text for + every file): a header over the file's own diff, Unified or Split, in one + vertical scroller. One text had stacked headers into gaps, needed a separate + layer for Split's full-width files and mapped the top row to a file, and each + brought a bug. The document still joins the files' rows, as the address find, + the step buttons, the saved scroll and comments use; each file's view shows + its own slice of it (`AllChangesFileSlice`), folds and notices renumbered to + its rows. +- **Each row's fragment reports its row and the gap under it as its height.** + TextKit finds a scroll's top by summing fragment heights; with a gap every few + rows, as the one text's headers were, its sum fell thousands of rows short of + the forced geometry and the rows on screen were left blank. Card gaps are + sparse enough that the file tab never showed it + (`theRowsOnScreenAreInTextKitsViewportWithAGapEverySixRows`). +- **The gap above the first row starts TextKit's container**, not a row's + height. A tall gap there, the one text's collapsed files then a file's fold, + is counted by no fragment, and TextKit left the first rows blank (owner's + report; `theFirstRowsAreLaidOutUnderATallGapAboveTheFirstRow`). +- **Each file is a box with a margin either side, as the mockups drew it**: its + view's own border. The vertical scroller sits in the right margin, outside the + boxes, as wide as it grows under the pointer, 17 pt. +- **Three lines of context around each change, as `git diff` keeps.** An + unchanged run shorter than four lines shows whole, its fold row saving little. +- **A fold's click shows every line it held.** The mockup opened a few at the + top of a large file and offered Open file for the rest; the simplest rule was + taken and the owner kept it. Opened folds are kept for the run by the file on + disk's line numbers, so a re-read keeps them. +- **A collapsed file keeps its header, counts and comment badge**, and is kept + for the run only, by tab and path; the owner did not need it kept across + launches. Near the screen it is not read until expanded: it shows no rows. +- **The bar's chevron pair, right of Unified/Split, collapses every file**, or + expands every one once all are (owner's ask, as the mockups drew it). It + writes the same per-run set a header's chevron does. +- **The change letter's square, and a lit button on a header or card, sit on the + fill drawn again**, a shade up where the theme's fill is translucent. Eight of + the twelve built-in themes have an opaque fill, which drawn twice reads as + none, so those draw the selection colour instead (`ChipOnFill`). +- **The header of the file at the top is held over the text** once its own has + scrolled past: the one overlay, from the list's file tops. The next file's + header pushes it up and out as it arrives (owner's report). +- **Each file is highlighted as its view is built**, parsed over its own rows, a + folded slice parsing wrong, and the spans mapped onto the rows shown. The + parse is kept by path, so a fold opening or a scroll back parses nothing + again; parsing every file of a large worktree on each read held a core for + tens of seconds. +- **The bar's step buttons go across files**: every change of every file is a + stop, ordered by where it starts in the list (`AllChangesSteps`); a step + scrolls the list to it and boxes it in its file's view. A file shown whole in + Split is one change like any other. +- **A selection stays within one file**, each file being its own text; it copies + as that file's tab copies it. Copy across files was not wanted (owner). +- **Find searches the rows shown**, the document's, and paints each file's share + in its view; the selected match scrolls the list to it. Folded and collapsed + lines are not searched; the file tab has them all. In Split it searches the + right side, the file on disk, so a deleted file is not searched. +- **The scroll is saved by the file at the top and its line there**, so files + coming or going above, or folds opening, return to the same line. It is put + back by the built file's own row geometry, folds included; by row height alone + each return crept up by the folds above (owner's report). +- **Review cards are the file tab's**: the same cards, composer, gutter + and + drag, Comment on Lines, chips and Review rows, through one set of tables keyed + by `ReviewTabID`, the id of a tab hosting cards. A comment written in either + view shows in both, and one Send carries them all. +- **Cards are placed per file against that file's own rows**, then moved to the + document's: placing over the document's rows put one file's card on another's + line of the same number. +- **The composer carries its file's path**; a drag or Comment on Lines reads the + rows as the file of the row it started on, stopping at that file's last row. +- **A drag or Comment on Lines stops at a fold**, as the owner picked: it never + quotes lines it hid. To comment on them, open the fold first. +- **Each read re-anchors the comments of every file whose rows moved**, and the + composer where it is on that file, as a file tab's read does. +- **A comment holds its lines and two either side open inside a fold**, as the + owner picked; a comment's lines are always on screen to place its card under. +- **The tab's badge counts every comment to send in its worktree.** +- **Closing the tab asks first while its composer holds text**, as a file tab's + close does. +- **A comment picked in Review is revealed in the All changes tab where a group + shows it**, its file expanded if collapsed, and otherwise in its file's tab as + before. This follows the mockup, not an explicit pick. A comment on a file + still unread scrolls to that file and shows once it is read; taken at once, + the reveal found no card and was lost (owner's report). +- **`review add` quotes only through a file tab** (owner's pick): a command line + comment goes through the file's own tab, never this one. +- **Modified/Branch and Unified/Split are the one choice every file tab and + Changes follow.** Where the project has no base branch the tab counts from + `HEAD` and offers no scope switch, as a file tab does. +- **Split lays each file's two sides row for row**, as its file tab's split + does, and folds only rows unchanged on both. +- **In Split a file all added or all removed shows full width** (owner's pick): + its view is Unified, across the box. Its rows still lie row for row in the + split's sides, padding opposite, so find, the step buttons and the saved + scroll address it as any other file. +- **In Split the columns' divider runs down each file's diff**, its folds and + notices laid over it across both columns. +- **Each file's folds and notices sit in its own diff's gaps**, laid across its + gutter and text or both columns, flush with the box as the mockups drew them: + no inset above the first row or below the last. A file's diff scrolls sideways + on its own (owner's ask) and hands a vertical wheel to the list. +- **A step onto a file still to be read lands on its header** (owner's pick): it + is then near the screen and read, and the next step goes into its changes. + Steps over read files alone greyed the buttons out at the last one. +- **A fold's label starts where its file's code does**, its glyph centred in the + gutter, as the mockup lines them up; the gutter widens with its digits. +- **The sticky header keeps the box's rounded top corners** (mockup). +- **Cmd+Up and Cmd+Down reach the list's ends from any file**, and from the list + itself: a file view let go of with its text focused hands the focus to the + list, or the keys beeped (owner's report). +- **A trackpad gesture keeps the axis its first moving frame chose**, momentum + included (`WheelAxisLock`): chosen a frame at a time, a sideways swipe leaning + vertical for a frame went to the list mid-swipe (owner's report). A file never + bounces vertically. +- **The step buttons' enabled state places the first and last change alone**, + the list's order being the document's: placing every change on each scroll + took two thirds of a scroll step over 2,000 files. +- **Debug Info counts the tab with the file tabs**: each file's rows and the + document joined from them, not the layout. +- **`tabs step` and `tabs find` reach the tab** as they reach a file tab, the + document being rows whatever its files hold. +- **A notice offers what the file's tab offers**: Open in Editor for a file too + large, binary or unreadable, as the mockup's file past the cap did; Open File + for an image or a file past the row cap, which its tab shows. +- **With nothing to show, the tab says why as the mockup drew it**: under + Modified it names the worktree and offers Show Branch where the project has a + base; under Branch it names the base. The mockup also counted the branch's + commits, which no read gives yet. +- **The file at the top is noted after every layout**, not only on a scroll: a + restore or a first show reports no scroll, and left the sticky header and the + lit row unset (UI review). The saved scroll is put back there too, a queued + restore never running inside a test. +- **One Changes rotor walks every file's changed lines in list order**, the list + scrolling to each so its file's view is built to read it; a file's own text + offers none, two rotors of one name reading as a bug. In Split it walks the + right side, as find does. +- **The sticky header takes no clicks while the next header pushes it up**: it + reaches under the bar, where `.clipped()` hides it but leaves it hit-testable, + so one click on Split also opened the file (owner's report). +- **Costs**: an image shows a notice with Open File, not both sides as the + mockup drew; a mode-only change shows its unchanged rows folded with no mode + note. Scrolling raises the footprint by about 300 MB of layer backing stores, + released when it stops (debug build, 1,993 files, 2026-11-17); the owner once + saw 1.5 GB, not reproduced, and put the work on hold. + +## Reviewed and left as is + +Review findings settled without a change, and why, are in +[all-changes-tab-reviewed.md](all-changes-tab-reviewed.md). diff --git a/Docs/design/files/file-tabs.md b/Docs/design/files/file-tabs.md index b713b93d4..282178326 100644 --- a/Docs/design/files/file-tabs.md +++ b/Docs/design/files/file-tabs.md @@ -3,7 +3,8 @@ What a file tab shows and why each went the way it did. Newest at the bottom. - **One tab per file, its changes drawn inside it.** The user reads a file and - its change as one thing, so there is no diff tab and no Show Diff button. + its change as one thing, so there is no diff tab and no Show Diff button, bar + the All changes tab, a whole worktree's review (files/all-changes-tab.md). Opening a file already open turns to its tab; there is no preview tab. - **Read-only.** Editing is the editor's job, a click away in each menu. - **A file opens in a tab by the clicked-link rule**: a regular file typed as @@ -134,9 +135,16 @@ What a file tab shows and why each went the way it did. Newest at the bottom. sign of an addition. - **A file tab's memory is labelled in Debug Info**, estimated from the text it keeps, as a line under the Multishell row's heap in use (debug-tools.md). -- **Split is offset-locked**, the same offset being the same row on both sides - under the forced geometry; a lock by row left the scrollers thousands of - points apart. +- **Unified and Split are one scroller over a canvas**, `DiffCanvasView`, its + document holding each column's gutter and text and the views in the gaps, so + all of it scrolls natively and nothing is kept in step. Split's two columns + had two scrollers locked by offset: the lock pulled one back where the other + clamped, a wheel over the left had to be forwarded, and every view laid over + both was moved on each scroll. The same offset is still the same row on both + sides under the forced geometry. Both columns scroll sideways together under + one horizontal scroller (owner's pick), each text in its own clip right of its + gutter. `NSTextView` scrolls nothing on a canvas, not being the scroller's + document, so the column brings a range into view itself. - **Unified or Split is one choice for every tab, kept with the settings**, so the next file opens as the last was read. A file only added to or only removed from stays Unified and offers no switch: one side would be blank. @@ -205,6 +213,12 @@ What a file tab shows and why each went the way it did. Newest at the bottom. - **The caret a file opens with counts as no selection**, so a step down from there lands on a change on the first row: a new or deleted file is one change from row 0, and counting from that caret left both arrows grey. +- **A row's fragment counts the gap under it in its height**, so TextKit's sum + of heights, which it finds a scroll's top by, agrees with the geometry; the + All changes tab's dense gaps left it laying out rows far from the clip + (files/all-changes-tab.md). +- **The step buttons are chevrons**, as the All changes mockup drew them, in a + file tab's bar and the All changes bar alike (owner's pick, 2026-11-17). ## Reviewed and left as is diff --git a/Docs/design/files/panel.md b/Docs/design/files/panel.md index a4c5e8267..64cbfd9ad 100644 --- a/Docs/design/files/panel.md +++ b/Docs/design/files/panel.md @@ -53,8 +53,10 @@ What the panel lists and why each went the way it did. Newest at the bottom. then opening with the first worktree having read as a bug; a launch now selects nothing, so the panel shows with the worktree picked, and a panel closed at every launch read as forgotten. The model holds the switch, so a - click on a row's badge can open it. No keyboard shortcut yet; a View menu - item. + click on a row's badge can open it. View has an item per page, Files Pane, + Changes Pane and Review Pane (Cmd+Shift+F, C and R), each opening the panel on + its page or shutting it where it shows that page; Close Find moved to + Cmd+Option+F to free Cmd+Shift+F. - **Double-clicking either edge fits its column to its rows**, laid out off screen at their ideal widths, since a lazy list holds only those on screen: every sidebar row, and the panel's 64 longest by characters, every row of a diff --git a/Docs/design/files/review-comments.md b/Docs/design/files/review-comments.md index ee6cf7d92..57a076fdd 100644 --- a/Docs/design/files/review-comments.md +++ b/Docs/design/files/review-comments.md @@ -65,7 +65,8 @@ panel's Review page (issue #6). Newest at the bottom. missing, so a missing quote says nothing of the agent. - **Only a shown tab re-anchors.** A hidden tab holds no rows (file-tabs.md), so a comment on a file not shown keeps its lines until the file is shown. Cost: - Review can list a stale line number for a file nobody has open. + Review can list a stale line number for a file nobody has open. The All + changes tab re-anchors each of its files whose rows a read moved. - **A comment on removed lines shows only under the scope it was written in**, `HEAD` and the merge base holding different text. Review lists it either way, marked "(Branch)" or "(Modified)". Cost: switching scope hides those cards. A @@ -79,9 +80,9 @@ panel's Review page (issue #6). Newest at the bottom. file stays as fast; with none the geometry gives what it gave before, which the drift tests hold, with a second run with gaps open. - **A split opens each gap in both columns at the taller column's height**, so - the offset lock still means the same row. The card sits in the column holding - its lines. Cost: a comment inside a change sits between that change's removed - and added rows. + one offset is still the same row on both sides. The card sits in the column + holding its lines. Cost: a comment inside a change sits between that change's + removed and added rows. - **Cards are hosted views over the text, not text.** Copy, find and the Changes rotor see rows only, and a selection dragged across a card copies the rows either side. @@ -119,9 +120,14 @@ panel's Review page (issue #6). Newest at the bottom. Review's Send takes both, so Return is one key away. - **`review add` on the command line needs the file's tab shown**, the quote coming from its rows as a comment written in the tab does. A hidden tab holds - none, so it is refused rather than quoting nothing. + none, so it is refused rather than quoting nothing. It never quotes through + the All changes tab (owner's pick). - **The handoff is its own type, `AgentHandoff`**, writing entries and wording the mention, so #34 can send a pull request's failing checks the same way. +- **Cards show in the All changes tab too** (files/all-changes-tab.md), placed + per file against that file's rows. The composer carries its file's path, the + All changes tab holding several, and the tables a composer and its draft live + in are keyed by the tab hosting cards, a file or All changes tab. ## Reviewed and left as is @@ -193,9 +199,6 @@ panel's Review page (issue #6). Newest at the bottom. which end it was dragged from. - **A comment's text goes to the agent as typed**, its own Markdown: a heading or a `---` in it is the user's. Escaping it changed code the text quoted. -- **A split's first card pass can end the following column's wait for the lock** - before the other column restores. Traced twice; its report maps back to the - scroll handed over. - **A worktree git stops listing and lists again at once can lose its comments**: the forget's delete, still in flight, lands after the new read. A list read takes a second or more, the delete milliseconds. diff --git a/Docs/design/quick-switcher/lists-and-matching.md b/Docs/design/quick-switcher/lists-and-matching.md index 6758387f2..aec736fbd 100644 --- a/Docs/design/quick-switcher/lists-and-matching.md +++ b/Docs/design/quick-switcher/lists-and-matching.md @@ -185,9 +185,9 @@ Raised by reviews and settled; a review need not raise these again. it at once, and a second walk point would be a second place the list is read. - **Each arrow press building the rows again.** It is the same build as a render, above, well under a millisecond. -- **Files Panel listed under a cover while the panel is on.** Choosing it turns - the panel off, as View > Files Panel does there; leaving it out hid a command - that acts. +- **The View menu's panes listed under a cover while the panel is on.** Choosing + one turns the panel off, as the menu item does there; leaving them out hid a + command that acts. - **`ui switcher` waiting on file-tree builds with no bound.** Unproven: a listing starts its change set and both end; a build that never settles under steady status changes was not reproduced. diff --git a/Docs/design/worktrees/line-count-badge.md b/Docs/design/worktrees/line-count-badge.md index a5444ffcd..1628fcd38 100644 --- a/Docs/design/worktrees/line-count-badge.md +++ b/Docs/design/worktrees/line-count-badge.md @@ -103,6 +103,9 @@ algorithm. Newest at the bottom, above "Reviewed and left as is". over git's own Myers. It is about the person reading the badge, not the repository, so no project overrides it, and a change re-reads every badge as the indicator's does. +- **A count of five digits or more is grouped**, `+16,621`, where `+16621` was + hard to read (owner's pick, 2026-11-17); four digits stay plain. The badge, + Changes rows and the All changes tab share it (`LineCountText`). ## Reviewed and left as is diff --git a/Docs/develop/adding/state-settings-and-command-line.md b/Docs/develop/adding/state-settings-and-command-line.md index 7870e0c9b..f4375bc5b 100644 --- a/Docs/develop/adding/state-settings-and-command-line.md +++ b/Docs/develop/adding/state-settings-and-command-line.md @@ -64,8 +64,9 @@ beyond the code itself. - **Runtime state.** On the model, never the workspace. Keyed by worktree it also goes in the forget, or it outlives its row and the next worktree at that path inherits it (design/worktrees/creating-and-removing.md); keyed by - project, in the project's removal; keyed by file tab, in `pruneFileTabs`, or a - closed tab's id keeps its entry for the run. Nothing forces any of the three. + project, in the project's removal; keyed by file tab, in `pruneFileTabs`, and + by All changes tab, in `pruneAllChangesTabs`, or a closed tab's id keeps its + entry for the run. Nothing forces any of the three. - **A request a view acts on is a model property the view takes** in its update, `takeChangeStepRequests` and `takeFileTabFocusRequest` the pattern: a SwiftUI bar cannot reach the AppKit view beside it, and the take, read in diff --git a/Docs/develop/state-on-disk.md b/Docs/develop/state-on-disk.md index 7a302d1fb..28e3c54e2 100644 --- a/Docs/develop/state-on-disk.md +++ b/Docs/develop/state-on-disk.md @@ -18,17 +18,18 @@ Under `~/Library/Application Support/Multishell`. - **Settings prints the state file**, and `multishell info` the state file and socket of the copy that answered. - **`state.json`**: sidebar, terminal tabs and file tabs by path with their - scroll, the groups they sit in with their widths, order and shown tab, pane - trees, worktree names, which worktrees are hidden, creation dates and port - blocks, the Agents board's Show all terminals, whether the Files panel is - open, every setting. + scroll, each worktree's All changes tab with its scroll, the groups they sit + in with their widths, order and shown tab, pane trees, worktree names, which + worktrees are hidden, creation dates and port blocks, the Agents board's Show + all terminals, whether the Files panel is open, every setting. - **Not in it**: processes, shell titles, the shell a tab resolved to, a branch's last commit time, the sidebar filter or a project collapsed under it, - which Hidden sections are expanded, a file tab's text, the Files panel's - filter and the folders opened in it, the pull requests and CI runs last read, - the quick switcher's recent worktrees, whether the Agents board is up, or - anything about the debug tools. Those are runtime state, so the debug tools - start off at every launch and write nothing to disk or defaults. + which Hidden sections are expanded, a file tab's text, the All changes tab's + collapsed files and opened folds, the Files panel's filter and the folders + opened in it, the pull requests and CI runs last read, the quick switcher's + recent worktrees, whether the Agents board is up, or anything about the debug + tools. Those are runtime state, so the debug tools start off at every launch + and write nothing to disk or defaults. - **A file written before groups existed names no group**, and carries a key for the active tab this build has no property for; the repair gathers each worktree's ungrouped tabs into the one group they were saved as. diff --git a/Sources/MultishellAppCore/Accessibility/AccessibilityText+TabStrip.swift b/Sources/MultishellAppCore/Accessibility/AccessibilityText+TabStrip.swift index a96105964..981119ae0 100644 --- a/Sources/MultishellAppCore/Accessibility/AccessibilityText+TabStrip.swift +++ b/Sources/MultishellAppCore/Accessibility/AccessibilityText+TabStrip.swift @@ -29,6 +29,13 @@ extension AccessibilityText { return parts.joined(separator: ", ") } + /// The All changes tab: its title and whether it is shown. + public static func allChangesTab(title: String, isShown: Bool) -> String { + var parts = [t("spoken.tab", title)] + if isShown { parts.append(t("spoken.selected")) } + return parts.joined(separator: ", ") + } + /// One group of tabs, said before its tabs are. Empty for a worktree with /// one group, "group 1 of 1" before every tab being noise. public static func tabGroup(position: Int, of count: Int, isFocused: Bool) -> String { diff --git a/Sources/MultishellAppCore/Control/QuickSwitcherItem.Kind+CommandName.swift b/Sources/MultishellAppCore/Control/QuickSwitcherItem.Kind+CommandName.swift index b7e4c56eb..aed881a02 100644 --- a/Sources/MultishellAppCore/Control/QuickSwitcherItem.Kind+CommandName.swift +++ b/Sources/MultishellAppCore/Control/QuickSwitcherItem.Kind+CommandName.swift @@ -3,6 +3,7 @@ extension QuickSwitcherItem.Kind { var commandName: String { switch self { case .agent: "agent" + case .allChangesTab: "all-changes-tab" case .command: "command" case .file: "file" case .fileTab: "file-tab" diff --git a/Sources/MultishellAppCore/Control/TabKind.swift b/Sources/MultishellAppCore/Control/TabKind.swift index f46128cf4..38a9b89fc 100644 --- a/Sources/MultishellAppCore/Control/TabKind.swift +++ b/Sources/MultishellAppCore/Control/TabKind.swift @@ -1,5 +1,6 @@ /// Which kind a tab the command line prints is, by the word it prints. enum TabKind: String, Encodable, Equatable { + case allChanges = "all-changes" case file case terminal } diff --git a/Sources/MultishellAppCore/Dialogs/PendingClose.swift b/Sources/MultishellAppCore/Dialogs/PendingClose.swift index e45e7be6c..3b66855ec 100644 --- a/Sources/MultishellAppCore/Dialogs/PendingClose.swift +++ b/Sources/MultishellAppCore/Dialogs/PendingClose.swift @@ -1,16 +1,16 @@ import Foundation import MultishellCore -/// A close waiting on its dialog: a pane or tab whose agent reported Working, or a -/// file tab with a review comment being written. Cmd+W there is often a mistake. +/// A close waiting on its dialog, Cmd+W there often a mistake: an agent reported +/// Working, or a file or All changes tab holds a review comment being written. public enum PendingClose: Identifiable, Equatable, Sendable { - case fileTab(FileTab.ID) case pane(TerminalSession.ID) + case reviewTab(ReviewTabID) case tab(TerminalTab.ID) public var id: String { switch self { - case .fileTab(let id): "file-tab-\(id.uuidString)" + case .reviewTab(let id): "review-tab-\(id.uuidString)" case .pane(let id): "pane-\(id.uuidString)" case .tab(let id): "tab-\(id.uuidString)" } @@ -19,13 +19,13 @@ public enum PendingClose: Identifiable, Equatable, Sendable { public var title: String { switch self { case .pane: t("close.pane-title") - case .fileTab, .tab: t("close.tab-title") + case .reviewTab, .tab: t("close.tab-title") } } public var message: String { switch self { - case .fileTab: t("close.review-draft-message") + case .reviewTab: t("close.review-draft-message") case .pane, .tab: t("dialog.agent-still-working") } } @@ -33,7 +33,7 @@ public enum PendingClose: Identifiable, Equatable, Sendable { public var buttonLabel: String { switch self { case .pane: t("close.pane-button") - case .fileTab, .tab: t("close.tab-button") + case .reviewTab, .tab: t("close.tab-button") } } @@ -41,7 +41,7 @@ public enum PendingClose: Identifiable, Equatable, Sendable { /// tab. What decides whether the question is asked at all. func sessionIDs(in tab: TerminalTab) -> [TerminalSession.ID] { switch self { - case .fileTab: [] + case .reviewTab: [] case .pane(let id): [id] case .tab: tab.sessionIDs } diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+ChangedLines.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+ChangedLines.swift new file mode 100644 index 000000000..12c26cf75 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+ChangedLines.swift @@ -0,0 +1,25 @@ +import MultishellCore + +/// One Changes rotor across the All changes tab's files, each walked by its +/// own view's text; see Docs/design/files/all-changes-tab.md. +extension AllChangesDocument { + /// The changed line after `start`, or before it going back, in the file of + /// `start` or the nearest that way showing one; from `nil`, the first or last. + public func changedLine( + _ direction: CycleDirection, + from start: AllChangesSteps.Stop?, + slice: (Int) -> AllChangesFileSlice?, + ) -> AllChangesSteps.Stop? { + let step = direction == .next ? 1 : -1 + var section = start?.section ?? (direction == .next ? 0 : sections.count - 1) + var row = start?.row + while sections.indices.contains(section) { + if let found = slice(section)?.changedRow(direction, from: row) { + return AllChangesSteps.Stop(section: section, row: found) + } + section += step + row = nil + } + return nil + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+FileSlice.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+FileSlice.swift new file mode 100644 index 000000000..05e85da18 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+FileSlice.swift @@ -0,0 +1,48 @@ +import MultishellCore + +/// Each file's own part of the document, for the per-file list. +extension AllChangesDocument { + /// `digest` is the whole file's committed side, which a fold opening leaves as it was. + private static func rows( + _ rows: Range, + of text: DiffDisplayText, + digest: Int?, + ) -> DiffDisplayText { + DiffDisplayText( + rows.map(text.uncutLine(ofRow:)), + wholeSides: text.wholeSides, + committedDigest: digest, + marksStaging: text.marksStaging, + changeBreaks: Set(text.changeBreaks.filter(rows.contains).map { $0 - rows.lowerBound }), + ) + } + + /// The file at `index`; one shown whole in Split gives its Unified rows. + public func slice(ofSection index: Int) -> AllChangesFileSlice { + let section = sections[index] + let gapItems = gapItems(ofSection: index) + if section.isShownWhole, let fileText = section.fileText { + return AllChangesFileSlice( + section: index, + text: fileText, + committedText: nil, + gapItems: gapItems, + ) + } + let rows = section.rows + return AllChangesFileSlice( + section: index, + text: Self.rows(rows, of: text, digest: section.fileText?.committedDigest), + committedText: committedText.map { committed in + Self.rows(rows, of: committed, digest: section.fileCommittedText?.committedDigest) + }, + gapItems: gapItems.map { item in + AllChangesGapItem( + afterRow: max(-1, item.afterRow - rows.lowerBound), + section: item.section, + kind: item.kind, + ) + }, + ) + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+HighlightSpans.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+HighlightSpans.swift new file mode 100644 index 000000000..4a28271cf --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+HighlightSpans.swift @@ -0,0 +1,46 @@ +import MultishellCore + +/// Highlighting runs over each file's own rows, a parse of a folded slice +/// colouring it wrong, and lands on the rows the document shows of it. +extension AllChangesDocument { + /// `spans` found over `section`'s file text, Split's left for the committed + /// side, cut to its shown rows and moved to that side's offsets, in text order. + func documentSpans( + _ spans: [HighlightSpan], + ofSection index: Int, + side: DiffSide? = nil, + ) -> [HighlightSpan] { + let section = sections[index] + let text = side == .committed ? committedText ?? self.text : self.text + guard let fileText = section.sideText(on: side), !section.rows.isEmpty else { return [] } + var placed: [HighlightSpan] = [] + placed.reserveCapacity(spans.count) + for span in spans where !span.range.isEmpty { + for fileRow in fileText.rows(touching: span.range) { + guard let row = section.documentRow(ofFileRow: fileRow) else { continue } + let part = span.range.clamped(to: fileText.range(ofRow: fileRow)) + guard !part.isEmpty else { continue } + let shift = text.rowStarts[row] - fileText.rowStarts[fileRow] + placed.append(HighlightSpan(range: part.shifted(by: shift), role: span.role)) + } + } + return placed + } + + /// The same spans on the file's own slice, for its view in the per-file list; + /// a file shown whole is its own Unified rows, the parse's own offsets. + public func sliceSpans( + _ spans: [HighlightSpan], + ofSection index: Int, + side: DiffSide? = nil, + ) -> [HighlightSpan] { + guard !sections[index].isShownWhole else { return spans } + let rows = sections[index].rows + let text = side == .committed ? committedText ?? self.text : self.text + guard !rows.isEmpty else { return [] } + let base = text.rowStarts[rows.lowerBound] + return documentSpans(spans, ofSection: index, side: side).map { span in + HighlightSpan(range: span.range.shifted(by: -base), role: span.role) + } + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+LineSelection.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+LineSelection.swift new file mode 100644 index 000000000..30d95b65e --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+LineSelection.swift @@ -0,0 +1,29 @@ +import MultishellCore + +/// The gutter's + and Comment on Lines in the All changes tab: the rows picked +/// read as one file's lines, that of the row the drag started on. +extension AllChangesDocument { + /// Rows past that file's or a fold are left out: a comment never spans two + /// files or quotes lines it hid. See Docs/design/files/all-changes-tab.md. + func lineSelection( + from start: Int, + to end: Int, + side: DiffSide?, + ) -> (selection: ReviewLineSelection, path: String)? { + guard let index = section(atRow: start) else { return nil } + let file = sections[index] + guard let fileText = file.sideText(on: side), !file.rows.isEmpty else { return nil } + let clamped = { (row: Int) in min(max(row, file.rows.lowerBound), file.rows.upperBound - 1) } + let reached = file.documentRow(from: clamped(start), towardBeforeFold: clamped(end)) + guard let fileStart = file.fileRow(ofDocumentRow: clamped(start)), + let fileEnd = file.fileRow(ofDocumentRow: reached), + let selection = ReviewLineSelection( + from: fileStart, + to: fileEnd, + in: fileText.lines, + side: side, + ) + else { return nil } + return (selection, file.path) + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+SameLine.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+SameLine.swift new file mode 100644 index 000000000..9d2ff582f --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+SameLine.swift @@ -0,0 +1,16 @@ +/// Find's selection carried across a relayout of the All changes tab: every file +/// numbers its own lines, so the match stays in its own file, found by path. +extension AllChangesDocument { + func rangeOnSameLine(_ range: Range, from previous: AllChangesDocument) -> Range? { + let row = previous.text.row(atOffset: range.lowerBound) + guard let previousIndex = previous.section(atRow: row), + let index = section(at: previous.sections[previousIndex].path) + else { return nil } + return text.rangeOnSameLine( + range, + from: previous.text, + inRows: sections[index].rows, + fromRows: previous.sections[previousIndex].rows, + ) + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+Scroll.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+Scroll.swift new file mode 100644 index 000000000..21ad4e132 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+Scroll.swift @@ -0,0 +1,47 @@ +import MultishellCore + +/// A scroll held by the file at the top and its line there, so folds opening +/// and files coming or going above keep the place. +extension AllChangesDocument { + /// `row` is the top row, a fraction where one is cut; `nil` with no files. + public func scroll(atRow row: Double, x: Double) -> AllChangesScroll? { + let top = Int(row.rounded(.down)) + guard let section = section(atRow: top) else { return nil } + let file = sections[section] + guard let fileText = file.fileText, let fileRow = file.fileRow(ofDocumentRow: top) else { + return scroll(atTopOf: section, x: x) + } + let fileTop = Double(fileRow) + row - Double(top) + let split = file.fileCommittedText.map { SplitDiff(committed: $0, onDisk: fileText) } + return AllChangesScroll( + path: file.path, + scroll: split?.scroll(atRow: fileTop, x: x) ?? fileText.scroll(atRow: fileTop, x: x), + ) + } + + /// A file's top, where it shows no rows to hold a line by. + public func scroll(atTopOf section: Int, x: Double) -> AllChangesScroll { + AllChangesScroll( + path: sections[section].path, + scroll: FileTabScroll(line: 0, isCommittedLine: false, rowsFromLine: 0, x: x), + ) + } + + /// The top row putting `scroll` back: its line's row, else the next shown in + /// that file, else the file's first; `nil` where the file has gone. + public func row(of scroll: AllChangesScroll) -> Double? { + guard let index = section(at: scroll.path) else { return nil } + let file = sections[index] + guard let fileText = file.fileText, !file.rows.isEmpty else { + return Double(file.rows.lowerBound) + } + // Split numbers a removed line by the left side, which holds it. + let byLine = scroll.scroll.isCommittedLine ? file.fileCommittedText ?? fileText : fileText + let fileRow = byLine.row(of: scroll.scroll) + let whole = Int(fileRow.rounded(.down)) + guard let row = file.documentRow(atOrAfterFileRow: whole) else { + return Double(file.rows.upperBound - 1) + } + return Double(row) + (file.documentRow(ofFileRow: whole) == row ? fileRow - Double(whole) : 0) + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+Stops.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+Stops.swift new file mode 100644 index 000000000..97867b69a --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument+Stops.swift @@ -0,0 +1,23 @@ +/// Where the bar's arrows stop across the files; see "The bar's arrows step +/// across files" in Docs/design/files/all-changes-tab.md. +extension AllChangesDocument { + /// The files still to be read, by section: each shows a Reading notice. + public var unreadSections: Set { + Set(gapItems.filter { $0.kind == .notice(.reading) }.map(\.section)) + } + + /// Each change, and each file still to be read as one stop at its top: a + /// step onto it brings it near, so it is read and its changes follow. + public var changeStops: [AllChangesSteps.Stop] { + var rowsBySection: [Int: [Int]] = [:] + for start in text.changeStarts { + guard let section = section(atRow: start) else { continue } + rowsBySection[section, default: []].append(start - sections[section].rows.lowerBound) + } + let unread = unreadSections + return sections.indices.flatMap { index -> [AllChangesSteps.Stop] in + let rows = unread.contains(index) ? [0] : rowsBySection[index] ?? [] + return rows.map { AllChangesSteps.Stop(section: index, row: $0) } + } + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument.swift new file mode 100644 index 000000000..c4e997e8a --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocument.swift @@ -0,0 +1,95 @@ +import MultishellCore + +/// Every file's shown rows end to end, with the folds and notices between them; +/// see Docs/design/files/all-changes-tab.md. +public struct AllChangesDocument: Equatable, Sendable { + /// Lines kept either side of a change, as `git diff` keeps them. + static let contextLines = 3 + /// A shorter run of unchanged lines shows whole: its fold row would save little. + static let shortestFold = 4 + + /// Unified's rows, or Split's right side, the file on disk: what find searches. + public let text: DiffDisplayText + /// Split's left side, row for row with `text`; `nil` in Unified. + let committedText: DiffDisplayText? + public let sections: [AllChangesSection] + /// In document order. + let gapItems: [AllChangesGapItem] + /// The same by file, which each file's view and estimate ask for as the list scrolls. + private let gapItemsBySection: [Int: [AllChangesGapItem]] + /// Each file's section, which the sticky header asks after on every scroll frame. + private let sectionByPath: [String: Int] + public let lineCounts: FileLineCounts + + /// Split's two sides as a split view takes them; `nil` in Unified. + var split: SplitDiff? { + committedText.map { SplitDiff(committed: $0, onDisk: text) } + } + + /// Whether a shown row changed or a file waits to be read, which the bar's + /// arrows step between. + public var hasChanges: Bool { + !text.changeStarts.isEmpty || gapItems.contains { $0.kind == .notice(.reading) } + } + + private init( + text: DiffDisplayText, + committedText: DiffDisplayText?, + sections: [AllChangesSection], + gapItems: [AllChangesGapItem], + lineCounts: FileLineCounts, + ) { + self.text = text + self.committedText = committedText + self.sections = sections + self.gapItems = gapItems + gapItemsBySection = Dictionary(grouping: gapItems, by: \.section) + sectionByPath = Dictionary(keepingFirst: sections.enumerated().map { ($1.path, $0) }) + self.lineCounts = lineCounts + } + + /// `collapsed` names files showing their header alone; `heldOpen` the lines + /// each file keeps out of its folds. + init( + _ reading: AllChangesReading, + collapsed: Set, + heldOpen: [String: [AllChangesLineSpan]], + layout: FileTabLayout = .unified, + ) { + var builder = AllChangesDocumentBuilder(layout: layout) + for file in reading.files { + builder.add( + file, + isCollapsed: collapsed.contains(file.path), + heldOpen: heldOpen[file.path] ?? [], + ) + } + self.init( + text: builder.text(marksStaging: true), + committedText: builder.committedText(marksStaging: true), + sections: builder.sections, + gapItems: builder.gapItems, + lineCounts: reading.lineCounts, + ) + } + + /// The file a row is in, by halving over the sections' rows. + public func section(atRow row: Int) -> Int? { + let index = sections.partitioningIndex { $0.headerAfterRow >= row } + return index > 0 ? index - 1 : nil + } + + /// Whether a file's view shows Split's two columns; one shown whole is + /// Unified across them. + public func showsSplitColumns(ofSection index: Int) -> Bool { + split != nil && !sections[index].isShownWhole + } + + public func gapItems(ofSection index: Int) -> [AllChangesGapItem] { + gapItemsBySection[index] ?? [] + } + + public func section(at path: String) -> Int? { + sectionByPath[path] + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocumentBuilder.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocumentBuilder.swift new file mode 100644 index 000000000..ea1e093da --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocumentBuilder.swift @@ -0,0 +1,193 @@ +import MultishellCore + +/// Lays the files end to end into `AllChangesDocument`'s rows and gaps: Unified's +/// one text, or Split's two row for row, a file only added or removed padded opposite. +struct AllChangesDocumentBuilder { + /// Unified's rows, or Split's right side. + private var lines: [DiffLine] = [] + /// Split's left side, `nil` in Unified. + private var committedLines: [DiffLine]? + private var changeBreaks: Set = [] + private(set) var sections: [AllChangesSection] = [] + private(set) var gapItems: [AllChangesGapItem] = [] + /// Whether any file's rows marked staging, which every file read under one base shares. + private var marksStaging: Bool? + + init(layout: FileTabLayout) { + committedLines = layout == .split ? [] : nil + } + + /// Rows within the context of a change or held open, and every row of an + /// unchanged run too short to fold. + private static func keptRows(of lines: [DiffLine], heldOpen: [AllChangesLineSpan]) -> [Bool] { + var kept = [Bool](repeating: false, count: lines.count) + let held = AllChangesHeldLines(heldOpen) + for (row, line) in lines.enumerated() { + if line.kind != .context { + let first = max(0, row - AllChangesDocument.contextLines) + let last = min(lines.count - 1, row + AllChangesDocument.contextLines) + for near in first...last { kept[near] = true } + } else if held.holds(line) { + kept[row] = true + } + } + var row = 0 + while row < lines.count { + guard !kept[row] else { + row += 1 + continue + } + var end = row + while end < lines.count, !kept[end] { end += 1 } + if end - row < AllChangesDocument.shortestFold { + for short in row.. AllChangesNotice { + switch content { + case .image: return .image + case .pastRowCap: return .pastRowCap + case .unread: return .reading + + case .read(let reading): + switch reading.content { + case .binary(let bytes): return .binary(bytes: bytes) + case .image: return .image + case .missing: return .missing + case .released, .releasedFollowingStatus: return .reading + case .text: return .empty + case .tooLarge(let bytes): return .tooLarge(bytes: bytes) + case .unreadable: return .unreadable + } + } + } + + /// One split row as the folds judge it: unchanged only where both sides are, + /// numbered by the left's committed line and the right's line on disk. + private static func pairedRows( + _ committed: DiffDisplayText, + _ onDisk: DiffDisplayText, + ) -> [DiffLine] { + zip(committed.lines, onDisk.lines).map { left, right in + DiffLine( + kind: left.kind == .context && right.kind == .context ? .context : .added, + oldNumber: left.oldNumber, + newNumber: right.newNumber, + text: "", + ) + } + } + + private static func text( + _ lines: [DiffLine], + marksStaging: Bool, + changeBreaks: Set, + ) -> DiffDisplayText { + DiffDisplayText( + lines, + wholeSides: [], + committedDigest: 0, + marksStaging: marksStaging, + changeBreaks: changeBreaks, + ) + } + + /// Unified's text, or Split's right side. + func text(marksStaging fallback: Bool) -> DiffDisplayText { + Self.text(lines, marksStaging: marksStaging ?? fallback, changeBreaks: changeBreaks) + } + + /// Split's left side, `nil` in Unified. + func committedText(marksStaging fallback: Bool) -> DiffDisplayText? { + committedLines.map { lines in + Self.text(lines, marksStaging: marksStaging ?? fallback, changeBreaks: changeBreaks) + } + } + + mutating func add(_ file: AllChangesFile, isCollapsed: Bool, heldOpen: [AllChangesLineSpan]) { + let section = sections.count + let headerAfterRow = lines.count - 1 + let rows = isCollapsed ? nil : file.rows + // A file with no line changed has no split; its unchanged rows read alike on both sides. + let onDisk = + committedLines == nil ? rows?.displayText : rows.map { $0.split?.onDisk ?? $0.displayText } + let committed = committedLines == nil ? nil : rows.map { $0.split?.committed ?? $0.displayText } + var fileRows: [Int] = [] + // Shown Unified across both columns in the list, but row for row in the split's + // sides too, so the arrows reach it; find, on the right, misses a deleted file. + let isShownWhole = committedLines != nil && rows?.isOneSided == true + if let rows, let onDisk { + marksStaging = marksStaging ?? rows.displayText.marksStaging + if rows.lines.isEmpty { + gapItems.append( + AllChangesGapItem(afterRow: headerAfterRow, section: section, kind: .notice(.empty)) + ) + } else { + changeBreaks.insert(lines.count) + fileRows = append(onDisk, beside: committed, of: section, heldOpen: heldOpen) + } + } else if !isCollapsed { + gapItems.append( + AllChangesGapItem( + afterRow: headerAfterRow, + section: section, + kind: .notice(Self.notice(for: file.content)), + ) + ) + } + sections.append( + AllChangesSection( + change: file.change, + lineCounts: file.lineCounts, + isCollapsed: isCollapsed, + rows: (headerAfterRow + 1).. [Int] { + let judged = committed.map { Self.pairedRows($0, text) } ?? text.lines + let kept = Self.keptRows(of: judged, heldOpen: heldOpen) + var fileRows: [Int] = [] + var row = 0 + while row < text.lines.count { + guard !kept[row] else { + fileRows.append(row) + lines.append(text.uncutLine(ofRow: row)) + if let committed { committedLines?.append(committed.uncutLine(ofRow: row)) } + row += 1 + continue + } + var end = row + while end < text.lines.count, !kept[end] { end += 1 } + let numbers = text.lines[row.. Bool { + inputs.reading == self.inputs.reading && inputs.collapsed == self.inputs.collapsed + && inputs.layout == self.inputs.layout && heldOpen == self.heldOpen + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocumentInputs.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocumentInputs.swift new file mode 100644 index 000000000..8de1b9323 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesDocumentInputs.swift @@ -0,0 +1,13 @@ +import MultishellCore + +/// What an All changes tab's document is built from. The lines held open are +/// kept as their sources, comparing which costs less than working them out. +struct AllChangesDocumentInputs: Equatable { + let reading: AllChangesReading + let collapsed: Set + let openedFolds: [String: [AllChangesLineSpan]] + let reviewComments: [ReviewComment] + let reviewComposer: ReviewComposer? + let scope: ChangeScope? + let layout: FileTabLayout +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesFile.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesFile.swift new file mode 100644 index 000000000..066e1c236 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesFile.swift @@ -0,0 +1,35 @@ +/// One file of the All changes tab: how the Changes list counts it and what +/// its read gave, if it was read. +struct AllChangesFile: Equatable, Sendable { + let change: AllChangesFileChange + let content: AllChangesFileContent + /// What the file looked like when read, `nil` for gone, so an event in its + /// folder reads it again only where it moved. + let signature: FileSignature? + /// Rows kept from a read that a change since has outdated, away from the + /// screen; read again as it nears it. + var isStale = false + + var path: String { change.path } + + /// The file tab's reading of it, where it was read. + var reading: FileTabReading? { + if case .read(let reading) = content { reading } else { nil } + } + + /// What its header counts: its rows', or the Changes list's where it has none + /// or they are stale and count an older comparison. + var lineCounts: FileLineCounts? { + isStale ? change.lineCounts : rows?.lineCounts ?? change.lineCounts + } + + /// Whether it shows rows to place a card under, or will once read; a notice + /// or a file past the row cap places none. + var holdsOrAwaitsRows: Bool { rows != nil || content == .unread } + + /// The rows, where the read gave some. + var rows: FileTabRows? { + guard case .text(let rows) = reading?.content else { return nil } + return rows + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileChange+Location.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileChange+Location.swift new file mode 100644 index 000000000..a7af11883 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileChange+Location.swift @@ -0,0 +1,14 @@ +import MultishellCore + +/// The header's folder and name, split by scalar as the tree splits: a name +/// starting with a combining mark would join the slash before it. +extension AllChangesFileChange { + /// Empty at the worktree's root. + public var folder: String { + path.slashSeparatedParts.dropLast().joined(separator: "/") + } + + public var fileName: String { + path.slashSeparatedParts.last.map(String.init) ?? path + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileChange.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileChange.swift new file mode 100644 index 000000000..521cee5f4 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileChange.swift @@ -0,0 +1,11 @@ +import MultishellGitKit + +/// One file as the Changes list counts it: what the header's letter and, for a +/// file with no rows to count, its `+n −n` come from. +public struct AllChangesFileChange: Hashable, Sendable { + /// Relative to the worktree. + public let path: String + public let kind: StatusChange.Kind + /// `nil` for a change git scores no lines for, a binary file's. + let lineCounts: FileLineCounts? +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileContent.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileContent.swift new file mode 100644 index 000000000..6df9f25dc --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileContent.swift @@ -0,0 +1,13 @@ +/// What the All changes tab holds of one file. +enum AllChangesFileContent: Equatable, Sendable { + /// A file its name types as an image: its notice alone, the bytes left for + /// its own tab to read. + case image + /// Past the rows the tab holds in all, so only its header shows; see + /// Docs/design/files/all-changes-tab.md. + case pastRowCap + /// What a file tab's read of it gives, so it reads the same in both. + case read(FileTabReading) + /// Listed since the last read, which has yet to reach it. + case unread +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileSlice+ChangedRows.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileSlice+ChangedRows.swift new file mode 100644 index 000000000..69846041f --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileSlice+ChangedRows.swift @@ -0,0 +1,18 @@ +import MultishellCore + +/// The Changes rotor's rows in one file: in Split a removed line sits on the +/// left beside the right's padding, so either side's change counts. +extension AllChangesFileSlice { + public func changedRow(_ direction: CycleDirection, from row: Int?) -> Int? { + let onDisk = text.changedRow(direction, from: row) + guard let committed = committedText?.changedRow(direction, from: row) else { return onDisk } + guard let onDisk else { return committed } + return direction == .next ? min(onDisk, committed) : max(onDisk, committed) + } + + /// Whether `row`'s change is Split's left side's alone. + public func changeIsCommittedSideOnly(atRow row: Int) -> Bool { + guard let committedText, !text.lines[row].isChange else { return false } + return committedText.lines[row].isChange + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileSlice.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileSlice.swift new file mode 100644 index 000000000..442230b29 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesFileSlice.swift @@ -0,0 +1,17 @@ +/// One file's part of the document for its own view: its shown rows and what +/// sits between them, numbered by its own rows. +public struct AllChangesFileSlice: Equatable, Sendable { + /// The document's section it is. + public let section: Int + /// The rows shown: Unified's, or Split's right side. + public let text: DiffDisplayText + /// Split's left side, row for row; `nil` in Unified or for a file shown whole. + public let committedText: DiffDisplayText? + /// Its folds and notices, each under a row of `text`, -1 above the first. + public let gapItems: [AllChangesGapItem] + + /// Its two sides as a split view takes them; `nil` where it is Unified. + public var split: SplitDiff? { + committedText.map { SplitDiff(committed: $0, onDisk: text) } + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesGapItem.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesGapItem.swift new file mode 100644 index 000000000..cad37aae1 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesGapItem.swift @@ -0,0 +1,14 @@ +/// What sits between two rows of the All changes tab's text, hosted in a gap +/// as a review card is, so find, copy and the steps see rows only. +public struct AllChangesGapItem: Hashable, Sendable { + public enum Kind: Hashable, Sendable { + /// Unchanged rows of the file left out, by the file's own lines they hold. + case fold(lines: ClosedRange) + case notice(AllChangesNotice) + } + + /// The document row it sits under, -1 above the first. + public let afterRow: Int + public let section: Int + public let kind: Kind +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesHeldLines.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesHeldLines.swift new file mode 100644 index 000000000..f79da5aea --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesHeldLines.swift @@ -0,0 +1,37 @@ +import MultishellCore + +/// A file's held-open spans merged by side, so a build asks after each line by +/// halving them rather than walking every one: a comment holds five lines. +struct AllChangesHeldLines { + private let committed: [ClosedRange] + private let onDisk: [ClosedRange] + + init(_ spans: [AllChangesLineSpan]) { + committed = Self.merged(spans.filter { $0.side == .committed }.map(\.lines)) + onDisk = Self.merged(spans.filter { $0.side == .onDisk }.map(\.lines)) + } + + private static func number(_ number: Int?, isIn ranges: [ClosedRange]) -> Bool { + guard let number else { return false } + let index = ranges.partitioningIndex { $0.upperBound >= number } + return ranges.indices.contains(index) && ranges[index].lowerBound <= number + } + + /// Ascending and apart, overlapping or touching ranges joined. + private static func merged(_ ranges: [ClosedRange]) -> [ClosedRange] { + var merged: [ClosedRange] = [] + for range in ranges.sorted(by: { $0.lowerBound < $1.lowerBound }) { + if let last = merged.last, range.lowerBound <= last.upperBound + 1 { + merged[merged.count - 1] = last.lowerBound...max(last.upperBound, range.upperBound) + } else { + merged.append(range) + } + } + return merged + } + + func holds(_ line: DiffLine) -> Bool { + Self.number(line.number(on: .committed), isIn: committed) + || Self.number(line.number(on: .onDisk), isIn: onDisk) + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesLineSpan.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesLineSpan.swift new file mode 100644 index 000000000..1ce38039e --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesLineSpan.swift @@ -0,0 +1,8 @@ +import MultishellCore + +/// Lines of one file kept open inside a fold, by their number on one side: a +/// fold the user opened, or a comment's lines and two either side. +struct AllChangesLineSpan: Hashable, Sendable { + let side: DiffSide + let lines: ClosedRange +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesListCacheEntry.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesListCacheEntry.swift new file mode 100644 index 000000000..8dd47c349 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesListCacheEntry.swift @@ -0,0 +1,8 @@ +import MultishellGitKit + +/// A worktree's changes as git listed them and in the Changes list's order, so a +/// status landing that lists the same is not sorted again. +struct AllChangesListCacheEntry { + let changes: [StatusChange] + let list: [AllChangesFileChange] +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesNotice.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesNotice.swift new file mode 100644 index 000000000..65a597420 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesNotice.swift @@ -0,0 +1,24 @@ +/// Why a file of the All changes tab shows its header and no rows. +public enum AllChangesNotice: Hashable, Sendable { + case binary(bytes: Int) + /// A file with no lines, an empty file added. + case empty + case image + case missing + /// Past the rows the tab holds in all. + case pastRowCap + /// Listed, its read still to come. + case reading + /// Past a file tab's cap, on disk or on the committed side. + case tooLarge(bytes: Int) + case unreadable + + /// A file that is nowhere has nothing to open, as in its file tab. + public var action: AllChangesNoticeAction? { + switch self { + case .image, .pastRowCap: .openFile + case .binary, .tooLarge, .unreadable: .openInEditor + case .empty, .missing, .reading: nil + } + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesNoticeAction.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesNoticeAction.swift new file mode 100644 index 000000000..b8ab19ef4 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesNoticeAction.swift @@ -0,0 +1,6 @@ +/// The button beside a notice in the All changes tab: the file's own tab where +/// that shows what the notice cannot, else the editor, as a file tab offers it. +public enum AllChangesNoticeAction: Hashable, Sendable { + case openFile + case openInEditor +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesOrder.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesOrder.swift new file mode 100644 index 000000000..24b5df9bb --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesOrder.swift @@ -0,0 +1,49 @@ +import Foundation +import MultishellCore +import MultishellGitKit + +/// The files the All changes tab lists, in the Changes list's order: depth +/// first, folders before files, names as Finder sorts them. +enum AllChangesOrder { + /// One entry a path, a path listed twice combined as the Changes list counts + /// it; a nested repository's entry, which ends in `/`, is left out. + static func files(of changes: [StatusChange]) -> [AllChangesFileChange] { + var byPath: [String: AllChangesFileChange] = [:] + for change in changes where !change.path.hasSuffix("/") { + let counts = FileLineCounts(change.lines) + guard let listed = byPath[change.path] else { + byPath[change.path] = AllChangesFileChange( + path: change.path, + kind: change.kind, + lineCounts: counts, + ) + continue + } + byPath[change.path] = AllChangesFileChange( + path: change.path, + kind: listed.kind.combined(with: change.kind), + lineCounts: listed.lineCounts.map { total in counts.map { total + $0 } ?? total } + ?? counts, + ) + } + let parts = byPath.keys.map { ($0, $0.slashSeparatedParts) } + return parts.sorted { isBefore($0.1, $1.1) }.compactMap { byPath[$0.0] } + } + + /// Where the two paths first part ways, a folder goes before a file and + /// otherwise the names decide, as the tree's siblings sort. + private static func isBefore(_ first: [Substring], _ second: [Substring]) -> Bool { + for index in 0.. second.count + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesReadPlan.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesReadPlan.swift new file mode 100644 index 000000000..29765e53d --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesReadPlan.swift @@ -0,0 +1,51 @@ +import MultishellCore + +/// Which files a read of the All changes tab reads, and what the rest land as. +struct AllChangesReadPlan { + /// The last read under the same base, `nil` under another. + let kept: AllChangesReading? + let stale: AllChangesStaleness + /// The files near the screen; `nil` reads every file. + let near: Set? + let imageRule: ImageRule + + /// What a file lands as without a read; `nil` where it is read now. An image + /// shows its notice alone, its bytes, up to 32 MiB a side, left unread. + func landsWithoutRead( + _ change: AllChangesFileChange, + _ signature: FileSignature?, + ) + -> AllChangesFile? + { + guard !imageRule.opensAsImage(change.path) else { + return AllChangesFile(change: change, content: .image, signature: signature) + } + if let unchanged = unchangedSinceLast(change, signature) { return unchanged } + guard let near, !near.contains(change.path) else { return nil } + guard let last = kept?.file(at: change.path), case .read = last.content else { + return AllChangesFile(change: change, content: .unread, signature: signature) + } + // Away from the screen: its last rows, kept stale. + return AllChangesFile( + change: change, + content: last.content, + signature: last.signature, + isStale: true, + ) + } + + /// The last read of a file whose change and signature stand and that no event + /// named since. + private func unchangedSinceLast( + _ change: AllChangesFileChange, + _ signature: FileSignature?, + ) + -> AllChangesFile? + { + guard let last = kept?.file(at: change.path), last.change == change, + last.signature == signature, + case .read = last.content, !last.isStale, !stale.contains(change.path) + else { return nil } + return last + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesReadSlots.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesReadSlots.swift new file mode 100644 index 000000000..8b243e38a --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesReadSlots.swift @@ -0,0 +1,42 @@ +/// The reader's files as they land out of order, and the row cap: the first file +/// whose rows before it reach the cap, and every file after, shows its header alone. +struct AllChangesReadSlots { + private var files: [AllChangesFile?] + private let rowCap: Int + private(set) var capIndex: Int? + private var settled = 0 + private var heldRows = 0 + private var landedRows = 0 + + var isCapped: Bool { capIndex != nil } + /// Rows landed in any order reach the cap, so every file not yet read lies + /// past it whatever an earlier file still out holds. + var reachesRowCap: Bool { landedRows >= rowCap } + + init(count: Int, rowCap: Int) { + files = Array(repeating: nil, count: count) + self.rowCap = rowCap + } + + mutating func land(_ file: AllChangesFile, at index: Int) { + files[index] = file + landedRows += file.rows?.lines.count ?? 0 + // Set as the cap is reached, not on the next file: the reader starts no + // read past it, so that file may never land. + while capIndex == nil, settled < files.count, let landed = files[settled] { + heldRows += landed.rows?.lines.count ?? 0 + settled += 1 + if heldRows >= rowCap { capIndex = settled } + } + } + + /// Every listed file, past the cap or not yet read as such. + func files(of listed: [(AllChangesFileChange, FileSignature?)]) -> [AllChangesFile] { + listed.enumerated().map { index, entry in + if let capIndex, index >= capIndex { + return AllChangesFile(change: entry.0, content: .pastRowCap, signature: entry.1) + } + return files[index] ?? AllChangesFile(change: entry.0, content: .unread, signature: entry.1) + } + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesReader.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesReader.swift new file mode 100644 index 000000000..0348e1435 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesReader.swift @@ -0,0 +1,138 @@ +import Foundation +import MultishellCore +import MultishellGitKit + +/// Reads every changed file of a worktree for the All changes tab, each as a +/// file tab reads it; see Docs/design/files/all-changes-tab.md. +enum AllChangesReader { + /// The rows held across every file before the rest show their header + /// alone; measured in Docs/design/files/all-changes-tab.md. + static let rowCap = 200_000 + /// One file reads alone in fewer git runs than the batch's: 4 against 6, measured. + private static let fewestFilesBatched = 2 + + /// `previous` keeps each file `stale` does not name whose change and + /// signature stand; a folder, a submodule's, is left out as Changes leaves it. + static func read( + _ changes: [AllChangesFileChange], + in worktree: URL, + git: WorktreeGit, + diffAlgorithm: DiffAlgorithm, + since base: DefaultBranch?, + previous: AllChangesReading?, + rereading stale: AllChangesStaleness, + imageRule: ImageRule, + near: Set? = nil, + rowCap: Int = rowCap, + ) async -> (reading: AllChangesReading, filesRead: Int) { + // Rows diffed against another base are kept for no file, near or not. + let kept = previous?.baseName == base?.shortName ? previous : nil + let plan = AllChangesReadPlan(kept: kept, stale: stale, near: near, imageRule: imageRule) + let listed = await files(of: changes, in: worktree) + let landingsWithoutRead = listed.map(plan.landsWithoutRead) + let toRead = zip(listed, landingsWithoutRead).filter { $1 == nil }.map(\.0) + let bases = await bases( + of: toRead, + in: worktree, + since: base, + diffAlgorithm: diffAlgorithm, + imageRule: imageRule, + git: git, + ) + var slots = AllChangesReadSlots(count: listed.count, rowCap: rowCap) + var filesRead = 0 + await withTaskGroup(of: (Int, AllChangesFile).self) { group in + var next = 0 + var inFlight = 0 + while true { + // A steady few in flight: a batch waited on its slowest file. + while inFlight < WorktreeGit.runsAtOnce, next < listed.count, !slots.reachesRowCap { + let index = next + next += 1 + let (change, signature) = listed[index] + if let file = landingsWithoutRead[index] { + slots.land(file, at: index) + continue + } + let last = kept?.file(at: change.path)?.reading + filesRead += 1 + inFlight += 1 + group.addTask { + let reading = await FileTabReader.read( + path: change.path, + in: worktree, + git: git, + diffAlgorithm: diffAlgorithm, + since: base, + previous: last, + imageRule: imageRule, + bases: bases, + ) + return ( + index, AllChangesFile(change: change, content: .read(reading), signature: signature), + ) + } + } + guard inFlight > 0 else { + if next < listed.count, !slots.isCapped { continue } + break + } + guard let (index, file) = await group.next() else { break } + inFlight -= 1 + slots.land(file, at: index) + } + } + let files = slots.files(of: listed) + return ( + AllChangesReading(listed: changes, files: files, baseName: base?.shortName), filesRead, + ) + } + + /// What the files read count from, asked of git once; `nil` for one file, which + /// reads alone in fewer runs. + private static func bases( + of toRead: [(AllChangesFileChange, FileSignature?)], + in worktree: URL, + since base: DefaultBranch?, + diffAlgorithm: DiffAlgorithm, + imageRule: ImageRule, + git: WorktreeGit, + ) async -> WorktreeDiffBases? { + guard toRead.count >= fewestFilesBatched else { return nil } + return await WorktreeDiffBases.resolve( + in: worktree, + since: base, + paths: toRead.map(\.0.path), + diffable: diffable(toRead, imageRule), + diffAlgorithm: diffAlgorithm, + git: git, + ) + } + + /// Each change's file and its signature, a folder left out. + private static func files( + of changes: [AllChangesFileChange], + in worktree: URL, + ) async -> [(AllChangesFileChange, FileSignature?)] { + await runOnDispatch { + changes.compactMap { change -> (AllChangesFileChange, FileSignature?)? in + let signature = FileSignature.of(worktree.appending(path: change.path)) + guard signature?.isFolder != true else { return nil } + return (change, signature) + } + } + } + + /// The files worth diffing up front: text under the cap, by name and size on disk. + private static func diffable( + _ files: [(AllChangesFileChange, FileSignature?)], + _ imageRule: ImageRule, + ) -> Set { + Set( + files.filter { change, signature in + !imageRule.opensAsImage(change.path) && (signature?.size ?? 0) <= FileTabReader.sizeLimit + } + .map(\.0.path) + ) + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesReading+FilesTouched.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesReading+FilesTouched.swift new file mode 100644 index 000000000..18a344753 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesReading+FilesTouched.swift @@ -0,0 +1,22 @@ +import MultishellCore + +extension AllChangesReading { + /// The read files a watcher batch named, by path or by the folder holding them; + /// one unread or stale is read once near, one past the cap or an image as the list moves. + func filesTouched(by changed: [String]) -> [AllChangesFile] { + // Substrings of each path, so a batch over thousands of files builds no strings. + let changed = Set(changed.map { $0[...] }) + return files.filter { file in + guard case .read = file.content, !file.isStale else { return false } + let path = file.path + let folder = path.unicodeScalars.lastIndex(of: "/").map { path[..<$0] } ?? "" + return changed.contains(path[...]) || changed.contains(folder) + } + } + + /// The files inside repositories whose git moved, by their folders: the + /// rest of the worktree's diffs stand. + func paths(inRepositories folders: Set) -> Set { + Set(files.map(\.path).filter { path in folders.contains(where: path.isPath(under:)) }) + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesReading.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesReading.swift new file mode 100644 index 000000000..4aa77a6d7 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesReading.swift @@ -0,0 +1,46 @@ +import MultishellCore + +/// An All changes tab's last read, runtime only: every listed file in the +/// Changes list's order. +struct AllChangesReading: Equatable, Sendable { + /// The list the read was given, so a status read listing the same reads nothing. + let listed: [AllChangesFileChange] + let files: [AllChangesFile] + /// The base the files were diffed against, Branch's; `nil` under Modified. + let baseName: String? + /// Each file's place in `files`: the view asks after files by path as it scrolls. + private let indexByPath: [String: Int] + + /// What the bar counts: every file's rows, or the list's count where none. + var lineCounts: FileLineCounts { + files.reduce(FileLineCounts(insertions: 0, deletions: 0)) { total, file in + file.lineCounts.map { total + $0 } ?? total + } + } + + init(listed: [AllChangesFileChange], files: [AllChangesFile], baseName: String? = nil) { + self.listed = listed + self.files = files + self.baseName = baseName + indexByPath = Dictionary(keepingFirst: files.enumerated().map { ($1.path, $0) }) + } + + static func == (lhs: Self, rhs: Self) -> Bool { + lhs.listed == rhs.listed && lhs.files == rhs.files && lhs.baseName == rhs.baseName + } + + func file(at path: String) -> AllChangesFile? { + indexByPath[path].map { files[$0] } + } + + /// Whether `path` waits unread, away from the screen when the read ran. + func isUnread(_ path: String) -> Bool { + file(at: path)?.content == .unread + } + + /// Whether `path` is owed a read once near the screen: unread, or its rows stale. + func owesRead(_ path: String) -> Bool { + guard let file = file(at: path) else { return false } + return file.isStale || file.content == .unread + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesSection.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesSection.swift new file mode 100644 index 000000000..b27f3e1c7 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesSection.swift @@ -0,0 +1,60 @@ +import MultishellCore + +/// One file of the All changes tab as its text lays it out. +public struct AllChangesSection: Equatable, Sendable { + public let change: AllChangesFileChange + /// Its rows' counts where it has rows, else the Changes list's. + public let lineCounts: FileLineCounts? + public let isCollapsed: Bool + /// The document rows its shown rows take, empty where it shows none. + public let rows: Range + /// Each of those rows' index in the file's own rows, ascending. + let fileRows: [Int] + /// The file's own rows, folded or not, which highlighting, anchoring and a + /// saved scroll read; `nil` where it has none. + public let fileText: DiffDisplayText? + /// Split's left side of the file, row for row with `fileText`; `nil` in Unified. + public let fileCommittedText: DiffDisplayText? + /// In Split, a file only added or removed, its Unified rows in `fileText` + /// shown across both columns and none in either. + public let isShownWhole: Bool + /// Where its header sits: under this document row, -1 above the first. + let headerAfterRow: Int + + public var path: String { change.path } + + /// One column's side of the file: Split's left for the committed side. + func sideText(on side: DiffSide?) -> DiffDisplayText? { + side == .committed ? fileCommittedText ?? fileText : fileText + } + + /// The document row showing `fileRow`, else the next one shown after it. + func documentRow(atOrAfterFileRow fileRow: Int) -> Int? { + let index = fileRows.partitioningIndex { $0 >= fileRow } + return fileRows.indices.contains(index) ? rows.lowerBound + index : nil + } + + func fileRow(ofDocumentRow row: Int) -> Int? { + rows.contains(row) ? fileRows[row - rows.lowerBound] : nil + } + + /// The row a drag from `start` toward `end` reaches before a fold, whose + /// hidden lines it never takes in. + func documentRow(from start: Int, towardBeforeFold end: Int) -> Int { + let step = end >= start ? 1 : -1 + var row = start + while row != end, let here = fileRow(ofDocumentRow: row), + let next = fileRow(ofDocumentRow: row + step), abs(next - here) == 1 + { + row += step + } + return row + } + + /// The document row showing `fileRow`, `nil` where a fold hides it. + func documentRow(ofFileRow fileRow: Int) -> Int? { + let index = fileRows.partitioningIndex { $0 >= fileRow } + guard fileRows.indices.contains(index), fileRows[index] == fileRow else { return nil } + return rows.lowerBound + index + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesStaleFiles.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesStaleFiles.swift new file mode 100644 index 000000000..d84eb5dd2 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesStaleFiles.swift @@ -0,0 +1,23 @@ +import MultishellCore + +/// What each All changes tab's next read must read again, gathered between +/// reads and taken by the read that starts. +struct AllChangesStaleFiles { + private var staleness: [AllChangesTab.ID: AllChangesStaleness] = [:] + + mutating func mark(_ stale: AllChangesStaleness, in id: AllChangesTab.ID) { + staleness[id] = (staleness[id] ?? .nothing).adding(stale) + } + + func pending(_ id: AllChangesTab.ID) -> AllChangesStaleness { + staleness[id] ?? .nothing + } + + mutating func take(_ id: AllChangesTab.ID) -> AllChangesStaleness { + staleness.removeValue(forKey: id) ?? .nothing + } + + mutating func keep(only ids: Set) { + staleness = staleness.filter { ids.contains($0.key) } + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesStaleness.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesStaleness.swift new file mode 100644 index 000000000..fe1afb25f --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesStaleness.swift @@ -0,0 +1,23 @@ +/// Which files an All changes tab's next read reads again rather than keeps. +enum AllChangesStaleness: Equatable, Sendable { + /// A git change, a new scope, algorithm or base: every diff may have moved. + case everything + /// Files an event or the status read moved; the rest keep their rows. + case paths(Set) + + static let nothing = Self.paths([]) + + func contains(_ path: String) -> Bool { + switch self { + case .everything: true + case .paths(let paths): paths.contains(path) + } + } + + func adding(_ other: Self) -> Self { + switch (self, other) { + case (.everything, _), (_, .everything): .everything + case (.paths(let paths), .paths(let others)): .paths(paths.union(others)) + } + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesSteps.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesSteps.swift new file mode 100644 index 000000000..838480f88 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesSteps.swift @@ -0,0 +1,52 @@ +import MultishellCore + +/// The All changes tab's arrows across its files: each change of each file is +/// one stop, ordered by where it starts in the list. +public struct AllChangesSteps: Sendable { + /// A change: its file's section and its first row in that file's view. + public struct Stop: Equatable, Sendable { + public let section: Int + public let row: Int + + public init(section: Int, row: Int) { + self.section = section + self.row = row + } + } + + public struct Placed: Sendable { + public let stop: Stop + /// Where it starts in the list. + public let top: Double + + public init(stop: Stop, top: Double) { + self.stop = stop + self.top = top + } + } + + private let placed: [Placed] + + public init(_ placed: [Placed]) { + self.placed = placed.sorted { $0.top < $1.top } + } + + /// The stop a step lands on from `origin`: the boxed stop's top, or with + /// nothing boxed the clip's top, where a stop at it is the first step. + public func stop(_ direction: CycleDirection, from origin: Double, isBoxed: Bool) -> Stop? { + switch direction { + case .next: + placed.first { isBoxed ? $0.top > origin : $0.top >= origin }?.stop + + case .previous: + placed.last { $0.top < origin }?.stop + } + } + + public func changeSteps(from origin: Double, isBoxed: Bool) -> ChangeSteps { + ChangeSteps( + hasNext: stop(.next, from: origin, isBoxed: isBoxed) != nil, + hasPrevious: stop(.previous, from: origin, isBoxed: isBoxed) != nil, + ) + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesText.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesText.swift new file mode 100644 index 000000000..21d483fa3 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesText.swift @@ -0,0 +1,39 @@ +import MultishellCore +import MultishellGitKit + +/// The All changes tab's words: its bar's count, a fold's label, why a file +/// shows no rows, and each file's change letter. +public enum AllChangesText { + public static func fileCount(_ count: Int) -> String { + t("all-changes.file-count", count) + } + + public static func foldTitle(_ lines: ClosedRange) -> String { + t("all-changes.show-unchanged", lines.count) + } + + public static func foldLines(_ lines: ClosedRange) -> String { + t("all-changes.fold-lines", lines.lowerBound, lines.upperBound) + } + + public static func notice(_ notice: AllChangesNotice) -> String { + switch notice { + case .binary(let bytes): FileTabNoticeText.message(for: .binary(bytes: bytes)) ?? "" + case .empty: t("all-changes.empty-file") + case .image: t("all-changes.image") + case .missing: FileTabNoticeText.message(for: .missing) ?? "" + case .pastRowCap: t("all-changes.past-row-cap") + case .reading: t("all-changes.reading") + case .tooLarge(let bytes): FileTabNoticeText.message(for: .tooLarge(bytes: bytes)) ?? "" + case .unreadable: FileTabNoticeText.message(for: .unreadable) ?? "" + } + } + + public static func letter(_ kind: StatusChange.Kind) -> String { + switch kind { + case .added: t("all-changes.letter-added") + case .deleted: t("all-changes.letter-deleted") + case .modified: t("all-changes.letter-modified") + } + } +} diff --git a/Sources/MultishellAppCore/Files/AllChanges/AllChangesTopFile.swift b/Sources/MultishellAppCore/Files/AllChanges/AllChangesTopFile.swift new file mode 100644 index 000000000..1803b9d78 --- /dev/null +++ b/Sources/MultishellAppCore/Files/AllChanges/AllChangesTopFile.swift @@ -0,0 +1,37 @@ +/// The file at the top of an All changes tab's view: what the Changes list +/// lights, and whether its header has scrolled away so a sticky copy shows. +public struct AllChangesTopFile: Equatable, Sendable { + public let path: String + public let isHeaderScrolledPast: Bool + /// How far the next file's header, scrolling up into the sticky copy, + /// pushes it up and out of the way. + public let pushedUp: Double + + /// Pushed up, the sticky copy reaches under the bar, where `.clipped()` hides + /// it but leaves it taking the bar's clicks (owner's report). + public var takesClicks: Bool { pushedUp == 0 } + + init(path: String, isHeaderScrolledPast: Bool) { + self.path = path + self.isHeaderScrolledPast = isHeaderScrolledPast + pushedUp = 0 + } + + /// From where the file's header bar and the next file's start in the + /// document, the scroll, and the bar's height. + public init( + path: String, + headerBarTop: Double?, + nextHeaderBarTop: Double?, + scrolledTo: Double, + barHeight: Double, + ) { + self.path = path + isHeaderScrolledPast = headerBarTop.map { scrolledTo > $0 } ?? false + guard isHeaderScrolledPast, let nextHeaderBarTop else { + pushedUp = 0 + return + } + pushedUp = max(0, barHeight - (nextHeaderBarTop - scrolledTo)) + } +} diff --git a/Sources/MultishellAppCore/Files/Diffs/DiffDisplayText+ChangeStep.swift b/Sources/MultishellAppCore/Files/Diffs/DiffDisplayText+ChangeStep.swift index 11837299e..1e6e3d471 100644 --- a/Sources/MultishellAppCore/Files/Diffs/DiffDisplayText+ChangeStep.swift +++ b/Sources/MultishellAppCore/Files/Diffs/DiffDisplayText+ChangeStep.swift @@ -43,7 +43,7 @@ extension DiffDisplayText { guard lines.indices.contains(row), lines[row].kind != .context else { return nil } let start = changeStarts[changeStarts.partitioningIndex { $0 > row } - 1] var end = row + 1 - while end < lines.count, lines[end].kind != .context { end += 1 } + while end < lines.count, lines[end].kind != .context, !changeBreaks.contains(end) { end += 1 } return start.. Int? { + switch direction { + case .next: + let start = min(lines.count, (row ?? -1) + 1) + return (start.., from previous: DiffDisplayText) -> Range? { - guard !previous.lines.isEmpty, !lines.isEmpty else { return nil } + /// A line this layout lacks gives an empty range at the next line it has, else the + /// end of the last before it; `rows` hold the search to one file of several. + func rangeOnSameLine( + _ range: Range, + from previous: DiffDisplayText, + inRows rows: Range? = nil, + fromRows previousRows: Range? = nil, + ) -> Range? { + let rows = rows ?? lines.indices + let previousRows = previousRows ?? previous.lines.indices + guard !previousRows.isEmpty, !rows.isEmpty else { return nil } let row = previous.row(atOffset: range.lowerBound) + guard previousRows.contains(row) else { return nil } let line = previous.lines[row] - let target = lines.indices.first { candidate in + let target = rows.first { candidate in let other = lines[candidate] return line.newNumber.map { other.newNumber == $0 } ?? (other.newNumber == nil && other.oldNumber == line.oldNumber) } guard let target else { - let next = previous.lines[row...].first { $0.newNumber != nil }?.newNumber - if let nextRow = next.flatMap({ number in - lines.indices.first { lines[$0].newNumber == number } + let next = previous.lines[row.. DiffLine { + let line = lines[row] + guard cutRemainders[row] != nil else { return line } + return DiffLine( + kind: line.kind, + oldNumber: line.oldNumber, + newNumber: line.newNumber, + text: uncutText(ofRow: row), + isStaged: line.isStaged, + changedParts: line.changedParts, + ) + } + func uncutText(ofRow row: Int) -> String { guard let remainder = cutRemainders[row] else { return lines[row].text } return lines[row].text.dropLast() + remainder diff --git a/Sources/MultishellAppCore/Files/Diffs/DiffDisplayText.swift b/Sources/MultishellAppCore/Files/Diffs/DiffDisplayText.swift index f1d791b1e..5062946ab 100644 --- a/Sources/MultishellAppCore/Files/Diffs/DiffDisplayText.swift +++ b/Sources/MultishellAppCore/Files/Diffs/DiffDisplayText.swift @@ -20,6 +20,9 @@ public struct DiffDisplayText: Equatable, Sendable { public let rowStarts: [Int] /// The first row of each change, ascending: what a step lands on. let changeStarts: [Int] + /// Rows a change starts at whatever is above them, so the All changes tab's + /// files, put end to end, keep their changes apart. + let changeBreaks: Set /// The sides every line of which these rows hold: a split side holds one, and /// a parse of the other's partial text would colour it wrong. let wholeSides: [DiffSide] @@ -40,8 +43,15 @@ public struct DiffDisplayText: Equatable, Sendable { } /// `committedDigest` where already hashed, or for rows missing some committed lines. - init(_ lines: [DiffLine], wholeSides: [DiffSide], committedDigest: Int?, marksStaging: Bool) { + init( + _ lines: [DiffLine], + wholeSides: [DiffSide], + committedDigest: Int?, + marksStaging: Bool, + changeBreaks: Set = [], + ) { self.wholeSides = wholeSides + self.changeBreaks = changeBreaks self.marksStaging = marksStaging var starts: [Int] = [] starts.reserveCapacity(lines.count) @@ -68,7 +78,8 @@ public struct DiffDisplayText: Equatable, Sendable { self.cutRemainders = remainders self.rowStarts = starts self.changeStarts = capped.indices.filter { row in - capped[row].kind != .context && (row == 0 || capped[row - 1].kind == .context) + capped[row].kind != .context + && (row == 0 || capped[row - 1].kind == .context || changeBreaks.contains(row)) } self.string = capped.map(\.text).joined(separator: "\n") self.committedDigest = committedDigest ?? Self.committedDigest(of: capped) diff --git a/Sources/MultishellAppCore/Files/Diffs/FileLineCounts.swift b/Sources/MultishellAppCore/Files/Diffs/FileLineCounts.swift index d602b7cf4..10b453226 100644 --- a/Sources/MultishellAppCore/Files/Diffs/FileLineCounts.swift +++ b/Sources/MultishellAppCore/Files/Diffs/FileLineCounts.swift @@ -20,4 +20,8 @@ public struct FileLineCounts: Hashable, Sendable { guard case .counted(let insertions, let deletions) = lines else { return nil } self.init(insertions: insertions, deletions: deletions) } + + static func + (lhs: Self, rhs: Self) -> Self { + Self(insertions: lhs.insertions + rhs.insertions, deletions: lhs.deletions + rhs.deletions) + } } diff --git a/Sources/MultishellAppCore/Files/Diffs/SplitDiff.swift b/Sources/MultishellAppCore/Files/Diffs/SplitDiff.swift index 7e8dcf0f2..3d935e416 100644 --- a/Sources/MultishellAppCore/Files/Diffs/SplitDiff.swift +++ b/Sources/MultishellAppCore/Files/Diffs/SplitDiff.swift @@ -6,6 +6,12 @@ public struct SplitDiff: Equatable, Sendable { public let committed: DiffDisplayText public let onDisk: DiffDisplayText + /// Two sides already laid row for row, as the All changes tab keeps a file's. + init(committed: DiffDisplayText, onDisk: DiffDisplayText) { + self.committed = committed + self.onDisk = onDisk + } + /// `committedDigest` is the Unified text's where it was already hashed. init(_ lines: [DiffLine], marksStaging: Bool, committedDigest: Int? = nil) { var left: [DiffLine] = [] diff --git a/Sources/MultishellAppCore/Files/FileTabs/CommittedSide+Resolving.swift b/Sources/MultishellAppCore/Files/FileTabs/CommittedSide+Resolving.swift index 5375249df..af3bea1d9 100644 --- a/Sources/MultishellAppCore/Files/FileTabs/CommittedSide+Resolving.swift +++ b/Sources/MultishellAppCore/Files/FileTabs/CommittedSide+Resolving.swift @@ -3,37 +3,49 @@ import MultishellCore import MultishellGitKit extension CommittedSide { - /// The merge base with `base` for the worktree's own file, else `HEAD`; `nil` - /// where git cannot say which. + /// The merge base with `base` for the worktree's own file, else `HEAD`, taken from + /// `bases` where a read resolved them; `nil` where git cannot say which. static func resolved( of repository: RepositoryLocation, in worktree: URL, since base: DefaultBranch?, isGone: Bool, git: WorktreeGit, + bases: WorktreeDiffBases? = nil, ) async -> Self? { var commit: String? - if let base, repository.directory == worktree { - async let mergeBase = git.mergeBase(with: base, inRepositoryAt: worktree) - async let head = git.headCommit(in: worktree) - // No shared history is an answer, `HEAD`; only a throw leaves git unable to say. + let ownBases = repository.directory == worktree ? bases : nil + if base != nil, let ownBases { + commit = ownBases.branchCommit + } else if let base, repository.directory == worktree { do { - commit = try await mergeBase + commit = try await git.branchCommit(since: base, in: worktree) } catch { return nil } - // On the base itself the index holds nothing past `HEAD`, so its marks stay exact. - if let found = commit, found == (await head) { commit = nil } } // A size git could not read is no answer, not a file the merge base lacks. let size: Int? - do { - size = try await git.committedSize(of: repository.path, in: repository.directory, at: commit) - } catch { - return nil + if let known = ownBases?.committedSize(of: repository.path) { + size = known + } else { + do { + size = try await git.committedSize( + of: repository.path, + in: repository.directory, + at: commit, + ) + } catch { + return nil + } } guard commit != nil, size == nil, isGone else { - return Self(commit: commit, size: size, marksStaging: commit == nil) + return Self( + commit: commit, + size: size, + marksStaging: commit == nil, + bases: ownBases, + ) } // Added by the branch and deleted, `HEAD`'s copy is shown removed, staging unmarked; // none there either is the missing notice, and only a throw leaves git unable to say. @@ -43,6 +55,11 @@ extension CommittedSide { } catch { return nil } - return Self(commit: nil, size: headSize, marksStaging: false) + return Self( + commit: nil, + size: headSize, + marksStaging: false, + bases: ownBases, + ) } } diff --git a/Sources/MultishellAppCore/Files/FileTabs/CommittedSide.swift b/Sources/MultishellAppCore/Files/FileTabs/CommittedSide.swift index 8ff210bf0..3ad4432e4 100644 --- a/Sources/MultishellAppCore/Files/FileTabs/CommittedSide.swift +++ b/Sources/MultishellAppCore/Files/FileTabs/CommittedSide.swift @@ -5,4 +5,7 @@ struct CommittedSide { let size: Int? /// Not against an older commit than `HEAD`, whose changes the index holds too. let marksStaging: Bool + /// What a read of many files asked git once, where this file's repository + /// is the worktree's own. + var bases: WorktreeDiffBases? } diff --git a/Sources/MultishellAppCore/Files/FileTabs/FileFindResult.swift b/Sources/MultishellAppCore/Files/FileTabs/FileFindResult.swift index 4514506bf..04fc40961 100644 --- a/Sources/MultishellAppCore/Files/FileTabs/FileFindResult.swift +++ b/Sources/MultishellAppCore/Files/FileTabs/FileFindResult.swift @@ -72,7 +72,7 @@ struct FileFindResult: Equatable, Sendable { /// The selected match carried onto another layout of the same rows, its /// offset meaning nothing there; `nil` selected where its line's text differs. - func carried(from old: DiffDisplayText, to new: DiffDisplayText) -> Self { + func carried(from old: SearchedLayout, to new: SearchedLayout) -> Self { var carried = self let match = selected.flatMap { matches.indices.contains($0) ? matches[$0] : nil } let moved = match.flatMap { new.rangeOnSameLine($0, from: old) } diff --git a/Sources/MultishellAppCore/Files/FileTabs/FileSignature.swift b/Sources/MultishellAppCore/Files/FileTabs/FileSignature.swift index 8a69cfd41..fcae97ce2 100644 --- a/Sources/MultishellAppCore/Files/FileTabs/FileSignature.swift +++ b/Sources/MultishellAppCore/Files/FileTabs/FileSignature.swift @@ -3,7 +3,9 @@ import Foundation /// What says a file changed without reading it: its size, date and inode, by /// `lstat`, so an atomic save that swaps the inode counts. struct FileSignature: Equatable, Sendable { - private let size: Int + let size: Int + /// A folder listed as a change, a submodule or nested repository. + let isFolder: Bool private let modified: Date private let inode: Int @@ -14,6 +16,11 @@ struct FileSignature: Equatable, Sendable { let modified = attributes[.modificationDate] as? Date, let inode = attributes[.systemFileNumber] as? Int else { return nil } - return Self(size: size, modified: modified, inode: inode) + return Self( + size: size, + isFolder: attributes[.type] as? FileAttributeType == .typeDirectory, + modified: modified, + inode: inode, + ) } } diff --git a/Sources/MultishellAppCore/Files/FileTabs/FileTabReadLog.swift b/Sources/MultishellAppCore/Files/FileTabs/FileTabReadLog.swift index 98e3cac8f..dfbba77d2 100644 --- a/Sources/MultishellAppCore/Files/FileTabs/FileTabReadLog.swift +++ b/Sources/MultishellAppCore/Files/FileTabs/FileTabReadLog.swift @@ -1,7 +1,7 @@ import MultishellCore -/// Each file tab's reads: what the last one cost, which run now, which had a -/// change land meanwhile, and which hidden tabs are owed one when shown. +/// Each file tab's reads, or All changes tab's in a log of their own: last cost, +/// which run now, which had a change land meanwhile, which hidden tabs are owed one. struct FileTabReadLog { /// A re-read waits ten times what the last cost, so an agent rewriting a /// file in bursts takes at most a tenth of a core. @@ -30,11 +30,12 @@ struct FileTabReadLog { signatures[id] = .some(signature) } - /// `nil` for a tab never read, which is due now. - func nextDue(_ id: FileTab.ID) -> ContinuousClock.Instant? { + /// `nil` for a tab never read, which is due now. `costScale` multiplies the + /// cost noted, the All changes tab noting a file's and reading `costScale` files. + func nextDue(_ id: FileTab.ID, costScale: Int = 1) -> ContinuousClock.Instant? { guard let finished = lastFinished[id] else { return nil } return finished + ((lastCost[id] ?? .zero) + (lastHighlightCost[id] ?? .zero)) - * Self.costMultiple + * Self.costMultiple * max(1, costScale) } mutating func begin(_ id: FileTab.ID) { diff --git a/Sources/MultishellAppCore/Files/FileTabs/FileTabReader+ReadAnswers.swift b/Sources/MultishellAppCore/Files/FileTabs/FileTabReader+ReadAnswers.swift new file mode 100644 index 000000000..e5f0a5abb --- /dev/null +++ b/Sources/MultishellAppCore/Files/FileTabs/FileTabReader+ReadAnswers.swift @@ -0,0 +1,59 @@ +import Foundation +import MultishellCore +import MultishellGitKit + +/// A file with no diff to show, whether git ignores it, and its patches: the +/// read's own batched answers taken where it has them. +extension FileTabReader { + /// No diff to show: a new file is every line added; one git ignores, or one + /// unchanged, is shown as it is. + static func unchangedContent( + _ text: String, + path: String, + in repository: URL, + against side: CommittedSide, + git: WorktreeGit, + ) async -> (FileTabContent, isFileGone: Bool)? { + var isNew = side.size == nil + if isNew { + guard let ignored = await isIgnored(path, in: repository, against: side, git: git) + else { return nil } + isNew = !ignored + } + let rows = FileTabRows( + lines: PlainDiffLines.of(text, kind: isNew ? .added : .context), + marksStaging: side.marksStaging, + ) + return (.text(rows), false) + } + + /// Whether git ignores the file, from the read's own check where it made one. + static func isIgnored( + _ path: String, + in repository: URL, + against side: CommittedSide, + git: WorktreeGit, + ) async -> Bool? { + if let known = side.bases?.isIgnored(path) { return known } + return await git.ignoredPaths([path], in: repository)?.contains(path) + } + + /// The read's patches diffed up front where it made them, else git's for this file. + static func patches( + of path: String, + in repository: URL, + since commit: String?, + against side: CommittedSide, + git: WorktreeGit, + _ diffAlgorithm: DiffAlgorithm, + ) async -> FilePatches? { + if let diffed = side.bases?.patches(of: path, since: commit) { return diffed } + return await git.patches( + of: path, + in: repository, + diffAlgorithm: diffAlgorithm, + since: commit, + knownBase: side.bases?.headOrEmptyTree, + ) + } +} diff --git a/Sources/MultishellAppCore/Files/FileTabs/FileTabReader.swift b/Sources/MultishellAppCore/Files/FileTabs/FileTabReader.swift index 90746f10e..d97f4bf75 100644 --- a/Sources/MultishellAppCore/Files/FileTabs/FileTabReader.swift +++ b/Sources/MultishellAppCore/Files/FileTabs/FileTabReader.swift @@ -19,6 +19,7 @@ enum FileTabReader { since base: DefaultBranch?, previous: FileTabReading?, imageRule: ImageRule, + bases: WorktreeDiffBases? = nil, ) async -> FileTabReading { let url = worktree.appending(path: pathInWorktree) let (onDisk, repository, isImage, image, isSpelledAsGiven) = await runOnDispatch { @@ -57,6 +58,7 @@ enum FileTabReader { since: base, isGone: isGone, git: git, + bases: bases, ) if readsAsImage, let content = await FileTabImageReader.content( @@ -185,11 +187,13 @@ enum FileTabReader { // Naming `HEAD` skips the staged diff, which rows marking no staging never read. let commit = side.marksStaging ? nil : side.commit ?? "HEAD" guard - let patches = await git.patches( + let patches = await patches( of: path, in: repository, - diffAlgorithm: diffAlgorithm, since: commit, + against: side, + git: git, + diffAlgorithm, ) else { return nil } // The patch holds the committed bytes, so it is guessed as the file would be. @@ -228,12 +232,24 @@ enum FileTabReader { return (.binary(bytes: data.count), false) } let marksStaging = side.marksStaging + // In no commit and not in the index, its diffs are empty: no runs asked. + if side.size == nil, side.bases?.isUntracked(path) == true { + return await unchangedContent( + text, + path: path, + in: repository, + against: side, + git: git, + ) + } guard - let patches = await git.patches( + let patches = await patches( of: path, in: repository, - diffAlgorithm: diffAlgorithm, since: side.commit, + against: side, + git: git, + diffAlgorithm, ) else { return nil } switch UnifiedPatchParser.parse(patches.onDisk, encoding: encoding) { @@ -254,8 +270,9 @@ enum FileTabReader { if isWhollyRemoved, !isSpelledAsGiven { return (.text(stagedRows), true) } if isWhollyRemoved { // A failed check is no answer, not a file git ignores. - guard let ignored = await git.ignoredPaths([path], in: repository) else { return nil } - guard ignored.contains(path) else { + guard let ignored = await isIgnored(path, in: repository, against: side, git: git) + else { return nil } + guard ignored else { let added = FileTabRows( lines: PlainDiffLines.of(text, kind: .added), marksStaging: marksStaging, @@ -274,17 +291,7 @@ enum FileTabReader { return (.text(rows), false) case .unchanged: - // A new file is every line added; one git ignores is shown as it is. - var isNew = side.size == nil - if isNew { - guard let ignored = await git.ignoredPaths([path], in: repository) else { return nil } - isNew = !ignored.contains(path) - } - let rows = FileTabRows( - lines: PlainDiffLines.of(text, kind: isNew ? .added : .context), - marksStaging: marksStaging, - ) - return (.text(rows), false) + return await unchangedContent(text, path: path, in: repository, against: side, git: git) } } } diff --git a/Sources/MultishellAppCore/Files/FileTabs/FileTabRows.swift b/Sources/MultishellAppCore/Files/FileTabs/FileTabRows.swift index c6bae52a8..ca3f1aa6d 100644 --- a/Sources/MultishellAppCore/Files/FileTabs/FileTabRows.swift +++ b/Sources/MultishellAppCore/Files/FileTabs/FileTabRows.swift @@ -11,6 +11,15 @@ public struct FileTabRows: Equatable, Sendable { var lines: [DiffLine] { displayText.lines } public var hasLineChanges: Bool { !lineCounts.isEmpty } + /// Every row added, or every row removed: a file new or deleted whole, which + /// Split would show on one side with the other blank. + var isOneSided: Bool { + guard let first = lines.first?.kind, first == .added || first == .removed else { + return false + } + return lines.allSatisfy { $0.kind == first } + } + /// False where every row is the committed side's, removed: a deleted file's. var holdsTextOnDisk: Bool { lines.contains { $0.kind != .removed } } diff --git a/Sources/MultishellAppCore/Files/FileTabs/Review/ReviewCardPlacement.swift b/Sources/MultishellAppCore/Files/FileTabs/Review/ReviewCardPlacement.swift index afb9859f7..1092d32aa 100644 --- a/Sources/MultishellAppCore/Files/FileTabs/Review/ReviewCardPlacement.swift +++ b/Sources/MultishellAppCore/Files/FileTabs/Review/ReviewCardPlacement.swift @@ -78,6 +78,11 @@ public struct ReviewCardPlacement: Identifiable, Equatable, Sendable { } } + /// The same card on other rows: the All changes tab's, placed by a file's rows. + func moved(to rows: ClosedRange) -> Self { + Self(card: card, rows: rows) + } + /// The card a reveal asks for, or the composer editing that comment in its place. public func stands(for card: CardID) -> Bool { if id == card { return true } diff --git a/Sources/MultishellAppCore/Files/FileTabs/Review/ReviewComposer.swift b/Sources/MultishellAppCore/Files/FileTabs/Review/ReviewComposer.swift index c985a44f6..97a4be6f5 100644 --- a/Sources/MultishellAppCore/Files/FileTabs/Review/ReviewComposer.swift +++ b/Sources/MultishellAppCore/Files/FileTabs/Review/ReviewComposer.swift @@ -1,10 +1,12 @@ import Foundation import MultishellCore -/// A comment being written or edited in a file tab, under the lines it is on. -/// Each opening is a new one, so its card's field starts from its own draft. +/// A comment being written or edited under its lines. Each opening is a new one, +/// so its card's field starts from its own draft. public struct ReviewComposer: Identifiable, Equatable, Sendable { public let id = UUID() + /// The file its lines are in, which the All changes tab holds several of. + let path: String let side: DiffSide /// Moved as a read moves the comments, so the card stays under the lines it quotes. var lines: ClosedRange diff --git a/Sources/MultishellAppCore/Files/FileTabs/SearchedLayout.swift b/Sources/MultishellAppCore/Files/FileTabs/SearchedLayout.swift new file mode 100644 index 000000000..8f50fd15f --- /dev/null +++ b/Sources/MultishellAppCore/Files/FileTabs/SearchedLayout.swift @@ -0,0 +1,26 @@ +/// What find searched in a tab, kept across a change to carry its selection +/// by line: a file tab's text, or the All changes tab's files end to end. +enum SearchedLayout { + case allChanges(AllChangesDocument) + case fileText(DiffDisplayText) + + var text: DiffDisplayText { + switch self { + case .allChanges(let document): document.text + case .fileText(let text): text + } + } + + func rangeOnSameLine(_ range: Range, from previous: Self) -> Range? { + switch (self, previous) { + case (.allChanges(let document), .allChanges(let previousDocument)): + document.rangeOnSameLine(range, from: previousDocument) + + case (.fileText(let text), .fileText(let previousText)): + text.rangeOnSameLine(range, from: previousText) + + case (.allChanges, .fileText), (.fileText, .allChanges): + nil + } + } +} diff --git a/Sources/MultishellAppCore/Files/FileTabs/WorktreeDiffBases.swift b/Sources/MultishellAppCore/Files/FileTabs/WorktreeDiffBases.swift new file mode 100644 index 000000000..35db5ba7a --- /dev/null +++ b/Sources/MultishellAppCore/Files/FileTabs/WorktreeDiffBases.swift @@ -0,0 +1,104 @@ +import Foundation +import MultishellCore +import MultishellGitKit + +/// What every file of one read counts from, asked of git once a read: asked a file +/// at a time, the All changes tab cost several git runs a file. +struct WorktreeDiffBases: Sendable { + /// The merge base with the Branch list's base; `nil` under Modified, or on + /// the base itself, where `HEAD` serves. + let branchCommit: String? + /// `HEAD`, or the empty tree's id where `HEAD` is unborn. + let headOrEmptyTree: String + /// The read's files' sizes on the committed side; one absent has none there. + private let committedSizes: [String: Int] + private let ignored: Set + private let indexed: Set + /// Diffed up front, many files a run, against `branchCommit`. + private let patches: [String: FilePatches] + /// The paths the sizes and ignores were asked for; any other asks git itself. + private let paths: Set + + /// `nil` where git cannot say, each file then asking for itself. + /// `diffable` names the paths worth diffing up front: text under the cap. + static func resolve( + in worktree: URL, + since base: DefaultBranch?, + paths: [String], + diffable: Set, + diffAlgorithm: DiffAlgorithm, + git: WorktreeGit, + ) async -> Self? { + async let diffBase = git.diffBase(in: worktree) + var branchCommit: String? + if let base { + do { + branchCommit = try await git.branchCommit(since: base, in: worktree) + } catch { + return nil + } + } + guard let headOrEmptyTree = await diffBase else { return nil } + async let sizes = git.committedSizes( + of: paths, + in: worktree, + at: branchCommit ?? headOrEmptyTree, + ) + async let ignored = ignoredPaths(paths, in: worktree, git: git) + async let indexed = git.indexedPaths(paths, in: worktree) + guard let sizes = await sizes, let ignored = await ignored, let indexed = await indexed + else { return nil } + // An untracked file is read with no diff, and one past the cap never diffs. + let toDiff = paths.filter { path in + diffable.contains(path) && indexed.contains(path) + && (sizes[path] ?? 0) <= FileTabReader.sizeLimit + } + let patches = await git.patches( + ofMany: toDiff, + in: worktree, + diffAlgorithm: diffAlgorithm, + since: branchCommit, + base: headOrEmptyTree, + ) + return Self( + branchCommit: branchCommit, + headOrEmptyTree: headOrEmptyTree, + committedSizes: sizes, + ignored: ignored, + indexed: indexed, + patches: patches ?? [:], + paths: Set(paths), + ) + } + + private static func ignoredPaths( + _ paths: [String], + in worktree: URL, + git: WorktreeGit, + ) async -> Set? { + await WorktreeGit.runs(over: paths) { await git.ignoredPaths($0, in: worktree) } + .map { Set($0.joined()) } + } + + /// The committed size of a path the read asked about, `.some(nil)` where + /// the committed side lacks it; `nil` for a path it did not ask about. + func committedSize(of path: String) -> Int?? { + paths.contains(path) ? .some(committedSizes[path]) : nil + } + + /// A path's patches diffed up front where they were against `commit`; + /// `nil` for any other, read alone. + func patches(of path: String, since commit: String?) -> FilePatches? { + commit == branchCommit ? patches[path] : nil + } + + /// Whether the index lacks a path the read asked about; `nil` for any other. + func isUntracked(_ path: String) -> Bool? { + paths.contains(path) ? !indexed.contains(path) : nil + } + + /// Whether git ignores a path the read asked about; `nil` for any other. + func isIgnored(_ path: String) -> Bool? { + paths.contains(path) ? ignored.contains(path) : nil + } +} diff --git a/Sources/MultishellAppCore/Files/Panel/FileTree+Building.swift b/Sources/MultishellAppCore/Files/Panel/FileTree+Building.swift index 8963c6dce..83e2e32a2 100644 --- a/Sources/MultishellAppCore/Files/Panel/FileTree+Building.swift +++ b/Sources/MultishellAppCore/Files/Panel/FileTree+Building.swift @@ -3,11 +3,21 @@ import MultishellCore /// Building a worktree's tree from its paths, once per listing. extension FileTree { - /// The order rows sort in: folders first, then by name as Finder does. + /// The order siblings sort in: folders first, then by name as Finder does. + /// The All changes tab lists its files in it too. + static func sortsBefore( + _ first: some StringProtocol, + isFolder firstIsFolder: Bool, + _ second: some StringProtocol, + isFolder secondIsFolder: Bool, + ) -> Bool { + if firstIsFolder != secondIsFolder { return firstIsFolder } + return first.localizedStandardCompare(second) == .orderedAscending + } + private static func sorted(_ nodes: [Node]) -> [Node] { nodes.sorted { first, second in - if first.isFolder != second.isFolder { return first.isFolder } - return first.name.localizedStandardCompare(second.name) == .orderedAscending + sortsBefore(first.name, isFolder: first.isFolder, second.name, isFolder: second.isFolder) } } diff --git a/Sources/MultishellAppCore/Files/Panel/FileTree.swift b/Sources/MultishellAppCore/Files/Panel/FileTree.swift index 03d736875..650e7c88e 100644 --- a/Sources/MultishellAppCore/Files/Panel/FileTree.swift +++ b/Sources/MultishellAppCore/Files/Panel/FileTree.swift @@ -39,11 +39,7 @@ struct FileTree: Sendable { let path = change.path.hasSuffix("/") ? String(change.path.dropLast()) : change.path kinds[path] = kinds[path]?.combined(with: change.kind) ?? change.kind guard let changeCounts = FileLineCounts(change.lines) else { return } - let total = counts[path] - counts[path] = FileLineCounts( - insertions: (total?.insertions ?? 0) + changeCounts.insertions, - deletions: (total?.deletions ?? 0) + changeCounts.deletions, - ) + counts[path] = counts[path].map { $0 + changeCounts } ?? changeCounts } sources.markedChanges.forEach(add) // A submodule's paths sit under its folder, so none is one of the worktree's. diff --git a/Sources/MultishellAppCore/Files/Review/ReviewCardSources.swift b/Sources/MultishellAppCore/Files/Review/ReviewCardSources.swift new file mode 100644 index 000000000..ee8542fda --- /dev/null +++ b/Sources/MultishellAppCore/Files/Review/ReviewCardSources.swift @@ -0,0 +1,16 @@ +import MultishellCore + +/// What a tab's review cards show on one side under its scope: its composer, and +/// the comments by file, less the one the composer edits. +struct ReviewCardSources { + let composer: ReviewComposer? + let commentsByPath: [String: [ReviewComment]] + + func composer(onFile path: String) -> ReviewComposer? { + composer?.path == path ? composer : nil + } + + func comments(onFile path: String) -> [ReviewComment] { + commentsByPath[path] ?? [] + } +} diff --git a/Sources/MultishellAppCore/Files/Review/ReviewTabID.swift b/Sources/MultishellAppCore/Files/Review/ReviewTabID.swift new file mode 100644 index 000000000..78ce7fe2d --- /dev/null +++ b/Sources/MultishellAppCore/Files/Review/ReviewTabID.swift @@ -0,0 +1,5 @@ +import MultishellCore + +/// A tab that hosts review cards: a file tab, or the All changes tab, whose +/// composer and drafts are keyed alike; see Docs/design/files/review-comments.md. +public typealias ReviewTabID = WorkspaceTab.ID diff --git a/Sources/MultishellAppCore/Model/AppModel+InView.swift b/Sources/MultishellAppCore/Model/AppModel+InView.swift index 9eb0044b6..06feb5239 100644 --- a/Sources/MultishellAppCore/Model/AppModel+InView.swift +++ b/Sources/MultishellAppCore/Model/AppModel+InView.swift @@ -57,6 +57,15 @@ extension AppModel { worktreeIDInView == worktree.id } + /// A tab of any kind in front of its group, in the worktree in view: a file or + /// All changes tab reads its rows only then. + func isTabShown(_ id: WorkspaceTab.ID) -> Bool { + guard let tab = workspace.workspaceTab(id), tab.worktreeID == worktreeIDInView else { + return false + } + return workspace.group(tab.groupID)?.shownTabID == id + } + func isWorktreeInView(of tab: TerminalTab) -> Bool { worktreeIDInView == tab.worktreeID } diff --git a/Sources/MultishellAppCore/Model/AppModel+Persistence.swift b/Sources/MultishellAppCore/Model/AppModel+Persistence.swift index bf29633b9..80a74e2a8 100644 --- a/Sources/MultishellAppCore/Model/AppModel+Persistence.swift +++ b/Sources/MultishellAppCore/Model/AppModel+Persistence.swift @@ -9,6 +9,7 @@ extension AppModel { pendingSave = nil guard !isYieldingToRunningInstance else { return } store.setFileTabScrolls(fileTabScrolls) + store.setAllChangesScrolls(allChangesScrolls) recordSaveOutcome(Result { try store.save() }) writeReviewCommentsNow() } diff --git a/Sources/MultishellAppCore/Model/AppModel+Reconcile.swift b/Sources/MultishellAppCore/Model/AppModel+Reconcile.swift index 3f42ac318..f4a87a6f7 100644 --- a/Sources/MultishellAppCore/Model/AppModel+Reconcile.swift +++ b/Sources/MultishellAppCore/Model/AppModel+Reconcile.swift @@ -53,5 +53,8 @@ extension AppModel { pruneFileTabs() releaseHiddenFileTabs() readShownFileTabs() + pruneAllChangesTabs() + releaseHiddenAllChangesTabs() + readShownAllChangesTabs() } } diff --git a/Sources/MultishellAppCore/Model/AppModel.swift b/Sources/MultishellAppCore/Model/AppModel.swift index 5bc5ab887..923d7f1dd 100644 --- a/Sources/MultishellAppCore/Model/AppModel.swift +++ b/Sources/MultishellAppCore/Model/AppModel.swift @@ -158,6 +158,35 @@ public final class AppModel { @ObservationIgnored var fileTabReadLog = FileTabReadLog() /// One coalesced read per file tab; see `scheduleFileTabRead`. @ObservationIgnored var pendingFileTabReads: [FileTab.ID: Task] = [:] + /// Each All changes tab's last read, never saved, let go while hidden. + var allChangesReadings: [AllChangesTab.ID: AllChangesReading] = [:] + /// Paced as a file tab's reads are, by the tab: one read covers every file. + @ObservationIgnored var allChangesReadLog = FileTabReadLog() + @ObservationIgnored var allChangesStaleFiles = AllChangesStaleFiles() + /// The files each All changes tab's view has near its screen: the only ones read. + @ObservationIgnored var allChangesFilesNear: [AllChangesTab.ID: Set] = [:] + /// Written on every scroll, as a file tab's is, and saved at quit. + @ObservationIgnored var allChangesScrolls: [AllChangesTab.ID: AllChangesScroll] = [:] + /// Files collapsed to their header in each tab, kept for the run only; see + /// Docs/design/files/all-changes-tab.md. + var allChangesCollapsedFiles: [AllChangesTab.ID: Set] = [:] + /// Folds opened in each tab, by file, the lines held by the file on disk's numbering. + var allChangesOpenedFolds: [AllChangesTab.ID: [String: [AllChangesLineSpan]]] = [:] + /// The file at the top of each tab's view, which its sticky header names; it + /// moves each frame the next header pushes it. + var allChangesTopFiles: [AllChangesTab.ID: AllChangesTopFile] = [:] + /// That file's path alone, which the Changes list lights: apart, so a push + /// redraws only the sticky header. + var allChangesLitPaths: [AllChangesTab.ID: String] = [:] + /// A file a Changes row asked each tab's view to scroll to, taken as + /// `changeStepRequests` are. + var allChangesFileReveals: [AllChangesTab.ID: String] = [:] + /// Each tab's document as last built, so a render reuses it. + @ObservationIgnored var allChangesDocuments: [AllChangesTab.ID: AllChangesDocumentCacheEntry] = + [:] + + @ObservationIgnored var pendingAllChangesReads: [AllChangesTab.ID: Task] = [:] + @ObservationIgnored var allChangesLists: [Worktree.ID: AllChangesListCacheEntry] = [:] /// Each worktree's review comments, kept in a file per worktree rather than /// the workspace; see files/review-comments.md. @@ -174,14 +203,14 @@ public final class AppModel { var focusedSessionHistory: [Worktree.ID: [TerminalSession.ID]] = [:] /// The comment last clicked in each worktree's Review, its card outlined. var selectedReviewComments: [Worktree.ID: ReviewComment.ID] = [:] - /// Each file tab's open composer, at most one, closed with its tab. - var reviewComposers: [FileTab.ID: ReviewComposer] = [:] + /// Each file or All changes tab's open composer, at most one, closed with its tab. + var reviewComposers: [ReviewTabID: ReviewComposer] = [:] /// What each composer holds as it is typed, which nothing redraws for. - @ObservationIgnored var reviewDrafts: [FileTab.ID: String] = [:] - /// A card each file tab's view scrolls into view, taken as `changeStepRequests` are. - var reviewCardRevealRequests: [FileTab.ID: ReviewCardPlacement.CardID] = [:] + @ObservationIgnored var reviewDrafts: [ReviewTabID: String] = [:] + /// A card each tab's view scrolls into view, taken as `changeStepRequests` are. + var reviewCardRevealRequests: [ReviewTabID: ReviewCardPlacement.CardID] = [:] /// Composers opened since their card last took the keyboard. - @ObservationIgnored var reviewComposerKeyboardRequests: Set = [] + @ObservationIgnored var reviewComposerKeyboardRequests: Set = [] /// Worktrees whose review file was read, at launch or when first listed after. @ObservationIgnored var worktreesWithReviewFilesRead: Set = [] /// Where Review's handoffs are written. diff --git a/Sources/MultishellAppCore/Model/Control/AppModel+ControlFileTabs.swift b/Sources/MultishellAppCore/Model/Control/AppModel+ControlFileTabs.swift index 18448582f..e748607ea 100644 --- a/Sources/MultishellAppCore/Model/Control/AppModel+ControlFileTabs.swift +++ b/Sources/MultishellAppCore/Model/Control/AppModel+ControlFileTabs.swift @@ -16,6 +16,15 @@ extension AppModel { return .json(["tab": tab.id]) } + /// Made or turned to, as the Changes page's button does; out of view it opens + /// without switching to its worktree. + func replyToOpenAllChangesTab(in id: String) -> ControlReply { + guard let worktree = worktree(withControlID: id), + let tab = openAllChangesTab(in: worktree.id) + else { return .refused(.noWorktree(id: id)) } + return .json(["tab": tab.id]) + } + /// The bar's arrow. Queued for the tab's view, which the arrow needs on screen. func replyToStepToChange(_ direction: CycleDirection, in id: FileTab.ID) async -> ControlReply { let refusal = await refusalToActOnRowsOnceRead(of: id) { @@ -26,6 +35,9 @@ extension AppModel { if case .text(let rows) = fileTabReadings[id]?.content, !rows.hasLineChanges { return .refused(.noChangeThatWay(id: id)) } + if allChangesDocument(of: id)?.hasChanges == false { + return .refused(.noChangeThatWay(id: id)) + } // What the view said holds only until it takes a step queued since. guard changeStepRequests[id]?.isEmpty ?? true else { return .refused(.stepNotYetTaken(id: id)) @@ -64,6 +76,9 @@ extension AppModel { _ refusalNow: () -> ControlRefusal?, ) async -> ControlRefusal? { if let refusal = refusalNow() { return refusal } + if workspace.allChangesTab(id) != nil { + return await refusalToActOnAllChangesOnceRead(of: id, refusalNow) + } let holdsNothing = !holdsContent(id) // A notice or an image may yet turn to rows, so its scheduled read is waited on too. let awaitsRead = holdsNothing || (drawsNoRows(id) && pendingFileTabReads[id] != nil) @@ -83,11 +98,29 @@ extension AppModel { return holdsImage(id) ? .fileTabShowsImage(id: id) : .fileTabShowsNotice(id: id) } + /// The All changes tab's read waited on as a file tab's is, a reading against + /// another base counting as none; its document is rows, so no notice refuses it. + private func refusalToActOnAllChangesOnceRead( + of id: AllChangesTab.ID, + _ refusalNow: () -> ControlRefusal?, + ) async -> ControlRefusal? { + if allChangesDocument(of: id) == nil, !allChangesReadLog.isReading(id) { + if coordinator == nil { return .gitNotFound } + if let scheduled = pendingAllChangesReads[id] { + await scheduled.value + } else { + await readAllChangesTab(id) + } + if let refusal = refusalNow() { return refusal } + } + return allChangesDocument(of: id) == nil ? .fileTabNotRead(id: id) : nil + } + /// A hidden tab lets its rows go, and the arrows and find read the view's, /// which a worktree's operation draws in place of its groups. private func refusalToShowReachedFileTab(_ id: WorkspaceTab.ID) -> ControlRefusal? { if let refusal = refusalToReadInWorkspaceWindow { return refusal } - guard isFileTabShown(id) else { return .tabNotShown(id: id) } + guard isTabShown(id) else { return .tabNotShown(id: id) } if case .operation(let worktree, _) = detailContent { return .worktreeNotReady(id: ControlID.worktree(worktree.id)) } diff --git a/Sources/MultishellAppCore/Model/Control/AppModel+ControlPanes.swift b/Sources/MultishellAppCore/Model/Control/AppModel+ControlPanes.swift index 94344c262..905471ba6 100644 --- a/Sources/MultishellAppCore/Model/Control/AppModel+ControlPanes.swift +++ b/Sources/MultishellAppCore/Model/Control/AppModel+ControlPanes.swift @@ -7,14 +7,16 @@ extension AppModel { func replyToSplitPane(_ axis: SplitAxis, inTab id: WorkspaceTab.ID?) -> ControlReply { if let id { // Refused before it is brought into view, which would switch to it. - if workspace.fileTab(id) != nil { return .refused(.tabShowsAFile(id: id)) } + if let refusal = refusalToSplit(id) { return .refused(refusal) } if let tab = workspace.tab(id), isBusy(tab.worktreeID) { return .refused(.worktreeNotReady(id: ControlID.worktree(tab.worktreeID))) } let selected = replyToSelectTab(id) guard selected == .done else { return selected } } - if case .file(let file) = workspaceTabInView { return .refused(.tabShowsAFile(id: file.id)) } + if let shown = workspaceTabInView, let refusal = refusalToSplit(shown.id) { + return .refused(refusal) + } guard let before = tabInView else { return .refused(.nothingInView) } // The split looks for the directory itself, raising the alert this answers with. guard let worktree = worktreeInView, !isBusy(worktree.id) else { diff --git a/Sources/MultishellAppCore/Model/Control/AppModel+ControlReach.swift b/Sources/MultishellAppCore/Model/Control/AppModel+ControlReach.swift index 0e403ca01..100cbcbbe 100644 --- a/Sources/MultishellAppCore/Model/Control/AppModel+ControlReach.swift +++ b/Sources/MultishellAppCore/Model/Control/AppModel+ControlReach.swift @@ -13,16 +13,30 @@ extension AppModel { /// A terminal tab, which has panes and a title of its own to set. func reachTerminalTab(_ id: WorkspaceTab.ID) throws(ControlRefusal) -> TerminalTab { - guard let tab = workspace.tab(id) else { - throw workspace.fileTab(id) == nil ? .noTab(id: id) : .tabShowsAFile(id: id) + switch workspace.workspaceTab(id) { + case .terminal(let tab): return tab + case .file: throw .tabShowsAFile(id: id) + case .allChanges: throw .tabShowsAllChanges(id: id) + case nil: throw .noTab(id: id) } - return tab } - /// A file tab, which has a bar to step and find in. + /// A file or All changes tab, which has a bar to step and find in. func refusalToReachFileTab(_ id: WorkspaceTab.ID) -> ControlRefusal? { - guard workspace.fileTab(id) == nil else { return nil } - return workspace.tab(id) == nil ? .noTab(id: id) : .tabShowsNoFile(id: id) + switch workspace.workspaceTab(id) { + case .allChanges, .file: nil + case .terminal: .tabShowsNoFile(id: id) + case nil: .noTab(id: id) + } + } + + /// Panes a split acts on: a terminal tab's, refused before anything turns to it. + func refusalToSplit(_ id: WorkspaceTab.ID) -> ControlRefusal? { + switch workspace.workspaceTab(id) { + case .terminal, nil: nil + case .file: .tabShowsAFile(id: id) + case .allChanges: .tabShowsAllChanges(id: id) + } } /// Turns the store to a tab or pane and hands it the keyboard, selecting its diff --git a/Sources/MultishellAppCore/Model/Control/AppModel+ControlRequests.swift b/Sources/MultishellAppCore/Model/Control/AppModel+ControlRequests.swift index b1c71e333..b022c625d 100644 --- a/Sources/MultishellAppCore/Model/Control/AppModel+ControlRequests.swift +++ b/Sources/MultishellAppCore/Model/Control/AppModel+ControlRequests.swift @@ -87,6 +87,7 @@ extension AppModel { case .debugGitRuns(let last): replyToDebugGitRuns(last: last) case .screenshot(let pane): replyToScreenshot(pane: pane) case .settingsScreenshot: replyToSettingsScreenshot() + case .openAllChangesTab(let worktree): replyToOpenAllChangesTab(in: worktree) case .openFileTab(let worktree, let path): await replyToOpenFileTab(path, in: worktree) case .stepToChange(let tab, let direction): await replyToStepToChange(direction, in: tab) case .findInFileTab(let id, let action): await replyToFindInFileTab(action, in: id) diff --git a/Sources/MultishellAppCore/Model/Control/AppModel+ControlReview.swift b/Sources/MultishellAppCore/Model/Control/AppModel+ControlReview.swift index 0f4e2688d..414fda2f1 100644 --- a/Sources/MultishellAppCore/Model/Control/AppModel+ControlReview.swift +++ b/Sources/MultishellAppCore/Model/Control/AppModel+ControlReview.swift @@ -7,7 +7,8 @@ extension AppModel { await replyingInReviewedWorktree(id) { worktree in reviewListing(of: worktree) } } - /// Quoted from the file's open tab, as a comment written there is. + /// Quoted from the file's open tab, as a comment written there is; never + /// the All changes tab (owner's pick). func replyToAddReviewComment(_ order: ReviewCommentOrder) async -> ControlReply { await replyingInReviewedWorktree(order.worktreeID) { worktree in await replyToAdd(order, in: worktree) @@ -23,34 +24,24 @@ extension AppModel { } // A link's tab is keyed by its target, as a click on the link opens it. let path = WorktreeLinkTarget.path(of: order.path, in: worktree.path) ?? order.path - guard let tab = workspace.fileTab(showing: path, in: worktree.id) else { - return .refused(.noReviewTab(path: order.path)) - } - let refusalToQuote = { - self.refusalToReadInWorkspaceWindow - ?? (self.isFileTabShown(tab.id) ? nil : .tabNotShown(id: tab.id)) - } - if let refusal = refusalToQuote() { return .refused(refusal) } - // Read now, so an edit made a moment ago, noticed or not, is what is quoted; the - // checks below then judge that reading, a notice or image refused as `tabs step` is. - if fileTabReadLog.isReading(tab.id) { return .refused(.fileTabNotRead(id: tab.id)) } - await readFileTab(tab.id) - if let unread = await refusalToActOnRowsOnceRead(of: tab.id, refusalToQuote) { - return .refused(unread) + let host: ReviewTabID + switch await readReviewHost(showing: path, asked: order.path, in: worktree) { + case .success(let id): host = id + case .failure(let refusal): return .refused(refusal) } guard workspace.worktree(worktree.id) != nil else { return .refused(.noWorktree(id: ControlID.worktree(worktree.id))) } - let quote = reviewQuote(of: order.lines, on: order.side, in: tab.id) + let quote = reviewQuote(of: order.lines, on: order.side, ofFile: path, in: host) // Lines start at 1, and a socket line can name any range: `count` traps past `Int.max`. guard order.lines.lowerBound >= 1, quote.count == order.lines.count else { return .refused(.noReviewLines(path: order.path)) } - guard order.side == .onDisk || holdsRemovedLines(order.lines, in: tab.id) else { + guard order.side == .onDisk || holdsRemovedLines(order.lines, ofFile: path, in: host) else { return .refused(.noRemovedLines(path: order.path)) } let comment = ReviewComment( - path: tab.path, + path: path, side: order.side, scope: fileTabScope(in: worktree.id), lines: order.lines, @@ -63,6 +54,30 @@ extension AppModel { return reviewListing(of: worktree) } + /// The shown file tab whose rows the quote comes from, read now, so an edit made a + /// moment ago, noticed or not, is what is quoted; `asked` is the path as named. + private func readReviewHost( + showing path: String, + asked: String, + in worktree: Worktree, + ) async -> Result { + guard let tab = workspace.fileTab(showing: path, in: worktree.id) else { + return .failure(.noReviewTab(path: asked)) + } + let refusalToQuote = { + self.refusalToReadInWorkspaceWindow + ?? (self.isTabShown(tab.id) ? nil : .tabNotShown(id: tab.id)) + } + if let refusal = refusalToQuote() { return .failure(refusal) } + if fileTabReadLog.isReading(tab.id) { return .failure(.fileTabNotRead(id: tab.id)) } + await readFileTab(tab.id) + // A notice or image is refused as `tabs step` refuses it. + if let unread = await refusalToActOnRowsOnceRead(of: tab.id, refusalToQuote) { + return .failure(unread) + } + return .success(tab.id) + } + func replyToSendReview(in id: String?, to sessionID: UUID?) async -> ControlReply { await replyingInReviewedWorktree(id) { worktree in replyToSend(of: worktree, to: sessionID) } } @@ -109,9 +124,12 @@ extension AppModel { return await reply(worktree) } - private func holdsRemovedLines(_ lines: ClosedRange, in tabID: FileTab.ID) -> Bool { - guard case .text(let rows) = fileTabReadings[tabID]?.content else { return false } - return rows.lines.contains { line in + private func holdsRemovedLines( + _ lines: ClosedRange, + ofFile path: String, + in tabID: ReviewTabID, + ) -> Bool { + (reviewRows(ofFile: path, in: tabID) ?? []).contains { line in line.kind == .removed && line.number(on: .committed).map(lines.contains) == true } } diff --git a/Sources/MultishellAppCore/Model/Control/AppModel+ControlTabDescription.swift b/Sources/MultishellAppCore/Model/Control/AppModel+ControlTabDescription.swift index 395ec9cbf..0d187734c 100644 --- a/Sources/MultishellAppCore/Model/Control/AppModel+ControlTabDescription.swift +++ b/Sources/MultishellAppCore/Model/Control/AppModel+ControlTabDescription.swift @@ -7,6 +7,23 @@ extension AppModel { guard let tab = workspace.workspaceTab(id) else { return .refused(.noTab(id: id)) } let isShown = workspace.group(tab.groupID)?.shownTabID == id switch tab { + case .allChanges(let allChanges): + return .json( + TabDescription( + id: allChanges.id, + kind: .allChanges, + worktree: ControlID.worktree(allChanges.worktreeID), + title: title(of: allChanges), + isShown: isShown, + path: nil, + isDeleted: nil, + focusedPane: nil, + state: nil, + layout: nil, + find: fileFindBar(of: allChanges.id), + ) + ) + case .file(let file): return .json( TabDescription( @@ -43,11 +60,12 @@ extension AppModel { } } - /// A notice draws no bar, though the find stays for rows read again; an image - /// ends any find when read. + /// A file or All changes tab's: a notice draws no bar, though the find stays + /// for rows read again; an image ends any find when read. private func fileFindBar(of id: FileTab.ID) -> FindBarDescription? { guard findBarTargetIDs.contains(id), !drawsNoRows(id) else { return nil } - let count = holdsContent(id) ? findMatchCount(of: id) : nil + let holdsRows = holdsContent(id) || allChangesReadings[id] != nil + let count = holdsRows ? findMatchCount(of: id) : nil return FindBarDescription( text: findText(of: id), total: count?.total, diff --git a/Sources/MultishellAppCore/Model/Control/AppModel+ControlTabs.swift b/Sources/MultishellAppCore/Model/Control/AppModel+ControlTabs.swift index 18d7c2569..ed7f77371 100644 --- a/Sources/MultishellAppCore/Model/Control/AppModel+ControlTabs.swift +++ b/Sources/MultishellAppCore/Model/Control/AppModel+ControlTabs.swift @@ -35,6 +35,19 @@ extension AppModel { private func listing(of tab: WorkspaceTab, isShown: Bool) -> TabListing.Tab { switch tab { + case .allChanges(let allChanges): + return TabListing.Tab( + id: allChanges.id, + kind: .allChanges, + title: title(of: allChanges), + isShown: isShown, + path: nil, + isDeleted: nil, + focusedPane: nil, + state: nil, + panes: nil, + ) + case .file(let file): return TabListing.Tab( id: file.id, diff --git a/Sources/MultishellAppCore/Model/Debug/AppModel+DebugMemoryTable.swift b/Sources/MultishellAppCore/Model/Debug/AppModel+DebugMemoryTable.swift index 85fa448f7..b10dee485 100644 --- a/Sources/MultishellAppCore/Model/Debug/AppModel+DebugMemoryTable.swift +++ b/Sources/MultishellAppCore/Model/Debug/AppModel+DebugMemoryTable.swift @@ -8,8 +8,8 @@ extension AppModel { /// The command line's table, read on while the panel is paused. var liveDebugMemoryTable: DebugMemoryTable { debugMemoryTable(of: liveDebugSnapshot) } - /// UTF-16 kept for each line, twice over for the rows' joined text, and an - /// image's bytes: the model's copy, not the layout or picture a shown tab adds. + /// The model's copy, not a shown tab's layout or picture: UTF-16 per line, twice + /// for joined text, and image bytes. All changes tabs count with the file tabs. private var debugFileTabMemory: DebugFileTabMemory { let bytes = fileTabReadings.values.reduce(UInt64(0)) { total, reading in switch reading.content { @@ -23,7 +23,25 @@ extension AppModel { return total } } - return DebugFileTabMemory(tabCount: workspace.fileTabs.count, contentMemory: bytes) + return DebugFileTabMemory( + tabCount: workspace.fileTabs.count + workspace.allChangesTabs.count, + contentMemory: bytes + debugAllChangesMemory, + ) + } + + private var debugAllChangesMemory: UInt64 { + let rows = allChangesReadings.values.reduce(UInt64(0)) { total, reading in + reading.files.reduce(total) { total, file in + total + UInt64(file.rows?.displayText.string.utf16.count ?? 0) * 4 + } + } + let documents = allChangesDocuments.values.reduce(UInt64(0)) { total, entry in + let document = entry.document + let units = + document.text.string.utf16.count + (document.committedText?.string.utf16.count ?? 0) + return total + UInt64(units) * 4 + } + return rows + documents } private func debugMemoryTable(of snapshot: DebugSnapshot) -> DebugMemoryTable { diff --git a/Sources/MultishellAppCore/Model/Detail/AppModel+DetailCover.swift b/Sources/MultishellAppCore/Model/Detail/AppModel+DetailCover.swift index eb3b42590..524823ec6 100644 --- a/Sources/MultishellAppCore/Model/Detail/AppModel+DetailCover.swift +++ b/Sources/MultishellAppCore/Model/Detail/AppModel+DetailCover.swift @@ -15,5 +15,6 @@ extension AppModel { func uncoverDetailAndReadItsTabs() { uncoverDetail() readShownFileTabs() + readShownAllChangesTabs() } } diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesDocument.swift b/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesDocument.swift new file mode 100644 index 000000000..7f3a1697c --- /dev/null +++ b/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesDocument.swift @@ -0,0 +1,127 @@ +import MultishellCore +import MultishellGitKit + +/// What an All changes tab lays out: its files' rows, folds opened, files +/// collapsed; see Docs/design/files/all-changes-tab.md. +extension AppModel { + /// Rebuilt only where its inputs moved; `nil` before a read, while hidden, or + /// until a read against a new base lands, its wait or failure shown instead. + public func allChangesDocument(of id: AllChangesTab.ID) -> AllChangesDocument? { + let tab = workspace.allChangesTab(id) + guard let reading = allChangesReadings[id], + reading.baseName == tab.flatMap({ fileTabBase(in: $0.worktreeID)?.shortName }) + else { return nil } + let inputs = AllChangesDocumentInputs( + reading: reading, + collapsed: allChangesCollapsedFiles[id] ?? [], + openedFolds: allChangesOpenedFolds[id] ?? [:], + reviewComments: tab.map { reviewComments(in: $0.worktreeID) } ?? [], + reviewComposer: reviewComposers[id], + scope: tab.map { fileTabScope(in: $0.worktreeID) }, + layout: workspace.fileTabLayout, + ) + let cached = allChangesDocuments[id] + if let cached, cached.inputs == inputs { return cached.document } + let heldOpen = allChangesHeldOpenLines(of: id) + let document = + cached.flatMap { $0.laysOut(inputs, holdingOpen: heldOpen) ? $0.document : nil } + ?? AllChangesDocument( + reading, + collapsed: inputs.collapsed, + heldOpen: heldOpen, + layout: inputs.layout, + ) + allChangesDocuments[id] = AllChangesDocumentCacheEntry( + inputs: inputs, + heldOpen: heldOpen, + document: document, + ) + return document + } + + /// The header's chevron. + public func toggleAllChangesFileCollapsed(_ path: String, in id: AllChangesTab.ID) { + guard workspace.allChangesTab(id) != nil else { return } + relayingOutAllChanges(id) { + if allChangesCollapsedFiles[id, default: []].remove(path) == nil { + allChangesCollapsedFiles[id, default: []].insert(path) + } + } + } + + /// A change to the rows shown: the find runs again over them, and a file it + /// brings near the screen unread is read. + func relayingOutAllChanges(_ id: AllChangesTab.ID, _ change: () -> Void) { + let before = allChangesDocument(of: id).map(SearchedLayout.allChanges) + change() + rerunFileFind(in: id, laidOutBefore: before) + readNearFilesOwed(in: id) + } + + /// Whether the bar's button expands every file rather than collapsing them. + public func isEveryAllChangesFileCollapsed(in id: AllChangesTab.ID) -> Bool { + guard let files = allChangesReadings[id]?.files, !files.isEmpty else { return false } + let collapsed = allChangesCollapsedFiles[id] ?? [] + return files.allSatisfy { collapsed.contains($0.path) } + } + + /// The bar's button: every file collapsed, or every one expanded once all are. + public func toggleEveryAllChangesFileCollapsed(in id: AllChangesTab.ID) { + guard workspace.allChangesTab(id) != nil, let files = allChangesReadings[id]?.files else { + return + } + relayingOutAllChanges(id) { + allChangesCollapsedFiles[id] = + isEveryAllChangesFileCollapsed(in: id) ? [] : Set(files.map(\.path)) + } + } + + /// A fold's click shows every line it held. + public func openAllChangesFold( + _ lines: ClosedRange, + of path: String, + in id: AllChangesTab.ID, + ) { + guard workspace.allChangesTab(id) != nil else { return } + relayingOutAllChanges(id) { + allChangesOpenedFolds[id, default: [:]][path, default: []].append( + AllChangesLineSpan(side: .onDisk, lines: lines) + ) + } + } + + /// The view's, as it scrolls: the file at the top of the clip. + public func noteAllChangesTopFile(_ top: AllChangesTopFile?, in id: AllChangesTab.ID) { + setIfChanged(\.allChangesTopFiles[id], top) + setIfChanged(\.allChangesLitPaths[id], top?.path) + } + + public func allChangesTopFile(of id: AllChangesTab.ID) -> AllChangesTopFile? { + allChangesTopFiles[id] + } + + /// Uncached, as `layout` though another may be shown: what a find searched + /// before a switch that came while the tab was hidden. + func allChangesDocument( + of id: AllChangesTab.ID, + laidOutAs layout: FileTabLayout, + ) -> AllChangesDocument? { + guard allChangesDocument(of: id) != nil, let reading = allChangesReadings[id] else { + return nil + } + return AllChangesDocument( + reading, + collapsed: allChangesCollapsedFiles[id] ?? [], + heldOpen: allChangesHeldOpenLines(of: id), + layout: layout, + ) + } + + /// The lines each file keeps out of its folds: the folds opened, and each + /// comment's lines with two either side. + private func allChangesHeldOpenLines(of id: AllChangesTab.ID) -> [String: [AllChangesLineSpan]] { + let opened = allChangesOpenedFolds[id] ?? [:] + guard let tab = workspace.allChangesTab(id) else { return opened } + return opened.merging(allChangesReviewLines(of: tab), uniquingKeysWith: +) + } +} diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesEmptyText.swift b/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesEmptyText.swift new file mode 100644 index 000000000..fe7fded15 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesEmptyText.swift @@ -0,0 +1,56 @@ +import MultishellCore +import MultishellGitKit + +/// What an All changes tab says with no file to show, as the mockup's empty +/// state does; see Docs/design/files/all-changes-tab.md. +extension AppModel { + /// Under Branch, the base it counts from; under Modified, the worktree, and + /// what Branch would show where the project has a base. + public func allChangesEmptyText(of tab: AllChangesTab) -> PanelPageEmptyText { + if listsOnlyNestedRepositories(tab) { + return PanelPageEmptyText( + title: t("all-changes.only-nested-repositories"), + detail: t("all-changes.only-nested-repositories-hint"), + ) + } + if let base = fileTabBase(in: tab.worktreeID) { + return PanelPageEmptyText( + title: t("files-panel.no-branch-changes", base.shortName), + detail: nil, + ) + } + let name = workspace.worktree(tab.worktreeID).map(workspace.displayName(of:)) ?? "" + return PanelPageEmptyText( + title: t("all-changes.no-uncommitted", name), + detail: defaultBranch(ofWorktree: tab.worktreeID).map { branch in + t("all-changes.branch-hint", branch.shortName) + }, + ) + } + + /// Changes lists a nested repository, a submodule's folder or one git leaves + /// untracked with a trailing `/`, which the tab's read leaves out. + private func listsOnlyNestedRepositories(_ tab: AllChangesTab) -> Bool { + guard let reading = allChangesReadings[tab.id] else { return false } + if !reading.listed.isEmpty { return true } + let listed = allChangesListedChanges(of: tab.worktreeID) ?? [] + return !listed.isEmpty && listed.allSatisfy { $0.path.hasSuffix("/") } + } + + /// The Branch read that failed, said in place of the wait for a list that will + /// not come; `nil` while there is none. + public func allChangesReadFailure(of tab: AllChangesTab) -> PanelPageEmptyText? { + guard let base = fileTabBase(in: tab.worktreeID), + failedBranchReads[tab.worktreeID] == base.shortName + else { return nil } + return PanelPageEmptyText( + title: t("files-panel.branch-unreadable", base.shortName), + detail: nil, + ) + } + + /// Show Branch, under Modified where the project has a base to count from. + public func offersBranchScope(onEmpty tab: AllChangesTab) -> Bool { + workspace.changeScope == .modified && defaultBranch(ofWorktree: tab.worktreeID) != nil + } +} diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesIndex.swift b/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesIndex.swift new file mode 100644 index 000000000..446df699e --- /dev/null +++ b/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesIndex.swift @@ -0,0 +1,49 @@ +import Foundation +import MultishellCore +import MultishellGitKit + +/// The Changes list as the All changes tab's index: a row's click shows the +/// tab at that file; see Docs/design/files/all-changes-tab.md. +extension AppModel { + /// A file row's click: the All changes tab at that file on the Changes page; the + /// file's own tab on the Files page or for a file the tab does not list. + public func activateFileRow(_ path: String, in id: Worktree.ID) async { + guard shownFilesPanelMode == .changes, await allChangesTabMayList(path, in: id) else { + await openFileAsTab(path, in: id) + return + } + showFileInAllChangesTab(path, in: id) + } + + /// Listed by git, or its list still to land, and not a folder: a submodule's + /// change, which the tab's read leaves out. Off the main actor, as a dead mount holds an lstat. + private func allChangesTabMayList(_ path: String, in id: Worktree.ID) async -> Bool { + guard let changes = allChangesListedChanges(of: id) else { return true } + guard changes.contains(where: { $0.path == path }), let worktree = workspace.worktree(id) + else { return false } + let url = worktree.path.appending(path: path) + return await runOnDispatch { FileSignature.of(url)?.isFolder != true } + } + + /// The tab turned to, `path` expanded, scrolled to and lit at once: a file near + /// the end may never reach the top, so the view holds it lit until scrolled. + func showFileInAllChangesTab(_ path: String, in id: Worktree.ID) { + guard let tab = openAllChangesTab(in: id) else { return } + expandAllChangesFile(path, in: tab.id) + allChangesFileReveals[tab.id] = path + noteAllChangesTopFile(AllChangesTopFile(path: path, isHeaderScrolledPast: false), in: tab.id) + } + + /// A file picked from elsewhere shows its rows, not a collapsed header. + func expandAllChangesFile(_ path: String, in id: AllChangesTab.ID) { + guard allChangesCollapsedFiles[id]?.contains(path) == true else { return } + relayingOutAllChanges(id) { _ = allChangesCollapsedFiles[id]?.remove(path) } + } + + /// The view's, as it updates. Read first, as a removal of nothing still + /// redraws every All changes tab. + public func takeAllChangesFileReveal(_ id: AllChangesTab.ID) -> String? { + guard allChangesFileReveals[id] != nil else { return nil } + return allChangesFileReveals.removeValue(forKey: id) + } +} diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesOpening.swift b/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesOpening.swift new file mode 100644 index 000000000..cdbce5d50 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesOpening.swift @@ -0,0 +1,15 @@ +import MultishellCore + +/// The All changes tab opened from the Changes page or the command line; see +/// Docs/design/files/all-changes-tab.md. +extension AppModel { + /// The worktree's All changes tab, made or turned to, taking the keyboard. + @discardableResult + public func openAllChangesTab(in id: Worktree.ID) -> AllChangesTab? { + guard workspace.worktree(id) != nil, let tab = store.openAllChangesTab(in: id) else { + return nil + } + reconcileSessions(takingFocus: worktreeIDInView == id) + return tab + } +} diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesReads.swift b/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesReads.swift new file mode 100644 index 000000000..735fb867c --- /dev/null +++ b/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesReads.swift @@ -0,0 +1,233 @@ +import Foundation +import MultishellCore +import MultishellGitKit + +/// Keeping each All changes tab's files current with the worktree's changes, +/// paced and released as a file tab's are; see Docs/design/files/all-changes-tab.md. +extension AppModel { + /// The worktree's All changes tab where it is shown. + func shownAllChangesTab(in worktreeID: Worktree.ID) -> AllChangesTab? { + workspace.allChangesTab(in: worktreeID).flatMap { isTabShown($0.id) ? $0 : nil } + } + + /// What the Changes list lists under the scope, in its order; `nil` while + /// the read it comes from has yet to land. + func allChangesList(of id: Worktree.ID) -> [AllChangesFileChange]? { + guard let changes = allChangesListedChanges(of: id) else { return nil } + if let cached = allChangesLists[id], cached.changes == changes { return cached.list } + let list = AllChangesOrder.files(of: changes) + allChangesLists[id] = AllChangesListCacheEntry(changes: changes, list: list) + return list + } + + /// The same changes as git listed them, unsorted, for a check of whether a + /// list has landed or holds a path: sorting thousands costs a status landing. + func allChangesListedChanges(of id: Worktree.ID) -> [StatusChange]? { + if let base = fileTabBase(in: id) { + guard let changes = branchChanges[id], changes.baseName == base.shortName else { return nil } + return changes.changes + } + return statuses[id]?.changes + } + + /// A shown tab reads once the burst settles; a hidden one is owed a read. + func noteAllChangesTabChanged(_ id: AllChangesTab.ID, staleness: AllChangesStaleness) { + guard workspace.allChangesTab(id) != nil else { return } + allChangesStaleFiles.mark(staleness, in: id) + if isTabShown(id), platform.isWorkspaceWindowVisible { + scheduleAllChangesRead(id) + } else { + allChangesReadLog.owe(id) + } + } + + /// The tabs on screen holding nothing, or owed a read while hidden, and the + /// Branch read their list waits on. + func readShownAllChangesTabs() { + guard platform.isWorkspaceWindowVisible, let worktree = worktreeIDInView, + let tab = shownAllChangesTab(in: worktree) + else { return } + scheduleBranchChangesRead(of: worktree) + let isWaitedFor = allChangesReadings[tab.id] == nil + guard isWaitedFor || allChangesReadLog.owed.contains(tab.id) else { return } + guard !allChangesReadLog.isReading(tab.id) else { + if allChangesReadLog.owed.contains(tab.id) { allChangesReadLog.askAgain(tab.id) } + return + } + scheduleAllChangesRead(tab.id, atOnce: isWaitedFor) + } + + /// A shown tab that has read nothing, its list just landed: read at once, + /// without the settle and pace a change waits for. + func readAllChangesTabWaitingForItsList(_ id: AllChangesTab.ID) { + guard platform.isWorkspaceWindowVisible else { + allChangesReadLog.owe(id) + return + } + scheduleAllChangesRead(id, atOnce: true) + } + + /// The view's, as it builds files: those near its screen, which a read reads; + /// one there unread or stale is read at once. + public func noteAllChangesFilesNear(_ paths: Set, in id: AllChangesTab.ID) { + guard allChangesFilesNear[id] != paths else { return } + allChangesFilesNear[id] = paths + readNearFilesOwed(in: id) + } + + /// The files near the screen a read reads, a collapsed one showing no rows, and + /// the composer's wherever it is: its quote is checked against them on Add. + private func nearFilesToRead(in id: AllChangesTab.ID) -> Set { + var near = (allChangesFilesNear[id] ?? []).subtracting(allChangesCollapsedFiles[id] ?? []) + if let composer = reviewComposers[id] { near.insert(composer.path) } + return near + } + + /// Read at once where a file near the screen is owed one, as scrolled to, + /// expanded or left stale; a covered window owes the read instead. + func readNearFilesOwed(in id: AllChangesTab.ID) { + guard let reading = allChangesReadings[id], isTabShown(id), + nearFilesToRead(in: id).contains(where: reading.owesRead) + else { return } + guard platform.isWorkspaceWindowVisible else { + allChangesReadLog.owe(id) + return + } + scheduleAllChangesRead(id, atOnce: true) + } + + /// A hidden tab holds no rows, so content nobody sees holds no memory; its + /// waiting read is owed instead. + func releaseHiddenAllChangesTabs() { + for tab in workspace.allChangesTabs where !isTabShown(tab.id) { + forgetChangeSteps(of: tab.id) + if let task = pendingAllChangesReads.removeValue(forKey: tab.id) { + task.cancel() + allChangesReadLog.owe(tab.id) + } + guard allChangesReadings[tab.id] != nil, !allChangesReadLog.isReading(tab.id) else { + continue + } + allChangesReadings[tab.id] = nil + allChangesDocuments[tab.id] = nil + } + } + + /// One read per tab at a time, after the settle and once its pace allows, or + /// `atOnce` in place of one waiting; a change during a read is read again after it. + private func scheduleAllChangesRead(_ id: AllChangesTab.ID, atOnce: Bool = false) { + if atOnce { pendingAllChangesReads.removeValue(forKey: id)?.cancel() } + guard pendingAllChangesReads[id] == nil else { return } + pendingAllChangesReads[id] = pacedRead(atOnce: atOnce) { model in + model.allChangesReadLog.nextDue(id, costScale: model.filesOwed(by: id)) + } read: { model in + model.pendingAllChangesReads[id] = nil + await model.readAllChangesTab(id) + } + } + + func readAllChangesTab(_ id: AllChangesTab.ID) async { + guard let coordinator, let tab = workspace.allChangesTab(id), + let worktree = workspace.worktree(tab.worktreeID) + else { return } + // A Branch list still to land reads the tab when it does. + guard let list = allChangesList(of: tab.worktreeID) else { return } + guard !allChangesReadLog.isReading(id) else { + allChangesReadLog.askAgain(id) + return + } + allChangesReadLog.begin(id) + let started = ContinuousClock.now + let rereading = allChangesStaleFiles.take(id) + let (reading, filesRead) = await AllChangesReader.read( + list, + in: worktree.path, + git: coordinator.git, + diffAlgorithm: workspace.diffAlgorithm, + since: fileTabBase(in: tab.worktreeID), + previous: allChangesReadings[id], + rereading: rereading, + imageRule: imageRule, + near: nearFilesToRead(in: id), + ) + let isSuperseded = allChangesReadLog.isSuperseded(id) + // Noted a file's worth, the next read waiting by the files it will read. + let readsAgain = allChangesReadLog.finish( + id, + cost: started.duration(to: .now) / max(1, filesRead), + ) + guard workspace.allChangesTab(id) != nil else { return } + guard !isSuperseded else { + if isTabShown(id) { scheduleAllChangesRead(id) } else { allChangesReadLog.owe(id) } + return + } + // Hidden while it ran, it would hold rows nobody sees; shown again it reads anew. + guard isTabShown(id) else { + allChangesStaleFiles.mark(rereading, in: id) + allChangesReadLog.owe(id) + releaseHiddenAllChangesTabs() + return + } + let previous = allChangesReadings[id] + let before = allChangesDocument(of: id).map(SearchedLayout.allChanges) + if setIfChanged(\.allChangesReadings[id], reading) { + reanchorReview(in: tab, toFilesMovedSince: previous, in: reading) + rerunFileFind(in: id, laidOutBefore: before) + } + // Files scrolled to while it ran were read by none; the near set did not change since. + readNearFilesOwed(in: id) + if readsAgain { scheduleAllChangesRead(id) } + } + + /// Each file whose rows moved has its comments, and the composer on it, + /// follow their quotes, as a file tab's read does; a gone or stale file's stay put. + private func reanchorReview( + in tab: AllChangesTab, + toFilesMovedSince previous: AllChangesReading?, + in reading: AllChangesReading, + ) { + let scope = fileTabScope(in: tab.worktreeID) + var rowsByPath: [String: [DiffLine]] = [:] + for file in reading.files where !file.isStale && file != previous?.file(at: file.path) { + guard let rows = file.rows, file.reading?.isFileGone == false else { continue } + rowsByPath[file.path] = rows.lines + reanchorReviewComposer(in: tab.id, onFile: file.path, to: rows.lines, readUnder: scope) + } + reanchorReviewComments(onFiles: rowsByPath, in: tab.worktreeID, readUnder: scope) + } + + /// How many files the next read reads: those near the screen that a git + /// change, an event or the list moved, the rest only kept stale. + func filesOwed(by id: AllChangesTab.ID) -> Int { + let near = nearFilesToRead(in: id) + switch allChangesStaleFiles.pending(id) { + case .everything: return max(1, near.count) + case .paths(let paths): return max(1, paths.intersection(near).count) + } + } + + /// A closed tab's rows, reads and pending work go with it. Run from the reconcile. + func pruneAllChangesTabs() { + let open = Set(workspace.allChangesTabs.map(\.id)) + setIfChanged(\.allChangesReadings, allChangesReadings.filter { open.contains($0.key) }) + for (id, task) in pendingAllChangesReads where !open.contains(id) { + task.cancel() + pendingAllChangesReads[id] = nil + } + allChangesReadLog.keep(only: open) + allChangesStaleFiles.keep(only: open) + allChangesFilesNear = allChangesFilesNear.filter { open.contains($0.key) } + let listed = Set(workspace.allChangesTabs.map(\.worktreeID)) + allChangesLists = allChangesLists.filter { listed.contains($0.key) } + allChangesScrolls = allChangesScrolls.filter { open.contains($0.key) } + setIfChanged( + \.allChangesCollapsedFiles, + allChangesCollapsedFiles.filter { open.contains($0.key) }, + ) + setIfChanged(\.allChangesOpenedFolds, allChangesOpenedFolds.filter { open.contains($0.key) }) + setIfChanged(\.allChangesTopFiles, allChangesTopFiles.filter { open.contains($0.key) }) + setIfChanged(\.allChangesLitPaths, allChangesLitPaths.filter { open.contains($0.key) }) + setIfChanged(\.allChangesFileReveals, allChangesFileReveals.filter { open.contains($0.key) }) + allChangesDocuments = allChangesDocuments.filter { open.contains($0.key) } + } +} diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesScroll.swift b/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesScroll.swift new file mode 100644 index 000000000..64e53afb8 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesScroll.swift @@ -0,0 +1,13 @@ +import MultishellCore + +/// An All changes tab's scroll, which outlives the view a hidden tab drops and, +/// saved at quit, the launch. +extension AppModel { + public func noteAllChangesScrolled(_ id: AllChangesTab.ID, to scroll: AllChangesScroll) { + allChangesScrolls[id] = scroll + } + + public func allChangesScroll(of id: AllChangesTab.ID) -> AllChangesScroll? { + allChangesScrolls[id] ?? workspace.allChangesTab(id)?.scroll + } +} diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesWatch.swift b/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesWatch.swift new file mode 100644 index 000000000..b1942ecea --- /dev/null +++ b/Sources/MultishellAppCore/Model/Files/AppModel+AllChangesWatch.swift @@ -0,0 +1,84 @@ +import Foundation +import MultishellCore +import MultishellGitKit + +/// Which All changes tabs a watcher batch, a status or Branch read, or a new +/// scope moved, and which of their files; see Docs/design/files/all-changes-tab.md. +extension AppModel { + /// What moved each tab's files, as each file tab would read it; see "A read + /// reads only what moved" in Docs/design/files/all-changes-tab.md. + func noteAllChangesTabChanges(_ targets: FileChangeTargets) { + for tab in workspace.allChangesTabs { + guard let worktree = workspace.worktree(tab.worktreeID) else { continue } + let changed = targets.fileChangesByWorktree[worktree.id] ?? [] + let embedded = targets.embeddedRepositoriesWithGitChanges[worktree.id] ?? [] + let reading = allChangesReadings[tab.id] + if targets.projectsWithGitChanges.contains(worktree.projectID) + || changed.contains(FileChangeTargets.wholeWorktree) + || (!embedded.isEmpty && reading == nil) + { + noteAllChangesTabChanged(tab.id, staleness: .everything) + } else if let reading { + let inRepositories = reading.paths(inRepositories: embedded) + if !inRepositories.isEmpty { + noteAllChangesTabChanged(tab.id, staleness: .paths(inRepositories)) + } + let touched = changed.isEmpty ? [] : reading.filesTouched(by: changed) + if !touched.isEmpty { checkAllChangesSignatures(of: touched, in: tab, at: worktree.path) } + } + // Its window in the background, only the panel's worktree has its status read. + if !platform.isActive, isTabShown(tab.id), targets.mayHaveChangedStatus(of: worktree) { + scheduleStatusRefresh(of: worktree.id) + } + } + } + + /// Off the main actor, a dead mount being able to hold an `lstat`. + private func checkAllChangesSignatures( + of files: [AllChangesFile], + in tab: AllChangesTab, + at worktree: URL, + ) { + let checked = files.map { ($0.path, $0.signature) } + Task { @MainActor [weak self] in + let moved = await runOnDispatch { + checked.filter { path, signature in + FileSignature.of(worktree.appending(path: path)) != signature + } + .map(\.0) + } + guard let self, !moved.isEmpty else { return } + noteAllChangesTabChanged(tab.id, staleness: .paths(Set(moved))) + } + } + + /// A status or Branch read landing: files new to the list, or counted + /// otherwise, are read again; the rest keep their rows. + func noteAllChangesListLanded(in worktreeID: Worktree.ID) { + guard let tab = workspace.allChangesTab(in: worktreeID) else { return } + guard let reading = allChangesReadings[tab.id] else { + // A shown tab waiting on its first list reads now it has one, unpaced: it shows nothing. + if isTabShown(tab.id), allChangesListedChanges(of: worktreeID) != nil { + readAllChangesTabWaitingForItsList(tab.id) + } + return + } + guard let list = allChangesList(of: worktreeID) else { return } + // Unchanged, a read that waited on this list still has what it was to read. + guard list != reading.listed || allChangesStaleFiles.pending(tab.id) != .nothing else { return } + let listed = Set(reading.listed) + let moved = list.filter { !listed.contains($0) }.map(\.path) + noteAllChangesTabChanged(tab.id, staleness: .paths(Set(moved))) + } + + /// A new scope, algorithm or base: every file of the tabs it reaches is read + /// afresh, at once rather than at the pace the old diffs set. + func noteAllChangesTabsChanged(where isReached: (AllChangesTab) -> Bool) { + for tab in workspace.allChangesTabs where isReached(tab) { + allChangesReadLog.forgetPace(of: tab.id) + pendingAllChangesReads.removeValue(forKey: tab.id)?.cancel() + noteAllChangesTabChanged(tab.id, staleness: .everything) + } + readShownAllChangesTabs() + } +} diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+BranchChanges.swift b/Sources/MultishellAppCore/Model/Files/AppModel+BranchChanges.swift index 8d72fcced..3ff3ff8a2 100644 --- a/Sources/MultishellAppCore/Model/Files/AppModel+BranchChanges.swift +++ b/Sources/MultishellAppCore/Model/Files/AppModel+BranchChanges.swift @@ -8,6 +8,14 @@ extension AppModel { workspace.filesPanelMode == .changes && workspace.changeScope == .branch } + /// The panel's worktree while it lists Branch, or a worktree whose All + /// changes tab is shown under Branch, which takes its list from this read. + func readsBranchChanges(of id: Worktree.ID) -> Bool { + guard workspace.changeScope == .branch else { return false } + let isPanelListing = showsFilesPanel && filesPanelWorktree?.id == id && listsBranchChanges + return isPanelListing || shownAllChangesTab(in: id) != nil + } + /// What the panel counts the worktree's changes against, as its footer says. func changeComparison(of id: Worktree.ID) -> ChangeComparison { guard listsBranchChanges, let worktree = workspace.worktree(id) else { return .head } @@ -21,12 +29,14 @@ extension AppModel { return .branch(changes) } - /// Leaving Branch lets go of what it read, so coming back draws none as current. + /// Leaving Branch lets go of what it read, so coming back draws none as current; + /// a shown All changes tab's worktree keeps its own. func forgetBranchChangesUnlessListed() { + // The panel's mode is set before it shows, so its own listing is not yet "read". guard !listsBranchChanges else { return } - branchChangesReads.cancel { _ in true } - setIfChanged(\.branchChanges, [:]) - setIfChanged(\.failedBranchReads, [:]) + branchChangesReads.cancel { !readsBranchChanges(of: $0) } + setIfChanged(\.branchChanges, branchChanges.filter { readsBranchChanges(of: $0.key) }) + setIfChanged(\.failedBranchReads, failedBranchReads.filter { readsBranchChanges(of: $0.key) }) } /// The panel's worktree's, where it lists Branch. @@ -36,7 +46,7 @@ extension AppModel { /// Paced, as every status landing asks for one. func scheduleBranchChangesRead(of id: Worktree.ID) { - guard showsFilesPanel, filesPanelWorktree?.id == id, listsBranchChanges, let coordinator, + guard readsBranchChanges(of: id), let coordinator, let worktree = workspace.worktree(id), mayReadStatus(of: worktree), let base = defaultBranch(ofWorktree: id), // Its new files come from the status read, whose landing asks again. @@ -64,6 +74,7 @@ extension AppModel { else { return } if let changes { model.setIfChanged(\.branchChanges[id], changes) } model.setIfChanged(\.failedBranchReads[id], changes == nil ? base.shortName : nil) + model.noteAllChangesListLanded(in: id) }, rerun: { $0.scheduleBranchChangesRead(of: id) }, ) diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+ChangeScope.swift b/Sources/MultishellAppCore/Model/Files/AppModel+ChangeScope.swift index a47987672..868f8b5f2 100644 --- a/Sources/MultishellAppCore/Model/Files/AppModel+ChangeScope.swift +++ b/Sources/MultishellAppCore/Model/Files/AppModel+ChangeScope.swift @@ -12,9 +12,10 @@ extension AppModel { public func setChangeScope(_ scope: ChangeScope) { guard workspace.changeScope != scope else { return } store.setChangeScope(scope) - noteFileTabsChanged(releasingDots: true, where: offersChangeScopeSwitch(for:)) + noteFileTabsChanged(releasingDots: true) { offersChangeScopeSwitch(in: $0.worktreeID) } forgetBranchChangesUnlessListed() schedulePanelBranchChangesRead() + noteAllChangesTabsChanged { offersChangeScopeSwitch(in: $0.worktreeID) } } /// Branch counts from the base, which a fetch moves and a launch resolves late. @@ -30,12 +31,13 @@ extension AppModel { noteFileTabsChanged(releasingDots: isNewBase) { tab in workspace.worktree(tab.worktreeID)?.projectID == id } + noteAllChangesTabsChanged { workspace.worktree($0.worktreeID)?.projectID == id } } - /// Only where the project has a base branch, a tab there counting from `HEAD` - /// whatever the choice. - public func offersChangeScopeSwitch(for tab: FileTab) -> Bool { - defaultBranch(ofWorktree: tab.worktreeID) != nil + /// A file or All changes tab's bar offers it only where the project has a base + /// branch, a tab there counting from `HEAD` whatever the choice. + public func offersChangeScopeSwitch(in worktreeID: Worktree.ID) -> Bool { + defaultBranch(ofWorktree: worktreeID) != nil } /// What a file tab in the worktree counts from in place of `HEAD`: its diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+FileFind.swift b/Sources/MultishellAppCore/Model/Files/AppModel+FileFind.swift index 04fa46a2e..5dde2efab 100644 --- a/Sources/MultishellAppCore/Model/Files/AppModel+FileFind.swift +++ b/Sources/MultishellAppCore/Model/Files/AppModel+FileFind.swift @@ -1,8 +1,16 @@ import MultishellCore -/// The find bar over a file tab, searched in its rows rather than by the -/// engine; see Docs/design/files/file-tabs.md. `AppModel+Find` routes a file tab here. +/// The find bar over a file or All changes tab, searched in its rows rather +/// than by the engine; see Docs/design/files/file-tabs.md. extension AppModel { + /// A file or All changes tab: its rows are searched here, a pane's by the engine. + func searchesRowsInModel(_ id: FindTargetID) -> Bool { + switch workspace.workspaceTab(id) { + case .allChanges, .file: true + case .terminal, nil: false + } + } + /// While its bar is up; the view highlights each. public func fileFindMatches(of id: FileTab.ID) -> [Range] { findBarTargetIDs.contains(id) ? fileFindResults[id]?.matches ?? [] : [] @@ -37,11 +45,11 @@ extension AppModel { for text: String, in id: FileTab.ID, keepingSelection: Bool = false, - laidOutBefore previousText: DiffDisplayText? = nil, + laidOutBefore previousLayout: SearchedLayout? = nil, ) { // A hidden tab's rows are let go; its result waits for the read on show, // a new search starting over then. - if fileTabReadings[id]?.content.isReleased == true, !text.isEmpty { + if isAwaitingRowsToFind(id), !text.isEmpty { if !keepingSelection { setIfChanged( \.fileFindResults[id], @@ -50,27 +58,43 @@ extension AppModel { } return } - guard !text.isEmpty, let searched = searchedText(of: id) else { + guard !text.isEmpty, let searched = searchedLayout(of: id) else { setIfChanged(\.fileFindResults[id], nil) return } var previous = fileFindResults[id] - if let previousText { previous = previous?.carried(from: previousText, to: searched) } + if let previousLayout { previous = previous?.carried(from: previousLayout, to: searched) } var result = FileFindResult.searching( text, - in: searched, + in: searched.text, after: previous, keepingSelection: keepingSelection, ) - result.isSearchedInSplit = workspace.fileTab(id).flatMap(shownSplit(of:)) != nil + result.isSearchedInSplit = showsSplit(id) setIfChanged(\.fileFindResults[id], result) } - /// What find searches in a tab: a split's right side, the file on disk. - func searchedText(of id: FileTab.ID) -> DiffDisplayText? { - guard let tab = workspace.fileTab(id), case .text(let rows) = fileTabReadings[id]?.content - else { return nil } - return shownSplit(of: tab)?.onDisk ?? rows.displayText + /// What find searches in a tab: a split's right side, the file on disk; the + /// All changes tab's shown rows. + func searchedLayout(of id: FindTargetID) -> SearchedLayout? { + switch workspace.workspaceTab(id) { + case .file(let tab): + guard case .text(let rows) = fileTabReadings[id]?.content else { return nil } + return .fileText(shownSplit(of: tab)?.onDisk ?? rows.displayText) + + case .allChanges: return allChangesDocument(of: id).map(SearchedLayout.allChanges) + case .terminal, nil: return nil + } + } + + /// A hidden tab's rows are let go, so its find waits for the read on show; + /// an All changes tab's read under another base waits for the new base's. + private func isAwaitingRowsToFind(_ id: FindTargetID) -> Bool { + switch workspace.workspaceTab(id) { + case .file: fileTabReadings[id]?.content.isReleased == true + case .allChanges: allChangesDocument(of: id) == nil + case .terminal, nil: false + } } func stepFileFind(_ direction: CycleDirection, in id: FileTab.ID) { @@ -78,23 +102,42 @@ extension AppModel { } /// A re-read moves the text under a search, so its matches are found again. - func rerunFileFind(in id: FileTab.ID, laidOutBefore previousText: DiffDisplayText? = nil) { + func rerunFileFind(in id: FileTab.ID, laidOutBefore previousLayout: SearchedLayout? = nil) { guard findBarTargetIDs.contains(id) else { return } runFileFind( for: findText(of: id), in: id, keepingSelection: true, - laidOutBefore: previousText ?? otherLayoutSearched(in: id), + laidOutBefore: previousLayout ?? otherLayoutSearched(in: id), ) } /// The other layout's text where the result was searched in it, a switch /// having come while the tab was hidden and its rows let go. - private func otherLayoutSearched(in id: FileTab.ID) -> DiffDisplayText? { - guard let result = fileFindResults[id], let tab = workspace.fileTab(id), - case .text(let rows) = fileTabReadings[id]?.content, - result.isSearchedInSplit != (shownSplit(of: tab) != nil) - else { return nil } - return result.isSearchedInSplit ? rows.split?.onDisk : rows.displayText + private func otherLayoutSearched(in id: FindTargetID) -> SearchedLayout? { + guard let result = fileFindResults[id], result.isSearchedInSplit != showsSplit(id) else { + return nil + } + switch workspace.workspaceTab(id) { + case .file: + guard case .text(let rows) = fileTabReadings[id]?.content else { return nil } + return (result.isSearchedInSplit ? rows.split?.onDisk : rows.displayText) + .map(SearchedLayout.fileText) + + case .allChanges: + return allChangesDocument(of: id, laidOutAs: result.isSearchedInSplit ? .split : .unified) + .map(SearchedLayout.allChanges) + + case .terminal, nil: + return nil + } + } + + private func showsSplit(_ id: FindTargetID) -> Bool { + switch workspace.workspaceTab(id) { + case .file(let tab): shownSplit(of: tab) != nil + case .allChanges: workspace.fileTabLayout == .split + case .terminal, nil: false + } } } diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+FileTabChangeStep.swift b/Sources/MultishellAppCore/Model/Files/AppModel+FileTabChangeStep.swift index 9a0907f4b..5714934f4 100644 --- a/Sources/MultishellAppCore/Model/Files/AppModel+FileTabChangeStep.swift +++ b/Sources/MultishellAppCore/Model/Files/AppModel+FileTabChangeStep.swift @@ -33,4 +33,11 @@ extension AppModel { guard changeStepRequests[id] != nil else { return [] } return changeStepRequests.removeValue(forKey: id) ?? [] } + + /// A hidden tab's view goes, and the next one says afresh where its arrows + /// lead; a step queued for a view that never drew would jump the next one. + func forgetChangeSteps(of id: FileTab.ID) { + if fileTabChangeSteps[id] != nil { fileTabChangeSteps[id] = nil } + if changeStepRequests[id] != nil { changeStepRequests[id] = nil } + } } diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+FileTabFocus.swift b/Sources/MultishellAppCore/Model/Files/AppModel+FileTabFocus.swift index 6a6516483..a725f9a7f 100644 --- a/Sources/MultishellAppCore/Model/Files/AppModel+FileTabFocus.swift +++ b/Sources/MultishellAppCore/Model/Files/AppModel+FileTabFocus.swift @@ -1,13 +1,16 @@ import MultishellCore -/// The keyboard and a file tab. Only a surface reports its own focus to the -/// store, so a file tab's view reports its own here; see tabs-and-groups/tab-strip.md. +/// The keyboard and a file or All changes tab, whose view reports its focus here +/// as only a surface reports to the store; see tabs-and-groups/tab-strip.md. extension AppModel { - /// The reconcile's hand-off: a file tab in front takes the keyboard, as the - /// focused pane of a terminal tab does. + /// The reconcile's hand-off: a file or All changes tab in front takes the + /// keyboard, as the focused pane of a terminal tab does. func requestFocusForFileTabInView() { - guard case .file(let tab) = workspaceTabInView else { return } - fileTabFocusRequest = tab.id + switch workspaceTabInView { + case .file(let tab): fileTabFocusRequest = tab.id + case .allChanges(let tab): fileTabFocusRequest = tab.id + case .terminal, nil: return + } } /// The view's, once on screen: `true` once per hand-off, and the view @@ -18,10 +21,10 @@ extension AppModel { return true } - /// A click into a file tab: its tab and group take the focus, so Cmd+W and - /// the menus act there and not on the group the keyboard was in before. - public func noteFileTabFocused(_ id: FileTab.ID) { - guard let tab = workspace.fileTab(id) else { return } + /// A click into a file or All changes tab: its tab and group take the focus, + /// so Cmd+W and the menus act there and not on the group the keyboard was in. + public func noteFileTabFocused(_ id: WorkspaceTab.ID) { + guard let tab = workspace.workspaceTab(id) else { return } if workspace.activeWorkspaceTab(in: tab.worktreeID)?.id != id { store.activateTab(id) } } } diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+FileTabLayout.swift b/Sources/MultishellAppCore/Model/Files/AppModel+FileTabLayout.swift index d5048bc2b..f005af8c5 100644 --- a/Sources/MultishellAppCore/Model/Files/AppModel+FileTabLayout.swift +++ b/Sources/MultishellAppCore/Model/Files/AppModel+FileTabLayout.swift @@ -27,7 +27,9 @@ extension AppModel { /// again over the text now shown, its selection carried by line. public func setFileTabLayout(_ layout: FileTabLayout) { guard workspace.fileTabLayout != layout else { return } - let searchedBefore = workspace.fileTabs.map { ($0.id, searchedText(of: $0.id)) } + let searchedBefore = (workspace.fileTabs.map(\.id) + workspace.allChangesTabs.map(\.id)).map { + id in (id, searchedLayout(of: id)) + } store.setFileTabLayout(layout) for (id, text) in searchedBefore { rerunFileFind(in: id, laidOutBefore: text) } } diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+FileTabReads.swift b/Sources/MultishellAppCore/Model/Files/AppModel+FileTabReads.swift index 64d2da278..ecc1af81b 100644 --- a/Sources/MultishellAppCore/Model/Files/AppModel+FileTabReads.swift +++ b/Sources/MultishellAppCore/Model/Files/AppModel+FileTabReads.swift @@ -5,10 +5,7 @@ import MultishellGitKit /// Keeping each file tab's rows or image current with its file and its git; see /// Docs/design/files/file-tabs.md. extension AppModel { - /// A burst of saves becomes one read: 0.15 s of FSEvents latency, then this. - private static var fileTabSettleDelay: Duration { .milliseconds(75) } - - private var imageRule: ImageRule { + var imageRule: ImageRule { let platform = self.platform return ImageRule( opensAsImage: { platform.opensAsImage(named: $0) }, @@ -16,17 +13,11 @@ extension AppModel { ) } - /// In front of its group, in the worktree in view. - func isFileTabShown(_ id: FileTab.ID) -> Bool { - guard let tab = workspace.fileTab(id), tab.worktreeID == worktreeIDInView else { return false } - return workspace.group(tab.groupID)?.shownTabID == id - } - /// A shown tab reads again once the burst settles; a hidden one is owed a /// read for when shown, but a deletion strikes its title at once. func noteFileTabChanged(_ id: FileTab.ID) { guard workspace.fileTab(id) != nil else { return } - if isFileTabShown(id), platform.isWorkspaceWindowVisible { + if isTabShown(id), platform.isWorkspaceWindowVisible { scheduleFileTabRead(id) return } @@ -85,11 +76,8 @@ extension AppModel { /// A hidden tab keeps its dot and strike, and a gone file's rows or copy on /// disk, the last it showed; see files/file-tabs.md. Its waiting read is owed instead. func releaseHiddenFileTabs() { - for tab in workspace.fileTabs where !isFileTabShown(tab.id) { - // Its view goes with it, and the next one says afresh where its arrows lead; - // a step queued for a view that never drew would jump the next one. - if fileTabChangeSteps[tab.id] != nil { fileTabChangeSteps[tab.id] = nil } - if changeStepRequests[tab.id] != nil { changeStepRequests[tab.id] = nil } + for tab in workspace.fileTabs where !isTabShown(tab.id) { + forgetChangeSteps(of: tab.id) if let task = pendingFileTabReads.removeValue(forKey: tab.id) { task.cancel() fileTabReadLog.owe(tab.id) @@ -106,14 +94,11 @@ extension AppModel { /// `atOnce`; a change during a read is read again after it. private func scheduleFileTabRead(_ id: FileTab.ID, atOnce: Bool = false) { guard pendingFileTabReads[id] == nil else { return } - pendingFileTabReads[id] = Task { @MainActor [weak self] in - if !atOnce { try? await Task.sleep(for: Self.fileTabSettleDelay) } - while !atOnce, !Task.isCancelled, let due = self?.fileTabReadLog.nextDue(id), due > .now { - try? await Task.sleep(until: due) - } - guard !Task.isCancelled, let self else { return } - pendingFileTabReads[id] = nil - await readFileTab(id) + pendingFileTabReads[id] = pacedRead(atOnce: atOnce) { model in + model.fileTabReadLog.nextDue(id) + } read: { model in + model.pendingFileTabReads[id] = nil + await model.readFileTab(id) } } @@ -141,7 +126,7 @@ extension AppModel { let readsAgain = fileTabReadLog.finish(id, cost: started.duration(to: .now)) guard workspace.fileTab(id) != nil else { return } guard !isSuperseded else { - if isFileTabShown(id) { scheduleFileTabRead(id) } else { fileTabReadLog.owe(id) } + if isTabShown(id) { scheduleFileTabRead(id) } else { fileTabReadLog.owe(id) } return } // An unchanged reading has nothing new to anchor to, and a 1 MiB file is a long search. @@ -155,6 +140,7 @@ extension AppModel { ) reanchorReviewComposer( in: id, + onFile: tab.path, to: rows.lines, readUnder: Self.fileTabScope(readingSince: base), ) @@ -170,7 +156,7 @@ extension AppModel { releaseHiddenFileTabs() rerunFileFind(in: id) if readsAgain { - if isFileTabShown(id) { scheduleFileTabRead(id) } else { fileTabReadLog.owe(id) } + if isTabShown(id) { scheduleFileTabRead(id) } else { fileTabReadLog.owe(id) } } // Hidden meanwhile, its file may have gone since this read looked. if fileTabReadLog.owed.contains(id) { strikeIfGoneOrBack(id) } @@ -195,7 +181,7 @@ extension AppModel { } // A file back on a hidden or released tab lets go of what was kept, its dot // following the status: that is no diff of what came back. - let isBackUnread = !isGone && (!isFileTabShown(id) || content.isReleased) + let isBackUnread = !isGone && (!isTabShown(id) || content.isReleased) let kept = isBackUnread ? FileTabContent.releasedFollowingStatus : content setIfChanged(\.fileTabReadings[id], FileTabReading(content: kept, isFileGone: isGone)) rerunFileFind(in: id) @@ -207,10 +193,10 @@ extension AppModel { fileTabReadLog.noteHighlightCost(cost, of: id) } - /// A closed tab's rows or image, reads, selection, scroll and requests go - /// with it. Run from the reconcile. + /// A closed tab's rows, reads, selection, scroll and requests go with it, the All + /// changes tab sharing every table but the reads. Run from the reconcile. func pruneFileTabs() { - let open = Set(workspace.fileTabs.map(\.id)) + let open = Set(workspace.fileTabs.map(\.id) + workspace.allChangesTabs.map(\.id)) setIfChanged(\.fileTabReadings, fileTabReadings.filter { open.contains($0.key) }) for (id, task) in pendingFileTabReads where !open.contains(id) { task.cancel() diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+FilesPanel.swift b/Sources/MultishellAppCore/Model/Files/AppModel+FilesPanel.swift index 671c4a239..d51a8b0ec 100644 --- a/Sources/MultishellAppCore/Model/Files/AppModel+FilesPanel.swift +++ b/Sources/MultishellAppCore/Model/Files/AppModel+FilesPanel.swift @@ -25,6 +25,9 @@ extension AppModel { /// Modified or Branch, drawn over the Changes list alone, Files counting from `HEAD`. public var filesPanelShowsChangeScopeSwitch: Bool { shownFilesPanelMode == .changes } + /// The button beside the filter opening the All changes tab, on the Changes page. + public var filesPanelOffersAllChangesTab: Bool { shownFilesPanelMode == .changes } + /// Where the panel can be but is shut: open, its own header carries the toggle. public var worktreeHeaderShowsFilesPanelToggle: Bool { !showsFilesPanel && filesPanelWorktree != nil @@ -45,6 +48,22 @@ extension AppModel { setShowsFilesPanel(!showsFilesPanel) } + /// Whether the panel is open on `mode`'s page, which View ticks. + public func isFilesPanelShowing(_ mode: FilesPanelMode) -> Bool { + showsFilesPanel && shownFilesPanelMode == mode + } + + /// A View menu pane: shut where the panel shows its page or has no worktree + /// to list, else open on it. + public func toggleFilesPanel(on mode: FilesPanelMode) { + if isFilesPanelShowing(mode) || filesPanelWorktree == nil { + setShowsFilesPanel(false) + } else { + setFilesPanelMode(mode) + setShowsFilesPanel(true) + } + } + /// The rows' fit, measured only where asked: a services' page wraps its text /// rather than cut it, so a double-click on the edge puts it back to its first width. public func filesPanelWidthOnDoubleClick(fittingRows rowsWidth: () -> Double) -> Double { @@ -152,13 +171,19 @@ extension AppModel { ) } - /// The row of the file whose tab is in front of the focused group. + /// The row of the file whose tab is in front of the focused group, or at the + /// top of the All changes tab there. public func isShownFile(_ row: FileTreeRow, in id: Worktree.ID) -> Bool { row.isShown(whenFileInFrontIs: shownFilePath(in: id)) } - /// The file whose tab is in front of the focused group, which its row lights. + /// The file whose tab is in front of the focused group, or the file at the top + /// of the All changes tab in front, which its row lights. func shownFilePath(in id: Worktree.ID) -> String? { - workspace.activeWorkspaceTab(in: id)?.fileTab?.path + switch workspace.activeWorkspaceTab(in: id) { + case .file(let tab): tab.path + case .allChanges(let tab): allChangesLitPaths[tab.id] + case .terminal, nil: nil + } } } diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+FilesPanelReads.swift b/Sources/MultishellAppCore/Model/Files/AppModel+FilesPanelReads.swift index 5fe244c4d..61e584e96 100644 --- a/Sources/MultishellAppCore/Model/Files/AppModel+FilesPanelReads.swift +++ b/Sources/MultishellAppCore/Model/Files/AppModel+FilesPanelReads.swift @@ -48,9 +48,11 @@ extension AppModel { } trackedFilesReadsAskedAgain = trackedFilesReadsAskedAgain.filter { !isForgotten($0) } ignoredEntriesReads.cancel(where: isForgotten) - branchChangesReads.cancel(where: isForgotten) - setIfChanged(\.branchChanges, branchChanges.filter { !isForgotten($0.key) }) - setIfChanged(\.failedBranchReads, failedBranchReads.filter { !isForgotten($0.key) }) + // A shown All changes tab takes its list from the Branch read, panel or not. + func forgetsBranch(_ id: Worktree.ID) -> Bool { isForgotten(id) && !readsBranchChanges(of: id) } + branchChangesReads.cancel(where: forgetsBranch) + setIfChanged(\.branchChanges, branchChanges.filter { !forgetsBranch($0.key) }) + setIfChanged(\.failedBranchReads, failedBranchReads.filter { !forgetsBranch($0.key) }) setIfChanged(\.trackedFiles, trackedFiles.filter { !isForgotten($0.key) }) setIfChanged(\.ignoredEntries, ignoredEntries.filter { !isForgotten($0.key) }) fileTreeCache = fileTreeCache.filter { !isForgotten($0.key) } @@ -183,18 +185,20 @@ extension AppModel { ) } - /// Events skipped while the window was covered: its file tabs and, in the - /// background where no return to the front reads it, the panel. + /// Events skipped while the window was covered: its file and All changes + /// tabs and, in the background where no return to the front reads it, the panel. func readWhatTheWindowShowsOnceVisible() { readShownFileTabs() + readShownAllChangesTabs() if showsFilesPanel, !platform.isActive, let worktree = filesPanelWorktree { readFilesPanel(of: worktree.id) } } - /// The panel's worktree is read on its events while its window shows, front - /// or not, so coming back never shows a stale list. + /// The panel's worktree, and a shown All changes tab's, is read on its events + /// while its window shows, front or not, so coming back never shows a stale list. func readsStatusInTheBackground(_ id: Worktree.ID) -> Bool { - isFileListOnScreen && platform.isWorkspaceWindowVisible && filesPanelWorktree?.id == id + guard platform.isWorkspaceWindowVisible else { return false } + return (isFileListOnScreen && filesPanelWorktree?.id == id) || shownAllChangesTab(in: id) != nil } } diff --git a/Sources/MultishellAppCore/Model/Files/AppModel+PacedRead.swift b/Sources/MultishellAppCore/Model/Files/AppModel+PacedRead.swift new file mode 100644 index 000000000..24004beb9 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Files/AppModel+PacedRead.swift @@ -0,0 +1,23 @@ +/// The wait before a file tab's or the All changes tab's read, which a burst +/// of saves and the last read's cost set; see Docs/design/files/file-tabs.md. +extension AppModel { + /// A burst of saves becomes one read: 0.15 s of FSEvents latency, then this. + private static var readSettleDelay: Duration { .milliseconds(75) } + + /// `read` after the settle and once `nextDue` allows, or `atOnce`; the model + /// is not held while it waits. + func pacedRead( + atOnce: Bool, + nextDue: @escaping @MainActor (AppModel) -> ContinuousClock.Instant?, + read: @escaping @MainActor (AppModel) async -> Void, + ) -> Task { + Task { @MainActor [weak self] in + if !atOnce { try? await Task.sleep(for: Self.readSettleDelay) } + while !atOnce, !Task.isCancelled, let due = self.flatMap(nextDue), due > .now { + try? await Task.sleep(until: due) + } + guard !Task.isCancelled, let self else { return } + await read(self) + } + } +} diff --git a/Sources/MultishellAppCore/Model/GitReads/AppModel+FileChanges.swift b/Sources/MultishellAppCore/Model/GitReads/AppModel+FileChanges.swift index 2e10e50f3..edc988010 100644 --- a/Sources/MultishellAppCore/Model/GitReads/AppModel+FileChanges.swift +++ b/Sources/MultishellAppCore/Model/GitReads/AppModel+FileChanges.swift @@ -15,6 +15,7 @@ extension AppModel { var targets = fileChangeTargets(changed) if targets.hasThemeChanges { await reloadThemes() } noteFileTabChanges(targets) + noteAllChangesTabChanges(targets) noteFilesPanelChanges(targets) await refreshProjectsIfChanged(withGitDirectoryChanges: targets.projectsWithGitDirectoryChanges) guard platform.isActive else { return } diff --git a/Sources/MultishellAppCore/Model/GitReads/AppModel+StatusReads.swift b/Sources/MultishellAppCore/Model/GitReads/AppModel+StatusReads.swift index 971976d39..fce8f2335 100644 --- a/Sources/MultishellAppCore/Model/GitReads/AppModel+StatusReads.swift +++ b/Sources/MultishellAppCore/Model/GitReads/AppModel+StatusReads.swift @@ -38,6 +38,7 @@ extension AppModel { statusReadLog.invalidate() // An image has no diff for the algorithm to change. noteFileTabsChanged(releasingDots: false) { !holdsImage($0.id) } + noteAllChangesTabsChanged { _ in true } Task { await refreshStatuses() } } @@ -109,7 +110,10 @@ extension AppModel { /// What every status read's landing sets off, from the poll or one worktree's. func noteStatusesLanded(_ fresh: [Worktree.ID: WorktreeStatus]) async { // Even one that moved no count: an edit can change the diff since the base alone. - for id in fresh.keys { scheduleBranchChangesRead(of: id) } + for id in fresh.keys { + scheduleBranchChangesRead(of: id) + noteAllChangesListLanded(in: id) + } await refreshWorktreesWhoseBranchMoved(fresh) } diff --git a/Sources/MultishellAppCore/Model/QuickSwitcher/AppModel+QuickSwitcher.swift b/Sources/MultishellAppCore/Model/QuickSwitcher/AppModel+QuickSwitcher.swift index 5d63efe1b..cf85dbe83 100644 --- a/Sources/MultishellAppCore/Model/QuickSwitcher/AppModel+QuickSwitcher.swift +++ b/Sources/MultishellAppCore/Model/QuickSwitcher/AppModel+QuickSwitcher.swift @@ -156,7 +156,7 @@ extension AppModel { let opening = chooseFileRow(path, in: worktreeID, as: asker) return .openingFile(path: path, worktreeID: worktreeID, opening) - case .fileTab(let id): + case .allChangesTab(let id), .fileTab(let id): return goTo(worktreeChosen(by: target), as: asker) { store.activateTab(id) } case .pane(let id): @@ -179,7 +179,10 @@ extension AppModel { switch target { case .command: nil case .file(_, let worktreeID): workspace.worktree(worktreeID) - case .fileTab(let id): workspace.fileTab(id).flatMap { workspace.worktree($0.worktreeID) } + + case .allChangesTab(let id), .fileTab(let id): + workspace.workspaceTab(id).flatMap { workspace.worktree($0.worktreeID) } + case .pane(let id): workspace.session(id).flatMap { workspace.worktree($0.worktreeID) } case .project(let id): preferredWorktree(ofProject: id) case .worktree(let id): workspace.worktree(id) diff --git a/Sources/MultishellAppCore/Model/QuickSwitcher/AppModel+QuickSwitcherItems.swift b/Sources/MultishellAppCore/Model/QuickSwitcher/AppModel+QuickSwitcherItems.swift index 2c568d52d..88a16f924 100644 --- a/Sources/MultishellAppCore/Model/QuickSwitcher/AppModel+QuickSwitcherItems.swift +++ b/Sources/MultishellAppCore/Model/QuickSwitcher/AppModel+QuickSwitcherItems.swift @@ -36,7 +36,7 @@ extension AppModel { return quickSwitcherWorktrees(in: places, sessionIDsByWorktree) } - /// Every pane and file tab, the saved ones of worktrees not yet opened + /// Every pane and file or All changes tab, the saved ones of worktrees not yet opened /// included, worktree by worktree in sidebar order, each in its strips' order. func quickSwitcherPanesAndFileTabs() -> [QuickSwitcherItem] { quickSwitcherTabRows( @@ -139,7 +139,7 @@ extension AppModel { QuickSwitcherItem.path([project.name, worktree.name]) } - /// Every pane, or only the agents' without file tabs, worktree by worktree in + /// Every pane and tab, or only the agents' panes, worktree by worktree in /// `order` and each in its strips' order. private func quickSwitcherTabRows( in order: [SidebarPlace], @@ -172,6 +172,9 @@ extension AppModel { case .file(let tab): agentsOnly ? [] : [quickSwitcherFileTab(tab, at: place)] + + case .allChanges(let tab): + agentsOnly ? [] : [quickSwitcherAllChangesTab(tab, at: place)] } } } @@ -186,6 +189,18 @@ extension AppModel { ) } + private func quickSwitcherAllChangesTab( + _ tab: AllChangesTab, + at place: String, + ) -> QuickSwitcherItem { + QuickSwitcherItem( + target: .allChangesTab(tab.id), + kind: .allChangesTab, + title: QuickSwitcherItem.path([place, title(of: tab)]), + location: "", + ) + } + /// Every worktree as the sidebar lists it, projects in order and each one's /// worktrees by its sort, its hidden ones after the rest. private func quickSwitcherSidebarOrder(sessions: SessionIDsByWorktree) -> [SidebarPlace] { diff --git a/Sources/MultishellAppCore/Model/QuickSwitcher/AppModel+QuickSwitcherRanking.swift b/Sources/MultishellAppCore/Model/QuickSwitcher/AppModel+QuickSwitcherRanking.swift index 52a678f56..624ce0cb5 100644 --- a/Sources/MultishellAppCore/Model/QuickSwitcher/AppModel+QuickSwitcherRanking.swift +++ b/Sources/MultishellAppCore/Model/QuickSwitcher/AppModel+QuickSwitcherRanking.swift @@ -34,7 +34,7 @@ extension AppModel { case .agent: 40 case .worktree: 30 case .project: 20 - case .shell, .fileTab: 10 + case .shell, .fileTab, .allChangesTab: 10 case .file, .command: 0 } } diff --git a/Sources/MultishellAppCore/Model/Review/AppModel+AllChangesCommentRows.swift b/Sources/MultishellAppCore/Model/Review/AppModel+AllChangesCommentRows.swift new file mode 100644 index 000000000..3b065c8aa --- /dev/null +++ b/Sources/MultishellAppCore/Model/Review/AppModel+AllChangesCommentRows.swift @@ -0,0 +1,40 @@ +import MultishellCore + +/// Rows picked for a comment in one file of the All changes tab, by a gutter +/// drag or Comment on Lines. +extension AppModel { + /// Rows of the file view's own, from where a drag started: a file shown whole + /// reads its Unified lines, any other the document's, stopping at a fold or its last. + public func openReviewComposer( + fromRow start: Int, + toRow end: Int, + ofSection index: Int, + side: DiffSide?, + in tabID: AllChangesTab.ID, + ) { + guard let document = allChangesDocument(of: tabID), document.sections.indices.contains(index) + else { return } + let section = document.sections[index] + if section.isShownWhole { + guard let lines = section.fileText?.lines, + let selection = ReviewLineSelection( + from: start, + to: end, + in: lines, + side: nil, + ) + else { return } + openReviewComposer(on: selection, ofFile: section.path, in: tabID) + return + } + let first = section.rows.lowerBound + guard + let picked = document.lineSelection( + from: first + start, + to: first + end, + side: side, + ) + else { return } + openReviewComposer(on: picked.selection, ofFile: picked.path, in: tabID) + } +} diff --git a/Sources/MultishellAppCore/Model/Review/AppModel+AllChangesReviewCards.swift b/Sources/MultishellAppCore/Model/Review/AppModel+AllChangesReviewCards.swift new file mode 100644 index 000000000..bf91bf573 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Review/AppModel+AllChangesReviewCards.swift @@ -0,0 +1,108 @@ +import MultishellCore + +/// Review cards in the All changes tab: each file's placed against that file's +/// own rows, then moved to the document's, so two files' line numbers never meet. +extension AppModel { + /// A comment on an unchanged line keeps this many either side open inside a fold. + private static var reviewLinesHeldAround: Int { 2 } + + /// Where a card Review picked sits: its file and its first line's row in that + /// file's view, either side in Split; `nil` where no card stands for it. + public func reviewCardStop( + _ card: ReviewCardPlacement.CardID, + of tab: AllChangesTab, + in document: AllChangesDocument, + ) -> AllChangesSteps.Stop? { + guard let path = reviewCardPath(card, in: tab), let section = document.section(at: path) + else { return nil } + let sides: [DiffSide?] = document.split == nil ? [nil] : [.onDisk, .committed] + let placement = sides.lazy.compactMap { side in + self.reviewCardPlacements(of: tab, in: document, section: section, side: side) + .first { $0.stands(for: card) } + }.first + return placement.map { AllChangesSteps.Stop(section: section, row: $0.rows.lowerBound) } + } + + /// The file a card is on: its comment's, or the composer's. + private func reviewCardPath(_ card: ReviewCardPlacement.CardID, in tab: AllChangesTab) -> String? + { + switch card { + case .comment(let id): reviewComments(in: tab.worktreeID).first { $0.id == id }?.path + case .composer: reviewComposers[tab.id]?.path + } + } + + /// One file's cards on its own shown rows, for its view in the per-file list: + /// a collapsed file's are left out, and a committed-side card shows only under + /// its scope, as in a file tab. `side` is a split column's. + public func reviewCardPlacements( + of tab: AllChangesTab, + in document: AllChangesDocument, + section index: Int, + side: DiffSide? = nil, + ) -> [ReviewCardPlacement] { + let section = document.sections[index] + let sources = reviewCardSources(of: tab.id, in: tab.worktreeID, side: side) + let comments = sources.comments(onFile: section.path) + let fileComposer = sources.composer(onFile: section.path) + guard !comments.isEmpty || fileComposer != nil, let fileText = section.sideText(on: side) + else { return [] } + return ReviewCardPlacement.placements( + of: comments, + selected: selectedReviewComments[tab.worktreeID], + composer: fileComposer, + in: fileText.lines, + ) + // A card on lines no shown row holds, folded away, places none. + .compactMap { placement in + guard let first = section.documentRow(ofFileRow: placement.rows.lowerBound), + let last = section.documentRow(ofFileRow: placement.rows.upperBound) + else { return nil } + return placement.moved( + to: (first - section.rows.lowerBound)...(last - section.rows.lowerBound) + ) + } + } + + /// The cards of one file the All changes tab shows whole across Split's + /// columns, on that file's own Unified rows. + public func reviewCardPlacements( + of tab: AllChangesTab, + onWholeFile path: String, + in lines: [DiffLine], + ) -> [ReviewCardPlacement] { + let sources = reviewCardSources(of: tab.id, in: tab.worktreeID, side: nil) + return ReviewCardPlacement.placements( + of: sources.comments(onFile: path), + selected: selectedReviewComments[tab.worktreeID], + composer: sources.composer(onFile: path), + in: lines, + ) + } + + /// Each file's comments and composer, two lines either side, kept out of its + /// folds so their cards have rows to sit under. + func allChangesReviewLines(of tab: AllChangesTab) -> [String: [AllChangesLineSpan]] { + let scope = fileTabScope(in: tab.worktreeID) + let shown = + reviewComments(in: tab.worktreeID).filter { $0.appliesUnder(scope) } + .map { ($0.path, $0.side, $0.lines) } + + (reviewComposers[tab.id].map { [($0.path, $0.side, $0.lines)] } ?? []) + return Dictionary( + grouping: shown.map { path, side, lines in + ( + path, + AllChangesLineSpan( + side: side, + lines: max( + 1, + lines.lowerBound - Self.reviewLinesHeldAround, + )...(lines.upperBound + Self.reviewLinesHeldAround), + ), + ) + }, + by: \.0, + ) + .mapValues { $0.map(\.1) } + } +} diff --git a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewAnchoring.swift b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewAnchoring.swift index 3cd09385b..587156231 100644 --- a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewAnchoring.swift +++ b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewAnchoring.swift @@ -8,21 +8,36 @@ extension AppModel { in worktreeID: Worktree.ID, to rows: [DiffLine], readUnder scope: ChangeScope, + ) { + reanchorReviewComments(onFiles: [path: rows], in: worktreeID, readUnder: scope) + } + + /// Every file's at once and set once: each set saves the comments and can + /// search the All changes tab again. + func reanchorReviewComments( + onFiles rowsByPath: [String: [DiffLine]], + in worktreeID: Worktree.ID, + readUnder scope: ChangeScope, ) { let comments = reviewComments(in: worktreeID) - guard comments.contains(where: { $0.path == path }) else { return } - let moved = ReviewAnchoring.reanchor(comments, onFile: path, to: rows, readUnder: scope) + var moved = comments + for path in Set(comments.map(\.path)) { + guard let rows = rowsByPath[path] else { continue } + moved = ReviewAnchoring.reanchor(moved, onFile: path, to: rows, readUnder: scope) + } guard moved != comments else { return } setReviewComments(moved, of: worktreeID) } - /// The open composer follows its lines too, or its card would sit under other code. + /// The open composer follows its lines too, or its card would sit under other + /// code; only `path`'s, an All changes tab reading each file in turn. func reanchorReviewComposer( - in tabID: FileTab.ID, + in tabID: ReviewTabID, + onFile path: String, to rows: [DiffLine], readUnder scope: ChangeScope, ) { - guard let composer = reviewComposers[tabID] else { return } + guard let composer = reviewComposers[tabID], composer.path == path else { return } setIfChanged( \.reviewComposers[tabID], ReviewAnchoring.reanchor(composer, to: rows, readUnder: scope), diff --git a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewCards.swift b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewCards.swift index 1d15154f9..8f3a34131 100644 --- a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewCards.swift +++ b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewCards.swift @@ -8,29 +8,62 @@ extension AppModel { in lines: [DiffLine], side: DiffSide? = nil, ) -> [ReviewCardPlacement] { - let scope = fileTabScope(in: tab.worktreeID) - let composer = reviewComposers[tab.id].flatMap { composer in + let sources = reviewCardSources(of: tab.id, in: tab.worktreeID, side: side) + return ReviewCardPlacement.placements( + of: sources.comments(onFile: tab.path), + selected: selectedReviewComments[tab.worktreeID], + composer: sources.composer(onFile: tab.path), + in: lines, + ) + } + + /// The composer and comments a tab's cards show on `side`, `nil` for both; + /// those that do not apply under the worktree's scope are left out. + func reviewCardSources( + of tabID: ReviewTabID, + in worktreeID: Worktree.ID, + side: DiffSide?, + ) -> ReviewCardSources { + let scope = fileTabScope(in: worktreeID) + let composer = reviewComposers[tabID].flatMap { composer in (side == nil || composer.side == side) && composer.appliesUnder(scope) ? composer : nil } - let comments = reviewComments(in: tab.worktreeID).filter { comment in - comment.path == tab.path && comment.id != composer?.editing - && (side == nil || comment.side == side) + let shown = reviewComments(in: worktreeID).filter { comment in + comment.id != composer?.editing && (side == nil || comment.side == side) && comment.appliesUnder(scope) } - return ReviewCardPlacement.placements( - of: comments, - selected: selectedReviewComments[tab.worktreeID], + return ReviewCardSources( composer: composer, - in: lines, + commentsByPath: Dictionary(grouping: shown, by: \.path), ) } /// The view's, as it updates: the card to scroll to, once the tab has rows to /// place it by. Taken then even where it is not drawn, so it never fires later. - public func takeReviewCardReveal(_ id: FileTab.ID) -> ReviewCardPlacement.CardID? { + public func takeReviewCardReveal(_ id: ReviewTabID) -> ReviewCardPlacement.CardID? { // A removal of nothing still redraws every file tab, each update asking here. - guard reviewCardRevealRequests[id] != nil, case .text = fileTabReadings[id]?.content - else { return nil } + guard let card = reviewCardRevealRequests[id], holdsReviewRows(id, for: card) else { + return nil + } return reviewCardRevealRequests.removeValue(forKey: id) } + + /// Rows to place a card by: a file tab's text, or in the All changes tab + /// the read of the comment's file, which waits unread away from the screen. + private func holdsReviewRows(_ id: ReviewTabID, for card: ReviewCardPlacement.CardID) -> Bool { + switch workspace.workspaceTab(id) { + case .allChanges(let tab): + guard let reading = allChangesReadings[id] else { return false } + guard case .comment(let commentID) = card, + let path = reviewComments(in: tab.worktreeID).first(where: { $0.id == commentID })?.path + else { return true } + return !reading.isUnread(path) + + case .file: + guard case .text = fileTabReadings[id]?.content else { return false } + return true + + case .terminal, nil: return false + } + } } diff --git a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewComments.swift b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewComments.swift index 365fcbb0a..0dce9abfc 100644 --- a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewComments.swift +++ b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewComments.swift @@ -30,6 +30,11 @@ extension AppModel { reviewComments[tab.worktreeID]?.count { $0.path == tab.path && $0.isPending } ?? 0 } + /// Every file's in the worktree, which the All changes tab shows together. + public func pendingReviewCommentCount(of tab: AllChangesTab) -> Int { + reviewComments[tab.worktreeID]?.count(where: \.isPending) ?? 0 + } + /// Every file's count at once, for its row in Files and Changes, so a list's rows /// take theirs from one pass. public func pendingReviewCommentCounts(in worktreeID: Worktree.ID) -> [String: Int] { @@ -39,9 +44,9 @@ extension AppModel { } /// A sent or outdated comment's Dismiss, and a pending one's Delete. - public func removeReviewComment(_ id: ReviewComment.ID, in tabID: FileTab.ID) { - guard let tab = workspace.fileTab(tabID) else { return } - removeReviewComments([id], in: tab.worktreeID) + public func removeReviewComment(_ id: ReviewComment.ID, in tabID: ReviewTabID) { + guard let worktreeID = reviewWorktree(of: tabID) else { return } + removeReviewComments([id], in: worktreeID) } public func removeReviewComments(_ ids: Set, in worktreeID: Worktree.ID) { diff --git a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewComposer.swift b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewComposer.swift index b9e59ea33..3eb8ab617 100644 --- a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewComposer.swift +++ b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewComposer.swift @@ -2,20 +2,24 @@ import Foundation import MultishellCore extension AppModel { - /// A line's + in the gutter, a drag down it, or Comment on Lines. - /// Not over a composer holding text, which would lose what was typed. - public func openReviewComposer(on selection: ReviewLineSelection, in tabID: FileTab.ID) { - guard let tab = workspace.fileTab(tabID), !composerHoldsUnsavedShownText(in: tabID) else { - return - } + /// A line's + in the gutter, a drag down it, or Comment on Lines, on `path`'s + /// lines. Not over a composer holding text, which would lose what was typed. + public func openReviewComposer( + on selection: ReviewLineSelection, + ofFile path: String, + in tabID: ReviewTabID, + ) { + guard let worktreeID = reviewWorktree(of: tabID), !composerHoldsUnsavedShownText(in: tabID) + else { return } let composer = ReviewComposer( + path: path, side: selection.side, lines: selection.lines, - quote: reviewQuote(of: selection.lines, on: selection.side, in: tabID), - scope: fileTabScope(in: tab.worktreeID), + quote: reviewQuote(of: selection.lines, on: selection.side, ofFile: path, in: tabID), + scope: fileTabScope(in: worktreeID), editing: nil, ) - reviewComposers[tabID] = composer + setReviewComposer(composer, in: tabID) // A + on the clip's last row opens the card below it, so the view scrolls to show it. reviewCardRevealRequests[tabID] = .composer(composer.id) reviewDrafts[tabID] = "" @@ -25,36 +29,37 @@ extension AppModel { } /// A pending comment's Edit: its card becomes the composer, holding its text. - public func startEditingReviewComment(_ id: ReviewComment.ID, in tabID: FileTab.ID) { - guard let tab = workspace.fileTab(tabID), !composerHoldsUnsavedShownText(in: tabID), - let comment = reviewComments(in: tab.worktreeID).first(where: { $0.id == id }), + public func startEditingReviewComment(_ id: ReviewComment.ID, in tabID: ReviewTabID) { + guard let worktreeID = reviewWorktree(of: tabID), !composerHoldsUnsavedShownText(in: tabID), + let comment = reviewComments(in: worktreeID).first(where: { $0.id == id }), comment.isPending else { return } let composer = ReviewComposer( + path: comment.path, side: comment.side, lines: comment.lines, quote: comment.quote, scope: comment.scope, editing: id, ) - reviewComposers[tabID] = composer + setReviewComposer(composer, in: tabID) reviewCardRevealRequests[tabID] = .composer(composer.id) reviewDrafts[tabID] = comment.text reviewComposerKeyboardRequests.insert(tabID) noteFileTabFocused(tabID) } - public func reviewDraft(in tabID: FileTab.ID) -> String { + public func reviewDraft(in tabID: ReviewTabID) -> String { reviewDrafts[tabID] ?? "" } - public func noteReviewDraft(_ text: String, in tabID: FileTab.ID) { + public func noteReviewDraft(_ text: String, in tabID: ReviewTabID) { reviewDrafts[tabID] = text } /// The keyboard goes back to the tab, the card's field leaving with the card. - public func cancelReviewComposer(in tabID: FileTab.ID) { - setIfChanged(\.reviewComposers[tabID], nil) + public func cancelReviewComposer(in tabID: ReviewTabID) { + setReviewComposer(nil, in: tabID) reviewDrafts[tabID] = nil reviewComposerKeyboardRequests.remove(tabID) fileTabFocusRequest = tabID @@ -63,21 +68,21 @@ extension AppModel { /// Add comment, or Save while editing. Refused with no text or no lines /// read, the composer staying open. @discardableResult - public func commitReviewComposer(in tabID: FileTab.ID) -> Bool { - guard let composer = reviewComposers[tabID], let tab = workspace.fileTab(tabID), + public func commitReviewComposer(in tabID: ReviewTabID) -> Bool { + guard let composer = reviewComposers[tabID], let worktreeID = reviewWorktree(of: tabID), let text = reviewDraft(in: tabID).trimmedOfAllWhitespaceOrNil else { return false } - let isEditingAPendingComment = reviewComments(in: tab.worktreeID).contains { comment in + let isEditingAPendingComment = reviewComments(in: worktreeID).contains { comment in comment.id == composer.editing && comment.isPending } if let editing = composer.editing, isEditingAPendingComment { - editReviewComment(editing, in: tab.worktreeID, text: text) + editReviewComment(editing, in: worktreeID, text: text) } else { // A quote is what keeps the comment on its lines. An edit whose comment was // sent or removed meanwhile is kept as a new one, not lost. guard !composer.quote.isEmpty else { return false } var comment = ReviewComment( - path: tab.path, + path: composer.path, side: composer.side, scope: composer.scope, lines: composer.lines, @@ -85,24 +90,35 @@ extension AppModel { text: text, ) // Lines rewritten while it was typed no longer read as its quote. - if reviewQuote(of: composer.lines, on: composer.side, in: tabID) != composer.quote { - comment.noteLinesChanged() - } - guard addReviewComment(comment, in: tab.worktreeID) else { return false } + let quote = reviewQuote( + of: composer.lines, + on: composer.side, + ofFile: composer.path, + in: tabID, + ) + if quote != composer.quote { comment.noteLinesChanged() } + guard addReviewComment(comment, in: worktreeID) else { return false } } cancelReviewComposer(in: tabID) return true } - /// The lines' text as the tab last read it, empty where it holds no rows. + /// The All changes tab holds the composer's lines open, which moves what its find searched. + private func setReviewComposer(_ composer: ReviewComposer?, in tabID: ReviewTabID) { + let laidOutBefore = allChangesDocuments[tabID].map { SearchedLayout.allChanges($0.document) } + setIfChanged(\.reviewComposers[tabID], composer) + if let laidOutBefore { rerunFileFind(in: tabID, laidOutBefore: laidOutBefore) } + } + + /// The lines' text as the tab last read the file, empty where it holds no rows of it. func reviewQuote( of lines: ClosedRange, on side: DiffSide, - in tabID: FileTab.ID, + ofFile path: String, + in tabID: ReviewTabID, ) -> [String] { - guard case .text(let rows) = fileTabReadings[tabID]?.content else { return [] } // Walked rather than taken from the side's whole text, which copies every line. - return rows.lines.compactMap { line in + (reviewRows(ofFile: path, in: tabID) ?? []).compactMap { line in guard side.shows(line.kind), let number = line.number(on: side), lines.contains(number) else { return nil } return line.text @@ -110,36 +126,41 @@ extension AppModel { } /// Once per opening, so a card rebuilt by a layout switch leaves the keyboard be. - public func reviewComposerAsksForKeyboard(in tabID: FileTab.ID) -> Bool { + public func reviewComposerAsksForKeyboard(in tabID: ReviewTabID) -> Bool { reviewComposerKeyboardRequests.contains(tabID) } - public func noteReviewComposerTookKeyboard(in tabID: FileTab.ID) { + public func noteReviewComposerTookKeyboard(in tabID: ReviewTabID) { reviewComposerKeyboardRequests.remove(tabID) } /// Text a close or switch would lose: an Edit left as it was loses nothing. - func reviewComposerHoldsUnsavedText(in tabID: FileTab.ID) -> Bool { - guard reviewComposers[tabID] != nil, let tab = workspace.fileTab(tabID), + func reviewComposerHoldsUnsavedText(in tabID: ReviewTabID) -> Bool { + guard let composer = reviewComposers[tabID], let worktreeID = reviewWorktree(of: tabID), let draft = reviewDraft(in: tabID).trimmedOfAllWhitespaceOrNil else { return false } - let editing = reviewComposers[tabID]?.editing - return draft != reviewComments(in: tab.worktreeID).first { $0.id == editing }?.text + return draft != reviewComments(in: worktreeID).first { $0.id == composer.editing }?.text } /// Only a composer on screen: one hidden by the scope would block every +. - private func composerHoldsUnsavedShownText(in tabID: FileTab.ID) -> Bool { - guard let composer = reviewComposers[tabID], let tab = workspace.fileTab(tabID), - composer.appliesUnder(fileTabScope(in: tab.worktreeID)), - tabHasLines(on: composer.side, in: tabID) + private func composerHoldsUnsavedShownText(in tabID: ReviewTabID) -> Bool { + guard let composer = reviewComposers[tabID], let worktreeID = reviewWorktree(of: tabID), + composer.appliesUnder(fileTabScope(in: worktreeID)), + tabHasOrAwaitsLines(on: composer.side, ofFile: composer.path, in: tabID) else { return false } return reviewComposerHoldsUnsavedText(in: tabID) } - /// Placement's rule: a side with no numbered line left, its file emptied or - /// deleted and kept as last read, places no card. - private func tabHasLines(on side: DiffSide, in tabID: FileTab.ID) -> Bool { - guard case .text(let rows) = fileTabReadings[tabID]?.content else { return false } - return rows.lines.contains { side.shows($0.kind) && $0.number(on: side) != nil } + /// Placement's rule: a side with no numbered line, its file emptied or deleted, + /// places no card; an All changes file waiting on a read places it once read. + private func tabHasOrAwaitsLines( + on side: DiffSide, + ofFile path: String, + in tabID: ReviewTabID, + ) -> Bool { + if allChangesReadings[tabID]?.isUnread(path) == true { return true } + return (reviewRows(ofFile: path, in: tabID) ?? []).contains { line in + side.shows(line.kind) && line.number(on: side) != nil + } } } diff --git a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewFiles.swift b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewFiles.swift index 15617ab0e..c5de17af5 100644 --- a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewFiles.swift +++ b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewFiles.swift @@ -66,7 +66,13 @@ extension AppModel { /// Written off the main actor at once, a comment being rarer than a /// keystroke; the file's ticket keeps the writes in order. func setReviewComments(_ comments: [ReviewComment], of worktreeID: Worktree.ID) { + let allChanges = workspace.allChangesTab(in: worktreeID) + let laidOutBefore = allChanges.flatMap { tab in + allChangesDocuments[tab.id].map { SearchedLayout.allChanges($0.document) } + } setIfChanged(\.reviewComments[worktreeID], comments.isEmpty ? nil : comments) + // A comment holds lines open in the All changes tab, moving what its find searched. + if let allChanges { rerunFileFind(in: allChanges.id, laidOutBefore: laidOutBefore) } guard !isYieldingToRunningInstance else { return } let file = reviewFile(of: worktreeID) let ticket = file.issueTicket() diff --git a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewPage.swift b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewPage.swift index 4a4a97e72..4ba7ba6f1 100644 --- a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewPage.swift +++ b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewPage.swift @@ -38,13 +38,27 @@ extension AppModel { return .ready(picked: picked, recipients: recipients, canSend: hasPending) } - /// A click on a comment's row: its file's tab, opened where it is not, with - /// the card scrolled into view and outlined. + /// A click on a comment's row: its card outlined in the shown All changes tab + /// showing its file's rows, else in its file's tab, opened where it is not. public func selectReviewComment(_ id: ReviewComment.ID, in worktreeID: Worktree.ID) async { guard let comment = reviewComments(in: worktreeID).first(where: { $0.id == id }) else { return } setIfChanged(\.selectedReviewComments[worktreeID], id) + if let allChanges = workspace.allChangesTab(in: worktreeID), + workspace.group(allChanges.groupID)?.shownTabID == allChanges.id, + allChangesReadings[allChanges.id]?.file(at: comment.path)?.holdsOrAwaitsRows == true + { + activateTab(allChanges.id) + // A collapsed file places no card to scroll to. + expandAllChangesFile(comment.path, in: allChanges.id) + reviewCardRevealRequests[allChanges.id] = .comment(id) + // Brought near the screen to be read; the card shows once it is. + if allChangesReadings[allChanges.id]?.isUnread(comment.path) == true { + allChangesFileReveals[allChanges.id] = comment.path + } + return + } let tab: FileTab? if let open = workspace.fileTab(showing: comment.path, in: worktreeID) { activateTab(open.id) diff --git a/Sources/MultishellAppCore/Model/Review/AppModel+ReviewTabs.swift b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewTabs.swift new file mode 100644 index 000000000..acf23c6a4 --- /dev/null +++ b/Sources/MultishellAppCore/Model/Review/AppModel+ReviewTabs.swift @@ -0,0 +1,31 @@ +import MultishellCore + +/// The tabs review cards are written in: a file tab, on its one file, or the +/// All changes tab, on any of its files. +extension AppModel { + func reviewWorktree(of tabID: ReviewTabID) -> Worktree.ID? { + switch workspace.workspaceTab(tabID) { + case .allChanges(let tab): tab.worktreeID + case .file(let tab): tab.worktreeID + case .terminal, nil: nil + } + } + + /// `path`'s rows as the tab last read them, every line of the file folded + /// or not; `nil` where it holds none of that file. + func reviewRows(ofFile path: String, in tabID: ReviewTabID) -> [DiffLine]? { + switch workspace.workspaceTab(tabID) { + case .allChanges: + return allChangesReadings[tabID]?.file(at: path)?.rows?.lines + + case .file(let tab): + guard tab.path == path, case .text(let rows) = fileTabReadings[tabID]?.content else { + return nil + } + return rows.lines + + case .terminal, nil: + return nil + } + } +} diff --git a/Sources/MultishellAppCore/Model/Tabs/AppModel+Find.swift b/Sources/MultishellAppCore/Model/Tabs/AppModel+Find.swift index e02240893..9279f8da6 100644 --- a/Sources/MultishellAppCore/Model/Tabs/AppModel+Find.swift +++ b/Sources/MultishellAppCore/Model/Tabs/AppModel+Find.swift @@ -19,6 +19,7 @@ extension AppModel { switch workspaceTabInView { // An image has no lines to find in, and none come back as a notice's may. case .file(let tab): return holdsImage(tab.id) ? nil : tab.id + case .allChanges(let tab): return tab.id case .terminal(let tab): if let field = findFieldTargetID, findBarTargetIDs.contains(field), @@ -62,7 +63,7 @@ extension AppModel { private func takeSelection(in id: FindTargetID) -> String? { guard findFieldTargetID != id else { return nil } let selection = - workspace.fileTab(id) != nil ? fileTabSelections[id] : host.selectionText(of: id) + searchesRowsInModel(id) ? fileTabSelections[id] : host.selectionText(of: id) guard let text = selection?.withoutTrailingWhitespace else { takenFindSelections[id] = nil return nil @@ -119,7 +120,7 @@ extension AppModel { /// `nil` until the engine has counted; a file's is counted at once. public func findMatchCount(of id: FindTargetID) -> FindMatchCount? { - if workspace.fileTab(id) != nil { return fileFindResults[id]?.matchCount } + if searchesRowsInModel(id) { return fileFindResults[id]?.matchCount } return searchCounts[id]?.matchCount } @@ -145,7 +146,7 @@ extension AppModel { /// `searched` is the text the engine holds, `nil` for none: one equal but for /// ASCII case it skips, so its count and selected match stand. private func search(_ text: String, in id: FindTargetID, replacing searched: String? = nil) { - if workspace.fileTab(id) != nil { + if searchesRowsInModel(id) { runFileFind(for: text, in: id) return } @@ -167,7 +168,7 @@ extension AppModel { public func findNext() { stepKeystrokeFindTarget(.next) } public func findPrevious() { stepKeystrokeFindTarget(.previous) } - /// Cmd+Shift+F, from the pane, where Escape reaches the program, or from a + /// Cmd+Option+F, from the pane, where Escape reaches the program, or from a /// field: that one bar goes down and no other. public func closeFind() { guard let id = keystrokeFindTarget else { return } @@ -188,7 +189,7 @@ extension AppModel { /// asked: the engine selected nothing on the find text. See terminals/find.md. private func step(_ direction: CycleDirection, in id: FindTargetID) { guard findBarTargetIDs.contains(id), !findText(of: id).isEmpty else { return } - if workspace.fileTab(id) != nil { + if searchesRowsInModel(id) { stepFileFind(direction, in: id) return } @@ -205,7 +206,7 @@ extension AppModel { /// focused one, as clicking into a field moved the store's focus nowhere. public func closeFind(in id: FindTargetID) { guard endFind(in: id) else { return } - if workspace.fileTab(id) != nil { fileTabFocusRequest = id } else { host.focus(id) } + if searchesRowsInModel(id) { fileTabFocusRequest = id } else { host.focus(id) } } /// The bar down with the keyboard left where it was, as the command line @@ -217,7 +218,7 @@ extension AppModel { setIfChanged(\.searchCounts[id], nil) // The torn-down field may never say it lost the keyboard. if findFieldTargetID == id { findFieldTargetID = nil } - if workspace.fileTab(id) != nil { + if searchesRowsInModel(id) { setIfChanged(\.fileFindResults[id], nil) // The count starts over, so what a dropped view drew no longer compares. fileFindsShown[id] = nil @@ -230,7 +231,10 @@ extension AppModel { /// Bars and find texts whose pane or file tab has gone. From the reconcile, as /// `prunePendingClose` is, and from a shell exiting, which closes its session. func pruneFind() { - let existingTargetIDs = Set(workspace.sessions.map(\.id) + workspace.fileTabs.map(\.id)) + let existingTargetIDs = Set( + workspace.sessions.map(\.id) + workspace.fileTabs.map(\.id) + + workspace.allChangesTabs.map(\.id) + ) setIfChanged(\.fileFindResults, fileFindResults.filter { existingTargetIDs.contains($0.key) }) setIfChanged(\.findBarTargetIDs, findBarTargetIDs.filter(existingTargetIDs.contains)) setIfChanged(\.findTexts, findTexts.filter { existingTargetIDs.contains($0.key) }) diff --git a/Sources/MultishellAppCore/Model/Tabs/AppModel+TabClosing.swift b/Sources/MultishellAppCore/Model/Tabs/AppModel+TabClosing.swift index 905da3ba2..4fdd9b0c7 100644 --- a/Sources/MultishellAppCore/Model/Tabs/AppModel+TabClosing.swift +++ b/Sources/MultishellAppCore/Model/Tabs/AppModel+TabClosing.swift @@ -11,24 +11,24 @@ extension AppModel { closeInTabInView { .tab($0.id) } } - /// A middle click on a tab of either kind, closing it active or not. No + /// A middle click on a tab of any kind, closing it active or not. No /// key-window dance: the click landed here, so this window is the one acted in. public func closeTab(_ id: WorkspaceTab.ID) { switch workspace.workspaceTab(id) { case .terminal(let tab): requestClose(.tab(id), in: tab) - case .file: closeFileTab(id) + case .file, .allChanges: closeReviewCardTab(id) case nil: break } } - /// A file tab runs nothing, so it asks only where a review comment is being - /// written in it, which would go with it. - private func closeFileTab(_ id: FileTab.ID) { + /// A file or All changes tab runs nothing, so it asks only where a review + /// comment is being written in it, which would go with it. + private func closeReviewCardTab(_ id: WorkspaceTab.ID) { if reviewComposerHoldsUnsavedText(in: id) { - pendingClose = .fileTab(id) + pendingClose = .reviewTab(id) return } - closeWithoutAsking(.fileTab(id)) + closeWithoutAsking(.reviewTab(id)) } /// A close the engine was asked for, as by a keybind in the user's Ghostty @@ -50,15 +50,15 @@ extension AppModel { /// reconcile, so every path that takes one away is covered. func prunePendingClose() { switch pendingClose { - case .fileTab(let id) where workspace.fileTab(id) == nil: pendingClose = nil + case .reviewTab(let id) where workspace.workspaceTab(id) == nil: pendingClose = nil case .pane(let id) where workspace.session(id) == nil: pendingClose = nil case .tab(let id) where workspace.tab(id) == nil: pendingClose = nil default: break } } - /// Both keystrokes, which close a file tab whole. One issued in a settings - /// window closes that window instead, and nothing happens with no tab. + /// Both keystrokes, which close a file or All changes tab whole. One issued in + /// a settings window closes that window instead, and nothing happens with no tab. private func closeInTabInView(_ closing: (TerminalTab) -> PendingClose) { guard platform.isWorkspaceWindowKey else { platform.closeKeyWindow() @@ -66,7 +66,8 @@ extension AppModel { } switch workspaceTabDrawn { case .terminal(let tab): requestClose(closing(tab), in: tab) - case .file(let tab): closeFileTab(tab.id) + case .file(let tab): closeReviewCardTab(tab.id) + case .allChanges(let tab): closeReviewCardTab(tab.id) case nil: break } } @@ -83,7 +84,7 @@ extension AppModel { func closeWithoutAsking(_ close: PendingClose, takingFocus: Bool = true) { switch close { - case .fileTab(let id): store.closeTab(id) + case .reviewTab(let id): store.closeTab(id) case .pane(let id): store.closeSession(id) case .tab(let id): store.closeTab(id) } diff --git a/Sources/MultishellAppCore/Model/Tabs/AppModel+TabTitles.swift b/Sources/MultishellAppCore/Model/Tabs/AppModel+TabTitles.swift index 8786d04e3..1d0970bb0 100644 --- a/Sources/MultishellAppCore/Model/Tabs/AppModel+TabTitles.swift +++ b/Sources/MultishellAppCore/Model/Tabs/AppModel+TabTitles.swift @@ -13,6 +13,11 @@ extension AppModel { workspace.title(of: tab) } + /// The same words on every worktree's, there being one a worktree. + public func title(of _: AllChangesTab) -> String { + t("tab.all-changes") + } + /// One pane's, a split holding several: the user's name for the tab, else /// what this pane's shell last reported, else its starting title. Raw too. func title(ofPane session: TerminalSession, in tab: TerminalTab) -> String { diff --git a/Sources/MultishellAppCore/QuickSwitcher/QuickSwitcherItem.swift b/Sources/MultishellAppCore/QuickSwitcher/QuickSwitcherItem.swift index 338db9cd3..a908cf227 100644 --- a/Sources/MultishellAppCore/QuickSwitcher/QuickSwitcherItem.swift +++ b/Sources/MultishellAppCore/QuickSwitcher/QuickSwitcherItem.swift @@ -7,6 +7,7 @@ public struct QuickSwitcherItem: Identifiable, Equatable, Sendable { public enum Kind: Equatable, Sendable { /// A pane with an agent at its prompt, by catalogue id. case agent(id: String) + case allChangesTab case command case file case fileTab diff --git a/Sources/MultishellAppCore/QuickSwitcher/QuickSwitcherTarget.swift b/Sources/MultishellAppCore/QuickSwitcher/QuickSwitcherTarget.swift index 42b0cb89d..3feff6f19 100644 --- a/Sources/MultishellAppCore/QuickSwitcher/QuickSwitcherTarget.swift +++ b/Sources/MultishellAppCore/QuickSwitcher/QuickSwitcherTarget.swift @@ -2,6 +2,7 @@ import MultishellCore /// Where a quick switcher row goes when chosen. public enum QuickSwitcherTarget: Hashable, Sendable { + case allChangesTab(AllChangesTab.ID) /// A menu bar item, by its titles from the bar down. case command(path: [String]) /// A file of the selected worktree, opened as a file tab. diff --git a/Sources/MultishellAppCore/Shared/ChipOnFill.swift b/Sources/MultishellAppCore/Shared/ChipOnFill.swift new file mode 100644 index 000000000..0544a6b82 --- /dev/null +++ b/Sources/MultishellAppCore/Shared/ChipOnFill.swift @@ -0,0 +1,9 @@ +import MultishellCore + +/// A chip's fill on an area's fill: the fill again where translucent, a shade up, +/// else the selection, as an opaque fill drawn twice reads as none. +public enum ChipOnFill { + public static func colorKey(in section: InterfaceSection, of theme: Theme) -> InterfaceColorKey { + theme.interfaceRGB(.fill, in: section).opacity < 1 ? .fill : .selectionBackground + } +} diff --git a/Sources/MultishellAppCore/Shared/LineCountText.swift b/Sources/MultishellAppCore/Shared/LineCountText.swift new file mode 100644 index 000000000..3e46d66c0 --- /dev/null +++ b/Sources/MultishellAppCore/Shared/LineCountText.swift @@ -0,0 +1,12 @@ +import Foundation + +/// A count of lines as `+N` and `−N` show it: grouped from five digits, where +/// `+16621` was hard to read, and plain below, where `+1,204` reads no easier. +public enum LineCountText { + private static let groupedFrom = 10_000 + + public static func shown(_ count: Int, locale: Locale = .current) -> String { + guard abs(count) >= groupedFrom else { return String(count) } + return count.formatted(.number.grouping(.automatic).locale(locale)) + } +} diff --git a/Sources/MultishellAppUI/App/AppShortcutCatalogue.swift b/Sources/MultishellAppUI/App/AppShortcutCatalogue.swift index 580d1191d..c54c3f151 100644 --- a/Sources/MultishellAppUI/App/AppShortcutCatalogue.swift +++ b/Sources/MultishellAppUI/App/AppShortcutCatalogue.swift @@ -36,9 +36,12 @@ enum AppShortcutCatalogue { static let find = AppShortcut("f") static let findNext = AppShortcut("g") static let findPrevious = AppShortcut("g", .shift) - /// Ghostty's own end-search key, which would otherwise end a search under - /// a bar of ours that stayed up. - static let closeFind = AppShortcut("f", .shift) + static let closeFind = AppShortcut("f", .option) + /// The Files panel on each page. Cmd+Shift+F is Ghostty's own end-search key, + /// which would otherwise end a search under a bar of ours that stayed up. + static let filesPane = AppShortcut("f", .shift) + static let changesPane = AppShortcut("c", .shift) + static let reviewPane = AppShortcut("r", .shift) /// Copy, paste, cut and select-all. The menu carries them and the surface /// keeps them, a pane's Cmd+C being Ghostty's own clipboard action. @@ -54,7 +57,7 @@ enum AppShortcutCatalogue { addProject, openInEditor, splitRight, splitDown, moveTabToNewGroup, nextGroup, previousGroup, toggleAgentBoard, quickSwitcher, quickSwitcherCommands, undo, redo, nextTab, previousTab, - find, findNext, findPrevious, closeFind, + find, findNext, findPrevious, closeFind, filesPane, changesPane, reviewPane, cut, copy, paste, selectAll, ] } diff --git a/Sources/MultishellAppUI/App/MenuCommandAvailability.swift b/Sources/MultishellAppUI/App/MenuCommandAvailability.swift index f1c20137e..f235ef573 100644 --- a/Sources/MultishellAppUI/App/MenuCommandAvailability.swift +++ b/Sources/MultishellAppUI/App/MenuCommandAvailability.swift @@ -10,7 +10,9 @@ enum MenuCommandAvailability { (t("menu.new-agent-tab"), \.canOpenTab), (t("menu.new-worktree"), \.canStartNewWorktree), (t("action.open-in-editor"), \.canOpenWorktreeInEditor), - (t("menu.files-panel"), \.canToggleFilesPanel), + (t("menu.files-pane"), \.canToggleFilesPanel), + (t("menu.changes-pane"), \.canToggleFilesPanel), + (t("menu.review-pane"), \.canToggleFilesPanel), (t("menu.close-pane"), \.hasTabToClose), (t("menu.close-tab"), \.hasTabToClose), (t("menu.split-right"), \.canSplitPane), diff --git a/Sources/MultishellAppUI/App/MultishellCommands.swift b/Sources/MultishellAppUI/App/MultishellCommands.swift index a00f1d7c3..165061df3 100644 --- a/Sources/MultishellAppUI/App/MultishellCommands.swift +++ b/Sources/MultishellAppUI/App/MultishellCommands.swift @@ -128,8 +128,12 @@ struct MultishellCommands: Commands { .keyboardShortcut(AppShortcutCatalogue.quickSwitcher) Button(t("menu.quick-switcher-commands")) { model.toggleQuickSwitcher(.commands) } .keyboardShortcut(AppShortcutCatalogue.quickSwitcherCommands) - // No key yet; one is an `AppShortcut` in the catalogue (adding/interface.md). - Toggle(t("menu.files-panel"), isOn: model.showsFilesPanelBinding) + Toggle(t("menu.files-pane"), isOn: model.filesPanelBinding(on: .files)) + .keyboardShortcut(AppShortcutCatalogue.filesPane) + Toggle(t("menu.changes-pane"), isOn: model.filesPanelBinding(on: .changes)) + .keyboardShortcut(AppShortcutCatalogue.changesPane) + Toggle(t("menu.review-pane"), isOn: model.filesPanelBinding(on: .review)) + .keyboardShortcut(AppShortcutCatalogue.reviewPane) Toggle( t("menu.show-hidden-files"), isOn: model.settingBinding(\.showsIgnoredFiles, write: model.setShowsIgnoredFiles), diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesBar.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesBar.swift new file mode 100644 index 000000000..06a12a268 --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesBar.swift @@ -0,0 +1,73 @@ +import MultishellAppCore +import MultishellCore +import SwiftUI + +/// The All changes tab's bar: its title, how many files and lines changed, +/// the arrows stepping across files, and the switches every file tab has. +struct AllChangesBar: View { + let model: AppModel + let tab: AllChangesTab + let document: AllChangesDocument? + let theme: Theme + + var body: some View { + let palette = theme.fileTab + HStack(spacing: 6) { + Text(model.title(of: tab)) + .fontWeight(.semibold) + .foregroundStyle(palette.text) + .lineLimit(1) + if let document { + Text(AllChangesText.fileCount(document.sections.count)) + .foregroundStyle(palette.textTertiary) + .lineLimit(1) + if !document.lineCounts.isEmpty { + FileLineCountsText( + counts: document.lineCounts, + theme: theme, + size: model.metrics.caption, + showsZeroSides: false, + ) + } + } + Spacer(minLength: 8) + if document?.hasChanges == true { + ChangeStepButtons(model: model, tabID: tab.id, palette: palette) + } + if model.offersChangeScopeSwitch(in: tab.worktreeID) { + ChangeScopeSwitch(model: model, palette: palette) + } + FileTabLayoutSwitch( + model: model, + selection: FileTabLayoutSwitch.allChangesSelection(in: model), + palette: palette, + ) + if document?.sections.isEmpty == false { + collapseEveryFileButton(palette: palette) + } + } + .font(model.metrics.font(size: model.metrics.secondary)) + .padding(.leading, 12) + .padding(.trailing, 8) + .frame(height: UIMetrics.allChangesHeaderBarHeight) + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) + .clipped() + .background(palette.background) + .hairline(.bottom, palette) + } + + private func collapseEveryFileButton(palette: AreaPalette) -> some View { + let expands = model.isEveryAllChangesFileCollapsed(in: tab.id) + return AllChangesGlyphButton( + help: expands ? t("all-changes.expand-all") : t("all-changes.collapse-all"), + palette: palette, + ) { + model.toggleEveryAllChangesFileCollapsed(in: tab.id) + } glyph: { + AllChangesStrokedGlyph( + outline: ChevronPairShape(pointsInward: !expands), + metrics: model.metrics, + ) + } + } +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesChangesRotor.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesChangesRotor.swift new file mode 100644 index 000000000..49b2dd4ba --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesChangesRotor.swift @@ -0,0 +1,72 @@ +import AppKit +import MultishellAppCore +import MultishellCore + +/// The All changes list's one Changes rotor: every file's changed lines in list +/// order, the list scrolled to each so its file's view is built to read it. +@MainActor +final class AllChangesChangesRotor: NSObject, + @MainActor NSAccessibilityCustomRotorItemSearchDelegate +{ + private weak var list: AllChangesListView? + private weak var coordinator: AllChangesListCoordinator? + /// The last item given and its stop: its text view may since show another file. + private var given: (item: NSAccessibilityCustomRotor.ItemResult, stop: AllChangesSteps.Stop)? + + init(list: AllChangesListView, coordinator: AllChangesListCoordinator) { + self.list = list + self.coordinator = coordinator + } + + func rotor( + _ rotor: NSAccessibilityCustomRotor, + resultFor parameters: NSAccessibilityCustomRotor.SearchParameters, + ) -> NSAccessibilityCustomRotor.ItemResult? { + guard let list, let coordinator, let document = coordinator.document, + let geometry = coordinator.representable?.geometry + else { return nil } + let direction: CycleDirection = parameters.searchDirection == .next ? .next : .previous + let current = parameters.currentItem.flatMap { item in + given.flatMap { $0.item === item ? $0.stop : nil } ?? stop(of: item, in: list) + } + guard let stop = document.changedLine(direction, from: current, slice: coordinator.slice) + else { return nil } + coordinator.scroll(to: stop, below: list.clipHeight / 3, on: list, geometry: geometry) + let item = textView(showing: stop, in: list)?.changesRotorItem(atRow: stop.row) + given = item.map { ($0, stop) } + return item + } + + /// Split's left where the change is a removed line beside the right's padding. + private func textView( + showing stop: AllChangesSteps.Stop, + in list: AllChangesListView, + ) + -> DiffTextView? + { + guard let view = list.file(at: stop.section) else { return nil } + if let committed = view.split?.committed, + view.slice?.changeIsCommittedSideOnly(atRow: stop.row) == true + { + return committed.textView + } + return view.mainColumn.textView + } + + /// The file and row an item stands on, where its file is still built: one the + /// rotor did not give, VoiceOver's own place. + private func stop( + of item: NSAccessibilityCustomRotor.ItemResult, + in list: AllChangesListView, + ) -> AllChangesSteps.Stop? { + let target = item.targetElement + for (index, view) in list.builtFiles { + for column in [view.mainColumn, view.split?.committed].compactMap(\.self) + where column.textView === target { + let row = column.textView.displayText.row(atOffset: item.targetRange.location) + return AllChangesSteps.Stop(section: index, row: row) + } + } + return nil + } +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesFileHeader.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesFileHeader.swift new file mode 100644 index 000000000..26ba79fec --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesFileHeader.swift @@ -0,0 +1,108 @@ +import MultishellAppCore +import MultishellCore +import MultishellGitKit +import SwiftUI + +/// One file's header, and its sticky copy over the top: chevron, change letter, +/// path, counts, comments to send and the button opening its own tab. +struct AllChangesFileHeader: View, @MainActor Equatable { + let model: AppModel + let tabID: AllChangesTab.ID + let worktreeID: Worktree.ID + let section: AllChangesSection + let pendingComments: Int + let theme: Theme + + /// What sits a shade off the bar's fill: the letter's square and a lit button. + private var chipFill: Color { + theme.fileTab.color(ChipOnFill.colorKey(in: .fileTab, of: theme)) + } + + var body: some View { + let metrics = model.metrics + let palette = theme.fileTab + return HStack(spacing: UIMetrics.allChangesHeaderSpacing) { + AllChangesGlyphButton( + help: section.isCollapsed ? t("all-changes.expand") : t("all-changes.collapse"), + palette: palette, + litFill: chipFill, + ) { + model.toggleAllChangesFileCollapsed(section.path, in: tabID) + } glyph: { + Image(systemName: section.isCollapsed ? "chevron.right" : "chevron.down") + .font(metrics.font(size: metrics.small, weight: .semibold)) + .accessibilityHidden(true) + } + changeLetter + location(palette: palette) + if let counts = section.lineCounts { + FileLineCountsText( + counts: counts, + theme: theme, + size: metrics.caption, + showsZeroSides: false, + ) + } + if pendingComments > 0 { + ReviewCountBadge(count: pendingComments, theme: theme, metrics: metrics) + } + Spacer(minLength: 0) + AllChangesGlyphButton( + help: t("all-changes.open-file"), + palette: palette, + litFill: chipFill, + ) { + Task { await model.openFileAsTab(section.path, in: worktreeID) } + } glyph: { + AllChangesStrokedGlyph(outline: ExternalLinkShape(), metrics: metrics) + } + } + .font(metrics.font(size: metrics.secondary)) + .padding(.leading, UIMetrics.allChangesHeaderLeadingInset) + .padding(.trailing, UIMetrics.allChangesHeaderTrailingInset) + .frame(height: UIMetrics.allChangesHeaderBarHeight) + .frame(maxWidth: .infinity, alignment: .leading) + // Opaque, so the sticky copy hides the rows it sits over. + .background(palette.fill) + .background(palette.background) + .hairline(.bottom, palette) + .accessibilityElement(children: .contain) + .accessibilityLabel(section.path) + } + + private var changeLetter: some View { + let metrics = model.metrics + return Text(AllChangesText.letter(section.change.kind)) + .font(metrics.font(size: metrics.badge, weight: .bold)) + .foregroundStyle(theme.color(for: section.change.kind)) + .frame(width: metrics.allChangesLetterSide, height: metrics.allChangesLetterSide) + .background(chipFill, in: .rect(cornerRadius: UIMetrics.allChangesLetterCornerRadius)) + } + + /// The same file shown the same way, so a list update that moved nothing of it + /// leaves its hosted header be. + static func == (lhs: Self, rhs: Self) -> Bool { + lhs.model === rhs.model && lhs.tabID == rhs.tabID && lhs.worktreeID == rhs.worktreeID + && lhs.section == rhs.section && lhs.pendingComments == rhs.pendingComments + && lhs.theme == rhs.theme + } + + /// On a square, as the mockups drew it. + private func location(palette: AreaPalette) -> some View { + let folder = section.change.folder + return HStack(spacing: 0) { + if !folder.isEmpty { + Text(folder + "/") + .foregroundStyle(palette.textTertiary) + .lineLimit(1) + .truncationMode(.head) + } + Text(section.change.fileName) + .fontWeight(.semibold) + .strikethrough(section.change.kind == .deleted) + .foregroundStyle(palette.text) + .lineLimit(1) + .layoutPriority(1) + } + } +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesFileKey.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesFileKey.swift new file mode 100644 index 000000000..7f5448857 --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesFileKey.swift @@ -0,0 +1,6 @@ +/// A file of the All changes list as the list keeps its view: the path, and +/// whether the view shows Split's two columns, so a change of kind builds anew. +struct AllChangesFileKey: Hashable { + let path: String + let isSplit: Bool +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesFileNotice.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesFileNotice.swift new file mode 100644 index 000000000..dc4528aa0 --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesFileNotice.swift @@ -0,0 +1,45 @@ +import MultishellAppCore +import MultishellCore +import SwiftUI + +/// Why a file of the All changes tab shows no rows, with its own tab or the +/// editor a click away; `AllChangesNotice.action` says which. +struct AllChangesFileNotice: View { + let model: AppModel + let worktreeID: Worktree.ID + let path: String + let notice: AllChangesNotice + let theme: Theme + + var body: some View { + let metrics = model.metrics + HStack(spacing: 12) { + Text(AllChangesText.notice(notice)) + .foregroundStyle(theme.fileTab.textSecondary) + .lineLimit(1) + .truncationMode(.tail) + Spacer(minLength: 0) + switch notice.action { + case .openFile: + button(t("all-changes.open-file")) { + Task { await model.openFileAsTab(path, in: worktreeID) } + } + + case .openInEditor: + button(t("action.open-in-editor")) { model.openInEditor(path: path, in: worktreeID) } + + case nil: + EmptyView() + } + } + .font(metrics.font(size: metrics.secondary)) + .padding(.horizontal, 14) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) + .background(theme.fileTab.background) + } + + private func button(_ title: String, action: @escaping () -> Void) -> some View { + Button(title, action: action) + .buttonStyle(ThemedButtonStyle(fill: theme.fileTab.fill, text: theme.fileTab.text)) + } +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesFileView.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesFileView.swift new file mode 100644 index 000000000..8628fcb66 --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesFileView.swift @@ -0,0 +1,196 @@ +import AppKit +import MultishellAppCore +import MultishellCore +import SwiftUI + +/// One file of the list: its header over its own Unified or Split diff in a box; +/// see Docs/design/files/all-changes-tab.md. +@MainActor +final class AllChangesFileView: NSView { + static var headerHeight: CGFloat { CGFloat(UIMetrics.allChangesHeaderBarHeight) } + + /// Its diff: `unified`, or `split`'s two columns. + let canvas: DiffCanvasView + let unified: DiffDocumentView? + let split: SplitDiffDocumentView? + /// What find, highlighting and the arrows' box work on: Unified's column, or + /// Split's right. + let mainColumn: DiffColumn + private let headerHost = NSHostingView(rootView: AnyView(EmptyView())) + private var shownHeader: AllChangesFileHeader? + private let gapLayer = AllChangesGapLayer() + private(set) var slice: AllChangesFileSlice? + private var theme: Theme? + private var itemGaps: [Int: CGFloat] = [:] + private var cardGaps: [Int: CGFloat] = [:] + private var reportedHeight: CGFloat = 0 + var shownCards: ShownReviewCards? + var shownCommittedCards: ShownReviewCards? + var highlighting: Task? + /// Its height moving, as a card opens or a fold does, moves every file below. + var onHeightChanged: (() -> Void)? + + override var isFlipped: Bool { true } + + var height: CGFloat { Self.headerHeight + diffHeight } + + /// Where the code starts across the gap views: Unified's, or Split's left. + var codeX: CGFloat { + let column = split?.committed ?? mainColumn + return column.textClip.frame.minX - canvas.spanningGapViews.frame.minX + + column.textView.textContainerOrigin.x + } + + /// Its rows and gaps; a file with no rows but a notice, the notice's height. + private var diffHeight: CGFloat { + guard let slice, !slice.text.lines.isEmpty || !slice.gapItems.isEmpty else { return 0 } + return mainColumn.textView.geometry.documentHeight(rows: slice.text.lines.count) + } + + init(geometry: DiffRowGeometry, isSplit: Bool, scrollsWith list: NSView?) { + if isSplit { + let split = SplitDiffDocumentView(geometry: geometry) + canvas = split + self.split = split + unified = nil + mainColumn = split.onDisk + } else { + let unified = DiffDocumentView(geometry: geometry) + canvas = unified + self.unified = unified + split = nil + mainColumn = unified.column + } + super.init(frame: .zero) + wantsLayer = true + layer?.borderWidth = 1 + layer?.cornerRadius = CGFloat(UIMetrics.allChangesBoxCornerRadius) + layer?.masksToBounds = true + canvas.forwardsWheelTo = list + canvas.listHeaderHeight = Self.headerHeight + canvas.scrollView.keepsOverlayScrollers = true + for column in [split?.committed, mainColumn].compactMap(\.self) { + column.textView.offersChangesRotor = false + } + addSubview(canvas) + addSubview(headerHost) + unified?.onReviewCardGaps = { [weak self] gaps in + self?.cardGaps = gaps + self?.openGaps() + } + unified?.onGapViewsLaidOut = { [weak self] geometry, _ in self?.layOutItems(in: geometry) } + split?.onSpanningGapViewsLaidOut = { [weak self] geometry, cardGaps in + self?.gapLayer.noteCardGaps(cardGaps) + self?.layOutItems(in: geometry) + self?.noteHeight() + } + } + + required init?(coder: NSCoder) { nil } + + /// The file's header, rows and what sits between them; the text shown again + /// only where it or the theme moved, which drops its colours: `true` then. + @discardableResult + func show( + _ slice: AllChangesFileSlice, + header: AllChangesFileHeader, + item: @escaping (AllChangesGapItem, _ codeX: CGFloat) -> AnyView, + itemHeight: (AllChangesGapItem) -> CGFloat, + theme: Theme, + ) -> Bool { + if shownHeader != header { + shownHeader = header + headerHost.rootView = AnyView(header) + } + let border = NSColor(theme.fileTab.border).cgColor + if layer?.borderColor != border { layer?.borderColor = border } + let showsTextAnew = + self.slice?.text != slice.text || self.slice?.committedText != slice.committedText + || self.theme != theme + if showsTextAnew { + self.theme = theme + if let split, let sides = slice.split { + split.show(sides, theme: theme) + } else { + unified?.show(slice.text, theme: theme) + } + } + self.slice = slice + itemGaps = gapLayer.show( + slice.gapItems, + contentKey: theme, + height: itemHeight, + content: item, + in: canvas.spanningGapViews, + ) + openGaps() + return showsTextAnew + } + + /// Let go of by the list and kept for another file: what it showed of this + /// one is dropped, the next file's shown in full. + func forgetShownFile() { + highlighting?.cancel() + highlighting = nil + shownCards = nil + shownCommittedCards = nil + slice = nil + cardGaps = [:] + gapLayer.noteCardGaps([:]) + for column in [mainColumn, split?.committed].compactMap(\.self) { + column.textView.setSelectedRange(NSRange(location: 0, length: 0)) + column.forgetPendingScrolls() + } + // The next file reports its height though it match this one's: the list placed it by estimate. + reportedHeight = 0 + gapLayer.forgetContent() + // The header holds the whole section, its file's text with it. + shownHeader = nil + headerHost.rootView = AnyView(EmptyView()) + box(nil) + canvas.scroll(to: .zero) + } + + /// The list scrolled its rows from under the pointer: no + stays on one. + func forgetGutterHover() { + mainColumn.gutter.hoveredRow = nil + split?.committed.gutter.hoveredRow = nil + } + + /// The box around the change the arrows landed on, on both of Split's sides. + func box(_ rows: Range?) { + mainColumn.mirrorSteppedChange(rows) + split?.committed.mirrorSteppedChange(rows) + } + + private func openGaps() { + if let split { + split.extraRowGaps = itemGaps + } else if let unified { + gapLayer.noteCardGaps(cardGaps) + unified.setRowGaps(RowGaps(cardGaps.merging(itemGaps, uniquingKeysWith: +))) + unified.layOutGapViews() + } + noteHeight() + } + + private func layOutItems(in geometry: DiffRowGeometry) { + guard slice != nil else { return } + split?.dividerSpan = 0...diffHeight + gapLayer.layOut(in: geometry, width: canvas.spanningGapViews.bounds.width, codeX: codeX) + } + + /// A view let go of, showing no file, asks the list for no layout. + private func noteHeight() { + needsLayout = true + guard slice != nil, height != reportedHeight else { return } + reportedHeight = height + onHeightChanged?() + } + + override func layout() { + super.layout() + headerHost.frame = NSRect(x: 0, y: 0, width: bounds.width, height: Self.headerHeight) + canvas.frame = NSRect(x: 0, y: Self.headerHeight, width: bounds.width, height: diffHeight) + } +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesFoldRow.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesFoldRow.swift new file mode 100644 index 000000000..92bdaabe4 --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesFoldRow.swift @@ -0,0 +1,48 @@ +import MultishellAppCore +import MultishellCore +import SwiftUI + +/// Unchanged lines left out of the All changes tab, a click showing them. +struct AllChangesFoldRow: View { + /// The band under the label, the label's blue held well back. + private static let bandOpacity = 0.1 + + let model: AppModel + let tabID: AllChangesTab.ID + let path: String + let lines: ClosedRange + /// Where the file's code starts: the glyph centred left of it in the + /// gutter, the label on it, as the mockup lines them up. + let codeX: CGFloat + let theme: Theme + + var body: some View { + let metrics = model.metrics + let palette = theme.fileTab + // The waiting blue Review's To send chips and the gutter's + wear. + let blue = theme.color(.waiting, in: .states) + Button { + model.openAllChangesFold(lines, of: path, in: tabID) + } label: { + HStack(spacing: 0) { + Image(systemName: "chevron.up.chevron.down") + .font(metrics.font(size: metrics.small)) + .foregroundStyle(blue) + .frame(width: max(0, codeX)) + .accessibilityHidden(true) + Text(AllChangesText.foldTitle(lines)).foregroundStyle(blue) + Text(AllChangesText.foldLines(lines)) + .foregroundStyle(palette.textTertiary) + .padding(.leading, 10) + Spacer(minLength: 0) + } + .font(metrics.font(size: metrics.secondary)) + .padding(.trailing, 10) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) + .background(blue.opacity(Self.bandOpacity)) + .background(palette.background) + .contentShape(.rect) + } + .buttonStyle(.plain) + } +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesGapItemView.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesGapItemView.swift new file mode 100644 index 000000000..3ae93d038 --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesGapItemView.swift @@ -0,0 +1,37 @@ +import MultishellAppCore +import MultishellCore +import SwiftUI + +/// What one of the All changes tab's gaps holds: a fold or a notice, the same +/// in Unified and Split. +struct AllChangesGapItemView: View { + let model: AppModel + let tab: AllChangesTab + let path: String + let item: AllChangesGapItem + let codeX: CGFloat + let theme: Theme + + var body: some View { + switch item.kind { + case .fold(let lines): + AllChangesFoldRow( + model: model, + tabID: tab.id, + path: path, + lines: lines, + codeX: codeX, + theme: theme, + ) + + case .notice(let notice): + AllChangesFileNotice( + model: model, + worktreeID: tab.worktreeID, + path: path, + notice: notice, + theme: theme, + ) + } + } +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesGapLayer.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesGapLayer.swift new file mode 100644 index 000000000..1a52d895f --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesGapLayer.swift @@ -0,0 +1,99 @@ +import AppKit +import MultishellAppCore +import SwiftUI + +/// One file's folds and notices, each in the gap under the row before it and below +/// any cards there, across gutter and text or both split columns. +@MainActor +final class AllChangesGapLayer { + private var items: [AllChangesGapItem] = [] + private var heights: [AllChangesGapItem: CGFloat] = [:] + private var content: (AllChangesGapItem, CGFloat) -> AnyView = { _, _ in AnyView(EmptyView()) } + /// Where the file's code starts, which a fold's label lines up with. + private var codeX: CGFloat = 0 + private weak var parent: NSView? + /// What each item's host was last given, so a layout rebuilds none. + private var hosts: [AllChangesGapItem: NSHostingController] = [:] + private var hostedGeneration: [AllChangesGapItem: Int] = [:] + private var generation = 0 + private var contentKey: AnyHashable? + /// Hosts let go of as their items went, given to the next shown. + private var spareHosts: [NSHostingController] = [] + /// The cards' gap under each row, which the items stack below. + private var cardGaps: [Int: CGFloat] = [:] + + /// Keeps what each item shows and returns the gap each row needs; hosts come + /// with the next layout, built again only where the items or `contentKey` moved. + func show( + _ items: [AllChangesGapItem], + contentKey: AnyHashable, + height: (AllChangesGapItem) -> CGFloat, + content: @escaping (AllChangesGapItem, CGFloat) -> AnyView, + in parent: NSView, + ) -> [Int: CGFloat] { + if items != self.items || contentKey != self.contentKey { generation += 1 } + self.items = items + self.contentKey = contentKey + self.content = content + self.parent = parent + heights = Dictionary(items.map { ($0, height($0)) }, uniquingKeysWith: { first, _ in first }) + for item in hosts.keys where heights[item] == nil { retire(item) } + return items.reduce(into: [:]) { gaps, item in + gaps[item.afterRow, default: 0] += heights[item] ?? 0 + } + } + + /// Its view kept for another file, whose items are built afresh. + func forgetContent() { + contentKey = nil + } + + func noteCardGaps(_ gaps: [Int: CGFloat]) { + cardGaps = gaps + } + + /// Across the parent, stacked down each gap in order; `codeX` where the + /// file's code starts, a gutter widening with its line numbers' digits. + func layOut(in geometry: DiffRowGeometry, width: CGFloat, codeX: CGFloat) { + if codeX != self.codeX { + self.codeX = codeX + generation += 1 + } + var nextTop: [Int: CGFloat] = [:] + for item in items { + let height = heights[item] ?? 0 + let row = item.afterRow + let top = nextTop[row] ?? geometry.gapTop(afterRow: row) + (cardGaps[row] ?? 0) + nextTop[row] = top + height + let host = hosts[item] ?? takeHost() + hosts[item] = host + if hostedGeneration[item] != generation { + host.rootView = content(item, codeX) + hostedGeneration[item] = generation + } + let frame = NSRect(x: 0, y: top, width: width, height: height) + if host.view.frame != frame { host.view.frame = frame } + } + } + + private func retire(_ item: AllChangesGapItem) { + guard let host = hosts.removeValue(forKey: item) else { return } + hostedGeneration[item] = nil + host.view.isHidden = true + spareHosts.append(host) + } + + private func takeHost() -> NSHostingController { + if let spare = spareHosts.popLast() { + spare.view.isHidden = false + return spare + } + let host = NSHostingController(rootView: AnyView(EmptyView())) + host.sizingOptions = [] + host.view.wantsLayer = true + // TextKit 2 adds its fragments' views as it lays out; these stay over them. + host.view.layer?.zPosition = 1 + parent?.addSubview(host.view) + return host + } +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesGlyph.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesGlyph.swift new file mode 100644 index 000000000..afd3b3d77 --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesGlyph.swift @@ -0,0 +1,5 @@ +/// The All changes tab's symbol, the same on its face, the switcher's row and +/// the Changes page's button. +enum AllChangesGlyph { + static let symbolName = "plusminus" +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesGlyphButton.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesGlyphButton.swift new file mode 100644 index 000000000..112c184bd --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesGlyphButton.swift @@ -0,0 +1,32 @@ +import SwiftUI + +/// A glyph button of the All changes tab's bar or a file's header: a square +/// hit target, lit under the pointer as the app's other glyph buttons are. +struct AllChangesGlyphButton: View { + let help: String + let palette: AreaPalette + /// The lit square; `nil` is the area's fill. + var litFill: Color? + let action: () -> Void + @ViewBuilder let glyph: () -> Glyph + + @State private var isHovered = false + + var body: some View { + PlainGlyphButton(help: help, action: action) { + glyph() + .accessibilityHidden(true) + .frame( + width: UIMetrics.allChangesGlyphButtonSide, + height: UIMetrics.allChangesGlyphButtonSide, + ) + .glyphHover( + isHovered, + palette: palette, + resting: palette.textSecondary, + litFill: litFill, + ) + } + .tracksHover($isHovered) + } +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesHighlightCache.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesHighlightCache.swift new file mode 100644 index 000000000..34ffd37e0 --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesHighlightCache.swift @@ -0,0 +1,38 @@ +import MultishellAppCore +import MultishellCore + +/// The parses of files the All changes list built, kept so a fold opening or +/// a scroll back parses nothing again; the oldest go past a cap. +struct AllChangesHighlightCache { + /// Twice the files built and kept spare at once, so a short scroll back finds + /// its parses; a whole file's spans run to megabytes. + static let capacity = 64 + + private var parses: [AllChangesHighlightKey: (text: DiffDisplayText, spans: [HighlightSpan])] = + [:] + /// Oldest first. + private var order: [AllChangesHighlightKey] = [] + + /// The spans parsed from `text`, where the file's rows are still those. + func spans(of key: AllChangesHighlightKey, for text: DiffDisplayText) -> [HighlightSpan]? { + parses[key].flatMap { $0.text == text ? $0.spans : nil } + } + + mutating func keep( + _ spans: [HighlightSpan], + of key: AllChangesHighlightKey, + for text: DiffDisplayText, + ) { + if parses.updateValue((text, spans), forKey: key) == nil { order.append(key) } + while order.count > Self.capacity { + parses[order.removeFirst()] = nil + } + } + + /// Drops each parse `isCurrent` turns down: one of a file gone, or of rows a + /// read replaced, which would keep the old rows alive beside the new. + mutating func keepOnly(where isCurrent: (AllChangesHighlightKey, DiffDisplayText) -> Bool) { + parses = parses.filter { isCurrent($0.key, $0.value.text) } + order.removeAll { parses[$0] == nil } + } +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesHighlightKey.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesHighlightKey.swift new file mode 100644 index 000000000..809ba09a0 --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesHighlightKey.swift @@ -0,0 +1,8 @@ +import MultishellCore + +/// One side of a file whose parse the All changes list keeps: `nil` for +/// Unified's rows or Split's right, `.committed` for Split's left. +struct AllChangesHighlightKey: Hashable { + let path: String + let side: DiffSide? +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesListCoordinator.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesListCoordinator.swift new file mode 100644 index 000000000..ddd0ce357 --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesListCoordinator.swift @@ -0,0 +1,302 @@ +import AppKit +import MultishellAppCore +import MultishellCore +import MultishellHighlight + +/// What the list's representable keeps between updates: the document and its +/// slices, the parses, the boxed change and the find matches painted. +@MainActor +final class AllChangesListCoordinator { + /// The latest update's, which the list's closures call: the one that made + /// the list holds the document and theme it was made with. + var representable: AllChangesListRepresentable? + var document: AllChangesDocument? + /// Comments to send by path, counted once an update for every header shown. + var pendingComments: [String: Int] = [:] + var theme: Theme? + /// Each document's per-file parts, cut as their views are built. + private var slices: [Int: AllChangesFileSlice] = [:] + private var unreadSections: Set = [] + private var parses = AllChangesHighlightCache() + /// The tab's saved scroll, put back once the list has a size. + var savedScroll: AllChangesScroll? + /// Where the saved scroll left the list in its file while that file waits + /// to be read; the list found elsewhere was scrolled away. + var offsetIntoUnreadSavedFile: CGFloat? + var pendingReveal: String? + /// Where a Changes click left the list, its file lit there whatever is at the top. + var scrollYLeftByReveal: CGFloat? + /// The change the arrows last landed on, boxed in its file's view. + private(set) var boxed: AllChangesSteps.Stop? + private var paintedFind: FindMatchesShown? + /// Every change's file and row there, in list order, cut once a document. + private var stops: [AllChangesSteps.Stop]? + private var findTint = NSColor.clear + + func noteDocument(_ document: AllChangesDocument) { + boxed = boxed.flatMap { carried($0, to: document) } + self.document = document + slices = [:] + stops = nil + unreadSections = document.unreadSections + parses.keepOnly { key, text in + guard let index = document.section(at: key.path) else { return false } + let section = document.sections[index] + return (key.side == .committed ? section.fileCommittedText : section.fileText) == text + } + } + + /// The boxed change in a new document, by its lines as a file tab keeps its + /// box: rows move as folds open or files come and go above. + private func carried( + _ stop: AllChangesSteps.Stop, + to next: AllChangesDocument, + ) -> AllChangesSteps.Stop? { + guard let document, document.sections.indices.contains(stop.section), + let text = slice(stop.section)?.text, let rows = text.change(containing: stop.row), + let anchor = text.anchor(ofChangeAt: rows), + let section = next.section(at: document.sections[stop.section].path), + let moved = next.slice(ofSection: section).text.change(at: anchor) + else { return nil } + return AllChangesSteps.Stop(section: section, row: moved.lowerBound) + } + + func slice(_ index: Int) -> AllChangesFileSlice? { + guard let document, document.sections.indices.contains(index) else { return nil } + if let cached = slices[index] { return cached } + let slice = document.slice(ofSection: index) + slices[index] = slice + return slice + } + + /// A file's height before its view measures: its header, rows and the + /// folds and notices between them; cards come once measured. + func estimate(_ index: Int, geometry: DiffRowGeometry, metrics: UIMetrics) -> CGFloat { + guard let document, document.sections.indices.contains(index) else { return 0 } + let rows = document.sections[index].rows.count + let items = document.gapItems(ofSection: index) + let gaps = items.reduce(0) { $0 + CGFloat(metrics.allChangesHeight(of: $1.kind)) } + guard rows > 0 || !items.isEmpty else { return AllChangesFileView.headerHeight } + var rowsAlone = geometry + rowsAlone.rowGaps = .empty + return AllChangesFileView.headerHeight + rowsAlone.documentHeight(rows: rows) + gaps + } + + /// Colours a built file from its parses, kept by path, a fold opening or a + /// scroll back parsing nothing again: Split's left from the committed side. + func highlight(_ view: AllChangesFileView, theme: Theme) { + guard let document, let slice = view.slice else { return } + let section = document.sections[slice.section] + view.highlighting?.cancel() + view.highlighting = Task { @MainActor [weak self, weak view] in + var sides: [(DiffSide?, DiffDisplayText?, DiffColumn?)] = [ + (nil, section.fileText, view?.mainColumn) + ] + if slice.committedText != nil { + sides.append((.committed, section.fileCommittedText, view?.split?.committed)) + } + for (side, fileText, column) in sides { + guard let fileText, let column else { continue } + let key = AllChangesHighlightKey(path: section.path, side: side) + let spans: [HighlightSpan] + if let cached = self?.parses.spans(of: key, for: fileText) { + spans = cached + } else { + spans = await DiffHighlighting.spans(for: fileText, path: section.path) + guard !Task.isCancelled else { return } + self?.parses.keep(spans, of: key, for: fileText) + } + // The document the slice was cut from maps them: a newer one may hold fewer files. + let runs = document.sliceSpans(spans, ofSection: slice.section, side: side) + let text = side == .committed ? slice.committedText ?? slice.text : slice.text + _ = await column.textView.applyHighlights(runs, for: text, theme: theme) + guard !Task.isCancelled else { return } + } + } + } + + /// A built file's view shown its share of the boxed change and the matches. + func dress(_ view: AllChangesFileView, at index: Int) { + let rows = boxed.flatMap { stop in + stop.section == index ? view.slice?.text.change(containing: stop.row) : nil + } + view.box(rows) + // Each update dresses every built file; one whose matches stand is not redrawn. + let textView = view.mainColumn.textView + let matches = matches(ofSection: index) + guard textView.findMatchPaint.matches != matches || textView.findMatchPaint.tint != findTint + else { return } + textView.findMatchPaint = (matches, findTint) + textView.needsDisplay = true + } + + /// Where a row of a file starts in the list: its view's place once built, + /// else the rows above it at the row height. + private func top( + ofRow row: Int, + inFile index: Int, + on list: AllChangesListView, + geometry: DiffRowGeometry, + ) + -> CGFloat? + { + guard let fileTop = list.top(ofFile: index) else { return nil } + let intoRows = + list.file(at: index)?.mainColumn.textView.geometry.top(ofRow: row) + ?? geometry.verticalInset + CGFloat(row) * geometry.rowHeight + return fileTop + AllChangesFileView.headerHeight + intoRows + } + + /// `stop` put `offset` below the clip's top. Twice: the first scroll builds its + /// file, whose own geometry then places the row exactly. + func scroll( + to stop: AllChangesSteps.Stop, + below offset: CGFloat, + on list: AllChangesListView, + geometry: DiffRowGeometry, + ) { + for _ in 0..<2 { + guard let top = top(of: stop, on: list, geometry: geometry) else { return } + list.scroll(toY: top - offset) + } + } + + /// Where a step or reveal puts its change: under the sticky header, a few + /// rows of context above it. + func offsetAboveAChange(on list: AllChangesListView, geometry: DiffRowGeometry) -> CGFloat { + let header = AllChangesFileView.headerHeight + let rows = geometry.rowsAboveAChange(inClipOf: list.clipHeight - header) + return header + CGFloat(rows) * geometry.rowHeight + } + + /// Where a stop starts: a file still to be read, at its header. + private func top( + of stop: AllChangesSteps.Stop, + on list: AllChangesListView, + geometry: DiffRowGeometry, + ) -> CGFloat? { + guard !isUnread(stop.section) else { return list.top(ofFile: stop.section) } + return top(ofRow: stop.row, inFile: stop.section, on: list, geometry: geometry) + } + + func isUnread(_ section: Int) -> Bool { + unreadSections.contains(section) + } + + private func steps(on list: AllChangesListView, geometry: DiffRowGeometry) -> AllChangesSteps { + AllChangesSteps(placed(allStops(), on: list, geometry: geometry)) + } + + /// The first and last changes alone, enough to say whether either way has one: + /// placing every change on each scroll took two thirds of it. + func outermostSteps(on list: AllChangesListView, geometry: DiffRowGeometry) -> AllChangesSteps { + let stops = allStops() + let ends = [stops.first, stops.last].compactMap(\.self) + return AllChangesSteps(placed(ends, on: list, geometry: geometry)) + } + + private func allStops() -> [AllChangesSteps.Stop] { + if let stops { return stops } + let cut = document?.changeStops ?? [] + stops = cut + return cut + } + + private func placed( + _ stops: [AllChangesSteps.Stop], + on list: AllChangesListView, + geometry: DiffRowGeometry, + ) -> [AllChangesSteps.Placed] { + stops.compactMap { stop in + top(of: stop, on: list, geometry: geometry).map { top in + AllChangesSteps.Placed(stop: stop, top: Double(top)) + } + } + } + + /// The boxed change's top, else the clip's. + func stepOrigin( + on list: AllChangesListView, + geometry: DiffRowGeometry, + ) -> (Double, isBoxed: Bool) { + if let boxed, + let top = top(of: boxed, on: list, geometry: geometry) + { + return (Double(top), true) + } + return (Double(list.scrollY), false) + } + + /// The next or previous change across the files, a few rows under the top + /// and boxed. + func step(_ direction: CycleDirection, on list: AllChangesListView, geometry: DiffRowGeometry) { + let (origin, isBoxed) = stepOrigin(on: list, geometry: geometry) + guard + let stop = steps(on: list, geometry: geometry).stop( + direction, + from: origin, + isBoxed: isBoxed, + ) + else { return } + let previous = boxed + boxed = stop + if let previous, let view = list.file(at: previous.section) { + dress(view, at: previous.section) + } + scroll( + to: stop, + below: offsetAboveAChange(on: list, geometry: geometry), + on: list, + geometry: geometry, + ) + if let view = list.file(at: stop.section) { dress(view, at: stop.section) } + } + + /// The matches in one file's view, by its own offsets. + private func matches(ofSection index: Int) -> [Range] { + guard let document, let find = paintedFind, document.sections.indices.contains(index) else { + return [] + } + let rows = document.sections[index].rows + guard !rows.isEmpty else { return [] } + let text = document.text + let start = text.rowStarts[rows.lowerBound] + let end = text.range(ofRow: rows.upperBound - 1).upperBound + let first = find.matches.partitioningIndex { $0.upperBound > start } + return find.matches[first...].prefix { $0.lowerBound < end }.map { $0.shifted(by: -start) } + } + + /// Paints `find` in each built file and brings a moved selection into view; + /// what the model should keep, or `nil` where nothing changed. + func paint( + _ find: FindMatchesShown, + on list: AllChangesListView, + tint: NSColor, + geometry: DiffRowGeometry, + textChanged: Bool, + ) -> FileFindShown? { + guard textChanged || paintedFind != find else { return nil } + let previous = paintedFind + paintedFind = find + findTint = tint + for (index, view) in list.builtFiles { dress(view, at: index) } + guard find.movesSelection(from: previous), let document, let selected = find.selected, + find.matches.indices.contains(selected) + else { return find.shown } + let match = find.matches[selected] + let row = document.text.row(atOffset: match.lowerBound) + guard let section = document.section(atRow: row) else { return find.shown } + let fileRow = row - document.sections[section].rows.lowerBound + scroll( + to: AllChangesSteps.Stop(section: section, row: fileRow), + below: list.clipHeight / 3, + on: list, + geometry: geometry, + ) + if let view = list.file(at: section) { + let start = document.text.rowStarts[document.sections[section].rows.lowerBound] + view.mainColumn.textView.setSelectedRange(NSRange(match.shifted(by: -start))) + } + return find.shown + } +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesListRepresentable+Review.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesListRepresentable+Review.swift new file mode 100644 index 000000000..6482a3ce8 --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesListRepresentable+Review.swift @@ -0,0 +1,93 @@ +import AppKit +import MultishellAppCore +import MultishellCore + +/// Review in the All changes list: each file's cards, and a comment Review +/// picked brought into view. +extension AllChangesListRepresentable { + /// Each column its own side's cards; a file shown whole its own Unified rows'. + func showReviewCards(on view: AllChangesFileView, at index: Int) { + guard let slice = view.slice else { return } + let section = document.sections[index] + if let split = view.split { + split.placeReviewCards { + split.committed.showReviewCards( + ShownReviewCards( + of: tab, + in: document, + section: index, + model: model, + theme: theme, + side: .committed, + ), + replacing: &view.shownCommittedCards, + model: model, + tabID: tab.id, + ) + split.onDisk.showReviewCards( + ShownReviewCards( + of: tab, + in: document, + section: index, + model: model, + theme: theme, + side: .onDisk, + ), + replacing: &view.shownCards, + model: model, + tabID: tab.id, + ) + } + return + } + let shown = + section.isShownWhole + ? ShownReviewCards( + of: tab, + onWholeFile: section.path, + in: slice.text.lines, + model: model, + theme: theme, + ) + : ShownReviewCards(of: tab, in: document, section: index, model: model, theme: theme) + view.mainColumn.showReviewCards( + shown, + replacing: &view.shownCards, + model: model, + tabID: tab.id, + ) + } + + /// A comment Review picked: its lines a few rows under the top, its card below; + /// a composer, as in a file tab, scrolled only as far as shows it. + func revealReviewCard( + _ card: ReviewCardPlacement.CardID, + on list: AllChangesListView, + coordinator: Coordinator, + ) { + guard let stop = model.reviewCardStop(card, of: tab, in: document) else { return } + coordinator.savedScroll = nil + if case .composer = card, let span = shownSpan(of: card, in: stop.section, on: list) { + let belowHeader = span.lowerBound - AllChangesFileView.headerHeight + list.scroll(toY: min(belowHeader, max(list.scrollY, span.upperBound - list.clipHeight))) + return + } + let geometry = self.geometry + let above = coordinator.offsetAboveAChange(on: list, geometry: geometry) + coordinator.scroll(to: stop, below: above, on: list, geometry: geometry) + } + + /// Where a card sits in the list, in whichever column of its built file holds it. + private func shownSpan( + of card: ReviewCardPlacement.CardID, + in index: Int, + on list: AllChangesListView, + ) -> ClosedRange? { + guard let view = list.file(at: index), let fileTop = list.top(ofFile: index), + let span = [view.mainColumn, view.split?.committed].lazy + .compactMap({ $0?.reviewCards.span(of: card) }).first + else { return nil } + let top = fileTop + AllChangesFileView.headerHeight + return (top + span.lowerBound)...(top + span.upperBound) + } +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesListRepresentable+Scroll.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesListRepresentable+Scroll.swift new file mode 100644 index 000000000..3fc36c6fb --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesListRepresentable+Scroll.swift @@ -0,0 +1,91 @@ +import AppKit +import MultishellAppCore +import MultishellCore + +/// The All changes list's place: the file at the top noted as it scrolls, and +/// a saved scroll or a Changes click put back once the list has a size. +extension AllChangesListRepresentable { + /// The file at the top, lit in Changes and its header held over the rows, + /// and the scroll by that file's line. + func noteScroll(of list: AllChangesListView, coordinator: Coordinator) { + guard let document = coordinator.document, let index = list.fileIndex(at: list.scrollY), + let top = list.top(ofFile: index) + else { return } + let y = list.scrollY + // A clicked file too near the end to reach the top stays lit until the list moves. + if coordinator.scrollYLeftByReveal.map({ abs($0 - y) > 0.5 }) ?? true { + coordinator.scrollYLeftByReveal = nil + model.noteAllChangesTopFile( + AllChangesTopFile( + path: document.sections[index].path, + headerBarTop: Double(top), + nextHeaderBarTop: list.top(ofFile: index + 1).map(Double.init), + scrolledTo: Double(y), + barHeight: UIMetrics.allChangesHeaderBarHeight, + ), + in: tab.id, + ) + } + noteChangeSteps(of: list, coordinator: coordinator) + guard coordinator.savedScroll == nil, coordinator.pendingReveal == nil else { return } + let rows = document.sections[index].rows + guard !rows.isEmpty else { + model.noteAllChangesScrolled(tab.id, to: document.scroll(atTopOf: index, x: 0)) + return + } + let intoRows = y - top - AllChangesFileView.headerHeight + let row = + list.file(at: index).map { $0.mainColumn.textView.geometry.topRow(atScrollOffset: intoRows) } + ?? Double(max(0, intoRows) / geometry.rowHeight) + let documentRow = Double(rows.lowerBound) + min(max(0, row), Double(rows.count - 1)) + if let scroll = document.scroll(atRow: documentRow, x: 0) { + model.noteAllChangesScrolled(tab.id, to: scroll) + } + } + + /// A Changes click's file at the top, else the saved scroll's line, once the + /// list has a size. + func restoreScroll(of list: AllChangesListView, coordinator: Coordinator) { + guard list.clipHeight > 0, let document = coordinator.document else { return } + if let path = coordinator.pendingReveal { + coordinator.pendingReveal = nil + if let index = document.section(at: path), let top = list.top(ofFile: index) { + coordinator.scrollYLeftByReveal = list.scrollY(reaching: top) + list.scroll(toY: top) + } + return + } + guard let scroll = coordinator.savedScroll, let index = document.section(at: scroll.path), + let top = list.top(ofFile: index) + else { + coordinator.savedScroll = nil + return + } + // A file still to be read has no rows to put back: its top, until it is + // read or the list is scrolled off it. + guard !coordinator.isUnread(index) else { + if let held = coordinator.offsetIntoUnreadSavedFile, abs(list.scrollY - top - held) > 0.5 { + coordinator.savedScroll = nil + coordinator.offsetIntoUnreadSavedFile = nil + return + } + list.scroll(toY: top) + coordinator.offsetIntoUnreadSavedFile = list.scrollY - top + return + } + coordinator.savedScroll = nil + coordinator.offsetIntoUnreadSavedFile = nil + guard !document.sections[index].rows.isEmpty, let row = document.row(of: scroll) else { + list.scroll(toY: top) + return + } + let fileRow = row - Double(document.sections[index].rows.lowerBound) + let cut = CGFloat(fileRow - fileRow.rounded(.down)) * geometry.rowHeight + coordinator.scroll( + to: AllChangesSteps.Stop(section: index, row: Int(fileRow)), + below: -cut, + on: list, + geometry: geometry, + ) + } +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesListRepresentable.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesListRepresentable.swift new file mode 100644 index 000000000..8ff988c46 --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesListRepresentable.swift @@ -0,0 +1,206 @@ +import AppKit +import MultishellAppCore +import MultishellCore +import MultishellHighlight +import SwiftUI + +/// The All changes tab's files as a list of views, each coloured as it is built; +/// see Docs/design/files/all-changes-tab.md. +struct AllChangesListRepresentable: NSViewRepresentable { + typealias Coordinator = AllChangesListCoordinator + + /// Measuring the font's widest character took a tenth of each scroll. + @MainActor private static var geometryByFont: (font: FileFont, geometry: DiffRowGeometry)? + + let model: AppModel + let tab: AllChangesTab + let document: AllChangesDocument + let theme: Theme + let font: FileFont + let find: FindMatchesShown + /// Comments to send by path, counted once by the tab's body for every header. + var pendingComments: [String: Int] = [:] + + var geometry: DiffRowGeometry { + if let cached = Self.geometryByFont, cached.font == font { return cached.geometry } + var geometry = DiffRowGeometry(fontFamily: font.family, fontSize: font.size) + geometry.verticalInset = 0 + Self.geometryByFont = (font, geometry) + return geometry + } + + static func dismantleNSView(_ list: AllChangesListView, coordinator: Coordinator) { + for (_, view) in list.builtFiles { view.highlighting?.cancel() } + } + + func makeCoordinator() -> Coordinator { Coordinator() } + + func makeNSView(context: Context) -> AllChangesListView { + let coordinator = context.coordinator + coordinator.representable = self + let list = AllChangesListView(frame: .zero) + list.leadingInset = CGFloat(UIMetrics.allChangesBoxMargin) + list.scrollerMargin = CGFloat(UIMetrics.allChangesScrollerMargin) + // The representable's at each call: the text size can change with the list kept. + list.estimate = { [weak coordinator] index in + guard let coordinator, let representable = coordinator.representable else { return 0 } + return coordinator.estimate( + index, + geometry: representable.geometry, + metrics: representable.model.metrics, + ) + } + list.makeFile = { [weak list, weak coordinator] isSplit in + coordinator?.representable?.makeFile(isSplit: isSplit, in: list) + } + list.configure = { [weak coordinator] view, index in + guard let coordinator else { return } + coordinator.representable?.configure(view, at: index, coordinator: coordinator) + } + let tabID = tab.id + list.onNearFiles = { [weak model, weak coordinator] near in + guard let document = coordinator?.document else { return } + let indices = near.clamped(to: document.sections.indices) + model?.noteAllChangesFilesNear(Set(indices.map { document.sections[$0].path }), in: tabID) + } + list.onScroll = { [weak list, weak coordinator] in + guard let list, let coordinator else { return } + coordinator.representable?.noteScroll(of: list, coordinator: coordinator) + } + // A restore or a first show reports no scroll; the top file is noted anyway. + list.onLaidOut = { [weak list, weak coordinator] in + guard let list, let coordinator, let representable = coordinator.representable else { return } + representable.restoreScroll(of: list, coordinator: coordinator) + representable.noteScroll(of: list, coordinator: coordinator) + } + list.changesRotor = AllChangesChangesRotor(list: list, coordinator: coordinator) + coordinator.savedScroll = model.allChangesScroll(of: tab.id) + return list + } + + func updateNSView(_ list: AllChangesListView, context: Context) { + let coordinator = context.coordinator + coordinator.representable = self + coordinator.pendingComments = pendingComments + let textChanged = coordinator.document != document || coordinator.theme != theme + if textChanged { + coordinator.noteDocument(document) + coordinator.theme = theme + list.show( + document.sections.indices.map { index in + AllChangesFileKey( + path: document.sections[index].path, + isSplit: document.showsSplitColumns(ofSection: index), + ) + } + ) + } else { + for (index, view) in list.builtFiles { configure(view, at: index, coordinator: coordinator) } + } + if let shown = coordinator.paint( + find, + on: list, + tint: theme.findMatchTint, + geometry: geometry, + textChanged: textChanged, + ) { + model.noteFileFindShown(shown, of: tab.id) + } + for direction in model.takeChangeStepRequests(tab.id) { + coordinator.step(direction, on: list, geometry: geometry) + } + noteChangeSteps(of: list, coordinator: coordinator) + if let card = model.takeReviewCardReveal(tab.id) { + revealReviewCard(card, on: list, coordinator: coordinator) + } + if let path = model.takeAllChangesFileReveal(tab.id) { + coordinator.savedScroll = nil + coordinator.pendingReveal = path + } + list.takeKeyboard(ifAskedBy: model, for: tab.id) + list.needsLayout = true + } + + private func makeFile(isSplit: Bool, in list: AllChangesListView?) -> AllChangesFileView { + let view = AllChangesFileView( + geometry: geometry, + isSplit: isSplit, + scrollsWith: list?.scrollView, + ) + let tabID = tab.id + let columns = [view.split?.committed, view.mainColumn].compactMap(\.self) + for column in columns { + column.textView.onFocus = { [weak model] in model?.noteFileTabFocused(tabID) } + // Kept by the view as it is reused: the representable, and its document, stay out. + column.onCommentOnRows = { [weak model, weak view] start, end, side in + guard let model, let section = view?.slice?.section else { return } + model.openReviewComposer( + fromRow: start, + toRow: end, + ofSection: section, + side: side, + in: tabID, + ) + } + } + for column in columns { + column.textView.forwardsScrollsTo = list + } + // Several files' texts share the tab's selection: the focused one's is the user's. + view.mainColumn.textView.onSelectionChange = { [weak model, weak view] text in + guard view?.mainColumn.textView.isFirstResponder == true else { return } + model?.noteFileTabSelection(text, of: tabID) + } + return view + } + + private func configure( + _ view: AllChangesFileView, + at index: Int, + coordinator: Coordinator, + ) { + guard let slice = coordinator.slice(index) else { return } + let section = document.sections[index] + let showsTextAnew = view.show( + slice, + header: AllChangesFileHeader( + model: model, + tabID: tab.id, + worktreeID: tab.worktreeID, + section: section, + pendingComments: coordinator.pendingComments[section.path] ?? 0, + theme: theme, + ), + item: { [model, tab, theme, path = section.path] item, codeX in + AnyView( + AllChangesGapItemView( + model: model, + tab: tab, + path: path, + item: item, + codeX: codeX, + theme: theme, + ) + ) + }, + itemHeight: { [metrics = model.metrics] item in + CGFloat(metrics.allChangesHeight(of: item.kind)) + }, + theme: theme, + ) + showReviewCards(on: view, at: index) + if showsTextAnew { coordinator.highlight(view, theme: theme) } + coordinator.dress(view, at: index) + } + + /// Which ways the bar's arrows can step from the boxed change or the top. + func noteChangeSteps(of list: AllChangesListView, coordinator: Coordinator) { + let geometry = geometry + let (origin, isBoxed) = coordinator.stepOrigin(on: list, geometry: geometry) + model.noteChangeSteps( + coordinator.outermostSteps(on: list, geometry: geometry) + .changeSteps(from: origin, isBoxed: isBoxed), + of: tab.id, + ) + } +} diff --git a/Sources/MultishellAppUI/Files/AllChanges/AllChangesListView.swift b/Sources/MultishellAppUI/Files/AllChanges/AllChangesListView.swift new file mode 100644 index 000000000..128109096 --- /dev/null +++ b/Sources/MultishellAppUI/Files/AllChanges/AllChangesListView.swift @@ -0,0 +1,291 @@ +import AppKit +import MultishellAppCore +import MultishellCore + +/// The files in one vertical scroller, a view each for those near the clip only; +/// see Docs/design/files/all-changes-tab.md. +@MainActor +final class AllChangesListView: NSView { + private static var fileGap: CGFloat { CGFloat(UIMetrics.allChangesFileGap) } + /// Views let go of and kept for the next files of their kind: building one + /// anew for each file scrolled to cost some 150 MB while scrolling. + private static let sparesKept = 6 + + let scrollView = WheelForwardingScrollView() + private let canvas = FlippedDocumentView() + private var keys: [AllChangesFileKey] = [] + private var indexByKey: [AllChangesFileKey: Int] = [:] + private var tops: [CGFloat] = [] + private var heights: [CGFloat] = [] + private var hosted: [AllChangesFileKey: AllChangesFileView] = [:] + /// By whether they show Split's two columns. + private var spares: [Bool: [AllChangesFileView]] = [:] + private var observers: [any NSObjectProtocol] = [] + private var measured: [AllChangesFileKey: AllChangesMeasuredHeight] = [:] + /// The file at `index`'s height before its view measures, a new view of + /// Split's kind or not, and its content shown in a view. + var estimate: ((Int) -> CGFloat)? + var makeFile: ((_ isSplit: Bool) -> AllChangesFileView?)? + var configure: ((AllChangesFileView, Int) -> Void)? + /// The one Changes rotor across the files, which offer none of their own. + var changesRotor: AllChangesChangesRotor? + /// Each scroll, after the files near the clip are built. + var onScroll: (() -> Void)? + /// Each layout, once the files are placed: the first with a size can restore. + var onLaidOut: (() -> Void)? + /// The files built, as they change: those within half a clip of the clip. + var onNearFiles: ((Range) -> Void)? + private var reportedNear: Range? + + var leadingInset: CGFloat = 0 { + didSet { if leadingInset != oldValue { needsLayout = true } } + } + + var scrollerMargin: CGFloat { + get { scrollView.trailingContentInset } + set { scrollView.trailingContentInset = newValue } + } + + var scrollY: CGFloat { scrollView.contentView.bounds.origin.y } + var clipHeight: CGFloat { scrollView.contentView.bounds.height } + private var isPlacementQueued = false + /// A page down or up: the clip less the lines a scroller keeps in view and + /// the sticky header covering the top. + private var pageHeight: CGFloat { + max(0, clipHeight - AllChangesFileView.headerHeight - scrollView.verticalPageScroll) + } + /// The few files built near the clip, in no order, with their places in the list. + var builtFiles: [(index: Int, view: AllChangesFileView)] { + hosted.compactMap { key, view in indexByKey[key].map { ($0, view) } } + } + override var acceptsFirstResponder: Bool { true } + + override init(frame: NSRect) { + super.init(frame: frame) + scrollView.hasVerticalScroller = true + scrollView.hasHorizontalScroller = false + scrollView.horizontalScrollElasticity = .none + scrollView.autohidesScrollers = true + scrollView.drawsBackground = false + scrollView.documentView = canvas + scrollView.contentView.postsBoundsChangedNotifications = true + addSubview(scrollView) + let scrolled: @MainActor @Sendable (AllChangesListView) -> Void = { list in + for view in list.hosted.values { view.forgetGutterHover() } + list.buildNearClip() + list.onScroll?() + } + observers = NotificationCenter.default.observe( + [(NSView.boundsDidChangeNotification, scrolled)], + for: self, + from: scrollView.contentView, + ) + } + + required init?(coder: NSCoder) { nil } + + /// New files, the file at the top held where it was. + func show(_ keys: [AllChangesFileKey]) { + let anchor = fileAnchor() + self.keys = keys + indexByKey = Dictionary(keepingFirst: keys.enumerated().map { ($1, $0) }) + // Other files may sit at the same indices, which the screen reports by. + reportedNear = nil + for (key, view) in hosted where indexByKey[key] == nil { + retire(view) + hosted[key] = nil + } + measured = measured.filter { indexByKey[$0.key] != nil } + for (index, key) in keys.enumerated() { + if let view = hosted[key] { configure?(view, index) } + } + place(holding: anchor) + } + + /// The file at `index`'s top in the list, its box's top. + func top(ofFile index: Int) -> CGFloat? { + tops.indices.contains(index) ? tops[index] : nil + } + + /// The file whose box, or the gap below it, holds `y`; the first file above its own gap. + func fileIndex(at y: CGFloat) -> Int? { + guard !tops.isEmpty else { return nil } + return max(0, tops.partitioningIndex { $0 > y } - 1) + } + + func file(at index: Int) -> AllChangesFileView? { + keys.indices.contains(index) ? hosted[keys[index]] : nil + } + + /// Where a scroll to `y` lands, held within the list's ends. + func scrollY(reaching y: CGFloat) -> CGFloat { + scrollView.clamped(NSPoint(x: 0, y: y)).y + } + + func scroll(toY y: CGFloat) { scrollView.scrollClamped(to: NSPoint(x: 0, y: y)) } + + override func layout() { + super.layout() + let frame = NSRect( + x: leadingInset, + y: 0, + width: max(0, bounds.width - leadingInset), + height: bounds.height, + ) + if scrollView.frame != frame { scrollView.frame = frame } + place(holding: fileAnchor()) + onLaidOut?() + } + + /// The file at the clip's top, by path so a switch to Split keeps it, and + /// how far into it the top sits. + private func fileAnchor() -> (path: String, offset: CGFloat)? { + guard let index = fileIndex(at: scrollY) else { return nil } + return (keys[index].path, scrollY - tops[index]) + } + + private func place(holding anchor: (path: String, offset: CGFloat)?) { + var top = Self.fileGap + tops = [] + heights = [] + for (index, key) in keys.enumerated() { + let height = hosted[key]?.height ?? measuredOrEstimatedHeight(of: key, at: index) + tops.append(top) + heights.append(height) + top += height + Self.fileGap + } + let width = scrollView.contentView.bounds.width + let size = NSSize(width: width, height: max(top, clipHeight)) + if canvas.frame.size != size { canvas.setFrameSize(size) } + if let anchor, let index = keys.firstIndex(where: { $0.path == anchor.path }) { + scroll(toY: tops[index] + anchor.offset) + } + buildNearClip() + } + + private func measuredOrEstimatedHeight(of key: AllChangesFileKey, at index: Int) -> CGFloat { + let estimated = estimate?(index) ?? 0 + guard let last = measured[key], last.estimate == estimated else { return estimated } + return last.height + } + + /// Builds the files within half a clip of the clip and lets go of the rest. + private func buildNearClip() { + // Half a clip either side: enough for a short scroll, few views at once. + guard let first = fileIndex(at: scrollY - clipHeight / 2) else { return } + let end = scrollY + clipHeight * 1.5 + var near: Set = [] + var index = first + while index < keys.count, tops[index] <= end { + let key = keys[index] + near.insert(key) + // None where the representable that makes files is gone mid-update. + guard let view = hosted[key] ?? build(key, at: index) else { + index += 1 + continue + } + let frame = NSRect( + x: 0, + y: tops[index], + width: scrollView.contentView.bounds.width, + height: heights[index], + ) + if view.frame != frame { view.frame = frame } + index += 1 + } + if reportedNear != first..