package termview import ( "fmt" "image" "strings" "time" "gioui.org/f32" "gioui.org/io/event" "gioui.org/io/key" "gioui.org/io/pointer" "gioui.org/layout" "gioui.org/op" "gioui.org/op/clip" "go.mitchellh.com/libghostty" ) // Multi-click limits: presses within this time and distance of the last // one count as a double or triple click. const ( multiClickInterval = 500 * time.Millisecond multiClickDistance = 4.0 // pixels ) // selector turns the mouse into selections of a terminal's text, with // libghostty's selection gesture: drag to select cells, double-click for a // word, triple-click for a line, Alt-drag for a rectangle. type selector struct { gesture *libghostty.SelectionGesture term *libghostty.Terminal // the terminal the gesture was used with press *libghostty.SelectionGestureEvent drag *libghostty.SelectionGestureEvent release *libghostty.SelectionGestureEvent tick *libghostty.SelectionGestureEvent active bool // a press hasn't been released yet // While a drag is past the top or bottom edge, the viewport scrolls // that way, a line per tick. autoscroll libghostty.SelectionGestureAutoscroll lastPos libghostty.SurfacePosition lastCell libghostty.PointCoordinate // the viewport cell under the drag, clamped to the grid lastGeom libghostty.SelectionGestureGeometry lastTick time.Time } // autoscrollEvery is how often a drag past the edge scrolls a line. const autoscrollEvery = 50 * time.Millisecond func (s *selector) close() { if s.gesture != nil { // The terminal it was used with may already be freed: a pane // that goes away, or a terminal that a new snapshot replaced, // frees it before the view hears about it. libghostty's page // storage has then released the gesture's references itself. s.gesture.Close(nil) s.gesture = nil } for _, e := range []**libghostty.SelectionGestureEvent{&s.press, &s.drag, &s.release, &s.tick} { if *e != nil { (*e).Close() *e = nil } } } // ready makes the gesture and its events, anew if the terminal changed. func (s *selector) ready(term *libghostty.Terminal) error { if s.gesture != nil && s.term == term { return nil } s.close() s.term, s.active = term, false var err error if s.gesture, err = libghostty.NewSelectionGesture(); err != nil { return err } if s.press, err = libghostty.NewSelectionGestureEvent(libghostty.SelectionGestureEventTypePress); err != nil { return err } if s.drag, err = libghostty.NewSelectionGestureEvent(libghostty.SelectionGestureEventTypeDrag); err != nil { return err } if s.release, err = libghostty.NewSelectionGestureEvent(libghostty.SelectionGestureEventTypeRelease); err != nil { return err } if s.tick, err = libghostty.NewSelectionGestureEvent(libghostty.SelectionGestureEventTypeAutoscrollTick); err != nil { return err } if err := s.press.SetBehaviors(libghostty.SelectionGestureBehaviors{ SingleClick: libghostty.SelectionGestureBehaviorCell, DoubleClick: libghostty.SelectionGestureBehaviorWord, TripleClick: libghostty.SelectionGestureBehaviorLine, }); err != nil { return fmt.Errorf("behaviors: %w", err) } if err := s.press.SetRepeatDistance(multiClickDistance); err != nil { return fmt.Errorf("repeat distance: %w", err) } if err := s.press.SetRepeatIntervalNS(uint64(multiClickInterval)); err != nil { return fmt.Errorf("repeat interval: %w", err) } return nil } // handlePointer applies the mouse events since the last frame: reports to // a program that reads the mouse, selection with the primary button, a // middle click, and the wheel. It runs before // drawing, so the frame shows the result. func (v *View) handlePointer(gtx layout.Context, term *libghostty.Terminal, m metrics, pad int) error { tracking, motion, err := mouseTracking(term) if err != nil { return fmt.Errorf("mouse modes: %w", err) } kinds := pointer.Press | pointer.Drag | pointer.Release | pointer.Cancel | pointer.Scroll if motion || v.report.held != 0 { // Only then: every move would otherwise cost a frame. kinds |= pointer.Move } for { ev, ok := gtx.Event(pointer.Filter{ Target: &v.sel, Kinds: kinds, ScrollY: pointer.ScrollRange{Min: -1 << 20, Max: 1 << 20}, }) if !ok { break } e, ok := ev.(pointer.Event) if !ok { continue } if e.Kind == pointer.Scroll { if term != nil { if err := v.wheel(term, e, m, pad); err != nil { return fmt.Errorf("scroll: %w", err) } } continue } if e.Kind == pointer.Press && v.OnPress != nil { v.OnPress() } if reported, err := v.reportMouse(term, e, tracking, motion, m, pad); err != nil { return fmt.Errorf("mouse report: %w", err) } else if reported { continue } if e.Kind == pointer.Press && e.Buttons == pointer.ButtonTertiary { if v.OnMiddleClick != nil { v.OnMiddleClick() } continue } if term == nil || (e.Kind == pointer.Press && e.Buttons != pointer.ButtonPrimary) { continue } if err := v.selectEvent(term, e, m, pad); err != nil { return fmt.Errorf("select: %w", err) } } return v.autoscroll(gtx, term) } // autoscroll scrolls a line while a selection drag is past the top or // bottom edge, and asks for the frame that scrolls the next. func (v *View) autoscroll(gtx layout.Context, term *libghostty.Terminal) error { s := &v.sel if term == nil || !s.active || s.term != term || s.autoscroll == libghostty.SelectionGestureAutoscrollNone { return nil } if now := gtx.Now; now.Sub(s.lastTick) >= autoscrollEvery { s.lastTick = now if err := s.tick.SetPosition(s.lastPos); err != nil { return fmt.Errorf("autoscroll position: %w", err) } if err := s.tick.SetGeometry(s.lastGeom); err != nil { return fmt.Errorf("autoscroll geometry: %w", err) } if err := s.tick.SetViewport(s.lastCell); err != nil { return fmt.Errorf("autoscroll viewport: %w", err) } sel, err := s.gesture.Event(term, s.tick) if err != nil { return fmt.Errorf("autoscroll: %w", err) } if sel != nil { if err := term.SetSelection(sel); err != nil { return err } } if s.autoscroll, err = s.gesture.Autoscroll(term); err != nil { return err } } gtx.Execute(op.InvalidateCmd{At: gtx.Now.Add(autoscrollEvery)}) return nil } // wheel scrolls the scrollback, or passes the wheel to the program when it // reads the mouse, or is on the alternate screen, which has no scrollback. // Shift keeps the wheel on the scrollback. func (v *View) wheel(term *libghostty.Terminal, e pointer.Event, m metrics, pad int) error { v.scroll += e.Scroll.Y / float32(max(m.height, 1)) lines := int(v.scroll) if lines == 0 { return nil } v.scroll -= float32(lines) toProgram, err := programTakesWheel(term) if err != nil { return err } if toProgram && e.Modifiers&key.ModShift == 0 { if v.OnWheel != nil { c := gridCell(term, e, m, pad) v.OnWheel(uint16(c.X), uint16(c.Y), lines) } return nil } return term.ScrollViewportDelta(lines) } // programTakesWheel reports whether the program reads the mouse, or the // terminal is on the alternate screen. func programTakesWheel(term *libghostty.Terminal) (bool, error) { screen, err := term.ActiveScreen() if err != nil { return false, err } if screen == libghostty.ScreenAlternate { return true, nil } for _, mode := range []libghostty.Mode{ libghostty.ModeMouseEventX10, libghostty.ModeMouseEventNormal, libghostty.ModeMouseEventButton, libghostty.ModeMouseEventAny, } { if on, err := term.Mode(mode); err != nil { return false, err } else if on { return true, nil } } return false, nil } func (v *View) selectEvent(term *libghostty.Terminal, e pointer.Event, m metrics, pad int) error { s := &v.sel if err := s.ready(term); err != nil { return err } cols, err := term.Cols() if err != nil { return err } rows, err := term.Rows() if err != nil { return err } if cols == 0 || rows == 0 { return nil } ref, cell, err := cellAt(term, e.Position, m, pad, cols, rows) if err != nil { return err } pos := libghostty.SurfacePosition{X: float64(e.Position.X), Y: float64(e.Position.Y)} var event *libghostty.SelectionGestureEvent switch e.Kind { case pointer.Press: s.active = true event = s.press if err := event.SetTimeNS(uint64(e.Time)); err != nil { return fmt.Errorf("time: %w", err) } // A plain click clears the selection; a multi-click makes one. if err := term.SetSelection(nil); err != nil { return err } case pointer.Drag: if !s.active { return nil } event = s.drag s.lastGeom = libghostty.SelectionGestureGeometry{ Columns: uint32(cols), CellWidth: uint32(m.width), PaddingLeft: uint32(pad), ScreenHeight: uint32(int(rows)*m.height + 2*pad), } s.lastPos, s.lastCell = pos, cell if err := event.SetGeometry(s.lastGeom); err != nil { return fmt.Errorf("geometry: %w", err) } if err := event.SetRectangle(e.Modifiers&key.ModAlt != 0); err != nil { return fmt.Errorf("rectangle: %w", err) } case pointer.Release, pointer.Cancel: if !s.active { return nil } s.active = false s.autoscroll = libghostty.SelectionGestureAutoscrollNone event = s.release default: return nil } if err := event.SetRef(ref); err != nil { return fmt.Errorf("ref: %w", err) } // Press and drag events take the pointer's position; a release takes // only the cell. if event != s.release { if err := event.SetPosition(pos); err != nil { return fmt.Errorf("position: %w", err) } } sel, err := s.gesture.Event(term, event) if err != nil { return fmt.Errorf("%v event: %w", e.Kind, err) } if sel != nil { if err := term.SetSelection(sel); err != nil { return err } } switch event { case s.drag: if s.autoscroll, err = s.gesture.Autoscroll(term); err != nil { return err } case s.release: // A finished selection: a drag, or a double or triple click. if v.OnSelected != nil { if active, err := term.Selection(); err == nil && active != nil { v.OnSelected() } } } return nil } // cellAt returns the cell under a point in the view, clamped to the grid, // and its viewport coordinate. func cellAt(term *libghostty.Terminal, p f32.Point, m metrics, pad int, cols, rows uint16) (*libghostty.GridRef, libghostty.PointCoordinate, error) { x := min(max(floorDiv(int(p.X)-pad, max(m.width, 1)), 0), int(cols)-1) y := min(max(floorDiv(int(p.Y)-pad, max(m.height, 1)), 0), int(rows)-1) c := libghostty.PointCoordinate{X: uint16(x), Y: uint32(y)} ref, err := term.GridRef(libghostty.Point{Tag: libghostty.PointTagViewport, X: c.X, Y: c.Y}) return ref, c, err } // floorDiv divides rounding down, so that points left of or above the // grid land outside it. func floorDiv(a, b int) int { q := a / b if a%b != 0 && a < 0 { q-- } return q } // registerPointer makes the area of size receive mouse events for selection. func (v *View) registerPointer(gtx layout.Context, size image.Point) { defer clip.Rect{Max: size}.Push(gtx.Ops).Pop() pointer.CursorText.Add(gtx.Ops) event.Op(gtx.Ops, &v.sel) } // SelectionText returns the text of term's selection, or "" if there is // none. Lines a program's output wrapped are joined, and trailing space is // trimmed. func SelectionText(term *libghostty.Terminal) (string, error) { sel, err := term.Selection() if err != nil || sel == nil { return "", err } f, err := libghostty.NewFormatter(term, libghostty.WithFormatterSelection(sel), libghostty.WithFormatterUnwrap(true), libghostty.WithFormatterTrim(true), ) if err != nil { return "", err } defer f.Close() s, err := f.FormatString() return strings.TrimRight(s, "\n"), err }