// Package ui draws Rex servers in a Gio window, neo-brutalist: a title bar // with the session's tabs, a sidebar of hosts and their sessions, the // active window's panes as cards with headers, and a command palette. package ui import ( "context" "fmt" "image" "image/color" "io" "log" "math" "regexp" "slices" "strings" "sync" "time" "gioui.org/font" "gioui.org/font/gofont" "gioui.org/io/clipboard" "gioui.org/io/event" "gioui.org/io/pointer" "gioui.org/io/system" "gioui.org/io/transfer" "gioui.org/layout" "gioui.org/op" "gioui.org/op/clip" "gioui.org/text" "gioui.org/unit" "gioui.org/widget" "go.mitchellh.com/libghostty" "100gex/internal/glyph" "100gex/internal/keymap" "100gex/internal/rex" "100gex/internal/rexsession" "100gex/internal/termview" "100gex/internal/theme" "100gex/internal/workspace" ) // PrimarySelection is the desktop's primary selection, as package primary // provides it. type PrimarySelection interface { Set(text string) error Get(ctx context.Context) (string, error) } // tag identifies a widget to Gio's event routing, which tells handlers // apart by pointer. It is never empty: Go may give distinct variables of // size zero, such as two struct{} fields side by side, the same address, so // that two handlers would be one, and a click on a popup would reach the // backdrop that closes it. type tag struct{ _ byte } // DefaultFontSize is the size of the terminals' text until it is changed. const DefaultFontSize unit.Sp = 15 // UI draws a server's sessions and performs the actions its keys are bound // to. Its methods must be called from the goroutine that draws, except // HandleEvent. type UI struct { ws *workspace.Workspace session *rexsession.Session // shown now; nil if the server has none conn *rex.Conn notify func() theme *theme.Theme keys *termview.Keys glyphs *glyph.Rasterizer // draws every pane's characters, made with the first pane matcher *keymap.Matcher // FontSize is the size of the terminals' text. FontSize unit.Sp // TerminalTheme, if set, is asked of every terminal shown, on every // server switched to. TerminalTheme *rex.TerminalTheme // ShowFPS draws the latest frames' times in the title bar. Pass each // frame's cost to FrameDrawn for them. ShowFPS bool fps frameStats // Primary, if set, is the desktop's primary selection: selecting text // in a pane sets it, and a middle click pastes it. Primary PrimarySelection panes map[string]*paneView tabs map[string]*widget.Clickable newTab widget.Clickable commands widget.Clickable closeWindow widget.Clickable palette palette side sidebar menu hostMenu smenu sessionMenu lastPress image.Point // where the pointer last pressed, in the window shown sessionKey // the session shown last sessionKey // the session shown before it, for session.last pressTag tag serverActions map[string]rex.ActionInfo // the server's actions that keys can run bindings []rex.KeyBinding // what each key does, for showing wantPaste bool // read the clipboard and paste it wantCopy bool // copy the focused pane's selection wantSelectAll bool // select all of the focused pane pasteTag tag windowActions system.Action // asked of the window this frame // Where things were drawn, for tests. tabRects map[string]image.Rectangle tabDrag tabDrag // a press on a tab, and the drag it may become tabSlots []tabSlot // where the tabs were drawn last, in the strip paneDrag paneDrag // a press on a pane's header, and the drag it may become paneSlots []paneSlot // where the panes were drawn last, back to front panesArea image.Rectangle // where the active window's panes go // layerMoves are floating layers dropped somewhere the server hasn't // put them yet, by layer ID. layerMoves map[string]layerMove srv *server // the server shown; conn and ws are its servers []*server // every server connected to, in the order connected mu sync.Mutex // guards what other goroutines hand over closed bool keepHosts bool // connect to every host saved []rex.Host // the local server's hosts keepers map[string]*keeper // background connections being made, by target arrived []*server // made by keepers, to list watched *server // the server whose events count next *server // connected, waiting to be shown connecting *connecting paletteLoaded *paletteLoad // a list fetched for the palette paletteStatus *paletteStatus // news for the palette newKeymapConn *rex.Conn // the connection newKeymap came from newKeymap *keymap.Keymap newServerActions map[string]rex.ActionInfo newBindings []rex.KeyBinding keymapHash string queued []queuedAction } // paneView is the drawing state of one block. type paneView struct { view *termview.View // The header's buttons. splitRight, splitDown, float widget.Clickable } // New returns a UI for ws, whose connection is conn, drawing text with // shaper. notify is called from other goroutines when there is something new // to draw, and must not block. It starts with the built-in shortcuts, and // asks the server for the keymap the configuration file makes of them. func New(ws *workspace.Workspace, conn *rex.Conn, shaper *text.Shaper, notify func()) *UI { u := &UI{ ws: ws, conn: conn, notify: notify, theme: theme.New(shaper), keys: termview.NewKeys(), FontSize: DefaultFontSize, panes: make(map[string]*paneView), tabs: make(map[string]*widget.Clickable), bindings: defaultBindings(), tabRects: make(map[string]image.Rectangle), layerMoves: make(map[string]layerMove), } u.matcher = keymap.NewMatcher(localKeymap(), u.available) first := &server{conn: conn, ws: ws} u.setServer(first) u.servers = []*server{first} u.watched = first u.watch(first) go u.fetchKeymap(conn) go u.fetchServerDetails(first) return u } // Close frees the drawing state of every pane, and ends the connections to // every server, and to one still being switched to. func (u *UI) Close() { for id, p := range u.panes { p.view.Close() delete(u.panes, id) } u.mu.Lock() next := u.next u.next, u.connecting, u.watched = nil, nil, nil u.closed = true all := append(slices.Clone(u.servers), u.arrived...) u.arrived = nil u.mu.Unlock() if next != nil && !slices.Contains(all, next) { all = append(all, next) } for _, s := range all { if s != nil { s.ws.Close() s.conn.Close() } } } // Conn returns the connection to the server shown. It is safe to call from // any goroutine. func (u *UI) Conn() *rex.Conn { u.mu.Lock() defer u.mu.Unlock() if u.watched == nil { return nil } return u.watched.conn } // Title is the window's title: the session's label. func (u *UI) Title() string { if u.session == nil { return "100gex" } for _, s := range u.ws.Sessions() { if s.SessionID == u.session.ID() { return s.Label + " — 100gex" } } return "100gex" } // report tells people about a problem that doesn't stop the client. func (u *UI) report(err error) { log.Printf("ui: %v", err) } // Layout draws the window, filling gtx.Constraints.Max. It returns the // frame of the session it drew, and the actions the person asked of the // window, such as closing it, for the caller to perform. func (u *UI) Layout(gtx layout.Context) (rexsession.Frame, system.Action, error) { u.syncServer() u.syncHosts() u.trackPresses(gtx) u.updateCorner(gtx) u.mu.Lock() if u.newKeymap != nil { // A keymap fetched from a server since switched away from is // dropped. if u.newKeymapConn == u.conn { u.matcher.SetKeymap(u.newKeymap) u.serverActions, u.bindings = u.newServerActions, u.newBindings } u.newKeymap = nil } u.mu.Unlock() u.runQueued() u.session = u.ws.Sync() if u.session != nil { if k := (sessionKey{u.srv, u.session.ID()}); k != u.shown { u.last, u.shown = u.shown, k } } f, err := u.updateTerminals(gtx) if err != nil { return f, 0, err } // From here the frame draws what the panes took: the terminals are // their streams' again. size := gtx.Constraints.Max theme.Fill(gtx, theme.Cream, image.Rectangle{Max: size}) titlebar, sidebar := gtx.Dp(theme.TitlebarHigh), u.sidebarWide(gtx) if err := u.layoutWorkspace(gtx, f, image.Rect(sidebar, titlebar, size.X, size.Y)); err != nil { return f, 0, err } u.layoutSidebar(gtx, image.Rect(0, titlebar, sidebar, size.Y)) u.layoutTitlebar(gtx, f, image.Rect(0, 0, size.X, titlebar)) u.layoutPaneDrag(gtx, f) u.layoutHostMenu(gtx, u.hosts()) u.layoutSessionMenu(gtx) u.layoutPalette(gtx) u.layoutPressTracker(gtx) u.forgetPanes(f) actions := u.windowActions u.windowActions = 0 return f, actions, nil } // updateTerminals is the part of a frame that has the terminals. It holds // them, from Sync, while the keyboard, the clipboard and the mouse change // them and each pane shown takes what it draws, then lets them go: the // rest of the frame draws from what the panes took, and from the frame // returned, which holds no terminal. // // That is Ghostty's renderer's way: a terminal is held only to copy what // is drawn, and parsed into while it is drawn. Holding the terminals for // the whole frame stopped every pane's output for as long as the frame // took to draw, slow characters and all, rather than tens of microseconds. func (u *UI) updateTerminals(gtx layout.Context) (rexsession.Frame, error) { var f rexsession.Frame if u.session != nil { defer u.session.Release() var err error if f, err = u.session.Sync(); err != nil { return f, err } } // Typing goes to the focused block, wherever the pointer is, unless a // key binding or the palette takes it. u.keys.Layout(gtx, u.key, !u.palette.open && !u.renaming()) u.layoutPaste(gtx) for _, id := range f.Visible { if _, ok := f.Panes[id]; !ok { continue } p, err := u.paneView(id) if err != nil { return f, err } w := f.Window p.view.OnPress = func() { u.pressPane(w, id) } p.view.FontSize = u.FontSize if err := p.view.Update(gtx, u.session.Screen(id)); err != nil { return f, err } } return f, nil } // paneView returns a block's drawing state, made the first time it's shown. func (u *UI) paneView(blockID string) (*paneView, error) { if p := u.panes[blockID]; p != nil { return p, nil } if u.glyphs == nil { u.glyphs = termview.NewGlyphs(append(gofont.Collection(), theme.Fonts()...)) } v, err := termview.New(u.glyphs) if err != nil { return nil, err } v.FontSize = u.FontSize v.Padding = 6 v.SelectionFg, v.SelectionBg = theme.Ink, theme.Lavender v.OnResize = func(cols, rows uint16, cellWidth, cellHeight int) { if u.session != nil { u.session.RequestSize(blockID, cols, rows, cellWidth, cellHeight) } } v.OnSelected = func(text string) { if u.Primary == nil { return } go func() { if err := u.Primary.Set(text); err != nil { u.report(err) } }() } v.OnMiddleClick = func() { if u.Primary == nil || u.session == nil { return } s := u.session go func() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() text, err := u.Primary.Get(ctx) if err != nil { u.report(err) return } if text != "" { s.PasteTo(blockID, text) } }() } v.OnMouse = func(e rex.MouseEvent) { if u.session != nil { u.session.Mouse(blockID, e) } } v.OnWheel = func(col, row uint16, lines int) { if u.session != nil { u.session.Wheel(blockID, col, row, lines) } } p := &paneView{view: v} u.panes[blockID] = p return p, nil } // pressPane acts on a press anywhere on a block's card, in window w: it // takes the block, as typing in it would, since the person is using it // here. It also focuses the block if it isn't, and brings its layer to the // front if it floats behind another. The window gaining focus does none of // this. func (u *UI) pressPane(w *rex.Window, blockID string) { if u.session == nil { return } u.session.Claim(blockID) if w == nil { return } if w.ZoomedBlockID != blockID && w.FocusedBlockID != blockID { u.session.FocusBlock(blockID) } if layer, front := floatingLayer(w, blockID); layer != "" && !front { u.session.RaiseLayer(layer) } } // floatingLayer returns the floating layer of w that holds blockID, or "" // if it's tiled, and whether that layer is in front of the others. func floatingLayer(w *rex.Window, blockID string) (layer string, front bool) { last := "" for _, l := range w.Layers { if l.Kind == "tiled" { continue } last = l.LayerID if hasBlock(l, blockID) { layer = l.LayerID } } return layer, layer != "" && layer == last } // key acts on one key press: a binding takes it, or it goes to the focused // block. func (u *UI) key(k rex.KeyEvent) { r := u.matcher.Key(k) switch r.Outcome { case keymap.Pass: if u.session != nil { // Typing into a pane clears its selection, and goes back to // the bottom of its scrollback, as in Ghostty. if term := u.focusedTerm(); term != nil { _ = term.SetSelection(nil) _ = term.ScrollViewportBottom() } u.session.Key(k) } case keymap.Run: if err := u.perform(r.Binding.Action, r.Binding.Args, &k, r.Prefix); err != nil { u.report(err) } } } // focusedTerm returns the focused block's terminal, or nil. It is only // there while the frame holds the terminals: see updateTerminals. func (u *UI) focusedTerm() *libghostty.Terminal { if u.session == nil { return nil } return u.session.Terminal(u.session.FocusedBlock()) } // selectAll selects everything in the focused block. func (u *UI) selectAll() error { term := u.focusedTerm() if term == nil { return nil } sel, err := term.SelectAll() if err != nil || sel == nil { return err } return term.SetSelection(sel) } // selectionText returns the text selected in the focused block, or "". func (u *UI) selectionText() string { term := u.focusedTerm() if term == nil { return "" } text, err := termview.SelectionText(term) if err != nil { u.report(err) } return text } // layoutPaste reads the clipboard when pane.paste asks, and pastes what // arrives into the focused block. func (u *UI) layoutPaste(gtx layout.Context) { for { ev, ok := gtx.Event(transfer.TargetFilter{Target: &u.pasteTag, Type: "application/text"}) if !ok { break } if e, ok := ev.(transfer.DataEvent); ok { r := e.Open() data, err := io.ReadAll(io.LimitReader(r, 16<<20)) r.Close() if err == nil && len(data) > 0 && u.session != nil { u.session.Paste(string(data)) } } } area := clip.Rect{Max: gtx.Constraints.Max}.Push(gtx.Ops) event.Op(gtx.Ops, &u.pasteTag) area.Pop() if u.wantPaste { u.wantPaste = false gtx.Execute(clipboard.ReadCmd{Tag: &u.pasteTag}) } if u.wantSelectAll { u.wantSelectAll = false if err := u.selectAll(); err != nil { u.report(err) } } if u.wantCopy { u.wantCopy = false if text := u.selectionText(); text != "" { gtx.Execute(clipboard.WriteCmd{Type: "application/text", Data: io.NopCloser(strings.NewReader(text))}) } } } // keyState describes an unfinished key sequence or the active modes, or // returns "". func (u *UI) keyState() string { if p := u.matcher.Pending(); len(p) > 0 { return spell(p) + " …" } if m := u.matcher.Modes(); len(m) > 0 { return strings.Join(m, " › ") } return "" } // moveArea makes the area of gtx.Constraints.Max drag the window. func moveArea(gtx layout.Context) layout.Dimensions { size := gtx.Constraints.Max defer clip.Rect{Max: size}.Push(gtx.Ops).Pop() system.ActionInputOp(system.ActionMove).Add(gtx.Ops) return layout.Dimensions{Size: size} } // at runs w with its origin at r.Min and constraints exactly r's size. func at(gtx layout.Context, r image.Rectangle, w layout.Widget) { defer op.Offset(r.Min).Push(gtx.Ops).Pop() gtx.Constraints = layout.Exact(r.Size()) w(gtx) } // layoutTitlebar draws the sidebar's corner, a tab for each window, and // the window's buttons. Empty space drags the window. func (u *UI) layoutTitlebar(gtx layout.Context, f rexsession.Frame, r image.Rectangle) { border := gtx.Dp(theme.Border) sidebar := u.sidebarWide(gtx) theme.Fill(gtx, theme.White, r) theme.Fill(gtx, theme.Ink, image.Rect(r.Min.X, r.Max.Y-border, r.Max.X, r.Max.Y)) theme.Fill(gtx, theme.Ink, image.Rect(sidebar-border, r.Min.Y, sidebar, r.Max.Y)) // The sidebar's corner: its toggle and the session switcher. at(gtx, image.Rect(0, 0, sidebar-border, r.Max.Y-border), u.layoutCorner) if u.closeWindow.Clicked(gtx) { u.windowActions |= system.ActionClose } if u.newTab.Clicked(gtx) { u.perform("client.tab.new", nil, nil, nil) } if u.commands.Clicked(gtx) { u.palette.toggle(paletteCommands) } gap := tabGap children := []layout.FlexChild{layout.Rigid(layout.Spacer{Width: theme.Gap}.Layout)} var crumb layout.Dimensions if u.side.collapsed { // With the sidebar collapsed, the bar says where the window is. children = append(children, layout.Rigid(func(gtx layout.Context) layout.Dimensions { crumb = u.breadcrumb(gtx) crumb.Size.X += gtx.Dp(theme.Gap) return crumb })) } children = append(children, layout.Rigid(func(gtx layout.Context) layout.Dimensions { // The strip is the bar's height, so that the bar's other // buttons are centred beside it. gtx.Constraints.Min.Y = gtx.Constraints.Max.Y dims := u.layoutTabs(gtx, f, image.Pt(sidebar+gtx.Dp(theme.Gap)+crumb.Size.X, 0)) if dims.Size.X > 0 { dims.Size.X += gtx.Dp(gap) } return dims }), ) if f.Window != nil { children = append(children, layout.Rigid(theme.Button{Theme: u.theme, Clickable: &u.newTab, Label: "+"}.Layout)) } children = append(children, layout.Flexed(1, moveArea)) if state := u.keyState(); state != "" { children = append(children, layout.Rigid(func(gtx layout.Context) layout.Dimensions { return theme.Box{Fill: theme.Yellow, Padding: layout.Inset{Top: 3, Bottom: 3, Left: 10, Right: 10}}.Layout(gtx, u.theme.Label(13, state, theme.Ink, font.Bold).Layout) }), layout.Rigid(layout.Spacer{Width: gap}.Layout), ) } if u.ShowFPS { children = append(children, layout.Rigid(u.layoutFPS), layout.Rigid(layout.Spacer{Width: gap}.Layout)) } children = append(children, layout.Rigid(theme.Button{Theme: u.theme, Clickable: &u.commands, Label: "Commands"}.Layout), layout.Rigid(layout.Spacer{Width: gap}.Layout), layout.Rigid(theme.Button{Theme: u.theme, Clickable: &u.closeWindow, Label: "✕"}.Layout), layout.Rigid(layout.Spacer{Width: theme.Gap}.Layout), ) at(gtx, image.Rect(sidebar, 0, r.Max.X, r.Max.Y-border), func(gtx layout.Context) layout.Dimensions { // Buttons keep their own height, centred in the bar. gtx.Constraints.Min = image.Point{} return layout.Flex{Alignment: layout.Middle}.Layout(gtx, children...) }) } // defaultWindowLabel matches the labels the server gives windows, such as // Window 9673f63a, which say nothing to people. var defaultWindowLabel = regexp.MustCompile(`^Window [0-9a-f]{8}$`) // tabLabel is what a window's tab says: its label, unless it's the // server's default, in which case it shows the title of the program in its // focused block, or its position until that's known. func (u *UI) tabLabel(f rexsession.Frame, w *rex.Window, i int) string { if w.Label != "" && !defaultWindowLabel.MatchString(w.Label) { return w.Label } focused := w.FocusedBlockID if w.ZoomedBlockID != "" { focused = w.ZoomedBlockID } if t := programTitle(f, focused); t != "" { return truncate(t, 32) } return fmt.Sprintf("Tab %d", i+1) } // programTitle is the title the program in a block set, or "": from its // terminal, if it has a pane, else as the server reported it. func programTitle(f rexsession.Frame, blockID string) string { if p, ok := f.Panes[blockID]; ok && p.Restored { return strings.TrimSpace(p.Title) } return strings.TrimSpace(f.Titles[blockID]) } func truncate(s string, n int) string { r := []rune(s) if len(r) <= n { return s } return string(r[:n-1]) + "…" } // paneTitle is the title a block's program set, else the block's label. func paneTitle(f rexsession.Frame, blockID string) string { if t := programTitle(f, blockID); t != "" { return t } if f.Window != nil { if b := f.Window.Block(blockID); b != nil && b.Label != "" { return b.Label } } return "Terminal" } // layoutWorkspace draws the active window's blocks in area: the zoomed // block alone, or each layer's layout, back to front, as cards. func (u *UI) layoutWorkspace(gtx layout.Context, f rexsession.Frame, area image.Rectangle) error { defer clip.Rect(area).Push(gtx.Ops).Pop() gap, shadow := gtx.Dp(theme.Gap), gtx.Dp(theme.Shadow) u.paneSlots = u.paneSlots[:0] // Room for the outermost cards' shadows inside the padding. inner := image.Rect(area.Min.X+gap, area.Min.Y+gap, area.Max.X-gap-shadow, area.Max.Y-gap-shadow) u.panesArea = inner w := f.Window if w == nil { at(gtx, inner, func(gtx layout.Context) layout.Dimensions { msg := "No session. Make one with New session." if u.session != nil { msg = "This session has no windows." } return layout.Center.Layout(gtx, u.theme.Label(15, msg, theme.Muted, font.Normal).Layout) }) return nil } if w.ZoomedBlockID != "" { return u.layoutPane(gtx, f, w.ZoomedBlockID, inner, true, nil, theme.Shadow) } front := "" for _, l := range w.Layers { if l.Kind != "tiled" { front = l.LayerID } } for _, l := range w.Layers { if l.State == "minimized" || l.Layout == nil { continue } // Tiled panes are dragged by their headers to other places; // floating ones move their layer, drawn where it's being dragged // to. bounds, depth, offset := inner, theme.Shadow, image.Point{} var fl *floatLayer if l.Kind != "tiled" { bounds, depth = place(l.Bounds, inner, inner, 0), theme.ShadowLarge fl = &floatLayer{id: l.LayerID, bounds: u.layerBounds(l), front: l.LayerID == front} offset = place(fl.bounds, inner, inner, 0).Min.Sub(bounds.Min) } for _, leaf := range leaves(l.Layout, nil) { r := place(leaf.Rect, inner, bounds, gap).Intersect(bounds).Add(offset) if err := u.layoutPane(gtx, f, leaf.BlockID, r, leaf.BlockID == w.FocusedBlockID, fl, depth); err != nil { return err } } } return nil } // leaves appends the blocks under n, in layout order. func leaves(n *rex.LayoutNode, out []*rex.LayoutNode) []*rex.LayoutNode { if n == nil { return out } if n.Split != nil { return leaves(n.Split.After, leaves(n.Split.Before, out)) } if n.BlockID != "" { out = append(out, n) } return out } // place turns a rect given as fractions of the window into pixels within // area. Edges are rounded on their own, so neighbours line up exactly. // Wherever the rect doesn't reach the edge of bounds, the layer it is in, // it gives up half of gap, so that neighbours are gap apart. func place(frac [4]float64, area, bounds image.Rectangle, gap int) image.Rectangle { w, h := float64(area.Dx()), float64(area.Dy()) r := image.Rect( area.Min.X+int(math.Round(frac[0]*w)), area.Min.Y+int(math.Round(frac[1]*h)), area.Min.X+int(math.Round((frac[0]+frac[2])*w)), area.Min.Y+int(math.Round((frac[1]+frac[3])*h)), ) half := gap / 2 if r.Min.X > bounds.Min.X { r.Min.X += half } if r.Min.Y > bounds.Min.Y { r.Min.Y += half } if r.Max.X < bounds.Max.X { r.Max.X -= gap - half } if r.Max.Y < bounds.Max.Y { r.Max.Y -= gap - half } return r.Intersect(area) } // layoutPane draws one block as a card at r: a header with its title, and // its terminal. Dragging its header moves it: to another place in the // layout, or, if it is in floating layer fl, the layer. func (u *UI) layoutPane(gtx layout.Context, f rexsession.Frame, blockID string, r image.Rectangle, focused bool, fl *floatLayer, shadow unit.Dp) error { border, header := gtx.Dp(theme.Border), gtx.Dp(28) if r.Dx() < 4*border || r.Dy() < header+4*border { return nil } p, err := u.paneView(blockID) if err != nil { return err } theme.Card(gtx, r, theme.White, shadow) u.paneSlots = append(u.paneSlots, paneSlot{block: blockID, rect: r}) // A press on the header acts as one on the terminal does, which // reports it through OnPress: see pressPane. Dragging the header // moves the pane: see paneHeaderEvent. for { ev, ok := gtx.Event(pointer.Filter{Target: p, Kinds: pointer.Press | pointer.Drag | pointer.Release | pointer.Cancel}) if !ok { break } e, ok := ev.(pointer.Event) if !ok { continue } if e.Kind == pointer.Press { u.pressPane(f.Window, blockID) } u.paneHeaderEvent(gtx, p, blockID, fl, e) } hr := image.Rect(r.Min.X+border, r.Min.Y+border, r.Max.X-border, r.Min.Y+border+header) area := clip.Rect(image.Rect(r.Min.X, r.Min.Y, r.Max.X, hr.Max.Y+border)).Push(gtx.Ops) event.Op(gtx.Ops, p) area.Pop() // The header: purple while typing goes here. fill, fg := theme.Cream, theme.Ink if focused { fill, fg = theme.Purple, theme.White } theme.Fill(gtx, fill, hr) theme.Fill(gtx, theme.Ink, image.Rect(hr.Min.X, hr.Max.Y, hr.Max.X, hr.Max.Y+border)) pf := f.Panes[blockID] floating, dockable := floatState(f.Window, blockID) if u.session != nil { if p.splitRight.Clicked(gtx) { u.session.SplitBlock(blockID, "right") } if p.splitDown.Clicked(gtx) { u.session.SplitBlock(blockID, "down") } if p.float.Clicked(gtx) { if floating { u.session.DockBlock(blockID) } else { u.session.FloatBlock(blockID) } } } at(gtx, hr, func(gtx layout.Context) layout.Dimensions { // The row is centred in the header, at its own height, so that // badges don't stretch to the header's. return layout.W.Layout(gtx, func(gtx layout.Context) layout.Dimensions { // W only frees the width; the row must be free to be shorter // than the header too, or Flex puts it at the top. gtx.Constraints.Min = image.Pt(gtx.Constraints.Max.X, 0) return u.paneHeaderRow(gtx, f, pf, p, blockID, fg, focused, floating, dockable) }) }) body := image.Rect(r.Min.X+border, hr.Max.Y+border, r.Max.X-border, r.Max.Y-border) if body.Empty() { return nil } at(gtx, body, func(gtx layout.Context) layout.Dimensions { defer clip.Rect{Max: body.Size()}.Push(gtx.Ops).Pop() p.view.FontSize = u.FontSize p.view.Focused = focused var dims layout.Dimensions dims, err = p.view.Layout(gtx) return dims }) return err } // floatState reports whether a block is in one of w's floating layers, and // if so whether w's layout has a block for it to dock beside. func floatState(w *rex.Window, blockID string) (floating, dockable bool) { if w == nil { return false, false } for _, l := range w.Layers { if l.Kind == "tiled" { dockable = len(leaves(l.Layout, nil)) > 0 } else if hasBlock(l, blockID) { floating = true } } return floating, floating && dockable } func hasBlock(l rex.Layer, blockID string) bool { for _, b := range l.Blocks { if b.BlockID == blockID { return true } } return false } // paneHeaderRow lays out a pane header's title, badges, and buttons: split // beside, split below, and float, or dock for a floating pane. func (u *UI) paneHeaderRow(gtx layout.Context, f rexsession.Frame, pf rexsession.PaneFrame, p *paneView, blockID string, fg color.NRGBA, focused, floating, dockable bool) layout.Dimensions { return layout.Inset{Left: 10, Right: 8}.Layout(gtx, func(gtx layout.Context) layout.Dimensions { var badges []layout.FlexChild badge := func(s string) { badges = append(badges, layout.Rigid(func(gtx layout.Context) layout.Dimensions { return layout.Inset{Left: 6}.Layout(gtx, func(gtx layout.Context) layout.Dimensions { return theme.Tag(gtx, u.theme, s, theme.Yellow, theme.Ink) }) })) } if f.Window != nil && f.Window.ZoomedBlockID == blockID { badge("ZOOMED") } if pf.State.Owner != "" && !pf.State.Owned { badge("SIZED ELSEWHERE") } if pf.State.Exited { badge("EXITED") } children := append([]layout.FlexChild{ layout.Flexed(1, func(gtx layout.Context) layout.Dimensions { weight := font.SemiBold if focused { weight = font.Bold } return u.theme.Label(13, paneTitle(f, blockID), fg, weight).Layout(gtx) }), }, badges...) button := func(c *widget.Clickable, icon theme.Icon, left unit.Dp) layout.FlexChild { return layout.Rigid(func(gtx layout.Context) layout.Dimensions { return layout.Inset{Left: left}.Layout(gtx, theme.IconButton{Clickable: c, Icon: icon}.Layout) }) } children = append(children, button(&p.splitRight, theme.IconSplitRight, 10), button(&p.splitDown, theme.IconSplitDown, 4), ) switch { case !floating: children = append(children, button(&p.float, theme.IconFloat, 4)) case dockable: children = append(children, button(&p.float, theme.IconDock, 4)) } return layout.Flex{Alignment: layout.Middle}.Layout(gtx, children...) }) } // forgetPanes frees the drawing state of blocks that are no longer shown. func (u *UI) forgetPanes(f rexsession.Frame) { for id, p := range u.panes { if _, ok := f.Panes[id]; !ok { p.view.Close() delete(u.panes, id) } } }