Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added cpu.out
Binary file not shown.
110 changes: 74 additions & 36 deletions pkg/gocui/view.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@ type View struct {
// tained is true if the viewLines must be updated
tainted bool

// firstDirtyLine is the index of the lowest line in `lines` that has been
// written to or highlighted since viewLines was last refreshed, and whose
// cached wrapping (lineType.wrappedCells) may therefore be stale. Lines
// below it are unchanged and can reuse their cached wrapping instead of
// being re-wrapped, which keeps refreshViewLinesIfNeeded cheap while
// scrolling appends new lines to a long buffer.
firstDirtyLine int

// the last position that the mouse was hovering over; nil if the mouse is outside of
// this view, or not hovering over a cell
lastHoverPosition *pos
Expand Down Expand Up @@ -457,6 +465,16 @@ type viewLine struct {
type lineType struct {
cells cells
trailingFillAttributes *trailingFillAttributes

// wrappedCells caches the result of wrapping `cells` to `wrappedColumns`
// columns, so that unchanged lines don't have to be re-wrapped on every
// refreshViewLinesIfNeeded (which runs on every scroll event, via
// ViewLinesHeight). Wrapping measures every cell's width and allocates, so
// for a long buffer that dominates the cost of scrolling. The cache is used
// only for lines below View.firstDirtyLine whose wrappedColumns still
// matches the current width; nil means nothing is cached yet.
wrappedCells [][]cell
wrappedColumns int
}

// trailingFillAttributes describes the fg/bg colors that draw() should
Expand Down Expand Up @@ -815,6 +833,9 @@ func (v *View) Write(p []byte) (n int, err error) {

func (v *View) write(p []byte) {
v.tainted = true
// write only ever touches lines from v.wy onwards, so any cached wrapping
// below that stays valid.
v.firstDirtyLine = min(v.firstDirtyLine, v.wy)
v.clearHover()

// Fill with empty cells, if writing outside current view buffer
Expand Down Expand Up @@ -1358,48 +1379,64 @@ func (v *View) draw() {
}

func (v *View) refreshViewLinesIfNeeded() {
if v.tainted {
maxX := v.InnerWidth()
lineIdx := 0
lines := v.lines
for i, line := range lines {
wrap := 0
if v.Wrap {
wrap = maxX
}
if !v.tainted {
return
}

ls := lineWrap(line.cells, wrap)
for j := range ls {
// Per-segment trailing fill. When the source line opted in
// via '\x1b[K', the LAST wrapped segment uses those colors
// directly; earlier segments use the colors of their own
// last cell, so the trailing area matches the bg active
// where that segment ended rather than bleeding the
// '\x1b[K' bg back across color changes in the line.
var attrs *trailingFillAttributes
if line.trailingFillAttributes != nil {
if j == len(ls)-1 {
attrs = line.trailingFillAttributes
} else if len(ls[j]) > 0 {
last := ls[j][len(ls[j])-1]
attrs = &trailingFillAttributes{fg: last.fgColor, bg: last.bgColor}
}
}
vline := viewLine{
linesX: j, linesY: i, line: ls[j],
trailingFillAttributes: attrs,
}
maxX := v.InnerWidth()
wrap := 0
if v.Wrap {
wrap = maxX
}

if lineIdx > len(v.viewLines)-1 {
v.viewLines = append(v.viewLines, vline)
} else {
v.viewLines[lineIdx] = vline
lineIdx := 0
lines := v.lines
for i := range lines {
line := &lines[i]

// Reuse the previously wrapped result for lines that haven't changed
// since the last refresh (i.e. below firstDirtyLine) and were wrapped at
// the current width. Wrapping is expensive and this loop runs on every
// scroll event, so only the lines that were actually just read (or
// re-highlighted) should be wrapped afresh.
if line.wrappedCells == nil || line.wrappedColumns != wrap || i >= v.firstDirtyLine {
line.wrappedCells = lineWrap(line.cells, wrap)
line.wrappedColumns = wrap
}
ls := line.wrappedCells

for j := range ls {
// Per-segment trailing fill. When the source line opted in
// via '\x1b[K', the LAST wrapped segment uses those colors
// directly; earlier segments use the colors of their own
// last cell, so the trailing area matches the bg active
// where that segment ended rather than bleeding the
// '\x1b[K' bg back across color changes in the line.
var attrs *trailingFillAttributes
if line.trailingFillAttributes != nil {
if j == len(ls)-1 {
attrs = line.trailingFillAttributes
} else if len(ls[j]) > 0 {
last := ls[j][len(ls[j])-1]
attrs = &trailingFillAttributes{fg: last.fgColor, bg: last.bgColor}
}
lineIdx++
}
vline := viewLine{
linesX: j, linesY: i, line: ls[j],
trailingFillAttributes: attrs,
}

if lineIdx > len(v.viewLines)-1 {
v.viewLines = append(v.viewLines, vline)
} else {
v.viewLines[lineIdx] = vline
}
lineIdx++
}
v.tainted = false
}

v.firstDirtyLine = len(lines)
v.tainted = false
}

// if autoscroll is enabled but we only have a single row of cells shown to the
Expand Down Expand Up @@ -1599,6 +1636,7 @@ func (v *View) SetHighlight(y int, on bool) {
cells = append(cells, c)
}
v.tainted = true
v.firstDirtyLine = min(v.firstDirtyLine, y)
v.lines[y].cells = cells
v.clearHover()
}
Expand Down
8 changes: 2 additions & 6 deletions pkg/gui/controllers/vertical_scroll_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,8 @@ func (self *VerticalScrollController) HandleScrollUp() error {
}

func (self *VerticalScrollController) HandleScrollDown() error {
scrollHeight := self.c.UserConfig().Gui.ScrollHeight
self.context.GetViewTrait().ScrollDown(scrollHeight)

if manager := self.c.GetViewBufferManagerForView(self.context.GetView()); manager != nil {
manager.ReadLines(scrollHeight)
}
self.context.GetViewTrait().ScrollDown(self.c.UserConfig().Gui.ScrollHeight)
self.c.ReadLinesToFillView(self.context.GetView())

return nil
}
7 changes: 1 addition & 6 deletions pkg/gui/controllers/view_selection_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,12 @@ func (self *ViewSelectionController) GetMouseKeybindings(opts types.KeybindingsO
}

func (self *ViewSelectionController) handleLineChange(delta int) {
if delta > 0 {
if manager := self.c.GetViewBufferManagerForView(self.context.GetView()); manager != nil {
manager.ReadLines(delta)
}
}

v := self.Context().GetView()
if delta < 0 {
v.ScrollUp(-delta)
} else {
v.ScrollDown(delta)
self.c.ReadLinesToFillView(v)
}
}

Expand Down
8 changes: 2 additions & 6 deletions pkg/gui/global_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,8 @@ func (gui *Gui) scrollUpView(view *gocui.View) {
}

func (gui *Gui) scrollDownView(view *gocui.View) {
scrollHeight := gui.c.UserConfig().Gui.ScrollHeight
view.ScrollDown(scrollHeight)

if manager := gui.getViewBufferManagerForView(view); manager != nil {
manager.ReadLines(scrollHeight)
}
view.ScrollDown(gui.c.UserConfig().Gui.ScrollHeight)
gui.readLinesToFillView(view)
}

func (gui *Gui) scrollUpMain() error {
Expand Down
17 changes: 17 additions & 0 deletions pkg/gui/gui.go
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,23 @@ func (gui *Gui) getViewBufferManagerForView(view *gocui.View) *tasks.ViewBufferM
return manager
}

// When scrolling a lazy-loaded view, we read enough lines to fill the viewport
// plus this many extra screenfuls, so that further scrolling has some runway
// and doesn't have to block on reading (and re-rendering) more lines on every
// wheel notch.
const scrollReadAheadScreenfuls = 3

// readLinesToFillView reads enough lines into the view's buffer to cover
// everything currently scrolled into view, plus a few screenfuls of read-ahead.
// Reading is idempotent (see ViewBufferManager.ReadLines), so if the buffer
// already extends far enough this does nothing.
func (gui *Gui) readLinesToFillView(view *gocui.View) {
if manager := gui.getViewBufferManagerForView(view); manager != nil {
viewportBottom := view.OriginY() + view.InnerHeight()
manager.ReadLines(viewportBottom + scrollReadAheadScreenfuls*view.InnerHeight())
}
}

func (gui *Gui) initialWindowViewNameMap(contextTree *context.ContextTree) *utils.ThreadSafeMap[string, string] {
result := utils.NewThreadSafeMap[string, string]()

Expand Down
4 changes: 4 additions & 0 deletions pkg/gui/gui_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,10 @@ func (self *guiCommon) GetViewBufferManagerForView(view *gocui.View) *tasks.View
return self.gui.getViewBufferManagerForView(view)
}

func (self *guiCommon) ReadLinesToFillView(view *gocui.View) {
self.gui.readLinesToFillView(view)
}

func (self *guiCommon) State() types.IStateAccessor {
return self.gui.stateAccessor
}
Expand Down
13 changes: 9 additions & 4 deletions pkg/gui/layout.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,18 @@ func (gui *Gui) layout(g *gocui.Gui) error {
if prevMainView != nil {
prevMainHeight := prevMainView.Height()
newMainHeight := viewDimensions["main"].Y1 - viewDimensions["main"].Y0 + 1
heightDiff := newMainHeight - prevMainHeight
if heightDiff > 0 {
if newMainHeight > prevMainHeight {
// The main views have grown taller, so make sure enough lines are
// loaded to fill them. The views haven't been resized yet at this
// point, so we can't rely on their current height; compute the target
// total from the new height instead. (Reading past the actual content
// is harmless: ReadLines stops at the end of input.)
linesToRead := prevMainView.OriginY() + newMainHeight
if manager := gui.getViewBufferManagerForView(gui.Views.Main); manager != nil {
manager.ReadLines(heightDiff)
manager.ReadLines(linesToRead)
}
if manager := gui.getViewBufferManagerForView(gui.Views.Secondary); manager != nil {
manager.ReadLines(heightDiff)
manager.ReadLines(linesToRead)
}
}
}
Expand Down
7 changes: 6 additions & 1 deletion pkg/gui/tasks_adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,12 @@ func (gui *Gui) getManager(view *gocui.View) *tasks.ViewBufferManager {
view.Reset()
},
func() {
gui.render()
// As the task reads more lines, the only thing that changes is the
// view's content (and its scrollbar); the window layout doesn't. So a
// content-only render is enough, and it's much cheaper than a full
// layout-and-redraw on every read - which matters a lot when reading
// a long diff, where reads happen repeatedly as the user scrolls.
gui.renderContentOnly()
},
func() {
// Need to check if the content of the view is well past the origin.
Expand Down
4 changes: 4 additions & 0 deletions pkg/gui/types/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ type IGuiCommon interface {
// return the view buffer manager for the given view, or nil if it doesn't have one
GetViewBufferManagerForView(view *gocui.View) *tasks.ViewBufferManager

// read enough lines into the given view's buffer to fill it at its current
// scroll position, plus some read-ahead for smooth scrolling
ReadLinesToFillView(view *gocui.View)

// returns true if command completed successfully
RunSubprocess(cmdObj *oscommands.CmdObj) (bool, error)
RunSubprocessAndRefresh(*oscommands.CmdObj) error
Expand Down
8 changes: 8 additions & 0 deletions pkg/gui/view_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,14 @@ func (gui *Gui) render() {
gui.c.OnUIThread(func() error { return nil })
}

// renderContentOnly triggers a re-render that skips the layout pass and only
// redraws the views whose content changed (relying on tcell's cell-level dirty
// tracking to emit just the cells that actually differ). Use it when only a
// view's content changed, not the window layout.
func (gui *Gui) renderContentOnly() {
gui.c.OnUIThreadContentOnly(func() error { return nil })
}

// postRefreshUpdate is to be called on a context after the state that it depends on has been refreshed
// if the context's view is set to another context we do nothing.
// if the context's view is the current view we trigger a focus; re-selecting the current item.
Expand Down
24 changes: 19 additions & 5 deletions pkg/tasks/tasks.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,11 @@ type ViewBufferManager struct {
}

type LinesToRead struct {
// Total number of lines to read
// The total number of lines the task should have read once this request is
// satisfied. This is an absolute count from the start of the task, not a
// delta: the task keeps track of how many lines it has already read and only
// reads the shortfall, so a request for a total at or below what has already
// been read reads nothing. -1 means read all the way to the end.
Total int

// Number of lines after which we have read enough to fill the view, and can
Expand Down Expand Up @@ -119,10 +123,14 @@ func NewViewBufferManager(
}
}

func (self *ViewBufferManager) ReadLines(n int) {
// ReadLines asks the task to ensure it has read at least totalLines lines in
// total. Because the count is absolute rather than a delta, repeated requests
// (e.g. as the user scrolls down, back up, and down again) don't re-read lines
// that have already been read: the task only ever reads the shortfall.
func (self *ViewBufferManager) ReadLines(totalLines int) {
if self.readLines != nil {
go utils.Safe(func() {
self.readLines <- LinesToRead{Total: n, InitialRefreshAfter: -1}
self.readLines <- LinesToRead{Total: totalLines, InitialRefreshAfter: -1}
})
}
}
Expand Down Expand Up @@ -283,6 +291,11 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix
}
}

// The total number of lines we have read so far. Requests specify an
// absolute target total (see LinesToRead.Total), so we compare against
// this to work out how many more lines, if any, we still need to read.
linesRead := 0

outer:
for {
if stopped() {
Expand All @@ -297,7 +310,7 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix
linesToRead.Then()
}
}
for i := 0; linesToRead.Total == -1 || i < linesToRead.Total; i++ {
for linesToRead.Total == -1 || linesRead < linesToRead.Total {
if stopped() {
callThen()
break outer
Expand Down Expand Up @@ -331,8 +344,9 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix
}
writeToView(append(line, '\n'))
lineWrittenChan <- struct{}{}
linesRead++

if i+1 == linesToRead.InitialRefreshAfter {
if linesRead == linesToRead.InitialRefreshAfter {
// We have read enough lines to fill the view, so do a first refresh
// here to show what we have. Continue reading and refresh again at
// the end to make sure the scrollbar has the right size.
Expand Down
Loading