diff --git a/desktop/internal/textview/cells.go b/desktop/internal/textview/cells.go new file mode 100644 index 0000000000..5e38189a5f --- /dev/null +++ b/desktop/internal/textview/cells.go @@ -0,0 +1,55 @@ +package textview + +import ( + "unicode/utf8" + + "github.com/1lck/Lithe-IDEA/desktop/internal/term" +) + +// tabSize is how many columns a tab stop is apart, as in the console the old client drew. +const tabSize = 4 + +// runeCells is how many columns of the fixed-pitch grid r takes when it starts at +// column at: a tab reaches the next stop, a carriage return takes none, a wide character +// two and a combining mark none, as the editor counts them (editorview's runeCells). +func runeCells(r rune, at int) int { + switch { + case r == '\t': + return tabSize - at%tabSize + case r == '\r': + return 0 + case r < 0x80: + return 1 + } + return term.Width(r) +} + +// cellsOf is how many columns text takes, starting at column at. +func cellsOf(text string, at int) int { + cells := at + for _, r := range text { + cells += runeCells(r, cells) + } + return cells - at +} + +// byteAt is the byte offset of text that a point column columns from its start names. +// nearest picks the boundary closest to the point, as a caret is placed; otherwise it +// is the start of the character the point is on, as a word is picked. +func byteAt(text string, column float32, nearest bool) int { + cells := 0 + for i := 0; i < len(text); { + r, size := utf8.DecodeRuneInString(text[i:]) + width := runeCells(r, cells) + end := float32(cells + width) + if column < end { + if nearest && width > 0 && column >= float32(cells)+float32(width)/2 { + return i + size + } + return i + } + cells += width + i += size + } + return len(text) +} diff --git a/desktop/internal/textview/paint.go b/desktop/internal/textview/paint.go new file mode 100644 index 0000000000..086ab4d76b --- /dev/null +++ b/desktop/internal/textview/paint.go @@ -0,0 +1,305 @@ +package textview + +import ( + "math" + "unicode/utf8" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// labelWidth is how wide one label of a row is at most, as the editor cuts its rows +// (editorview's labelWidth), so a very long line is not one huge texture. +const labelWidth = float32(2048) + +// replacementChar is what a byte that is not UTF-8 shows. +const replacementChar = "\uFFFD" + +// painter gathers the runs of one label of a row. +type painter struct { + v *View + canvas *gfx.Canvas + runs []gfx.TextRun + style gfx.TextStyle + left float32 + y float32 + line int + // fit is how many cells of the row are drawn before the ellipsis of a line cut short, + // and -1 when the row is drawn whole. + fit int +} + +// paint draws the rows on screen: the selection behind them, then each row on the +// fixed-pitch grid in its spans' colors. It declares the view's hit again with the text +// cursor, and the links with the hand. +func (v *View) paint(dc *ui.DrawContext) { + canvas := dc.Canvas + src := v.spec.Source + if src == nil { + return + } + v.rect = dc.Rect + v.clip = visible(canvas, dc.Rect) + if v.spec.Wrap && dc.Rect.Width != v.width { + v.width = dc.Rect.Width + v.layout(v.width) + canvas.RequestFrame() // the rows changed, and with them the height declared + } + if v.pressed && v.moved { + v.extendTo(v.pointer) + } + canvas.HitWithOptions(v.id, v.clip, dc.Label, gfx.HitOptions{Role: gfx.RoleGroup, Cursor: gfx.PointerCursorText}) + from, to := v.rowRange() + selFrom, selTo, selected := v.Selection.Range(src) + p := &painter{v: v, canvas: canvas, style: v.spec.Font, left: v.rect.X + v.spec.PadX} + p.style.Mono = true + limit := max(int(labelWidth/v.cellW), 1) + cols := max(int(math.Ceil(float64((v.clip.X+v.clip.Width-p.left)/v.cellW))), 0) + // The columns a line fits in before its trail, less the pixels a label is drawn wider. + room := int((v.rect.Width - 2*v.spec.PadX - 2) / v.cellW) + v.trails = v.trails[:0] + for index := from; index < to; index++ { + line, start, end := v.rowBytes(index) + text := src.Line(line) + p.line = line + p.y = v.rect.Y + v.spec.PadY + float32(index)*v.lineH + if v.spec.LineBackground != nil { + if color := v.spec.LineBackground(line); color.Alpha > 0 { + canvas.Fill(gfx.Rect{X: v.rect.X, Y: p.y, Width: v.rect.Width, Height: v.lineH}, color) + } + } + var trail Trail + if v.spec.Trail != nil && start == 0 { + trail = v.spec.Trail(line) + } + v.spans = v.spans[:0] + if v.spec.Spans != nil && text != "" { + v.spans = v.spec.Spans(line, text, v.spans) + } + p.fit = -1 + if v.spec.Ellipsis && !v.spec.Wrap { + fit := room + if trail.Text != "" { + fit -= v.trailCells(line) + } + if fit = max(fit, 1); cellsOf(text, 0) > fit { + p.fit = fit - 1 + } + } + p.decorate(text, start, end) + if selected && line >= selFrom.Line && line <= selTo.Line { + v.paintSelection(canvas, text, line, start, end, index, selFrom, selTo, p.left, p.y, p.fit) + } + if p.fit < 0 { + p.row(text, start, end, cols, limit) + } else { + p.cut(text, start, end, min(cols, p.fit), limit) + } + if trail.Text != "" { + p.trail(line, trail) + } + } +} + +// cut draws a row cut short: the columns before fit, then the ellipsis in the color of the +// span the cut fell in. +func (p *painter) cut(text string, start, end, fit, limit int) { + stop := p.row(text, start, end, fit, limit) + color := p.style.Color + for _, span := range p.v.spans { + if span.From <= stop && stop < span.To { + color = p.spanColor(span) + break + } + } + p.runs = append(p.runs, gfx.TextRun{Bytes: int32(len(ellipsis)), Cells: 1, Color: color}) + p.flush(ellipsis, p.fit, p.fit+1) +} + +// trail draws line n's trail at the view's right edge, centered on the row, and keeps where +// a Button trail went so a click on it presses it. +func (p *painter) trail(n int, t Trail) { + v := p.v + width := p.canvas.TextWidthStyle(t.Text, t.Style) + height := t.Style.Size + 7 // the height of one line of a ui.Text + rect := gfx.Rect{X: v.rect.X + v.rect.Width - v.spec.PadX - width, Y: p.y + (v.lineH-height)/2, Width: width + 1, Height: height} + p.canvas.Label(t.Text, rect, t.Style) + if t.Button { + hit := gfx.Rect{X: rect.X, Y: p.y, Width: rect.Width, Height: v.lineH} + p.canvas.HitWithOptions(v.id, hit, t.Text, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand}) + v.trails = append(v.trails, trailHit{line: n, rect: hit}) + } +} + +// spanColor is the color a span is drawn in: its Hover color while the pointer is over its +// link. +func (p *painter) spanColor(span Span) gfx.Color { + v := p.v + if span.Link && span.Hover.Alpha > 0 && v.hovering && v.hover.Byte == span.From && p.line == v.hover.Line { + return span.Hover + } + return span.Color +} + +// visible is the part of r inside every clip the canvas paints with. +func visible(canvas *gfx.Canvas, r gfx.Rect) gfx.Rect { + for _, clip := range canvas.Clips() { + b := clip.Bounds + x0, y0 := max(r.X, b.X), max(r.Y, b.Y) + x1, y1 := min(r.X+r.Width, b.X+b.Width), min(r.Y+r.Height, b.Y+b.Height) + r = gfx.Rect{X: x0, Y: y0, Width: max(x1-x0, 0), Height: max(y1-y0, 0)} + } + return r +} + +// paintSelection fills the selected part of a row. A selection that goes on past the +// line's end covers one cell more, for the newline it holds. +func (v *View) paintSelection(canvas *gfx.Canvas, text string, line, start, end, index int, from, to Point, left, y float32, fit int) { + a, b := start, end + if line == from.Line { + a = max(a, from.Byte) + } + if line == to.Line { + b = min(b, to.Byte) + } + if a > b || a == b && !(line < to.Line && v.lastRow(index) && a == end) { + return + } + x0 := cellsOf(text[start:a], 0) + x1 := x0 + cellsOf(text[a:b], x0) + if line < to.Line && v.lastRow(index) && b == end { + x1++ + } + if fit >= 0 { + // A line cut short is selected up to its ellipsis, which stands for the rest. + x0, x1 = min(x0, fit+1), min(x1, fit+1) + if x0 >= x1 { + return + } + } + canvas.Fill(gfx.Rect{X: left + float32(x0)*v.cellW, Y: y, Width: float32(x1-x0) * v.cellW, Height: v.lineH}, v.spec.Selection) +} + +// row draws the bytes start to end of a line, the columns before cols of it, as labels +// of at most limit columns: each character on its cells, in the color of the span it is +// in. A tab or a control character leaves its cells empty; a combining mark is not drawn. +func (p *painter) row(text string, start, end, cols, limit int) int { + v := p.v + span := 0 + cells := 0 + run, runASCII := -1, false + label, labelEnd, labelAt, labelTo := -1, 0, start, start + for i := start; i < end; { + at := i + r, size := utf8.DecodeRuneInString(text[i:]) + i += size + width := runeCells(r, cells) + if width == 0 { + p.flush(text[labelAt:labelTo], label, labelEnd) + label = -1 + continue + } + if cells >= cols || p.fit >= 0 && cells+width > cols { + p.flush(text[labelAt:labelTo], label, labelEnd) + return at + } + for span < len(v.spans) && v.spans[span].To <= at { + span++ + } + var style Span + styled := span < len(v.spans) && v.spans[span].From <= at + if styled { + style = v.spans[span] + } + if r == '\t' || r < 0x20 { + p.flush(text[labelAt:labelTo], label, labelEnd) + label = -1 + cells += width + continue + } + invalid := r == utf8.RuneError && size == 1 + if label < 0 || invalid || cells+width-label > limit { + p.flush(text[labelAt:labelTo], label, labelEnd) + label, labelAt, labelTo, run = cells, at, at, -1 + } + color, weight := p.style.Color, float32(0) + if styled { + color = p.spanColor(style) + if style.Bold { + weight = gfx.WeightBold + } + } + italic := styled && style.Italic + ascii := r < 0x80 + if ascii && runASCII && run >= 0 && p.runs[run].Color == color && p.runs[run].Weight == weight && + p.runs[run].Italic == italic && p.runs[run].Underline == style.Underline && p.runs[run].Strike == style.Strike { + p.runs[run].Bytes += int32(size) + p.runs[run].Cells += int32(width) + } else { + bytes := size + if invalid { + bytes = len(replacementChar) + } + p.runs = append(p.runs, gfx.TextRun{ + Column: int32(cells - label), Bytes: int32(bytes), Cells: int32(width), + Color: color, Weight: weight, Italic: italic, Underline: style.Underline, Strike: style.Strike, + }) + run, runASCII = len(p.runs)-1, ascii + } + cells += width + labelEnd, labelTo = cells, i + if invalid { + p.flush(replacementChar, label, labelEnd) + label = -1 + } + } + p.flush(text[labelAt:labelTo], label, labelEnd) + return end +} + +// decorate fills the backgrounds of a row's spans and declares the hits of its links with +// the hand cursor, named by their text, under the view's own identity so a press on a link +// still selects. +func (p *painter) decorate(text string, start, end int) { + v := p.v + for _, span := range v.spans { + if span.Background.Alpha <= 0 && !span.Link { + continue + } + a, b := max(span.From, start), min(span.To, end) + if a >= b { + continue + } + x0 := cellsOf(text[start:a], 0) + x1 := x0 + cellsOf(text[a:b], x0) + if p.fit >= 0 { + if x0, x1 = min(x0, p.fit+1), min(x1, p.fit+1); x0 >= x1 { + continue + } + } + rect := gfx.Rect{X: p.left + float32(x0)*v.cellW, Y: p.y, Width: float32(x1-x0) * v.cellW, Height: v.lineH} + if span.Background.Alpha > 0 { + p.canvas.Fill(rect, span.Background) + } + if span.Link { + label := span.Label + if label == "" { + label = text[a:b] + } + p.canvas.HitWithOptions(v.id, rect, label, gfx.HitOptions{Role: gfx.RoleLink, Cursor: gfx.PointerCursorHand}) + } + } +} + +// flush draws the runs gathered for a label from column start to column end and empties +// them for the next label. +func (p *painter) flush(value string, start, end int) { + if len(p.runs) == 0 { + return + } + v := p.v + width := float32(math.Ceil(float64(float32(end-start)*v.cellW))) + 1 + rect := gfx.Rect{X: p.left + float32(start)*v.cellW, Y: p.y + (v.lineH-v.cellH)/2, Width: width, Height: v.cellH} + p.canvas.LabelRuns(value, rect, p.style, v.cellW, p.runs) + p.runs = p.runs[:0] +} diff --git a/desktop/internal/textview/rows.go b/desktop/internal/textview/rows.go new file mode 100644 index 0000000000..5a549f5b9e --- /dev/null +++ b/desktop/internal/textview/rows.go @@ -0,0 +1,145 @@ +package textview + +import ( + "math" + "unicode/utf8" +) + +// layout breaks the lines into rows for a text width, when the view wraps. A view that +// does not wrap has a row for each line and keeps no list of them, so a console of many +// thousands of lines costs nothing to lay out. +func (v *View) layout(width float32) { + src := v.spec.Source + key := layoutKey{revision: v.spec.Revision, width: width, cellW: v.cellW, wrap: v.spec.Wrap} + if src != nil { + key.first, key.count = src.First(), src.Count() + } + if key.revision != 0 && key == v.laid { + return + } + v.laid = key + v.rows = v.rows[:0] + v.wrapCols = 0 + if !v.spec.Wrap || src == nil || v.cellW <= 0 { + return + } + // Two pixels are kept back for the pixel a label is drawn wider (paint.go's flush) and + // its rounding, so a full row stays inside the view. + cols := int((width - 2*v.spec.PadX - 2) / v.cellW) + if cols <= 0 { + // Not painted yet: a row for each line until the width is known. + for n := src.First(); n < src.First()+src.Count(); n++ { + v.rows = append(v.rows, row{line: n, from: 0, to: len(src.Line(n))}) + } + return + } + v.wrapCols = cols + for n := src.First(); n < src.First()+src.Count(); n++ { + v.rows = wrapLine(v.rows, n, src.Line(n), max(cols-v.trailCells(n), 1)) + } +} + +// trailCells is how many cells line n's trail and the gap before it take from the line's +// text, 0 when it has none. +func (v *View) trailCells(n int) int { + if v.spec.Trail == nil || v.canvas == nil || v.cellW <= 0 { + return 0 + } + t := v.spec.Trail(n) + if t.Text == "" { + return 0 + } + return int(math.Ceil(float64((v.canvas.TextWidthStyle(t.Text, t.Style) + trailGap) / v.cellW))) +} + +// wrapLine appends the rows of one line cols columns wide: each ends after the last space +// that fits, or at the column limit when no space does. +func wrapLine(rows []row, n int, text string, cols int) []row { + start, cells, space := 0, 0, -1 + for i := 0; i < len(text); { + r, size := utf8.DecodeRuneInString(text[i:]) + width := runeCells(r, cells) + if cells+width > cols && cells > 0 { + end := i + if space > start { + end = space + } + rows = append(rows, row{line: n, from: start, to: end}) + start, space = end, -1 + cells = cellsOf(text[start:i], 0) + continue + } + cells += width + i += size + if r == ' ' || r == '\t' { + space = i + } + } + return append(rows, row{line: n, from: start, to: len(text)}) +} + +// rowCount is how many rows the text takes. +func (v *View) rowCount() int { + if v.spec.Source == nil { + return 0 + } + if v.spec.Wrap { + return len(v.rows) + } + return v.spec.Source.Count() +} + +// rowBytes is the line row index shows and the bytes of it the row holds. +func (v *View) rowBytes(index int) (line, from, to int) { + if v.spec.Wrap { + r := v.rows[index] + return r.line, r.from, r.to + } + line = v.spec.Source.First() + index + return line, 0, len(v.spec.Source.Line(line)) +} + +// rowLine is the line row index shows. +func (v *View) rowLine(index int) int { + if v.spec.Wrap { + if index >= len(v.rows) { + return v.spec.Source.First() + v.spec.Source.Count() + } + return v.rows[index].line + } + return v.spec.Source.First() + index +} + +// lastRow reports whether row index is the last row of its line. +func (v *View) lastRow(index int) bool { + return !v.spec.Wrap || index+1 >= len(v.rows) || v.rows[index+1].line != v.rows[index].line +} + +// firstRowOf is the index of line n's first row. +func (v *View) firstRowOf(n int) (int, bool) { + src := v.spec.Source + if src == nil || n < src.First() || n >= src.First()+src.Count() { + return 0, false + } + if !v.spec.Wrap { + return n - src.First(), true + } + for i, r := range v.rows { + if r.line == n { + return i, true + } + } + return 0, false +} + +// rowRange is the rows the clip shows, from the first to the one after the last. +func (v *View) rowRange() (int, int) { + count := v.rowCount() + if v.lineH <= 0 || count == 0 { + return 0, 0 + } + top := v.clip.Y - v.rect.Y - v.spec.PadY + from := max(int(math.Floor(float64(top/v.lineH))), 0) + to := min(int(math.Ceil(float64((top+v.clip.Height)/v.lineH))), count) + return min(from, count), max(to, min(from, count)) +} diff --git a/desktop/internal/textview/selection.go b/desktop/internal/textview/selection.go new file mode 100644 index 0000000000..2752776961 --- /dev/null +++ b/desktop/internal/textview/selection.go @@ -0,0 +1,252 @@ +// Package textview is read-only text the user can select and copy: the console of a run, +// a build or a test, and the details of a commit. The text is drawn on the fixed-pitch +// grid, every line of it or only the rows in view, and takes the selection a text field +// takes in IntelliJ IDEA: a drag, across lines too, a double click for a word, a triple +// click for a line, Shift with a click to extend it, Primary+C to copy it and Primary+A to +// select everything. It never edits what it shows. +package textview + +import ( + "strings" + "unicode" + "unicode/utf8" +) + +// Point is a place in the text: the number of a line, as the Source numbers it, and a +// byte offset into the line. +type Point struct { + Line, Byte int +} + +// Less reports whether p comes before q. +func (p Point) Less(q Point) bool { + return p.Line < q.Line || p.Line == q.Line && p.Byte < q.Byte +} + +// Source is the lines a view shows. The lines are numbered from First on, and a line +// number stays the line's while the source holds it: a console that drops its oldest +// lines raises First, so a selection made before still names the same text. +type Source interface { + First() int + Count() int + Line(n int) string +} + +// Strings is a Source of lines held in a slice, numbered from 0. +type Strings []string + +func (s Strings) First() int { return 0 } +func (s Strings) Count() int { return len(s) } +func (s Strings) Line(n int) string { return s[n] } + +// unit is what a press selects and a drag extends by: characters after one click, words +// after two and lines after three. +type unit uint8 + +const ( + unitChar unit = iota + unitWord + unitLine +) + +// Selection is the selected range of a view's text. The press that began it fixes the +// anchor, the character, word or line under it, and a drag or a Shift click moves the +// focus; the range runs between them, in whole words or lines for a press of two or +// three clicks. +type Selection struct { + anchorFrom, anchorTo Point + focusFrom, focusTo Point + unit unit + set bool +} + +// Begin starts a selection at a press: an empty one at the nearest character boundary +// after one click, the word under the pointer after two and the line after three. line +// is the text of at.Line. +func (s *Selection) Begin(at Point, line string, clicks int) { + s.unit = unitChar + switch { + case clicks >= 3: + s.unit = unitLine + case clicks == 2: + s.unit = unitWord + } + s.anchorFrom, s.anchorTo = s.span(at, line) + s.focusFrom, s.focusTo = s.anchorFrom, s.anchorTo + s.set = true +} + +// Extend moves the focus to at, by the unit of the press that began the selection. It +// begins a selection of characters when there is none. +func (s *Selection) Extend(at Point, line string) { + if !s.set { + s.Begin(at, line, 1) + return + } + s.focusFrom, s.focusTo = s.span(at, line) +} + +// span is the unit around at: at itself for characters, the word under it or the whole +// line, ending at the start of the next line. +func (s *Selection) span(at Point, line string) (Point, Point) { + at.Byte = boundary(line, at.Byte) + switch s.unit { + case unitWord: + from, to := wordAt(line, at.Byte) + return Point{at.Line, from}, Point{at.Line, to} + case unitLine: + return Point{at.Line, 0}, Point{at.Line + 1, 0} + } + return at, at +} + +// SelectAll selects every line src holds. +func (s *Selection) SelectAll(src Source) { + if src.Count() == 0 { + s.Clear() + return + } + last := src.First() + src.Count() - 1 + s.unit = unitChar + s.anchorFrom, s.anchorTo = Point{src.First(), 0}, Point{src.First(), 0} + s.focusFrom, s.focusTo = Point{last, len(src.Line(last))}, Point{last, len(src.Line(last))} + s.set = true +} + +// Clear drops the selection. +func (s *Selection) Clear() { *s = Selection{} } + +// Lines is the first and the last line the selection's anchor and focus are on, and false +// when there is no selection. A line selected by a triple click ends at the start of the line +// after it, which then is the last. +func (s *Selection) Lines() (int, int, bool) { + if !s.set { + return 0, 0, false + } + return min(s.anchorFrom.Line, s.focusFrom.Line), max(s.anchorTo.Line, s.focusTo.Line), true +} + +// Move renumbers the selection's lines by delta, for a source whose lines moved: the same +// text, now delta lines further on. +func (s *Selection) Move(delta int) { + for _, p := range []*Point{&s.anchorFrom, &s.anchorTo, &s.focusFrom, &s.focusTo} { + p.Line += delta + } +} + +// Range is the selection in src, from its start to its end, clamped to the lines src +// still holds and to character boundaries. ok is false when nothing is selected. +func (s *Selection) Range(src Source) (from, to Point, ok bool) { + if !s.set || src.Count() == 0 { + return Point{}, Point{}, false + } + from, to = s.anchorFrom, s.anchorTo + if s.focusFrom.Less(s.anchorFrom) { + from = s.focusFrom + } + if to.Less(s.focusTo) { + to = s.focusTo + } + from, to = clamp(src, from), clamp(src, to) + if !from.Less(to) { + return Point{}, Point{}, false + } + return from, to, true +} + +// Has reports whether anything is selected in src. +func (s *Selection) Has(src Source) bool { + _, _, ok := s.Range(src) + return ok +} + +// Text is the selected text of src, its lines joined with newlines. +func (s *Selection) Text(src Source) string { + from, to, ok := s.Range(src) + if !ok { + return "" + } + return Text(src, from, to) +} + +// Text is the text of src from one point to another, its lines joined with newlines. +func Text(src Source, from, to Point) string { + if from.Line == to.Line { + return src.Line(from.Line)[from.Byte:to.Byte] + } + var b strings.Builder + b.WriteString(src.Line(from.Line)[from.Byte:]) + for n := from.Line + 1; n < to.Line; n++ { + b.WriteByte('\n') + b.WriteString(src.Line(n)) + } + b.WriteByte('\n') + b.WriteString(src.Line(to.Line)[:to.Byte]) + return b.String() +} + +// clamp moves p into the lines src holds: before them to the start of the first, after +// them to the end of the last, and inside a character to its start. +func clamp(src Source, p Point) Point { + first, last := src.First(), src.First()+src.Count()-1 + switch { + case p.Line < first: + return Point{first, 0} + case p.Line > last: + return Point{last, len(src.Line(last))} + } + return Point{p.Line, boundary(src.Line(p.Line), p.Byte)} +} + +// boundary moves at into text and back to the start of the character it is inside. +func boundary(text string, at int) int { + at = min(max(at, 0), len(text)) + for at > 0 && at < len(text) && !utf8.RuneStart(text[at]) { + at-- + } + return at +} + +// wordAt is the word, the run of spaces or the run of punctuation under the character +// at at, as a double click in IntelliJ IDEA's editor selects it. At the end of the text +// it is the one before. +func wordAt(text string, at int) (int, int) { + if text == "" { + return 0, 0 + } + if at >= len(text) { + _, size := utf8.DecodeLastRuneInString(text) + at = len(text) - size + } + r, _ := utf8.DecodeRuneInString(text[at:]) + class := charClass(r) + from := at + for from > 0 { + r, size := utf8.DecodeLastRuneInString(text[:from]) + if charClass(r) != class { + break + } + from -= size + } + to := at + for to < len(text) { + r, size := utf8.DecodeRuneInString(text[to:]) + if charClass(r) != class { + break + } + to += size + } + return from, to +} + +// charClass sorts characters for wordAt: spaces, the characters of identifiers and +// numbers, and everything else. +func charClass(r rune) int { + switch { + case unicode.IsSpace(r): + return 1 + case r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r): + return 2 + } + return 3 +} diff --git a/desktop/internal/textview/selection_test.go b/desktop/internal/textview/selection_test.go new file mode 100644 index 0000000000..b58878da2c --- /dev/null +++ b/desktop/internal/textview/selection_test.go @@ -0,0 +1,177 @@ +package textview + +import ( + "slices" + "testing" +) + +// trimmed is a Source whose oldest lines are gone, as a console's are once it is full: its +// lines are numbered from first on. +type trimmed struct { + first int + lines []string +} + +func (s trimmed) First() int { return s.first } +func (s trimmed) Count() int { return len(s.lines) } +func (s trimmed) Line(n int) string { return s.lines[n-s.first] } + +func TestSelectionRunsBetweenAnchorAndFocusEitherWay(t *testing.T) { + src := Strings{"first line", "second line", "third"} + var s Selection + s.Begin(Point{2, 2}, src[2], 1) + s.Extend(Point{0, 6}, src[0]) + if got, want := s.Text(src), "line\nsecond line\nth"; got != want { + t.Fatalf("a drag back up selected %q, want %q", got, want) + } + s.Begin(Point{1, 3}, src[1], 1) + if s.Has(src) { + t.Fatalf("a press alone selected %q", s.Text(src)) + } +} + +func TestSelectionByWordsAndLinesKeepsTheWholeUnits(t *testing.T) { + src := Strings{"at demo.Main.run(Main.java:12)", "next line"} + var s Selection + s.Begin(Point{0, 5}, src[0], 2) + if got := s.Text(src); got != "demo" { + t.Fatalf("a double click selected %q, want the word", got) + } + // A drag after a double click extends by whole words, both ends kept whole. + s.Extend(Point{0, 15}, src[0]) + if got := s.Text(src); got != "demo.Main.run" { + t.Fatalf("a drag by words selected %q", got) + } + s.Begin(Point{0, 3}, src[0], 3) + if got, want := s.Text(src), src[0]+"\n"; got != want { + t.Fatalf("a triple click selected %q, want the line and its newline", got) + } + // The last line has no newline after it to take. + s.Begin(Point{1, 0}, src[1], 3) + if got := s.Text(src); got != "next line" { + t.Fatalf("a triple click on the last line selected %q", got) + } +} + +func TestSelectAllAndClear(t *testing.T) { + src := Strings{"a", "", "b c"} + var s Selection + s.SelectAll(src) + if got := s.Text(src); got != "a\n\nb c" { + t.Fatalf("Select All selected %q", got) + } + s.Clear() + if s.Has(src) { + t.Fatal("Clear kept a selection") + } + s.SelectAll(Strings{}) + if s.Has(Strings{}) { + t.Fatal("Select All of nothing selected something") + } +} + +// A console that drops its oldest lines keeps what is left of a selection over them. +func TestSelectionKeepsToItsLinesWhenTheOldestGo(t *testing.T) { + src := trimmed{first: 0, lines: []string{"zero", "one", "two", "three"}} + var s Selection + s.Begin(Point{0, 2}, src.Line(0), 1) + s.Extend(Point{2, 2}, src.Line(2)) + src = trimmed{first: 1, lines: src.lines[1:]} + if got, want := s.Text(src), "one\ntw"; got != want { + t.Fatalf("after the first line went the selection is %q, want %q", got, want) + } + src = trimmed{first: 3, lines: src.lines[2:]} + if s.Has(src) { + t.Fatalf("after every selected line went %q is still selected", s.Text(src)) + } +} + +func TestWordAtSortsSpacesWordsAndPunctuation(t *testing.T) { + text := "foo_bar1 (x) 中文" + cases := []struct { + at int + from, to int + }{ + {0, 0, 8}, // foo_bar1 + {8, 8, 10}, // the two spaces + {10, 10, 11}, // ( + {len(text), len("foo_bar1 (x) "), len(text)}, // at the end: the word before + {len("foo_bar1 (x) ") + 3, len("foo_bar1 (x) "), len(text)}, + } + for _, c := range cases { + if from, to := wordAt(text, c.at); from != c.from || to != c.to { + t.Errorf("wordAt(%d) = %d..%d (%q), want %d..%d", c.at, from, to, text[from:to], c.from, c.to) + } + } + if from, to := wordAt("", 0); from != 0 || to != 0 { + t.Errorf("wordAt of nothing = %d..%d", from, to) + } +} + +// A point inside a character, as a byte offset from another line can be, moves to its start. +func TestRangeClampsToCharacterBoundaries(t *testing.T) { + src := Strings{"中文", "abc"} + var s Selection + s.Begin(Point{0, 1}, "abc", 1) // made with the text of another line + s.Extend(Point{1, 2}, src[1]) + if got := s.Text(src); got != "中文\nab" { + t.Fatalf("selected %q, want it to start at the character", got) + } +} + +func TestByteAtPicksTheCellUnderAColumn(t *testing.T) { + text := "a\tb中c" + // a: column 0; tab: 1..4; b: 4; 中: 5..7; c: 7. + cases := []struct { + column float32 + nearest bool + want int + }{ + {0.2, true, 0}, + {0.6, true, 1}, + {0.6, false, 0}, + {2, false, 1}, + {4.2, false, 2}, + {5.2, true, 3}, + {6.5, true, 6}, + {6.5, false, 3}, + {7.1, false, 6}, + {40, true, len(text)}, + } + for _, c := range cases { + if got := byteAt(text, c.column, c.nearest); got != c.want { + t.Errorf("byteAt(%v, nearest %v) = %d, want %d", c.column, c.nearest, got, c.want) + } + } +} + +func TestWrapLineBreaksAfterASpaceOrAtTheLimit(t *testing.T) { + rows := wrapLine(nil, 0, "alpha beta gamma", 11) + got := make([]string, 0, len(rows)) + for _, r := range rows { + got = append(got, "alpha beta gamma"[r.from:r.to]) + } + if want := []string{"alpha beta ", "gamma"}; !slices.Equal(got, want) { + t.Fatalf("rows %q, want %q", got, want) + } + long := "" + rows = wrapLine(nil, 3, long, 10) + joined := "" + for _, r := range rows { + if r.line != 3 || cellsOf(long[r.from:r.to], 0) > 10 { + t.Fatalf("row %+v of %q is wider than the limit or of another line", r, long) + } + joined += long[r.from:r.to] + } + if joined != long || len(rows) < 4 { + t.Fatalf("the rows of a word wider than a line join to %q in %d rows", joined, len(rows)) + } + // A wide character that does not fit moves to the next row whole. + rows = wrapLine(nil, 0, "abc中", 4) + if len(rows) != 2 || rows[0].to != 3 { + t.Fatalf("rows %+v, want the wide character on a row of its own", rows) + } + if rows := wrapLine(nil, 0, "", 4); len(rows) != 1 || rows[0].from != 0 || rows[0].to != 0 { + t.Fatalf("an empty line has rows %+v, want one empty row", rows) + } +} diff --git a/desktop/internal/textview/view.go b/desktop/internal/textview/view.go new file mode 100644 index 0000000000..b665e6994a --- /dev/null +++ b/desktop/internal/textview/view.go @@ -0,0 +1,541 @@ +package textview + +import ( + "math" + "time" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Span is a styled byte range of one line: its color, an optional background, and +// whether it is a link a click opens. +type Span struct { + From, To int + Color gfx.Color + Background gfx.Color // drawn when its Alpha is above zero + Bold bool + Italic bool + Underline bool + Strike bool + Link bool + // Hover is the color of a link while the pointer is over it, when its Alpha is above + // zero. Label names the link for assistive technology; empty names it by its text. + Hover gfx.Color + Label string +} + +// Trail is a note drawn after a line, at the view's right edge on the line's first row: a +// badge, or with Button set a button a click presses. It is not part of the text, so a +// selection never takes it and a copy never holds it. +type Trail struct { + Text string + Style gfx.TextStyle + Button bool +} + +// trailGap is the room between a line's text and its trail. +const trailGap = 6 + +// ellipsis ends a line cut short; it takes one cell. +const ellipsis = "\u2026" + +// Spec is what a view shows and how, given again in every paint. +type Spec struct { + // Label names the text for assistive technology. + Label string + Source Source + // Font is the fixed-pitch face and size the text is drawn in; its Color is the color + // of what no span colors. LineHeight is the height of one row. + Font gfx.TextStyle + LineHeight float32 + PadX, PadY float32 + // Selection is the color behind the selected text. + Selection gfx.Color + // Scroll makes the view an area of its own that scrolls, keeps to the newest line + // while the user has not scrolled up (Follow) and fills the area's height. Without it + // the view is as tall as its text, to be placed in a scrolling area. + Scroll bool + Follow bool + // Wrap breaks a line wider than the view into rows, at a space where it can. + Wrap bool + // Ellipsis cuts a line wider than a view that does not wrap one cell short of the edge, + // and ends it in an ellipsis in the color it was cut in. The text cut off is still + // selected and copied. + Ellipsis bool + // Revision, when not zero, changes whenever the lines or their trails do, so a view + // that wraps breaks its lines again only when it or the width changed. Zero breaks them + // on every paint. + Revision uint64 + // LineBackground is the color behind line n, across the view, when its Alpha is above + // zero. + LineBackground func(n int) gfx.Color + // Trail is the note drawn after line n; one with no Text draws nothing. PressTrail is + // called with n when a click without a drag lands on a Button trail. + Trail func(n int) Trail + PressTrail func(n int) + // Spans styles line n, whose text is text, appending to dst. Nil draws every line in + // Font. It is asked only for the rows on screen and for the line a click lands on. + Spans func(n int, text string, dst []Span) []Span + // Open is called with a link span a click without a drag landed on. + Open func(n int, span Span) + // Copy puts the selection Primary+C copies on the clipboard; nil puts it there as it + // is. + Copy func(text string) + // Menu, when set, is the context menu a secondary press opens. + Menu func(*ui.MenuItems) +} + +// View is the state of one read-only text: its selection, the press being followed and +// where the last paint put its rows. Keep it in the model with what it shows. +type View struct { + Selection Selection + + spec Spec + input ui.Handlers + draw func(*ui.DrawContext) + id gfx.ID + + // rect is the control as the last paint placed it and clip the part of it on screen; + // cellW and lineH are the grid it was drawn on, width the text width it wrapped at, + // and rows its rows when it wraps. + rect, clip gfx.Rect + cellW, cellH float32 + lineH float32 + width float32 + rows []row + wrapCols int + + // pressed says a primary press on the view is held; press is where it went down and + // moved whether it has left that spot, and pointer where the pointer is now. + pressed bool + moved bool + press gfx.Point + pointer gfx.Point + clicks int + // stepAt is when the drag past an edge last scrolled the area. + stepAt time.Duration + + menuOpen bool + menuAt gfx.Point + menuLine int + menuSet bool + + toEnd bool + // scrollLine, when scrollSet, is the line the next paint of a scrolling view centers. + scrollLine int + scrollSet bool + spans []Span + // wrap lays out a view that wraps and does not scroll, at the width the page gives it. + wrap wrapLayout + // canvas is the canvas of the last declaration, which measures the trails. + canvas *gfx.Canvas + // laid is what the rows were broken for. + laid layoutKey + + // trails are the Button trails the last paint drew; trailHeld says a press went down on + // the trail of line trailLine. + trails []trailHit + trailHeld bool + trailLine int + // hover is the link under the pointer, when hovering: its line and its first byte. + hover Point + hovering bool +} + +// trailHit is where a paint drew the Button trail of a line. +type trailHit struct { + line int + rect gfx.Rect +} + +// layoutKey is what a wrapped view's rows depend on. +type layoutKey struct { + revision uint64 + width, cellW float32 + first, count int + wrap bool +} + +// row is one row of a wrapped view: the bytes from to to of line. +type row struct { + line, from, to int +} + +// ScrollToEnd keeps a scrolling view at its newest line from the next paint on. +func (v *View) ScrollToEnd() { v.toEnd, v.scrollSet = true, false } + +// ScrollTo scrolls a scrolling view in its next paint so that line n is in the middle of +// it, and stops it following the newest line. +func (v *View) ScrollTo(n int) { v.scrollLine, v.scrollSet, v.toEnd = n, true, false } + +// MenuLine is the line a secondary press opened the menu on, and false when it was below +// the text. +func (v *View) MenuLine() (int, bool) { return v.menuLine, v.menuSet } + +// Has reports whether text is selected. +func (v *View) Has() bool { return v.spec.Source != nil && v.Selection.Has(v.spec.Source) } + +// Text is the selected text. +func (v *View) Text() string { + if v.spec.Source == nil { + return "" + } + return v.Selection.Text(v.spec.Source) +} + +// SelectAll selects all the text. +func (v *View) SelectAll() { + if v.spec.Source != nil { + v.Selection.SelectAll(v.spec.Source) + } +} + +// RowRect is where the last paint put line n's first row, and false when that row was +// not on screen. +func (v *View) RowRect(n int) (gfx.Rect, bool) { + index, ok := v.firstRowOf(n) + if !ok { + return gfx.Rect{}, false + } + r := gfx.Rect{X: v.rect.X, Y: v.rect.Y + v.spec.PadY + float32(index)*v.lineH, Width: v.rect.Width, Height: v.lineH} + if r.Y+r.Height <= v.clip.Y || r.Y >= v.clip.Y+v.clip.Height { + return gfx.Rect{}, false + } + return r, true +} + +// PointOf is a point in the first quarter of the cell the last paint put byte p.Byte of +// line p.Line in, where a click places the caret before that character and a double click +// picks the word it is in; false when its row was not on screen. +func (v *View) PointOf(p Point) (gfx.Point, bool) { + src := v.spec.Source + index, ok := v.firstRowOf(p.Line) + if !ok { + return gfx.Point{}, false + } + for index+1 < v.rowCount() && !v.lastRow(index) { + if _, _, to := v.rowBytes(index); p.Byte < to { + break + } + index++ + } + _, from, _ := v.rowBytes(index) + text := src.Line(p.Line) + at := min(max(p.Byte, from), len(text)) + x := v.rect.X + v.spec.PadX + (float32(cellsOf(text[from:at], 0))+0.25)*v.cellW + y := v.rect.Y + v.spec.PadY + (float32(index)+0.5)*v.lineH + if y < v.clip.Y || y >= v.clip.Y+v.clip.Height { + return gfx.Point{}, false + } + return gfx.Point{X: x, Y: y}, true +} + +// Visible is the range of lines the last paint showed, from the first to the one after +// the last. +func (v *View) Visible() (int, int) { + src := v.spec.Source + if src == nil || v.lineH <= 0 { + return 0, 0 + } + from, to := v.rowRange() + return v.rowLine(from), v.rowLine(max(to-1, from)) + 1 +} + +// Declare declares the view with spec and returns its outermost box: the scrolling area, +// or the text itself. +func (v *View) Declare(c ui.C, spec Spec) ui.Box { + v.spec = spec + if v.draw == nil { + v.draw = v.paint + v.input = ui.Handlers{Role: gfx.RoleGroup, Pointer: v.onPointer, Key: v.onKey} + } + canvas := c.Canvas() + v.canvas = canvas + v.cellW, v.cellH = canvas.MonoCellSize(spec.Font.Size, spec.Font.MonoFace) + v.lineH = max(spec.LineHeight, v.cellH) + v.layout(v.width) + height := float32(v.rowCount())*v.lineH + 2*spec.PadY + var control, outer ui.Box + if spec.Scroll { + outer = ui.Scroll(c).Scrollbars().Follow(spec.Follow).Label(spec.Label) + state := outer.ScrollState() + if v.toEnd { + v.toEnd = false + state.ScrollToEnd() + } + v.dragScroll(canvas, state) + if v.scrollSet { + v.scrollSet = false + if index, ok := v.firstRowOf(v.scrollLine); ok { + // The area knows the new height only once it lays it out; it is told now, so + // the offset is not clamped to the old one and the area stops following. + state.Content = max(state.Content, height) + target := spec.PadY + float32(index)*v.lineH - (state.Viewport-v.lineH)/2 + state.ScrollTo(min(max(target, 0), max(state.Content-state.Viewport, 0))) + } + } + height = max(height, state.Viewport) + outer.Children(func() { + v.id = ui.ID(c.Part("text")) + control = ui.Control(c.Part("text"), spec.Label, &v.input).FillWidth().Height(height).Draw(v.draw) + }) + } else if spec.Wrap { + // The rows depend on the width, which the page knows only once it lays the view + // out: the layout wraps the lines there, before it asks for the height. + v.wrap.v = v + outer = ui.CustomLayout(c, &v.wrap).FillWidth().Children(func() { + v.id = ui.ID(c.Part("text")) + control = ui.Control(c.Part("text"), spec.Label, &v.input).Draw(v.draw) + }) + } else { + v.id = ui.ID(c.Part("text")) + control = ui.Control(c.Part("text"), spec.Label, &v.input).FillWidth().Height(height).Draw(v.draw) + outer = control + } + if control.Shortcut(ui.Primary, "c") && v.Has() { + text, copy := v.Text(), spec.Copy + c.After(func() { + if copy != nil { + copy(text) + return + } + _ = app.SetClipboardText(text) + }) + } + if control.Shortcut(ui.Primary, "a") { + v.SelectAll() + } + if spec.Menu != nil { + ui.ContextMenuAt(c.Key("menu"), control, &v.menuOpen, v.menuAt, spec.Menu) + } + return outer +} + +// wrapLayout lays out a view that wraps: the text takes the width it is given and is as +// tall as its rows at that width. +type wrapLayout struct{ v *View } + +func (l *wrapLayout) MeasureWidth(*ui.LayoutContext) float32 { return 0 } + +func (l *wrapLayout) PlaceWidth(ctx *ui.LayoutContext, bounds ui.Rect) { + if v := l.v; bounds.Width != v.width { + v.width = bounds.Width + v.layout(v.width) + } + if ctx.Count() > 0 { + ctx.SetX(0, bounds.X) + ctx.SetWidth(0, bounds.Width) + } +} + +func (l *wrapLayout) MeasureHeight(*ui.LayoutContext) float32 { + v := l.v + return float32(v.rowCount())*v.lineH + 2*v.spec.PadY +} + +func (l *wrapLayout) PlaceHeight(ctx *ui.LayoutContext, bounds ui.Rect) { + if ctx.Count() > 0 { + ctx.SetY(0, bounds.Y) + ctx.SetHeight(0, bounds.Height) + } +} + +// dragScroll scrolls the area while a drag holds the pointer past its top or bottom edge, +// a step of rows every 50 ms that grows with the distance, as IDEA's editor does. +func (v *View) dragScroll(canvas *gfx.Canvas, state *ui.ScrollState) { + if !v.pressed || !v.moved || v.lineH <= 0 { + return + } + top, bottom := v.clip.Y, v.clip.Y+v.clip.Height + distance := float32(0) + switch { + case v.pointer.Y < top: + distance = v.pointer.Y - top + case v.pointer.Y > bottom: + distance = v.pointer.Y - bottom + default: + return + } + now := canvas.Now() + if now-v.stepAt >= dragStep { + v.stepAt = now + lines := min(1+float32(math.Abs(float64(distance)))/v.lineH, 8) + if distance < 0 { + lines = -lines + } + state.ScrollTo(min(max(state.Offset+float32(int(lines))*v.lineH, 0), state.Max())) + } + canvas.RequestFrameIn(dragStep) +} + +const dragStep = 50 * time.Millisecond + +// onPointer selects with the primary button, opens a link a click lands on and opens +// the menu at a secondary press. +func (v *View) onPointer(event gfx.PointerEvent) gfx.EventResult { + src := v.spec.Source + if src == nil { + return gfx.EventResult{} + } + at := gfx.Point{X: event.X, Y: event.Y} + switch event.Kind { + case gfx.PointerDown: + if event.Button == gfx.PointerButtonSecondary { + if v.spec.Menu == nil { + return gfx.EventResult{} + } + v.menuLine, v.menuSet = 0, false + if p, ok := v.pointAt(at, false); ok { + v.menuLine, v.menuSet = p.Line, true + } + v.menuOpen, v.menuAt = true, at + return gfx.EventResult{Handled: true, Repaint: true} + } + if event.Button != gfx.PointerButtonPrimary { + return gfx.EventResult{} + } + if n, ok := v.trailAt(at); ok { + // A press on a button after a line presses it, and leaves the selection be. + v.trailHeld, v.trailLine = true, n + return gfx.EventResult{Handled: true} + } + v.pressed, v.moved, v.press, v.pointer, v.clicks = true, false, at, at, max(event.ClickCount, 1) + p, ok := v.pointAt(at, v.clicks == 1) + if !ok { + v.Selection.Clear() + return gfx.EventResult{Handled: true, Repaint: true} + } + if event.Modifiers&gfx.ModifierShift != 0 && v.clicks == 1 { + v.Selection.Extend(p, src.Line(p.Line)) + v.moved = true + } else { + v.Selection.Begin(p, src.Line(p.Line), v.clicks) + } + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.PointerMove: + if !v.pressed { + return gfx.EventResult{Handled: v.trailHeld, Repaint: v.hoverAt(at)} + } + v.pointer = at + if !v.moved && math.Abs(float64(at.X-v.press.X)) < 3 && math.Abs(float64(at.Y-v.press.Y)) < 3 { + return gfx.EventResult{Handled: true} + } + v.moved = true + v.extendTo(at) + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.PointerUp: + if v.trailHeld { + v.trailHeld = false + if n, ok := v.trailAt(at); ok && n == v.trailLine && v.spec.PressTrail != nil { + v.spec.PressTrail(n) + } + return gfx.EventResult{Handled: true, Repaint: true} + } + if !v.pressed { + return gfx.EventResult{} + } + v.pressed = false + if !v.moved && v.clicks == 1 && v.spec.Open != nil { + if n, span, ok := v.linkAt(at); ok { + v.spec.Open(n, span) + } + } + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.PointerExit: + if v.hovering { + v.hovering = false + return gfx.EventResult{Repaint: true} + } + return gfx.EventResult{} + } + return gfx.EventResult{} +} + +// trailAt is the line whose Button trail the last paint drew under a point. +func (v *View) trailAt(at gfx.Point) (int, bool) { + for _, t := range v.trails { + if r := t.rect; at.X >= r.X && at.X < r.X+r.Width && at.Y >= r.Y && at.Y < r.Y+r.Height { + return t.line, true + } + } + return 0, false +} + +// hoverAt follows the link under the pointer, for a link with a Hover color, and reports +// whether it changed. +func (v *View) hoverAt(at gfx.Point) bool { + n, span, ok := v.linkAt(at) + ok = ok && span.Hover.Alpha > 0 + p := Point{n, span.From} + if ok == v.hovering && (!ok || p == v.hover) { + return false + } + v.hover, v.hovering = p, ok + return true +} + +// extendTo moves the selection's focus to the point under the pointer, clamped into the +// text. +func (v *View) extendTo(at gfx.Point) { + src := v.spec.Source + if src.Count() == 0 { + return + } + if p, ok := v.pointAt(at, v.Selection.unit == unitChar); ok { + v.Selection.Extend(p, src.Line(p.Line)) + } +} + +// onKey clears the selection with Escape. +func (v *View) onKey(event gfx.KeyEvent) gfx.EventResult { + if event.Release || event.Key != gfx.KeyEscape || v.spec.Source == nil || !v.Has() { + return gfx.EventResult{} + } + v.Selection.Clear() + return gfx.EventResult{Handled: true, Repaint: true} +} + +// linkAt is the link span under a point. +func (v *View) linkAt(at gfx.Point) (int, Span, bool) { + p, ok := v.pointAt(at, false) + if !ok || v.spec.Spans == nil { + return 0, Span{}, false + } + text := v.spec.Source.Line(p.Line) + if p.Byte >= len(text) { + return 0, Span{}, false + } + v.spans = v.spec.Spans(p.Line, text, v.spans[:0]) + for _, span := range v.spans { + if span.Link && span.From <= p.Byte && p.Byte < span.To { + return p.Line, span, true + } + } + return 0, Span{}, false +} + +// pointAt is the place in the text under a point of the window, clamped into the text: +// a point above it is its start and one below its end. nearest picks the closest +// character boundary rather than the character under the point. ok is false for a view +// with no text. +func (v *View) pointAt(at gfx.Point, nearest bool) (Point, bool) { + src := v.spec.Source + count := v.rowCount() + if src == nil || src.Count() == 0 || count == 0 || v.lineH <= 0 || v.cellW <= 0 { + return Point{}, false + } + index := int(math.Floor(float64((at.Y - v.rect.Y - v.spec.PadY) / v.lineH))) + if index < 0 { + return Point{src.First(), 0}, true + } + if index >= count { + last := src.First() + src.Count() - 1 + return Point{last, len(src.Line(last))}, true + } + line, from, to := v.rowBytes(index) + text := src.Line(line) + column := (at.X - v.rect.X - v.spec.PadX) / v.cellW + return Point{line, from + byteAt(text[from:to], column, nearest)}, true +} diff --git a/desktop/internal/workbench/console_selection_test.go b/desktop/internal/workbench/console_selection_test.go new file mode 100644 index 0000000000..7813fff413 --- /dev/null +++ b/desktop/internal/workbench/console_selection_test.go @@ -0,0 +1,229 @@ +package workbench + +import ( + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/textview" + "github.com/vivaui/viva/gfx" +) + +// showRunConsole shows a run whose console holds text, in the Run window. +func showRunConsole(t *testing.T, text string) (*harness, *runEntry) { + t.Helper() + h := newHarnessWithLanguages(t, &testKernel{Client: core.NewClient()}, []string{"en-US"}) + h.open(t.TempDir()) + p := h.app.project + run := &runEntry{id: "run-1", label: "Serve", output: newOutputBuffer(runOutputMaxLines, runOutputBytes)} + chunk, err := newOutputDecoder(h.app.kernel).decode(text) + if err != nil { + t.Fatal(err) + } + run.output.apply(chunk) + p.build.runs = append(p.build.runs, run) + p.build.view = run.id + if !h.app.chrome.isOpen(catalogIndex[itemRun]) { + h.app.reduceChrome(core.SetChromeOpen(itemRun, true)) + } + h.settle() + return h, run +} + +// consolePoint is where the console of run drew byte at of its line n, counting from its +// first line. +func consolePoint(t *testing.T, run *runEntry, n, at int) gfx.Point { + t.Helper() + point, ok := run.console.PointOf(textview.Point{Line: run.output.start + n, Byte: at}) + if !ok { + t.Fatalf("line %d is not on screen", n) + } + return point +} + +// copyShortcut presses Primary+C and returns what the clipboard holds after it. +func (h *harness) copyShortcut() string { + h.t.Helper() + h.driver.SetClipboard("") + if _, err := h.driver.ShortcutChord(primaryModifier(), 'c'); err != nil { + h.t.Fatal(err) + } + h.settle() + return h.driver.Clipboard() +} + +const stackTrace = "Exception in thread \"main\" java.lang.IllegalStateException: boom\n" + + "\tat demo.Main.run(Main.java:12)\n" + + "\tat demo.Main.main(Main.java:5)\n" + +// A drag across the lines of the Run console selects them, and Primary+C copies them, so a +// stack trace pastes as it was printed (#2073). +func TestRunConsoleDragSelectsAcrossLinesAndCopies(t *testing.T) { + h, run := showRunConsole(t, stackTrace) + from := consolePoint(t, run, 0, len("Exception in thread \"main\" ")) + to := consolePoint(t, run, 2, len("\tat demo.Main.main")) + h.drag(from, to) + h.settle() + want := "java.lang.IllegalStateException: boom\n\tat demo.Main.run(Main.java:12)\n\tat demo.Main.main" + if got := run.console.Text(); got != want { + t.Fatalf("the drag selected %q, want %q", got, want) + } + if got := h.copyShortcut(); got != want { + t.Fatalf("Primary+C copied %q, want %q", got, want) + } + // Escape drops the selection, as in the editor. + if err := h.driver.Key(gfx.KeyEscape, 0); err != nil { + t.Fatal(err) + } + h.settle() + if run.console.Has() { + t.Fatalf("Escape left %q selected", run.console.Text()) + } +} + +// A double click selects the word under it, a triple click the whole line with its newline, +// as IntelliJ IDEA's console does. +func TestRunConsoleDoubleClickSelectsAWordAndTripleClickALine(t *testing.T) { + h, run := showRunConsole(t, stackTrace) + at := consolePoint(t, run, 0, len("Exception in thread \"main\" java.lang.Ill")) + if err := h.driver.DoubleClick(at.X, at.Y); err != nil { + t.Fatal(err) + } + h.settle() + if got := run.console.Text(); got != "IllegalStateException" { + t.Fatalf("the double click selected %q, want the word", got) + } + at = consolePoint(t, run, 1, 4) + if err := h.driver.ClickCount(at.X, at.Y, 3); err != nil { + t.Fatal(err) + } + h.settle() + if got, want := h.copyShortcut(), "\tat demo.Main.run(Main.java:12)\n"; got != want { + t.Fatalf("the triple click copied %q, want the line %q", got, want) + } +} + +// Shift with a click extends the selection from where the last click put it, and Primary+A +// selects the whole console. +func TestRunConsoleShiftClickExtendsAndSelectAllTakesEverything(t *testing.T) { + h, run := showRunConsole(t, "first line\nsecond line\nthird line\n") + start := consolePoint(t, run, 0, len("first ")) + h.click(start) + if run.console.Has() { + t.Fatalf("a single click selected %q", run.console.Text()) + } + end := consolePoint(t, run, 1, len("second")) + if err := h.driver.KeyDown(gfx.KeyShiftLeft, ""); err != nil { + t.Fatal(err) + } + h.click(end) + if err := h.driver.KeyUp(gfx.KeyShiftLeft, ""); err != nil { + t.Fatal(err) + } + if got, want := h.copyShortcut(), "line\nsecond"; got != want { + t.Fatalf("Shift-click copied %q, want %q", got, want) + } + if _, err := h.driver.ShortcutChord(primaryModifier(), 'a'); err != nil { + t.Fatal(err) + } + h.settle() + if got, want := h.copyShortcut(), "first line\nsecond line\nthird line"; got != want { + t.Fatalf("Primary+A then Primary+C copied %q, want %q", got, want) + } +} + +// The console menu's Copy takes the selection when there is one, and its Select All selects +// every line. +func TestRunConsoleMenuCopiesTheSelectionAndSelectsAll(t *testing.T) { + h, run := showRunConsole(t, "first line\nsecond line\n") + h.drag(consolePoint(t, run, 0, len("first ")), consolePoint(t, run, 1, len("second"))) + h.settle() + line, ok := run.console.RowRect(run.output.start + 1) + if !ok { + t.Fatal("the second line is not on screen") + } + h.driver.SetClipboard("") + h.rightClickAt(line) + h.click(center(h.popupHit(h.shared("menu.copy")))) + if got, want := h.driver.Clipboard(), "line\nsecond"; got != want { + t.Fatalf("Copy put %q on the clipboard, want the selection %q", got, want) + } + h.rightClickAt(line) + h.click(center(h.popupHit(h.shared("menu.selectAll")))) + if got, want := run.console.Text(), "first line\nsecond line"; got != want { + t.Fatalf("Select All selected %q, want %q", got, want) + } +} + +// showFetchInConsole opens a repository's Git console and puts a fetch in it, with Core's +// presentation of it: a header, a line and a closed fold of progress lines. +func showFetchInConsole(t *testing.T) (*harness, *consoleView) { + t.Helper() + h := newHarness(t, gitKernel{core.NewClient()}) + h.openConsole(t, newTestRepository(t)) + v := &h.app.consoleView + record, presented := consoleFetch() + presented.search, presented.display = v.searchFor, v.display + v.snapshot.Records = []core.GitConsoleRecord{record} + v.presented[record.ID] = presented + v.dirty = true + h.app.invalidator.Invalidate() + h.settle() + if len(v.rows) != 3 || v.rows[1].text != "From origin" { + t.Fatalf("the console's rows are %+v, want the fetch's header, line and fold", v.rows) + } + return h, v +} + +// gitConsolePoint is where the Git console drew byte at of its row n. +func gitConsolePoint(t *testing.T, v *consoleView, n, at int) gfx.Point { + t.Helper() + point, ok := v.text.PointOf(textview.Point{Line: n, Byte: at}) + if !ok { + t.Fatalf("row %d is not on screen", n) + } + return point +} + +// The Git console is read-only text as the Run console is: a drag across its rows selects +// them and Primary+C copies them, the menu's Copy takes the row right-clicked when nothing is +// selected and its Select All every row, without the toggles after them, and a fold's toggle +// still opens it (#2082). +func TestGitConsoleSelectsAndCopiesItsRows(t *testing.T) { + h, v := showFetchInConsole(t) + toggle := h.app.text.Console.ExpandLines(3) + + h.drag(gitConsolePoint(t, v, 1, len("From ")), gitConsolePoint(t, v, 2, len("Receiving"))) + h.settle() + if got, want := h.copyShortcut(), "origin\nReceiving"; got != want { + t.Fatalf("the drag then Primary+C copied %q, want %q", got, want) + } + if err := h.driver.Key(gfx.KeyEscape, 0); err != nil { + t.Fatal(err) + } + h.settle() + if v.text.Has() { + t.Fatalf("Escape left %q selected", v.text.Text()) + } + + line, ok := v.text.RowRect(1) + if !ok { + t.Fatal("the line row is not on screen") + } + h.driver.SetClipboard("") + h.rightClickAt(line) + h.click(center(h.popupHit(h.shared("menu.copy")))) + if got := h.driver.Clipboard(); got != "From origin" { + t.Fatalf("Copy with nothing selected put %q on the clipboard, want the row", got) + } + h.rightClickAt(line) + h.click(center(h.popupHit(h.shared("menu.selectAll")))) + if got, want := v.text.Text(), v.rows[0].text+"\nFrom origin\nReceiving 100%"; got != want { + t.Fatalf("Select All selected %q, want %q", got, want) + } + + h.clickNamed(toggle) + h.settle() + if !consoleHasRow(v, "Receiving 10%") { + t.Fatalf("the fold's toggle %q left the rows %+v", toggle, v.rows) + } +} diff --git a/desktop/internal/workbench/context_menu_test.go b/desktop/internal/workbench/context_menu_test.go index a130da2c8d..3dc50247a9 100644 --- a/desktop/internal/workbench/context_menu_test.go +++ b/desktop/internal/workbench/context_menu_test.go @@ -96,7 +96,10 @@ func TestRunConsoleMenuCopiesTheChosenLineAndTheWholeOutput(t *testing.T) { } h.settle() - line := h.topHit(run.list.RowID(1)) + line, ok := run.console.RowRect(run.output.start + 1) + if !ok { + t.Fatal("the second line is not on screen") + } h.rightClickAt(line) h.click(center(h.popupHit(h.shared("menu.copy")))) if got := h.driver.Clipboard(); got != "second line" { diff --git a/desktop/internal/workbench/gitconsole.go b/desktop/internal/workbench/gitconsole.go index c50ce76785..0b062a9cd8 100644 --- a/desktop/internal/workbench/gitconsole.go +++ b/desktop/internal/workbench/gitconsole.go @@ -11,6 +11,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/textview" "github.com/vivaui/viva/app" vivatext "github.com/vivaui/viva/text" "github.com/vivaui/viva/ui" @@ -69,9 +70,9 @@ const ( consolePartError ) -// consoleRowID names a row by what it shows, so that the row keeps its list key while rows -// are added above it or a fold around it opens: a line row is named by its record and line -// index, and a closed fold by the line it shows. +// consoleRowID names a row by what it shows, so that a selection keeps to its rows while rows +// are added around them: a line row is named by its record and line index, and a closed fold +// by the line it shows. type consoleRowID struct { // record is the record's ID, empty for a console-wide note. record string @@ -112,11 +113,9 @@ type consoleSpan struct { kind consoleSpanKind } -// consoleRow is one row of the console's list. +// consoleRow is one row of the console's text. type consoleRow struct { id consoleRowID - // key is the row's list key, unique among the rows and kept for the same id. - key int // record is the index of the row's record in the snapshot, or -1 for a console-wide // note, which has no context menu. record int @@ -208,29 +207,16 @@ type consoleView struct { open map[consoleFold]bool // wrap says long lines break into several instead of ending in an ellipsis. wrap bool - list ui.ListState - // drawRow is drawConsoleRow, made once because a method value made in each paint - // allocates. - drawRow func(ui.ListRow) - rows []consoleRow + // text shows the rows, read-only, and holds the selection; revision changes with each + // flattening, so the text breaks its rows again only when they changed. + text textview.View + revision uint64 + rows []consoleRow + // kept is the selected rows before a flattening, which keepSelection finds again. + kept []consoleRow // spans holds the spans of all the rows, which slice it; it is reused by each // flattening. spans []consoleSpan - // width is the width of the list as it was last drawn, which the rows are broken or cut - // to, or 0 before it was; measure, made once, records it and asks for a paint when it - // changed. pieces is the layout of the row being declared, reused from row to row. - width float32 - measure func(*ui.DrawContext) - pieces []consolePiece - // font is the run output's font the rows are drawn in, taken as the list is declared, - // with the width of its character cell and the height of a line in it. - font scopeFont - cellW, lineH float32 - // keys are the list keys of the rows by id; spareKeys is the map of the flattening - // before, reused so that flattening allocates no map once warm. nextKey is the key a - // new row gets. - keys, spareKeys map[consoleRowID]int - nextKey int // dirty says the rows must be flattened again before they are drawn. dirty bool // hits are the search hits placed on the rows, in the order Core reported them; total @@ -245,8 +231,6 @@ type consoleView struct { hasCurrent bool hitIndex int hitRow int - // detach says the list was just scrolled to a hit and must stop following its end. - detach bool } // gitConsoleChanged is the journal's change callback. Core calls it on any goroutine, so it @@ -374,46 +358,21 @@ func consoleSearchText(text string) string { return text[:end] } -// rowKey is the list key of row i. The list may ask for a row the rows no longer have while -// it settles, which gets zero, an identity reserved for a missing row. -func (v *consoleView) rowKey(i int) int { - if i < 0 || i >= len(v.rows) { - return 0 - } - return v.rows[i].key -} - -// rowLabel is the text of row i, which assistive technology reads and typing finds. -func (v *consoleView) rowLabel(i int) string { - if i < 0 || i >= len(v.rows) { - return "" - } - return v.rows[i].text -} - -// add appends row with the key its id had in old, the keys of the flattening before, or a new -// one, and returns its index. -func (v *consoleView) add(old map[consoleRowID]int, row consoleRow) int { - key, ok := old[row.id] - if _, taken := v.keys[row.id]; !ok || taken { - key = v.nextKey + 1 // Zero belongs to a missing row while the list settles. - v.nextKey++ - } - row.key = key - v.keys[row.id] = key +// add appends row and returns its index. +func (v *consoleView) add(row consoleRow) int { v.rows = append(v.rows, row) return len(v.rows) - 1 } // addLines appends a row for each of the lines [from, to) of r, the record at index. The // lines of a query are drawn subtle, as its header is. -func (v *consoleView) addLines(old map[consoleRowID]int, index int, r *core.GitConsoleRecord, from, to int) { +func (v *consoleView) addLines(index int, r *core.GitConsoleRecord, from, to int) { tone := consoleToneText if r.Query { tone = consoleToneSubtle } for j := from; j < to; j++ { - v.add(old, consoleRow{id: consoleRowID{record: r.ID, part: consolePartLine, index: j}, record: index, text: consoleExpandTabs(r.Lines[j].Text), tone: tone, first: j, last: j}) + v.add(consoleRow{id: consoleRowID{record: r.ID, part: consolePartLine, index: j}, record: index, text: consoleExpandTabs(r.Lines[j].Text), tone: tone, first: j, last: j}) } } @@ -421,18 +380,18 @@ func (v *consoleView) addLines(old map[consoleRowID]int, index int, r *core.GitC // the record at index: while closed, one row that says how many lines it holds, named by its // first line so that it keeps its key as it opens; while open, its lines, the last with the // toggle that closes it. -func (v *consoleView) addQueryFold(old map[consoleRowID]int, index int, r *core.GitConsoleRecord, fragment core.GitConsoleOutputFragment, start, end int, text *i18n.ConsoleMessages) { +func (v *consoleView) addQueryFold(index int, r *core.GitConsoleRecord, fragment core.GitConsoleOutputFragment, start, end int, text *i18n.ConsoleMessages) { fold := consoleFold{record: r.ID, fragment: fragment.ID} if v.open[fold] { - v.addLines(old, index, r, start, end-1) - v.add(old, consoleRow{id: consoleRowID{record: r.ID, part: consolePartLine, index: end - 1}, record: index, text: consoleExpandTabs(r.Lines[end-1].Text), tone: consoleToneSubtle, fold: fold, toggle: text.Collapse, first: end - 1, last: end - 1}) + v.addLines(index, r, start, end-1) + v.add(consoleRow{id: consoleRowID{record: r.ID, part: consolePartLine, index: end - 1}, record: index, text: consoleExpandTabs(r.Lines[end-1].Text), tone: consoleToneSubtle, fold: fold, toggle: text.Collapse, first: end - 1, last: end - 1}) return } count := fragment.Count if count <= 0 { count = end - start } - v.add(old, consoleRow{id: consoleRowID{record: r.ID, part: consolePartLine, index: start}, record: index, text: text.QueryOutput(count), tone: consoleToneSubtle, fold: fold, toggle: text.Expand, folded: true, summary: true, first: start, last: end - 1}) + v.add(consoleRow{id: consoleRowID{record: r.ID, part: consolePartLine, index: start}, record: index, text: text.QueryOutput(count), tone: consoleToneSubtle, fold: fold, toggle: text.Expand, folded: true, summary: true, first: start, last: end - 1}) } // endSpan ends the span of kind that runs to end in the spans of the row whose spans start at @@ -495,25 +454,25 @@ func consoleExpandTabs(line string) string { return b.String() } -// flatten turns the snapshot into the rows of the list and places the search hits on them. +// flatten turns the snapshot into the rows of the text and places the search hits on them. // text is the language's words and loc the zone the start times are shown in. func (v *consoleView) flatten(text *i18n.ConsoleMessages, loc *time.Location) { v.dirty = false - old := v.keys - v.keys = v.spareKeys - if v.keys == nil { - v.keys = map[consoleRowID]int{} + v.revision++ + selFrom, selTo, selected := v.text.Selection.Lines() + v.kept = v.kept[:0] + if selected && selFrom < len(v.rows) { + v.kept = append(v.kept, v.rows[max(selFrom, 0):min(selTo+1, len(v.rows))]...) } - clear(v.keys) v.rows, v.spans, v.hits, v.total, v.counted = v.rows[:0], v.spans[:0], v.hits[:0], 0, true if v.snapshot.Omitted { - v.add(old, consoleRow{id: consoleRowID{part: consolePartOmitted}, record: -1, text: text.HistoryTruncated, tone: consoleToneSubtle}) + v.add(consoleRow{id: consoleRowID{part: consolePartOmitted}, record: -1, text: text.HistoryTruncated, tone: consoleToneSubtle}) } if v.failed { - v.add(old, consoleRow{id: consoleRowID{part: consolePartUnavailable}, record: -1, text: text.Unavailable, tone: consoleToneSubtle}) + v.add(consoleRow{id: consoleRowID{part: consolePartUnavailable}, record: -1, text: text.Unavailable, tone: consoleToneSubtle}) } for i := range v.snapshot.Records { - v.flattenRecord(old, i, &v.snapshot.Records[i], text, loc) + v.flattenRecord(i, &v.snapshot.Records[i], text, loc) } v.hitIndex, v.hitRow = -1, -1 if v.hasCurrent { @@ -524,13 +483,43 @@ func (v *consoleView) flatten(text *i18n.ConsoleMessages, loc *time.Location) { } } } - v.spareKeys = old + if selected { + v.keepSelection(selFrom) + } +} + +// keepSelection moves the selection, which began on row from before the rows were flattened +// again, to where the rows it covered, v.kept, are now: rows added after them or before them, +// as a fold opening above, leave it on the same text. It drops the selection when those rows +// are gone or changed. +func (v *consoleView) keepSelection(from int) { + kept := v.kept + at := -1 + if len(kept) > 0 { + for i := range v.rows { + if v.rows[i].id == kept[0].id && v.rows[i].text == kept[0].text { + at = i + break + } + } + } + if at < 0 || at+len(kept) > len(v.rows) { + v.text.Selection.Clear() + return + } + for i := range kept { + if r := &v.rows[at+i]; r.id != kept[i].id || r.text != kept[i].text { + v.text.Selection.Clear() + return + } + } + v.text.Selection.Move(at - from) } // flattenRecord appends the rows of r, the record at index: its header, its output, its // status and its error. It uses Core's presentation while that still describes the lines r // has, even one made before more lines came, and draws the rest from the lines themselves. -func (v *consoleView) flattenRecord(old map[consoleRowID]int, index int, r *core.GitConsoleRecord, text *i18n.ConsoleMessages, loc *time.Location) { +func (v *consoleView) flattenRecord(index int, r *core.GitConsoleRecord, text *i18n.ConsoleMessages, loc *time.Location) { p := v.presented[r.ID] // A presentation made before lines were dropped from the front no longer indexes them. use := p != nil && !p.raw && !v.failed && (p.revision == r.Revision || !r.Truncated && p.lines <= len(r.Lines)) @@ -628,10 +617,10 @@ func (v *consoleView) flattenRecord(old map[consoleRowID]int, index int, r *core case quiet: header.tone = consoleToneSubtle } - headerRow := v.add(old, header) + headerRow := v.add(header) if r.Truncated { - v.add(old, consoleRow{id: consoleRowID{record: r.ID, part: consolePartTruncated}, record: index, text: text.Truncated, tone: consoleToneSubtle}) + v.add(consoleRow{id: consoleRowID{record: r.ID, part: consolePartTruncated}, record: index, text: text.Truncated, tone: consoleToneSubtle}) } lo, next := len(v.rows), 0 if use { @@ -640,22 +629,22 @@ func (v *consoleView) flattenRecord(old map[consoleRowID]int, index int, r *core if start >= end { continue } - v.addLines(old, index, r, next, start) + v.addLines(index, r, next, start) next = end // Core folds a successful query's output longer than ten lines whole, and shorter // output too when the display choices ask for it; it never folds a deletion's. if fragment.Kind == consoleFragmentQuery { - v.addQueryFold(old, index, r, fragment, start, end, text) + v.addQueryFold(index, r, fragment, start, end, text) continue } if fragment.Kind != consoleFragmentProgress || end-start <= 1 { - v.addLines(old, index, r, start, end) + v.addLines(index, r, start, end) continue } fold := consoleFold{record: r.ID, fragment: fragment.ID} last := consoleRow{id: consoleRowID{record: r.ID, part: consolePartLine, index: end - 1}, record: index, text: consoleExpandTabs(r.Lines[end-1].Text), fold: fold, first: end - 1, last: end - 1} if v.open[fold] { - v.addLines(old, index, r, start, end-1) + v.addLines(index, r, start, end-1) last.toggle = text.Collapse } else { count := fragment.Count @@ -664,33 +653,33 @@ func (v *consoleView) flattenRecord(old map[consoleRowID]int, index int, r *core } last.toggle, last.folded, last.first = text.ExpandLines(count), true, start } - v.add(old, last) + v.add(last) } } - v.addLines(old, index, r, next, len(r.Lines)) + v.addLines(index, r, next, len(r.Lines)) hi := len(v.rows) progressRow := -1 if r.State == core.GitConsoleRunning && r.Progress != "" { - progressRow = v.add(old, consoleRow{id: consoleRowID{record: r.ID, part: consolePartProgress}, record: index, text: r.Progress, tone: consoleToneSubtle}) + progressRow = v.add(consoleRow{id: consoleRowID{record: r.ID, part: consolePartProgress}, record: index, text: r.Progress, tone: consoleToneSubtle}) } // A notice the display choices no longer show is left out before Core presents the // record again. if exact && p.display == v.display { if notice := consoleNoticeText(text, p.entry.Notice); notice != "" { - v.add(old, consoleRow{id: consoleRowID{record: r.ID, part: consolePartNotice}, record: index, text: notice, tone: consoleToneSubtle}) + v.add(consoleRow{id: consoleRowID{record: r.ID, part: consolePartNotice}, record: index, text: notice, tone: consoleToneSubtle}) } } if r.State == core.GitConsoleUnconfirmed { - v.add(old, consoleRow{id: consoleRowID{record: r.ID, part: consolePartUnconfirmed}, record: index, text: text.Unconfirmed, tone: consoleToneError}) + v.add(consoleRow{id: consoleRowID{record: r.ID, part: consolePartUnconfirmed}, record: index, text: text.Unconfirmed, tone: consoleToneError}) } if consoleUnexpectedExit(r) { - v.add(old, consoleRow{id: consoleRowID{record: r.ID, part: consolePartExit}, record: index, text: text.ExitCode(r.ExitCode), tone: consoleToneError}) + v.add(consoleRow{id: consoleRowID{record: r.ID, part: consolePartExit}, record: index, text: text.ExitCode(r.ExitCode), tone: consoleToneError}) } errorRow := -1 if r.Error != "" { for j, line := range strings.Split(strings.TrimRight(r.Error, "\n"), "\n") { - at := v.add(old, consoleRow{id: consoleRowID{record: r.ID, part: consolePartError, index: j}, record: index, text: line, tone: consoleToneError}) + at := v.add(consoleRow{id: consoleRowID{record: r.ID, part: consolePartError, index: j}, record: index, text: line, tone: consoleToneError}) if j == 0 { errorRow = at } @@ -800,8 +789,7 @@ func (v *consoleView) step(delta int, text *i18n.ConsoleMessages, loc *time.Loca v.flatten(text, loc) } if v.hitRow >= 0 { - v.list.ScrollTo(v.hitRow, ui.ListCenter) - v.detach = true + v.text.ScrollTo(v.hitRow) } } @@ -846,8 +834,7 @@ func (a *App) toggleConsoleWrap() { // consoleScrollToEnd scrolls the list to its end, where it follows new rows again. func (a *App) consoleScrollToEnd() { a.performed("git.console.scrollToEnd", surfaceButton) - a.consoleView.list.ScrollToEnd() - a.consoleView.detach = false + a.consoleView.text.ScrollToEnd() } // showGitConsole shows the Console tab of the Git tool window, scrolled to its end, when the @@ -860,8 +847,7 @@ func (a *App) consoleScrollToEnd() { // does not take its place, and only its tab changes. func (a *App) showGitConsole(from string) { a.layout.gitTab = gitTabConsole - a.consoleView.list.ScrollToEnd() - a.consoleView.detach = false + a.consoleView.text.ScrollToEnd() git := catalogIndex[itemGit] if a.chrome.isOpen(git) { return diff --git a/desktop/internal/workbench/gitconsole_test.go b/desktop/internal/workbench/gitconsole_test.go index 247496afa9..53f6f371df 100644 --- a/desktop/internal/workbench/gitconsole_test.go +++ b/desktop/internal/workbench/gitconsole_test.go @@ -10,6 +10,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/textview" ) // openConsole opens dir, runs a Git command the console records, and shows the Console tab @@ -204,7 +205,7 @@ func consoleHasRow(v *consoleView, text string) bool { return false } -func TestConsoleFlattenFoldsAndKeepsKeys(t *testing.T) { +func TestConsoleFlattenFoldsAndKeepsRowIDs(t *testing.T) { text := &i18n.For(i18n.English).Console record, presented := consoleFetch() v := consoleViewOf([]core.GitConsoleRecord{record}, map[string]*consolePresented{record.ID: presented}) @@ -239,8 +240,8 @@ func TestConsoleFlattenFoldsAndKeepsKeys(t *testing.T) { if last.text != "Receiving 100%" || last.toggle != text.Collapse || last.folded { t.Fatalf("the open fold's last line is %+v", last) } - if opened.key != header.key || last.key != fold.key { - t.Fatalf("the keys changed: header %d to %d, fold %d to %d", header.key, opened.key, fold.key, last.key) + if opened.id != header.id || last.id != fold.id { + t.Fatalf("the ids changed: header %+v to %+v, fold %+v to %+v", header.id, opened.id, fold.id, last.id) } } @@ -304,8 +305,8 @@ func TestConsoleStepOpensTheFoldOfAHit(t *testing.T) { if !v.open[consoleFold{record: record.ID, fragment: "output-1"}] { t.Fatalf("stepping to the hit left its fold closed: %+v", v.open) } - if v.hitIndex != 0 || v.hitRow != 2 || v.rows[v.hitRow].text != "Receiving 10%" || !v.detach { - t.Fatalf("the current hit is %d on row %d (detach %v), want the first on the line it matched", v.hitIndex, v.hitRow, v.detach) + if v.hitIndex != 0 || v.hitRow != 2 || v.rows[v.hitRow].text != "Receiving 10%" { + t.Fatalf("the current hit is %d on row %d, want the first on the line it matched", v.hitIndex, v.hitRow) } } @@ -424,45 +425,6 @@ func TestConsoleHeaderIsSpannedForItsColorsAndItsInlineFold(t *testing.T) { } } -// consolePieceTexts is pieces as "line:kind:text". -func consolePieceTexts(pieces []consolePiece) []string { - out := make([]string, 0, len(pieces)) - for _, p := range pieces { - out = append(out, fmt.Sprintf("%d:%d:%s", p.line, p.kind, p.text)) - } - return out -} - -func TestLayoutConsoleRowBreaksAndCutsByCells(t *testing.T) { - spans := []consoleSpan{{end: 3, kind: consoleSpanStamp}, {end: 8, kind: consoleSpanText}} - cases := []struct { - name string - text string - spans []consoleSpan - cells int - wrap bool - want []string - }{ - {name: "unknown width", text: "abcdefgh", cells: 0, want: []string{"0:0:abcdefgh"}}, - {name: "fits", text: "abcd", cells: 4, want: []string{"0:0:abcd"}}, - {name: "cut", text: "abcdef", cells: 4, want: []string{"0:0:abc", "0:0:…"}}, - {name: "cut in the second span", text: "abcdefgh", spans: spans, cells: 6, want: []string{"0:1:abc", "0:0:de", "0:0:…"}}, - {name: "wrap across spans", text: "abcdefgh", spans: spans, cells: 5, wrap: true, want: []string{"0:1:abc", "0:0:de", "1:0:fgh"}}, - {name: "wide characters", text: "中文ab", cells: 3, wrap: true, want: []string{"0:0:中", "1:0:文a", "2:0:b"}}, - {name: "cut before a wide character", text: "a中文", cells: 4, want: []string{"0:0:a中", "0:0:…"}}, - {name: "wide character wider than the row", text: "中", cells: 1, wrap: true, want: []string{"0:0:中"}}, - {name: "empty", text: "", cells: 4, want: []string{}}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - got := consolePieceTexts(layoutConsoleRow(nil, tc.text, tc.spans, tc.cells, tc.wrap)) - if !slices.Equal(got, tc.want) { - t.Fatalf("layoutConsoleRow(%q, %d, wrap %v) = %q, want %q", tc.text, tc.cells, tc.wrap, got, tc.want) - } - }) - } -} - func TestConsoleExpandTabsToTheNextStop(t *testing.T) { cases := map[string]string{ "no tab": "no tab", @@ -543,8 +505,8 @@ func TestConsoleFoldsTheWholeOutputOfAQuery(t *testing.T) { if last.text != "d4" || last.toggle != text.Collapse || last.folded { t.Fatalf("the open fold's last line is %+v", last) } - if first.key != fold.key { - t.Fatalf("the fold's key changed from %d to %d as it opened", fold.key, first.key) + if first.id != fold.id { + t.Fatalf("the fold's id changed from %+v to %+v as it opened", fold.id, first.id) } } @@ -683,11 +645,45 @@ func TestConsoleDrawsTheProjectedCommandBeforeItIsPresented(t *testing.T) { } } -func TestConsoleRowKeysReserveValidMissingRowIdentity(t *testing.T) { - v := consoleView{keys: map[consoleRowID]int{}} - v.add(nil, consoleRow{}) - missing := v.rowKey(len(v.rows)) - if missing < 0 || uint64(missing) >= 1<<31 || missing == v.rowKey(0) { - t.Fatalf("missing row key %d is invalid or collides with the first row %d", missing, v.rowKey(0)) +// A selection keeps to its rows when the rows are flattened again: a fold opening above them +// moves it with them, and it goes when the rows it covered change. +func TestConsoleFlattenKeepsTheSelectionOnItsRows(t *testing.T) { + text := &i18n.For(i18n.English).Console + record, presented := consoleFetch() + v := consoleViewOf([]core.GitConsoleRecord{record}, map[string]*consolePresented{record.ID: presented}) + v.flatten(text, time.UTC) + // The line row and the closed progress fold after it. + src := consoleSource{v} + v.text.Selection.Begin(textview.Point{Line: 1, Byte: len("From ")}, src.Line(1), 1) + v.text.Selection.Extend(textview.Point{Line: 2, Byte: len("Receiving")}, src.Line(2)) + if got := v.text.Selection.Text(src); got != "origin\nReceiving" { + t.Fatalf("the selection is %q", got) + } + + // Opening the header's configuration changes the header, above the selection, only. + v.open = map[consoleFold]bool{v.rows[0].fold: true} + v.flatten(text, time.UTC) + if got := v.text.Selection.Text(src); got != "origin\nReceiving" { + t.Fatalf("after the header opened the selection is %q, want it on the same rows", got) + } + + // A record before this one moves the rows down; the selection goes with them. + before := core.GitConsoleRecord{ID: "r0", Revision: 1, Started: consoleStarted, Root: "/work/repo", Arguments: []string{"status"}, + Lines: []core.GitConsoleLine{{Stream: "stdout", Text: "clean"}}, State: core.GitConsoleCompleted, Exited: true} + v.snapshot.Records = []core.GitConsoleRecord{before, record} + v.flatten(text, time.UTC) + if got := v.text.Selection.Text(src); got != "origin\nReceiving" { + t.Fatalf("after a record came before the selection is %q, want it on the same rows", got) + } + + // Opening the progress fold changes a selected row, so the selection goes. + for _, r := range v.rows { + if r.toggle != "" && !r.inline { + v.open[r.fold] = true + } + } + v.flatten(text, time.UTC) + if v.text.Selection.Has(src) { + t.Fatalf("the selection %q stayed on rows that changed", v.text.Selection.Text(src)) } } diff --git a/desktop/internal/workbench/gitconsole_view.go b/desktop/internal/workbench/gitconsole_view.go index d2a5b16f29..a0d9979572 100644 --- a/desktop/internal/workbench/gitconsole_view.go +++ b/desktop/internal/workbench/gitconsole_view.go @@ -1,48 +1,38 @@ package workbench import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/1lck/Lithe-IDEA/desktop/internal/textview" "github.com/vivaui/viva/gfx" - vivatext "github.com/vivaui/viva/text" "github.com/vivaui/viva/ui" ) -// The Console tab is one Page: the toolbar with the search over the list of rows that -// gitconsole.go flattens. The rows are drawn in the run output's font (fonts.go), so the -// console reads like the run output beside it and, with the default fonts, like the editor. +// The Console tab is one Page: the toolbar with the search over the rows that gitconsole.go +// flattens, shown as read-only text the user selects and copies (textview), as the Run console +// is: a drag, across rows too, a double click for a word, a triple click for a row, Shift with +// a click, Primary+A and Primary+C. The rows are drawn in the run output's font (fonts.go), so +// the console reads like the run output beside it and, with the default fonts, like the editor. // A header's stamp is subtle, its repository is in the accent color, and its temporary // configuration is the toggle of its fold: a click on it opens or closes it. Other folds have -// their toggle after the row, and a header its running badge. -// -// The rows are broken into lines or cut to the list's width here, by the cells of the font, -// rather than by ui Wrap and Ellipsis. A row is several spans in different colors, and a -// header's configuration span is an inline toggle that takes clicks, while a Wrap or an -// Ellipsis breaks or cuts one Text. A wrapped row breaks anywhere a line is full, as a -// terminal breaks it, not between words. Viva lays each piece out on its cells, so a piece -// needs no width of its own. +// their toggle after the row, and a header its running badge, at the right edge, where a +// selection never takes them. A long row ends in an ellipsis, or breaks onto more lines when +// the console wraps. const ( - // consoleRowPadX is the room on either side of a row, and consoleRowGap the room between - // its text, its badge and its toggle. + // consoleRowPadX is the room on either side of a row. consoleRowPadX = 8 - consoleRowGap = 6 - // consoleMenuWidth is the width of a record's context menu. + // consoleMenuWidth is the width of the console's context menu. consoleMenuWidth = 220 - // consoleEllipsis ends a line cut short; it takes one cell. - consoleEllipsis = "…" ) // consolePageView declares the body of the Console tab: the toolbar over the rows, or the // empty message when the console holds no command. func (a *App) consolePageView(c ui.C) { v := &a.consoleView - if v.drawRow == nil { - v.list.Key, v.list.Label = v.rowKey, v.rowLabel - v.drawRow = a.drawConsoleRow - v.measure = v.measureWidth - } a.syncConsole() - ui.Column(c).Fill().Background(a.colors.Editor).Draw(v.measure).Children(func() { + ui.Column(c).Fill().Background(a.colors.Editor).Children(func() { a.drawConsoleToolbar(c) ui.Divider(c) if len(v.snapshot.Records) == 0 { @@ -107,199 +97,100 @@ func (a *App) drawConsoleCount(c ui.C, value string) { ui.Text(c, value).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Shrink(0) } -// drawConsoleList declares the rows. The list follows its end while the user leaves it -// there; a step to a hit scrolls it away from the end, which Follow would undo in the same -// layout, so the area is told it was left there. -func (a *App) drawConsoleList(c ui.C) { - v := &a.consoleView - v.font = a.outputFont() - v.cellW, _ = c.Canvas().MonoCellSize(v.font.Size, v.font.face) - v.lineH = v.font.lineHeight(c.Canvas()) - area := ui.List(c, &v.list, len(v.rows), v.drawRow).Scrollbars().Label(a.text.Git.Console).Grow(1).FillWidth().Follow(true) - if v.detach { - v.detach = false - s := area.ScrollState() - s.ScrollTo(s.Offset) - } -} +// consoleSource is the console's rows as the text of its view, numbered from 0. +type consoleSource struct{ v *consoleView } -// measureWidth records the width of the Console tab, which the list fills, as it is drawn. -// The rows were laid out for the width before, so a frame that finds it changed asks for one -// more, laid out for the new one. -func (v *consoleView) measureWidth(d *ui.DrawContext) { - if width := d.Rect.Width; width != v.width { - v.width = width - d.Canvas.RequestFrame() - } -} +func (s consoleSource) First() int { return 0 } +func (s consoleSource) Count() int { return len(s.v.rows) } +func (s consoleSource) Line(n int) string { return s.v.rows[n].text } -// drawConsoleRow declares one row: its text in the row's colors, broken into lines or cut to -// the list's width, then its badge and the toggle of a fold that is not inline, with the -// context menu of its record. The current hit's row is drawn selected and the other rows with -// a hit are tinted. -func (a *App) drawConsoleRow(row ui.ListRow) { +// drawConsoleList declares the rows as read-only text that scrolls and follows its end while +// the user leaves it there. The current hit's row is drawn selected and the other rows with a +// hit are tinted; a header's configuration is a link that opens or closes its fold, and the +// toggle of another fold, after its row, a button. +func (a *App) drawConsoleList(c ui.C) { v := &a.consoleView - if row.Index < 0 || row.Index >= len(v.rows) { - return - } - r := &v.rows[row.Index] - c := row.C - item := row.Element.FillWidth().MinHeight(v.lineH).PadX(consoleRowPadX).Gap(consoleRowGap).Items(ui.Center) - switch { - case row.Index == v.hitRow: - item.Background(a.colors.Selection) - case r.matched: - item.Background(a.colors.Hover) - } - if r.record >= 0 { - ui.ContextMenu(c, row.Element, a.consoleMenu(c, r.record)) - } - item.Children(func() { - v.pieces = layoutConsoleRow(v.pieces[:0], r.text, r.spans, a.consoleCells(c.Canvas(), r), v.wrap) - pieces := v.pieces - ui.Column(c).Grow(1).Shrink(1).MinWidth(0).Clip().Children(func() { - for len(pieces) > 0 { - n := 1 - for n < len(pieces) && pieces[n].line == pieces[0].line { - n++ - } - line := pieces[:n] - pieces = pieces[n:] - ui.Row(c.KeyInt(line[0].line)).Items(ui.Center).Children(func() { - a.drawConsolePieces(c, r, line) - }) + font := a.outputFont() + small := gfx.TextStyle{Size: a.theme.Metrics.FontSizeS, Weight: gfx.WeightRegular, Color: a.colors.Subtle} + toggle := small + toggle.Color = a.colors.Accent + spec := textview.Spec{ + Label: a.text.Git.Console, + Source: consoleSource{v}, + Font: font.textStyle(), + LineHeight: font.lineHeight(c.Canvas()), + PadX: consoleRowPadX, + Selection: a.terminalLook().Selection, + Scroll: true, + Follow: true, + Wrap: v.wrap, + Ellipsis: true, + Revision: v.revision, + Spans: func(n int, text string, dst []textview.Span) []textview.Span { + return a.consoleTextSpans(&v.rows[n], dst) + }, + Open: func(n int, _ textview.Span) { + if r := &v.rows[n]; r.inline && r.toggle != "" { + a.toggleConsoleFold(r.fold, r.folded) } - }) - if r.badge != "" { - ui.Text(c, r.badge).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Shrink(0) - } - if r.toggle == "" || r.inline { - return - } - // The toggle is named by the row's part, so each row's toggle is a control of its own. - fc := c.Part("fold") - id := ui.ID(fc) - toggle := ui.Row(fc).Shrink(0).Items(ui.Center). - HitWith(id, r.toggle, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand}) - toggle.Children(func() { - ui.Text(fc, r.toggle).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Accent) - }) - if toggle.Clicked() { - fold, opening := r.fold, r.folded - c.After(func() { a.toggleConsoleFold(fold, opening) }) - } - }) -} - -// drawConsolePieces declares the pieces of one drawn line of row r, each in the run output's -// font, which Viva lays out on its cells, and in the color of its kind. A piece of the -// configuration of a header is the toggle of its fold: it says what a click does to assistive -// technology, shows the hand and the accent color under the pointer, and opens or closes the -// fold. -func (a *App) drawConsolePieces(c ui.C, r *consoleRow, pieces []consolePiece) { - v := &a.consoleView - for _, piece := range pieces { - box := ui.Text(c, piece.text).FontSize(v.font.Size).MonoFace(v.font.face).LineHeight(v.lineH). - Shrink(0).Color(a.consoleSpanColor(r.tone, piece.kind)) - if piece.kind != consoleSpanFold || !r.inline { - continue - } - box.HitWith(ui.ID(c), r.toggle, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand}). - Hover(ui.Look{}.Color(a.colors.Accent)) - if box.Clicked() { - fold, opening := r.fold, r.folded - c.After(func() { a.toggleConsoleFold(fold, opening) }) - } - } -} - -// consoleCells is how many cells of the run output's font the text of row r has across: the -// list's width as last drawn, less the row's padding and the badge and toggle drawn after the -// text. It is 0, no limit, before the list has been drawn. -func (a *App) consoleCells(canvas *gfx.Canvas, r *consoleRow) int { - v := &a.consoleView - if v.width <= 0 || v.cellW <= 0 { - return 0 - } - room := v.width - 2*consoleRowPadX - small := gfx.TextStyle{Size: a.theme.Metrics.FontSizeS, Weight: gfx.WeightRegular} - if r.badge != "" { - room -= consoleRowGap + canvas.TextWidthStyle(r.badge, small) - } - if r.toggle != "" && !r.inline { - room -= consoleRowGap + canvas.TextWidthStyle(r.toggle, small) + }, + LineBackground: func(n int) gfx.Color { + switch { + case n == v.hitRow: + return a.colors.Selection + case v.rows[n].matched: + return a.colors.Hover + } + return gfx.Color{} + }, + // A header's toggle is its configuration, inline; only a header has a badge. + Trail: func(n int) textview.Trail { + switch r := &v.rows[n]; { + case r.badge != "": + return textview.Trail{Text: r.badge, Style: small} + case r.toggle != "" && !r.inline: + return textview.Trail{Text: r.toggle, Style: toggle, Button: true} + } + return textview.Trail{} + }, + PressTrail: func(n int) { + if r := &v.rows[n]; r.toggle != "" { + a.toggleConsoleFold(r.fold, r.folded) + } + }, + Copy: func(text string) { + a.performed("git.console.copySelection", surfaceShortcut) + a.copyConsoleText(text) + }, + Menu: a.consoleMenu(c), } - // The small margin keeps a width of exactly n cells from rounding down to n-1. - return max(int(room/v.cellW+0.001), 1) + spec.Font.Color = a.colors.Text + v.text.Declare(c.Key("rows"), spec).Grow(1).FillWidth() } -// consolePiece is a stretch of a row's text drawn on one of its lines: the text, the kind of -// the span it is from and the line it is on. -type consolePiece struct { - text string - kind consoleSpanKind - line int -} - -// layoutConsoleRow appends to dst the pieces text is drawn in on a row cells cells wide: the -// stretches of its spans, one span of text when spans is empty. With wrap set the text is -// broken onto as many lines as it takes, anywhere a line is full, as a terminal breaks it; -// otherwise it stays on one line, and a text too long for it is cut where the line less one -// cell is full and ends in consoleEllipsis, of the kind of the span it was cut in. A wide -// character that does not fit at the end of a line starts the next one. cells of zero or -// less, a width not known yet, keeps the text on one line, whole. -func layoutConsoleRow(dst []consolePiece, text string, spans []consoleSpan, cells int, wrap bool) []consolePiece { - var whole [1]consoleSpan - if len(spans) == 0 { - whole[0] = consoleSpan{end: len(text), kind: consoleSpanText} - spans = whole[:] - } - limit, cut := cells, false - if !wrap && cells > 0 && consoleTextCells(text) > cells { - limit, cut = cells-1, true +// consoleTextSpans appends to dst the spans of row r, each in the color of its kind. The +// configuration of a header is the toggle of its fold, a link named by what a click does that +// takes the accent color under the pointer. +func (a *App) consoleTextSpans(r *consoleRow, dst []textview.Span) []textview.Span { + if len(r.spans) == 0 { + return append(dst, textview.Span{From: 0, To: len(r.text), Color: a.consoleToneColor(r.tone)}) } - line, used, from := 0, 0, 0 - for _, span := range spans { - end := min(span.end, len(text)) + from := 0 + for _, span := range r.spans { + end := min(span.end, len(r.text)) if end <= from { continue } - at := from - for i, r := range text[from:end] { - i += from - w := vivatext.CellWidth(r) - if cells > 0 && used+w > limit && (cut || used > 0) { - dst = appendConsolePiece(dst, text[at:i], span.kind, line) - if cut { - return append(dst, consolePiece{text: consoleEllipsis, kind: span.kind, line: line}) - } - line, used, at = line+1, 0, i - } - used += w + s := textview.Span{From: from, To: end, Color: a.consoleSpanColor(r.tone, span.kind)} + if span.kind == consoleSpanFold && r.inline { + s.Link, s.Hover, s.Label = true, a.colors.Accent, r.toggle } - dst = appendConsolePiece(dst, text[at:end], span.kind, line) + dst = append(dst, s) from = end } return dst } -// appendConsolePiece appends the piece of text to dst unless it is empty. -func appendConsolePiece(dst []consolePiece, text string, kind consoleSpanKind, line int) []consolePiece { - if text == "" { - return dst - } - return append(dst, consolePiece{text: text, kind: kind, line: line}) -} - -// consoleTextCells is how many cells of a fixed-pitch font text takes. -func consoleTextCells(text string) int { - cells := 0 - for _, r := range text { - cells += vivatext.CellWidth(r) - } - return cells -} - // consoleSpanColor is the color of a stretch of kind in a row of tone: the stamp and the // configuration are subtle and the repository in the accent color whatever the tone, the // command green, so that it stands apart from its output, red when it failed and subtle for a @@ -333,26 +224,46 @@ func (a *App) consoleToneColor(tone consoleTone) gfx.Color { return a.colors.Text } -// consoleMenu declares the context menu of the record at index of the snapshot: copy its -// command, its output or the directory it ran in. The values are taken while the menu is -// declared, because the snapshot may change before the action runs. -func (a *App) consoleMenu(c ui.C, index int) func(*ui.MenuItems) { +// consoleMenu declares the console's context menu: Copy takes the selection, or the row +// right-clicked when nothing is selected, and Select All every row; then copy the command, the +// output or the directory of the record the row right-clicked is of. The values are taken +// while the menu is declared, because the snapshot may change before the action runs. +func (a *App) consoleMenu(c ui.C) func(*ui.MenuItems) { return func(menu *ui.MenuItems) { v, t := &a.consoleView, &a.text.Console - if index < 0 || index >= len(v.snapshot.Records) { - return - } - r := &v.snapshot.Records[index] + lang := a.language() menu.WidthRange(consoleMenuWidth, consoleMenuWidth) - if menu.Item(t.CopyCommand).Disabled(len(r.Arguments) == 0).Clicked() { + n, onRow := v.text.MenuLine() + onRow = onRow && n >= 0 && n < len(v.rows) + text, action, copyable := v.text.Text(), "copySelection", v.text.Has() + if !copyable && onRow { + text, action, copyable = v.rows[n].text, "copyLine", true + } + if menu.Item(i18n.Shared(lang, "menu.copy")).Disabled(!copyable).Clicked() { + c.After(func() { a.copyConsoleRecord(action, text) }) + } + if menu.Item(i18n.Shared(lang, "menu.selectAll")).Disabled(len(v.rows) == 0).Clicked() { + c.After(func() { + a.performed("git.console.selectAll", surfaceContextMenu) + v.text.SelectAll() + }) + } + menu.Separator() + var r *core.GitConsoleRecord + if onRow { + if index := v.rows[n].record; index >= 0 && index < len(v.snapshot.Records) { + r = &v.snapshot.Records[index] + } + } + if menu.Item(t.CopyCommand).Disabled(r == nil || len(r.Arguments) == 0).Clicked() { command := consoleCommand(r) c.After(func() { a.copyConsoleRecord("copyCommand", command) }) } - if menu.Item(t.CopyOutput).Disabled(len(r.Lines) == 0).Clicked() { + if menu.Item(t.CopyOutput).Disabled(r == nil || len(r.Lines) == 0).Clicked() { output := consoleOutput(r) c.After(func() { a.copyConsoleRecord("copyOutput", output) }) } - if menu.Item(t.CopyPath).Disabled(r.Root == "").Clicked() { + if menu.Item(t.CopyPath).Disabled(r == nil || r.Root == "").Clicked() { root := r.Root c.After(func() { a.copyConsoleRecord("copyPath", root) }) } diff --git a/desktop/internal/workbench/gitlog_details_test.go b/desktop/internal/workbench/gitlog_details_test.go index 4bb36e9cf3..9bbb4cf636 100644 --- a/desktop/internal/workbench/gitlog_details_test.go +++ b/desktop/internal/workbench/gitlog_details_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/textview" "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" ) @@ -54,24 +55,28 @@ func TestLogCommitDetailsShowWholeAuthorLine(t *testing.T) { } mailbox := parts[2].text - // Every text of the details at the body size lies inside the pane's padding and none - // ends in an ellipsis; the texts are drawn on at least two lines. The email's lines - // join into the whole email and have no other part on them, and the other parts are - // drawn whole. The details pane starts after its splitter, is detailWidth wide and as - // tall as the splitter; the commit details lie below the splitter of the changed files, - // which this commit, changing none, leaves empty. + // Every text of the details lies inside the pane's padding and none ends in an + // ellipsis; the author line is drawn on at least two lines. The lines drawn, joined, are + // the subject and the whole author line, so nothing is cut; the email starts a line of + // its own, as it is wider than one. The details pane starts after its splitter, is + // detailWidth wide and as tall as the splitter; the commit details lie below the splitter + // of the changed files, which this commit, changing none, leaves empty. split, files := h.logDetailsSplit(), h.logFilesSplit() left, top, bottom := split.Right(), files.Bottom(), split.Bottom() contentLeft, contentRight := left+logDetailPad, left+v.detailWidth-logDetailPad const slack = 0.5 var drawn []app.Label + var joined strings.Builder lines := map[float32]bool{} + emailStarts := false for _, label := range h.driver.Snapshot().Labels { - if label.FontSize != h.app.theme.Metrics.FontSizeM || label.Bounds.X < left || label.Bounds.Y < top || label.Bounds.Y >= bottom { + if label.FontSize != logFontSize || label.Bounds.X < left || label.Bounds.Y < top || label.Bounds.Y >= bottom { continue } drawn = append(drawn, label) + joined.WriteString(label.Value) lines[label.Bounds.Y] = true + emailStarts = emailStarts || strings.HasPrefix(label.Value, mailbox[:12]) if strings.Contains(label.Value, "…") { t.Errorf("%q is cut short", label.Value) } @@ -79,38 +84,72 @@ func TestLogCommitDetailsShowWholeAuthorLine(t *testing.T) { t.Errorf("%q drawn at %+v, outside the details' %v..%v", label.Value, label.Bounds, contentLeft, contentRight) } } - if len(lines) < 2 { - t.Fatalf("the author line is drawn on %d lines, want at least two; drawn %+v", len(lines), drawn) + if len(lines) < 3 { + t.Fatalf("the subject and the author line are drawn on %d lines, want at least three; drawn %+v", len(lines), drawn) } - // A label is a piece of the email when its text is part of the email and not another - // part's whole text, such as the hash. - isEmail := func(label app.Label) bool { - return label.Value != "" && strings.Contains(mailbox, label.Value) && - !slices.ContainsFunc(parts, func(part logMetaPart) bool { return part.text != mailbox && part.text == label.Value }) + var meta []string + for _, part := range parts { + meta = append(meta, part.text) } - var joined strings.Builder - mailLines := map[float32]bool{} - for _, label := range drawn { - if isEmail(label) { - joined.WriteString(label.Value) - mailLines[label.Bounds.Y] = true - } + if want := "long author" + strings.Join(meta, " "); joined.String() != want { + t.Errorf("the details' lines are %q, want the whole %q", joined.String(), want) } - if joined.String() != mailbox { - t.Errorf("the email's lines are %q, want the whole %q; drawn %+v", joined.String(), mailbox, drawn) + if !emailStarts { + t.Errorf("the email does not start a line of its own; drawn %+v", drawn) } - for _, label := range drawn { - if !isEmail(label) && mailLines[label.Bounds.Y] { - t.Errorf("%q shares a line with the email, which has its lines to itself; drawn %+v", label.Value, drawn) - } +} + +// TestLogCommitDetailsSelectAndCopy checks that the commit details are text the user selects +// and copies (#2073): a double click on the short hash selects it and Primary+C copies it, and +// Primary+A selects the subject, the author line and the message together. +func TestLogCommitDetailsSelectAndCopy(t *testing.T) { + h := newHarness(t, gitKernel{core.NewClient()}) + dir := newTestRepository(t) + gitRun(t, dir, "commit", "--allow-empty", "-m", "fix: copy the details\n\nfirst body line\nsecond body line") + head := gitRun(t, dir, "rev-parse", "HEAD") + h.app.delays = logDelays{} + h.open(dir) + h.app.reduceChrome(core.SetChromeOpen(itemGit, true)) + h.settleChain() + p := h.app.project + if p == nil || !p.git.isRepository() { + t.Fatalf("the project is not a loaded repository: %+v", p) } - for i, part := range parts { - if i == 2 { - continue - } - if !slices.ContainsFunc(drawn, func(label app.Label) bool { return label.Value == part.text }) { - t.Errorf("%q is not drawn whole; drawn %+v", part.text, drawn) - } + v := &h.app.logView + v.filesSplit.Pos = logFilesMin + h.app.layout.bottom = 10000 + h.app.layout.gitTab = gitTabLog + h.settle() + if !p.log.started { + h.click(center(h.button(itemGit))) + h.settle() + } + h.app.selectCommit(p, head) + h.settle() + h.settle() + if p.log.detail == nil { + t.Fatalf("no details of %q: files %v", head, p.log.filesState) + } + hash := p.log.detail.Commit.ShortHash + at, ok := v.detailText.PointOf(textview.Point{Line: 1, Byte: 1}) + if !ok { + t.Fatal("the author line is not on screen") + } + if err := h.driver.DoubleClick(at.X, at.Y); err != nil { + t.Fatal(err) + } + h.settle() + if got := h.copyShortcut(); got != hash { + t.Fatalf("a double click on the hash copied %q, want %q", got, hash) + } + if _, err := h.driver.ShortcutChord(primaryModifier(), 'a'); err != nil { + t.Fatal(err) + } + h.settle() + got := h.copyShortcut() + want := "fix: copy the details\n" + strings.Join(v.detailLines[1:2], "") + "\n\nfirst body line\nsecond body line" + if got != want || !strings.HasPrefix(v.detailLines[1], hash+" ") { + t.Fatalf("Primary+A then Primary+C copied %q, want %q", got, want) } } diff --git a/desktop/internal/workbench/gitlog_details_view.go b/desktop/internal/workbench/gitlog_details_view.go index af9ce26412..60eb3cb852 100644 --- a/desktop/internal/workbench/gitlog_details_view.go +++ b/desktop/internal/workbench/gitlog_details_view.go @@ -1,6 +1,7 @@ package workbench import ( + "math" "path" "slices" "strings" @@ -9,7 +10,9 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/fileicons" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/1lck/Lithe-IDEA/desktop/internal/textview" "github.com/1lck/Lithe-IDEA/desktop/internal/treelist" + "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -387,8 +390,7 @@ func (a *App) drawLogCommitDetail(c ui.C, p *project) ui.Box { } } ui.Scroll(c).Scrollbars().Grow(1).Pad(logDetailPad).Gap(8).Children(func() { - ui.Wrap(c, d.Commit.Subject).Mono().Bold().FontSize(logFontSize).FillWidth() - a.drawLogMeta(c, d) + a.drawLogDetailText(c, d) if chips := slices.DeleteFunc(slices.Clone(labels), func(x core.GraphLabel) bool { return x.Kind == "head" }); len(chips) > 0 { ui.Flow(c).FillWidth().Gap(logRefChipGap).Children(func() { for _, label := range chips { @@ -396,36 +398,90 @@ func (a *App) drawLogCommitDetail(c ui.C, p *project) ui.Box { } }) } - if body := strings.TrimSpace(d.Body); body != "" { - ui.Wrap(c, body).FontSize(logMetaSize) - } }) }) } -// drawLogMeta declares the author line of commit d's details: the short hash, the author, -// the email and the date. None of them is cut short. The parts are a Flow, so they wrap onto -// more lines when the details are narrow, a part that fits a line is drawn whole on one, and -// a part wider than a line, such as a long email, has one to itself and wraps inside it as a -// ui Wrap does. -func (a *App) drawLogMeta(c ui.C, d *core.GitCommitDetail) { +// drawLogDetailText declares the text of commit d's details as read-only text the user +// selects and copies, as IntelliJ IDEA's commit details are: the subject in bold, the author +// line, then the message after an empty line. The author line is the short hash, the author, +// the email and the date, each in its color. Nothing is cut short: a line wider than the +// details wraps, at a space where it can, so a long email breaks inside itself only when it +// is wider than a line. +func (a *App) drawLogDetailText(c ui.C, d *core.GitCommitDetail) { v := &a.logView + if v.detailHash != d.Commit.Hash { + v.detailHash = d.Commit.Hash + v.detailText.Selection.Clear() + } muted := a.theme.MutedForeground parts := append(v.metaParts[:0], - logMetaPart{text: d.Commit.ShortHash, mono: true, color: muted}, + logMetaPart{text: d.Commit.ShortHash, color: muted}, logMetaPart{text: d.Commit.AuthorName, color: a.theme.Foreground}) if d.Commit.AuthorEmail != "" { parts = append(parts, logMetaPart{text: "<" + d.Commit.AuthorEmail + ">", color: a.colors.Accent}) } parts = append(parts, logMetaPart{text: a.text.Git.On(v.date(d.Commit)), color: muted}) + var meta strings.Builder + for i := range parts { + if i > 0 { + meta.WriteByte(' ') + } + parts[i].from = meta.Len() + meta.WriteString(parts[i].text) + parts[i].to = meta.Len() + } v.metaParts = parts - ui.Flow(c).FillWidth().Items(ui.Center).Gap(logAuthorGap).LineGap(logAuthorLineGap).Children(func() { - for _, part := range parts { - text := ui.Wrap(c, part.text).Color(part.color) - if part.mono { - text.Mono() - } + lines := append(v.detailLines[:0], d.Commit.Subject, meta.String()) + if body := strings.TrimSpace(d.Body); body != "" { + lines = append(lines, "") + for line := range strings.SplitSeq(body, "\n") { + lines = append(lines, strings.TrimSuffix(line, "\r")) } + } + v.detailLines = lines + style := gfx.TextStyle{Size: logFontSize, Mono: true, Color: a.theme.Foreground} + _, cellH := c.Canvas().MonoCellSize(style.Size, style.MonoFace) + lang := a.language() + v.detailText.Declare(c.Key("details"), textview.Spec{ + Label: i18n.Shared(lang, "git.log.commitDetails"), + Source: lines, + Font: style, + LineHeight: float32(math.Round(float64(cellH * 1.4))), + Selection: a.terminalLook().Selection, + Wrap: true, + Spans: func(n int, text string, dst []textview.Span) []textview.Span { + switch n { + case 0: + return append(dst, textview.Span{From: 0, To: len(text), Color: style.Color, Bold: true}) + case 1: + for _, part := range v.metaParts { + dst = append(dst, textview.Span{From: part.from, To: part.to, Color: part.color}) + } + } + return dst + }, + Copy: func(text string) { + a.performed("git.log.copyDetails", surfaceShortcut) + _ = app.SetClipboardText(text) + }, + Menu: func(menu *ui.MenuItems) { + menu.WidthRange(180, 260) + view := &v.detailText + text, has := view.Text(), view.Has() + if menu.Item(i18n.Shared(lang, "menu.copy")).Disabled(!has).Clicked() { + c.After(func() { + a.performed("git.log.copyDetails", surfaceContextMenu) + _ = app.SetClipboardText(text) + }) + } + if menu.Item(i18n.Shared(lang, "menu.selectAll")).Clicked() { + c.After(func() { + a.performed("git.log.selectDetails", surfaceContextMenu) + view.SelectAll() + }) + } + }, }) } diff --git a/desktop/internal/workbench/gitlog_page.go b/desktop/internal/workbench/gitlog_page.go index 86039f2bae..8314c19e5b 100644 --- a/desktop/internal/workbench/gitlog_page.go +++ b/desktop/internal/workbench/gitlog_page.go @@ -2,6 +2,7 @@ package workbench import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/textview" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -68,20 +69,12 @@ const ( logRefChipGap = 4 ) -// The author line of the commit details: the short hash, the author, the email and the -// date. drawLogMeta lays the parts out in a Flow: parts stand logAuthorGap apart along a -// line, and the lines they wrap onto logAuthorLineGap. -const ( - logAuthorGap = 6 - logAuthorLineGap = 2 -) - -// logMetaPart is one part of the author line of the commit details, drawn whole in color, -// in the fixed-pitch font when mono is set. +// logMetaPart is one part of the author line of the commit details, the bytes from to to +// of the line, drawn in color. type logMetaPart struct { - text string - mono bool - color gfx.Color + text string + from, to int + color gfx.Color } // The filter chips of the commit list, for logView.chips. @@ -149,9 +142,15 @@ type logView struct { // focus is the field to give the keyboard to in the next paint. focus gfx.ID - // metaParts are the parts of the selected commit's author line; the array is kept so the - // next paint reuses it. - metaParts []logMetaPart + // detailText is the text of the selected commit's details, which the user selects and + // copies: its subject, its author line and its message. detailLines are its lines and + // detailHash the commit they are of, so choosing another commit drops the selection; + // metaParts are the parts of the author line. The arrays are kept so the next paint + // reuses them. + detailText textview.View + detailLines textview.Strings + detailHash string + metaParts []logMetaPart // file is the path of the selected changed file, and folder the path of the selected // folder of the changed files; at most one of them is set. diff --git a/desktop/internal/workbench/outputlinks_view.go b/desktop/internal/workbench/outputlinks_view.go index 6a246787f5..5018faf80d 100644 --- a/desktop/internal/workbench/outputlinks_view.go +++ b/desktop/internal/workbench/outputlinks_view.go @@ -7,28 +7,35 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/term" + "github.com/1lck/Lithe-IDEA/desktop/internal/textview" "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) // outputMenu is the context menu of a console's lines, as the old client's output view had: -// copy the line right-clicked, copy the whole output all returns, then the items extra adds. -// The empty space below the lines opens it too, with no line to copy; key names that space. +// copy the selection or the line right-clicked, copy the whole output all returns, select +// all, then the items extra adds. The empty space below the lines opens it too. key names +// the console, so each run's keeps its own scroll and focus. type outputMenu struct { key string all func() string extra func(*ui.MenuItems) } -// outputLineMenu is the menu of the console line text, or of no line when line is false. -func (a *App) outputLineMenu(c ui.C, text string, line bool, m *outputMenu) func(*ui.MenuItems) { +// outputLineMenu is the menu of a console: Copy takes the selection, or the line +// right-clicked when nothing is selected, and is off below the lines with no selection. +func (a *App) outputLineMenu(c ui.C, view *textview.View, src textview.Source, m *outputMenu) func(*ui.MenuItems) { return func(menu *ui.MenuItems) { lang := a.language() menu.WidthRange(180, 260) - if menu.Item(i18n.Shared(lang, "menu.copy")).Disabled(!line).Clicked() { + text, action, copyable := view.Text(), "output.copySelection", view.Has() + if n, ok := view.MenuLine(); !copyable && ok && n >= src.First() && n < src.First()+src.Count() { + text, action, copyable = src.Line(n), "output.copyLine", true + } + if menu.Item(i18n.Shared(lang, "menu.copy")).Disabled(!copyable).Clicked() { c.After(func() { - a.performed("output.copyLine", surfaceContextMenu) + a.performed(action, surfaceContextMenu) _ = app.SetClipboardText(text) }) } @@ -39,6 +46,12 @@ func (a *App) outputLineMenu(c ui.C, text string, line bool, m *outputMenu) func _ = app.SetClipboardText(all) }) } + if menu.Item(i18n.Shared(lang, "menu.selectAll")).Disabled(src.Count() == 0).Clicked() { + c.After(func() { + a.performed("output.selectAll", surfaceContextMenu) + view.SelectAll() + }) + } if m.extra != nil { menu.Separator() m.extra(menu) @@ -91,51 +104,104 @@ func rgbColor(red, green, blue uint8) gfx.Color { return gfx.Color{Red: float32(red) / 255, Green: float32(green) / 255, Blue: float32(blue) / 255, Alpha: 1} } -// outputList declares a console's lines from from on as a list that holds only the rows on -// screen. Each line is cut into the ranges Core styled from its escapes and the links Core -// matched, all at UTF-16 offsets, and every piece is drawn in its own colors. +// outputSource is a console's lines from row from on, as a view numbers them: by their +// sequence in the buffer, so a selection keeps to its text while the oldest lines go. +type outputSource struct { + output *outputBuffer + from int +} + +func (s outputSource) First() int { return s.output.start + s.from } +func (s outputSource) Count() int { return s.output.count() - s.from } +func (s outputSource) Line(n int) string { return s.output.row(n - s.output.start).text } + +// outputList declares a console's lines from row from on as read-only text the user selects +// and copies, which draws only the rows on screen. Each line is cut into the ranges Core +// styled from its escapes and the links Core matched, all at UTF-16 offsets, and every piece +// is drawn in its own colors; a click on a link opens it. // // The lines are drawn in the run output's font (fonts.go), each line as tall as that font's -// line spacing makes it. A line right-clicked opens menu, when there is one. The list keeps +// line spacing makes it. A secondary press opens menu, when there is one. The console keeps // to the newest line as output arrives, until the user scrolls up, and keeps to it again once // they scroll back down. -func (a *App) outputList(c ui.C, p *project, state *ui.ListState, scope, label string, output *outputBuffer, from int, menu *outputMenu) ui.Box { +func (a *App) outputList(c ui.C, p *project, view *textview.View, scope, label string, output *outputBuffer, from int, menu *outputMenu) ui.Box { + if menu != nil && menu.key != "" { + c = c.Key(menu.key) + } font := a.outputFont() - lineH := font.lineHeight(c.Canvas()) ink := a.outputInk() - from = min(max(from, 0), output.count()) - list := ui.List(c, state, output.count()-from, func(row ui.ListRow) { - line := output.row(from + row.Index) - a.outputLine(row, p, scope, line, &ink, font, lineH) - if menu != nil { - ui.ContextMenu(row.C, row.Element, a.outputLineMenu(row.C, line.text, true, menu)) - } - }).Scrollbars().Label(label).FillWidth().Follow(true) - a.flushOutputLinks(p) + src := outputSource{output: output, from: min(max(from, 0), output.count())} + spec := textview.Spec{ + Label: label, + Source: src, + Font: font.textStyle(), + LineHeight: font.lineHeight(c.Canvas()), + PadX: 8, + Selection: a.terminalLook().Selection, + Scroll: true, + Follow: true, + Spans: func(n int, text string, dst []textview.Span) []textview.Span { + return a.outputSpans(p, scope, output.row(n-output.start), &ink, dst) + }, + Open: func(n int, span textview.Span) { + if link, ok := a.outputLinkAt(p, scope, output.row(n-output.start), span.From); ok { + a.openOutputLink(p, link) + } + }, + Copy: func(text string) { + a.performed("output.copySelection", surfaceShortcut) + _ = app.SetClipboardText(text) + }, + } + spec.Font.Color = ink.foreground if menu != nil { - list = list.Hit(ui.ID(c.Key(menu.key)), label) - ui.ContextMenu(c, list, a.outputLineMenu(c, "", false, menu)) + spec.Menu = a.outputLineMenu(c, view, src, menu) + } + box := view.Declare(c, spec) + // The links of the lines on screen are asked for before they are drawn, so the request + // goes out in this frame; the answer repaints. + first, last := view.Visible() + for n := max(first, src.First()); n < min(last, src.First()+src.Count()); n++ { + a.outputLinksFor(p, scope, src.Line(n)) } - return list + a.flushOutputLinks(p) + return box } -// outputLine declares one console line in its row. -func (a *App) outputLine(row ui.ListRow, p *project, scope string, line styledLine, ink *outputInk, font scopeFont, lineH float32) { - c := row.C - row.Element.PadX(8) +// outputSpans styles one console line, appending to dst: a span for every piece +// outputSegments cuts it into, at byte offsets. +func (a *App) outputSpans(p *project, scope string, line styledLine, ink *outputInk, dst []textview.Span) []textview.Span { links := a.outputLinksFor(p, scope, line.text) if len(links) == 0 && len(line.spans) == 0 { - ui.Text(c, line.text).FontSize(font.Size).MonoFace(font.face).LineHeight(lineH).Color(ink.foreground) - return + return dst + } + at := 0 // the segments follow each other from the line's start + for _, segment := range outputSegments(line, links) { + span := ink.span(segment) + span.From, span.To = at, at+len(segment.text) + at = span.To + dst = append(dst, span) } + return dst +} + +// outputLinkAt is the link of a console line at byte at. +func (a *App) outputLinkAt(p *project, scope string, line styledLine, at int) (core.OutputLink, bool) { + links := a.outputLinksFor(p, scope, line.text) + offset := 0 for _, segment := range outputSegments(line, links) { - a.outputSegment(c, p, segment, ink, font, lineH) + end := offset + len(segment.text) + if segment.link != nil && offset <= at && at < end { + return *segment.link, true + } + offset = end } + return core.OutputLink{}, false } -// outputSegment declares one piece of a console line in its style. A link is drawn in the -// link color whatever its range's colors, so it reads as one. -func (a *App) outputSegment(c ui.C, p *project, segment outputSegment, ink *outputInk, font scopeFont, lineH float32) { +// span is the look of one piece of a console line. A link is drawn in the link color +// whatever its range's colors, so it reads as one. +func (ink *outputInk) span(segment outputSegment) textview.Span { style := segment.style foreground, ok := ink.color(style.Foreground, style.Bold) if !ok { @@ -157,32 +223,14 @@ func (a *App) outputSegment(c ui.C, p *project, segment outputSegment, ink *outp if style.Hidden { foreground.Alpha = 0 } - box := ui.Text(c, segment.text).FontSize(font.Size).MonoFace(font.face).LineHeight(lineH).Color(foreground).Shrink(0) - if style.Bold { - box = box.Weight(gfx.WeightBold) + span := textview.Span{ + Color: foreground, Bold: style.Bold, Italic: style.Italic, + Underline: style.Underline, Strike: style.Strikethrough, Link: segment.link != nil, } if filled { - box = box.Background(background) - } - if style.Underline || style.Strikethrough { - size, underline, strike := font.Size, style.Underline, style.Strikethrough - box = box.DrawOver(func(d *ui.DrawContext) { - middle := d.Rect.Y + d.Rect.Height/2 - color := d.Fade(foreground) - if underline { - d.Canvas.Fill(gfx.Rect{X: d.Rect.X, Y: middle + size*0.4, Width: d.Rect.Width, Height: 1}, color) - } - if strike { - d.Canvas.Fill(gfx.Rect{X: d.Rect.X, Y: middle + size*0.05 - 0.5, Width: d.Rect.Width, Height: 1}, color) - } - }) - } - if link := segment.link; link != nil { - box = box.HitWith(ui.ID(c), segment.text, gfx.HitOptions{Role: gfx.RoleLink, Cursor: gfx.PointerCursorHand}) - if box.Clicked() { - a.openOutputLink(p, *link) - } + span.Background = background } + return span } // outputSegment is a piece of one console line with one style and at most one link. diff --git a/desktop/internal/workbench/readonly_text_selection_visual_test.go b/desktop/internal/workbench/readonly_text_selection_visual_test.go new file mode 100644 index 0000000000..e2c34bfd47 --- /dev/null +++ b/desktop/internal/workbench/readonly_text_selection_visual_test.go @@ -0,0 +1,127 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/1lck/Lithe-IDEA/desktop/internal/textview" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +// TestVisualReadOnlyTextSelection captures the read-only text the user selects and copies +// (#2073, #2082), each with a selection across its lines: the Run console holding a stack +// trace, the details of a commit in the Git log, and the Git console holding a fetch with a +// closed fold, its toggle at the right edge. +func TestVisualReadOnlyTextSelection(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, look := range []struct{ theme, language string }{{"dark", "zh-Hans"}, {"light", "en"}} { + // open makes a window of the look over kernel, and the session that captures it. + open := func(t *testing.T, kernel Kernel) (*harness, *headless.Session) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(look.theme), Language: look.language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: kernel, Store: prefs, Languages: []string{look.language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1200, 760 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + return h, session + } + capture := func(t *testing.T, h *harness, session *headless.Session, id string) { + h.settleChain() + if err := session.Screenshot(filepath.Join(out, id+"-"+look.theme+".png")); err != nil { + t.Fatal(err) + } + } + + t.Run("run-console-"+look.theme, func(t *testing.T) { + h, session := open(t, &testKernel{Client: core.NewClient()}) + h.open(t.TempDir()) + p := h.app.project + run := &runEntry{id: "run-1", label: "Main", output: newOutputBuffer(runOutputMaxLines, runOutputBytes)} + chunk, err := newOutputDecoder(h.app.kernel).decode(stackTrace) + if err != nil { + t.Fatal(err) + } + run.output.apply(chunk) + p.build.runs = append(p.build.runs, run) + p.build.view = run.id + if !h.app.chrome.isOpen(catalogIndex[itemRun]) { + h.app.reduceChrome(core.SetChromeOpen(itemRun, true)) + } + h.settle() + h.drag(consolePoint(t, run, 0, len("Exception in thread \"main\" ")), consolePoint(t, run, 2, len("\tat demo.Main.main"))) + capture(t, h, session, "run-console-selection") + }) + + t.Run("git-log-details-"+look.theme, func(t *testing.T) { + h, session := open(t, gitKernel{core.NewClient()}) + dir := newTestRepository(t) + gitRun(t, dir, "commit", "--allow-empty", "-m", "fix: copy the details\n\nfirst body line\nsecond body line") + head := gitRun(t, dir, "rev-parse", "HEAD") + h.app.delays = logDelays{} + h.open(dir) + h.app.reduceChrome(core.SetChromeOpen(itemGit, true)) + h.settleChain() + p := h.app.project + if p == nil || !p.git.isRepository() { + t.Fatalf("the project is not a loaded repository: %+v", p) + } + v := &h.app.logView + v.filesSplit.Pos = logFilesMin + h.app.layout.bottom = 10000 + h.app.layout.gitTab = gitTabLog + h.settle() + if !p.log.started { + h.click(center(h.button(itemGit))) + h.settle() + } + h.app.selectCommit(p, head) + h.settle() + h.settle() + if p.log.detail == nil { + t.Fatalf("no details of %q", head) + } + from, ok := v.detailText.PointOf(textview.Point{Line: 1, Byte: 0}) + to, ok2 := v.detailText.PointOf(textview.Point{Line: 3, Byte: len("first body")}) + if !ok || !ok2 { + t.Fatal("the details are not on screen") + } + h.drag(from, to) + capture(t, h, session, "git-log-details-selection") + }) + + t.Run("git-console-"+look.theme, func(t *testing.T) { + h, session := open(t, gitKernel{core.NewClient()}) + h.openConsole(t, newTestRepository(t)) + v := &h.app.consoleView + record, presented := consoleFetch() + presented.search, presented.display = v.searchFor, v.display + v.snapshot.Records = []core.GitConsoleRecord{record} + v.presented[record.ID] = presented + v.dirty = true + h.app.invalidator.Invalidate() + h.settle() + h.drag(gitConsolePoint(t, v, 0, 0), gitConsolePoint(t, v, 2, len("Receiving"))) + capture(t, h, session, "git-console-selection") + }) + } +} diff --git a/desktop/internal/workbench/run_panels_test.go b/desktop/internal/workbench/run_panels_test.go index f6c27b508c..efa838ef9e 100644 --- a/desktop/internal/workbench/run_panels_test.go +++ b/desktop/internal/workbench/run_panels_test.go @@ -82,8 +82,8 @@ func TestRunConsoleDeclaresOnlyTheRowsOnScreen(t *testing.T) { h.settle() } rows := 0 - for _, hit := range h.driver.Snapshot().Hits { - if hit.Role == gfx.RoleOption { + for _, label := range h.driver.Snapshot().Labels { + if strings.HasPrefix(label.Value, "line ") { rows++ } } diff --git a/desktop/internal/workbench/run_view.go b/desktop/internal/workbench/run_view.go index ca67e78b20..8c8ed812b6 100644 --- a/desktop/internal/workbench/run_view.go +++ b/desktop/internal/workbench/run_view.go @@ -269,7 +269,7 @@ func (a *App) runConsole(c ui.C, p *project, run *runEntry) { return } menu := &outputMenu{ - key: "runsnapshot/" + run.id, + key: "runconsole/" + run.id, all: run.output.all, extra: func(menu *ui.MenuItems) { if menu.Item(a.text.Run.Snapshot.Menu).Clicked() { @@ -277,14 +277,14 @@ func (a *App) runConsole(c ui.C, p *project, run *runEntry) { } }, } - a.outputList(c, p, &run.list, outputScopeRun, a.text.Build.Output, &run.output, 0, menu).Grow(1) + a.outputList(c, p, &run.console, outputScopeRun, a.text.Build.Output, &run.output, 0, menu).Grow(1) }) ui.Divider(c) lang := a.language() ui.Column(c).FillHeight().Shrink(0).Gap(2).Pad(4).Children(func() { empty := run.output.empty() if a.runToolButton(c.Part("end"), i18n.Shared(lang, "git.console.scrollToEnd"), icons.ArrowDownToLine, a.colors.Text, empty) { - c.After(func() { run.list.ScrollToEnd() }) + c.After(func() { run.console.ScrollToEnd() }) } if a.runToolButton(c.Part("clear"), i18n.Shared(lang, "git.console.clear"), icons.Trash2, a.colors.Text, empty) { c.After(func() { run.output.clear() }) diff --git a/desktop/internal/workbench/runpanels.go b/desktop/internal/workbench/runpanels.go index 40ec1a71a9..d0dce15fe2 100644 --- a/desktop/internal/workbench/runpanels.go +++ b/desktop/internal/workbench/runpanels.go @@ -1,6 +1,9 @@ package workbench -import "github.com/vivaui/viva/ui" +import ( + "github.com/1lck/Lithe-IDEA/desktop/internal/textview" + "github.com/vivaui/viva/ui" +) // runPanels is the view state of the Run, Tests and Debug tool windows of one project. The // model they show (build, tests, debug) stays in the project, so this holds only what the @@ -17,12 +20,13 @@ type runPanels struct { buildRows []buildRow // choices is the Build window's tree of every build system. runSplit is the Run window's // divider between its execution tree and the selected execution's console; each - // execution keeps its own console list (runEntry.list). + // execution keeps its own console (runEntry.console). choices ui.ListState runSplit ui.SplitterState // testResults is the grouped result list, testOutput the console of a run that // failed before reporting results. - testResults, testOutput ui.ListState + testResults ui.ListState + testOutput textview.View // breakpoints, frames and console are the Debug tool window's lists, debugSplit the // divider between its call stack and its variables, and consoleSeen the output additions // the console has shown (see debugSessionView.outputCount). diff --git a/desktop/internal/workbench/runs.go b/desktop/internal/workbench/runs.go index a64b9a6228..d76eaf5791 100644 --- a/desktop/internal/workbench/runs.go +++ b/desktop/internal/workbench/runs.go @@ -13,8 +13,8 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/editorview" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/textview" "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" - "github.com/vivaui/viva/ui" ) const ( @@ -65,8 +65,8 @@ type runEntry struct { started, ended time.Time // summary is how the execution ended, shown under the console. summary string - // list is the console's scroll state. - list ui.ListState + // console is the console's selection and scroll state. + console textview.View // snapshots counts the output snapshots taken of this run, so each tab has its own URI. snapshots int // samples are the process tree's CPU and memory, oldest first, bounded; stopSampling ends the sampler. diff --git a/docs/assets/readonly-text-selection/after/git-console-selection-dark.png b/docs/assets/readonly-text-selection/after/git-console-selection-dark.png new file mode 100644 index 0000000000..8ed5b3ab09 Binary files /dev/null and b/docs/assets/readonly-text-selection/after/git-console-selection-dark.png differ diff --git a/docs/assets/readonly-text-selection/after/git-console-selection-light.png b/docs/assets/readonly-text-selection/after/git-console-selection-light.png new file mode 100644 index 0000000000..63d42345ac Binary files /dev/null and b/docs/assets/readonly-text-selection/after/git-console-selection-light.png differ diff --git a/docs/assets/readonly-text-selection/after/git-log-details-selection-dark.png b/docs/assets/readonly-text-selection/after/git-log-details-selection-dark.png new file mode 100644 index 0000000000..451aa6cbc4 Binary files /dev/null and b/docs/assets/readonly-text-selection/after/git-log-details-selection-dark.png differ diff --git a/docs/assets/readonly-text-selection/after/git-log-details-selection-light.png b/docs/assets/readonly-text-selection/after/git-log-details-selection-light.png new file mode 100644 index 0000000000..b0eba3d1dd Binary files /dev/null and b/docs/assets/readonly-text-selection/after/git-log-details-selection-light.png differ diff --git a/docs/assets/readonly-text-selection/after/run-console-selection-dark.png b/docs/assets/readonly-text-selection/after/run-console-selection-dark.png new file mode 100644 index 0000000000..d4e0d8080a Binary files /dev/null and b/docs/assets/readonly-text-selection/after/run-console-selection-dark.png differ diff --git a/docs/assets/readonly-text-selection/after/run-console-selection-light.png b/docs/assets/readonly-text-selection/after/run-console-selection-light.png new file mode 100644 index 0000000000..817f512432 Binary files /dev/null and b/docs/assets/readonly-text-selection/after/run-console-selection-light.png differ diff --git a/docs/assets/readonly-text-selection/before/git-console-selection-dark.png b/docs/assets/readonly-text-selection/before/git-console-selection-dark.png new file mode 100644 index 0000000000..6375593938 Binary files /dev/null and b/docs/assets/readonly-text-selection/before/git-console-selection-dark.png differ diff --git a/docs/assets/readonly-text-selection/before/git-console-selection-light.png b/docs/assets/readonly-text-selection/before/git-console-selection-light.png new file mode 100644 index 0000000000..302999f802 Binary files /dev/null and b/docs/assets/readonly-text-selection/before/git-console-selection-light.png differ diff --git a/docs/assets/readonly-text-selection/before/git-log-details-selection-dark.png b/docs/assets/readonly-text-selection/before/git-log-details-selection-dark.png new file mode 100644 index 0000000000..d316b242f8 Binary files /dev/null and b/docs/assets/readonly-text-selection/before/git-log-details-selection-dark.png differ diff --git a/docs/assets/readonly-text-selection/before/git-log-details-selection-light.png b/docs/assets/readonly-text-selection/before/git-log-details-selection-light.png new file mode 100644 index 0000000000..5dc0eda60a Binary files /dev/null and b/docs/assets/readonly-text-selection/before/git-log-details-selection-light.png differ diff --git a/docs/assets/readonly-text-selection/before/run-console-selection-dark.png b/docs/assets/readonly-text-selection/before/run-console-selection-dark.png new file mode 100644 index 0000000000..d9014ea4ee Binary files /dev/null and b/docs/assets/readonly-text-selection/before/run-console-selection-dark.png differ diff --git a/docs/assets/readonly-text-selection/before/run-console-selection-light.png b/docs/assets/readonly-text-selection/before/run-console-selection-light.png new file mode 100644 index 0000000000..ad4d4744fa Binary files /dev/null and b/docs/assets/readonly-text-selection/before/run-console-selection-light.png differ diff --git a/shared/platform-feature-matrix/features/readonly-text-selection.json b/shared/platform-feature-matrix/features/readonly-text-selection.json new file mode 100644 index 0000000000..1cb6f36d38 --- /dev/null +++ b/shared/platform-feature-matrix/features/readonly-text-selection.json @@ -0,0 +1,51 @@ +{ + "id": "readonly-text-selection", + "area": "工作台", + "group": "只读文本", + "capability": "只读文本区域可以像 IntelliJ IDEA 那样选择和复制:Run 窗口控制台、测试输出、Git Log 提交详情和 Git 工具窗口的 Console支持拖动选择(含跨行和拖出边缘自动滚动)、双击选词、三击选行、Shift+点击扩展选区、Cmd/Ctrl+A 全选、Cmd/Ctrl+C 复制、Esc 取消选择,右键菜单提供复制、全选(Run 控制台另有复制输出);内容不可编辑", + "owner": "Workbench", + "notes": "Viva 共享实现,在 desktop/internal/textview:按等宽字符格逐行绘制,只声明屏幕上的行;选区按控制台行序号记录,最早的行被丢弃时选区跟着文字,不会错位。控制台保留 ANSI 颜色与样式、输出链接点击打开(链接上按下拖动仍是选择)、自动跟随最新输出、清空和滚动到末尾;右键菜单在有选区时复制选区,否则复制右键所在行。Git 提交详情把标题、哈希/作者/邮箱/日期和正文作为一段等宽文字自动换行显示,引用标签移到文字下方。Git Console(gitconsole_view.go)同样改用 textview:命令头的临时配置仍是可点击的折叠开关(行内链接,悬停变强调色),其他折叠的“展开 N 行”开关和运行中徽标画在行尾、不进入选区;不换行时长行仍以省略号结尾,换行时为行尾开关留出列;搜索命中行高亮、跳到命中时居中滚动;折叠展开或新增命令重新排行后,选区跟着原来的行,原来的行变了才取消;右键菜单保留复制命令、复制输出、复制路径。", + "verification": "运行会抛出异常的程序,在 Run 窗口控制台从第一行中间拖到第三行,Cmd/Ctrl+C 后粘贴得到原样的堆栈文字;双击类名只选中该词,三击选中整行;点击后 Shift+点击扩展选区;Cmd/Ctrl+A 全选,Esc 取消;右键菜单的复制、复制输出、全选可用;点击文件链接仍能打开;输出持续追加时仍跟随最新行。在 Git Log 选中提交,双击哈希复制、拖动选择作者邮箱、全选复制整段提交信息,确认不能输入修改。在 Git 工具窗口的 Console 执行 fetch/pull 后,拖动跨行选择并复制,右键复制当前行和全选,点击“展开 N 行”和命令头的临时配置仍能展开折叠,搜索后上下跳转命中仍滚到命中行。自动化:textview/selection_test.go、workbench/console_selection_test.go、workbench/gitconsole_test.go、workbench/gitlog_details_test.go、workbench/context_menu_test.go、workbench/run_panels_test.go。", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/textview/view.go", + "desktop/internal/textview/selection.go", + "desktop/internal/textview/rows.go", + "desktop/internal/textview/paint.go", + "desktop/internal/textview/cells.go", + "desktop/internal/textview/selection_test.go", + "desktop/internal/workbench/outputlinks_view.go", + "desktop/internal/workbench/run_view.go", + "desktop/internal/workbench/gitlog_details_view.go", + "desktop/internal/workbench/console_selection_test.go", + "desktop/internal/workbench/gitlog_details_test.go", + "desktop/internal/workbench/context_menu_test.go", + "desktop/internal/workbench/gitconsole_view.go", + "desktop/internal/workbench/gitconsole.go", + "desktop/internal/workbench/gitconsole_test.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/textview/view.go", + "desktop/internal/textview/selection.go", + "desktop/internal/textview/rows.go", + "desktop/internal/textview/paint.go", + "desktop/internal/textview/cells.go", + "desktop/internal/textview/selection_test.go", + "desktop/internal/workbench/outputlinks_view.go", + "desktop/internal/workbench/run_view.go", + "desktop/internal/workbench/gitlog_details_view.go", + "desktop/internal/workbench/console_selection_test.go", + "desktop/internal/workbench/gitlog_details_test.go", + "desktop/internal/workbench/context_menu_test.go", + "desktop/internal/workbench/gitconsole_view.go", + "desktop/internal/workbench/gitconsole.go", + "desktop/internal/workbench/gitconsole_test.go" + ] + } +}