package ui import ( "context" "fmt" "image" "net" "os" "strconv" "strings" "time" "gioui.org/font" "gioui.org/io/event" "gioui.org/io/pointer" "gioui.org/layout" "gioui.org/op" "gioui.org/op/clip" "gioui.org/widget" "100gex/internal/hosts" "100gex/internal/sshtunnel" "100gex/internal/theme" ) // hostMenu is the card a right click on a host's heading opens: the // server's details, and what can be done with the host. type hostMenu struct { open bool key string // the host's hostEntry.key at image.Point backdrop tag card tag newSession, retry, remove widget.Clickable confirmRemove bool // remove was clicked once } // fetchServerDetails asks a server for what its menu shows that bootstrap // didn't say. func (u *UI) fetchServerDetails(s *server) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() v, verr := s.conn.ServerVersion(ctx) who, werr := s.conn.ServerWhoami(ctx) u.mu.Lock() defer u.mu.Unlock() if verr == nil { s.version = v.RexVersion } if werr == nil { s.account = who.Account } u.notify() } // serverName is what to call the server shown, as name says. func (u *UI) serverName() (name, where string) { return u.srv.name() } // name is what to call a server: the label it was reached by, as rex hosts // lists it, else this machine's name for a local socket, else the first // part of its host's name, such as studio for studio.tail1234.ts.net. func (srv *server) name() (name, where string) { ep := srv.ws.Endpoint() where = "remote" if ep.Local() { where = "local" } switch { case srv.label != "": name = srv.label case ep.Via != "": if a, err := sshtunnel.Parse(ep.Via); err == nil { name, _, _ = strings.Cut(a.Host(), ".") } case ep.Local(): name, _ = os.Hostname() case net.ParseIP(ep.Host) != nil: name = ep.Host default: name, _, _ = strings.Cut(ep.Host, ".") } if name == "" { name = "Rex server" } return name, where } // connected reports whether the control connection is up. func (u *UI) connected() bool { return u.conn.Err() == nil } // uptime spells how long ago t was, briefly: 45s, 12m, 5h, 3d. func uptime(t, now time.Time) string { d := now.Sub(t) switch { case d < time.Minute: return strconv.Itoa(max(int(d.Seconds()), 0)) + "s" case d < time.Hour: return strconv.Itoa(int(d.Minutes())) + "m" case d < 48*time.Hour: return strconv.Itoa(int(d.Hours())) + "h" } return strconv.Itoa(int(d.Hours()/24)) + "d" } // openHostMenu opens a host's menu where the pointer last pressed. func (u *UI) openHostMenu(e hostEntry) { u.menu = hostMenu{open: true, key: e.key, at: u.lastPress} } // serverRow is a label and value on a host's menu. type serverRow struct{ label, value string } // detailRows are what a host's menu says about it. func (u *UI) detailRows(e hostEntry, now time.Time) []serverRow { type row = serverRow var rows []row switch e.state { case hostOnline: rows = append(rows, row{"Connection", "Connected"}) case hostConnecting: rows = append(rows, row{"Connection", "Connecting…"}) case hostOffline: value := "couldn't connect" if e.err != nil { value += ": " + e.err.Error() } rows = append(rows, row{"Connection", value}) default: rows = append(rows, row{"Connection", "Not connected"}) } if e.srv == nil { if e.host != nil && len(e.host.Endpoints) > 0 { rows = append(rows, row{"Address", strings.Join(e.host.Endpoints, ", ")}) } return rows } s := e.srv st := s.ws.Status() u.mu.Lock() version, account := s.version, s.account u.mu.Unlock() rows = append(rows, row{"Address", s.ws.Endpoint().String()}) if version != "" { rows = append(rows, row{"Version", version}) } rows = append(rows, row{"API revision", strconv.Itoa(s.conn.Welcome().APIRevision)}) if t, err := time.Parse(time.RFC3339, st.StartedAt); err == nil { rows = append(rows, row{"Running for", uptime(t, now) + ", since " + t.Local().Format("2 Jan 15:04")}) } rows = append(rows, row{"Sessions", strconv.Itoa(len(s.ws.Sessions()))}) if account != "" { rows = append(rows, row{"Runs as", account}) } tailscale := "Off" if st.Tailscale.State != "" && st.Tailscale.State != "disabled" { tailscale = st.Tailscale.State if st.Tailscale.DNSName != "" { tailscale += " · " + st.Tailscale.DNSName } } return append(rows, row{"Tailscale", tailscale}) } // layoutHostMenu draws the open host menu. A click outside closes it. func (u *UI) layoutHostMenu(gtx layout.Context, entries []hostEntry) { m := &u.menu if !m.open { return } var e *hostEntry for i := range entries { if entries[i].key == m.key { e = &entries[i] } } if e == nil { m.open = false // the host is gone return } for { ev, ok := gtx.Event(pointer.Filter{Target: &m.backdrop, Kinds: pointer.Press}) if !ok { break } if _, ok := ev.(pointer.Event); ok { m.open = false return } } if m.newSession.Clicked(gtx) && e.srv != nil { m.open = false u.newSessionOn(e.srv) return } if m.retry.Clicked(gtx) { m.open = false u.retryHost(e.target) return } if m.remove.Clicked(gtx) && e.host != nil { if !m.confirmRemove { m.confirmRemove = true } else { m.open = false u.removeHost(*e) return } } size := gtx.Constraints.Max backdrop := clip.Rect{Max: size}.Push(gtx.Ops) event.Op(gtx.Ops, &m.backdrop) backdrop.Pop() gtx.Constraints.Min = image.Point{} gtx.Constraints.Max.X = gtx.Dp(360) // Draw it off screen first, to know its size, then where it fits. rec := op.Record(gtx.Ops) dims := opaque(gtx, &m.card, func(gtx layout.Context) layout.Dimensions { return theme.Box{Fill: theme.White, Shadow: theme.ShadowLarge, Padding: layout.UniformInset(16)}.Layout(gtx, u.hostMenuBody(*e, gtx.Now)) }) call := rec.Stop() pos := m.at.Add(image.Pt(gtx.Dp(4), gtx.Dp(4))) pos.X = max(0, min(pos.X, size.X-dims.Size.X-gtx.Dp(8))) pos.Y = max(0, min(pos.Y, size.Y-dims.Size.Y-gtx.Dp(8))) defer op.Offset(pos).Push(gtx.Ops).Pop() call.Add(gtx.Ops) } // hostMenuBody lays out a host menu's contents. func (u *UI) hostMenuBody(e hostEntry, now time.Time) layout.Widget { m := &u.menu rows := u.detailRows(e, now) where := "remote" switch { case e.local: where = "this machine" case e.srv != nil: _, where = e.srv.name() } return func(gtx layout.Context) layout.Dimensions { children := []layout.FlexChild{ layout.Rigid(func(gtx layout.Context) layout.Dimensions { return theme.Highlighted(gtx, u.theme.Display(20, e.name, theme.Ink)) }), layout.Rigid(func(gtx layout.Context) layout.Dimensions { return layout.Inset{Top: 2, Bottom: 12}.Layout(gtx, u.theme.Label(12, fmt.Sprintf("Rex server, %s", where), theme.Muted, font.Medium).Layout) }), } for _, r := range rows { children = append(children, layout.Rigid(func(gtx layout.Context) layout.Dimensions { return layout.Inset{Bottom: 6}.Layout(gtx, func(gtx layout.Context) layout.Dimensions { return layout.Flex{Alignment: layout.Baseline}.Layout(gtx, layout.Rigid(func(gtx layout.Context) layout.Dimensions { gtx.Constraints.Min.X = gtx.Dp(100) return u.theme.Label(12, r.label, theme.Muted, font.Medium).Layout(gtx) }), layout.Flexed(1, func(gtx layout.Context) layout.Dimensions { c := theme.Ink if strings.HasPrefix(r.value, "couldn't") { c = theme.Red } l := u.theme.Label(13, r.value, c, font.SemiBold) l.MaxLines = 3 return l.Layout(gtx) }), ) }) })) } var buttons []layout.FlexChild button := func(c *widget.Clickable, label string, kind theme.ButtonKind) { if len(buttons) > 0 { buttons = append(buttons, layout.Rigid(layout.Spacer{Width: 8}.Layout)) } buttons = append(buttons, layout.Rigid(theme.Button{Theme: u.theme, Clickable: c, Label: label, Kind: kind}.Layout)) } if e.state == hostOnline { button(&m.newSession, "New session", theme.Primary) } if e.state == hostOffline || e.state == hostIdle { button(&m.retry, "Try again", theme.Primary) } if e.host != nil { label := "Remove host" if m.confirmRemove { label = "Really remove?" } button(&m.remove, label, theme.Plain) } if len(buttons) > 0 { children = append(children, layout.Rigid(func(gtx layout.Context) layout.Dimensions { return layout.Inset{Top: 8}.Layout(gtx, func(gtx layout.Context) layout.Dimensions { return layout.Flex{}.Layout(gtx, buttons...) }) })) } return layout.Flex{Axis: layout.Vertical}.Layout(gtx, children...) } } // removeHost takes a saved host off the local server's list, and stops // connecting to it. A connection to it stays, listed by its server's name, // until it ends. func (u *UI) removeHost(e hostEntry) { u.mu.Lock() delete(u.keepers, e.target) u.mu.Unlock() go func() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := hosts.Remove(ctx, e.host.ID); err != nil { u.report(fmt.Errorf("remove host %s: %w", e.name, err)) } u.fetchSaved() }() } // opaque lays out w, and keeps presses on it from reaching what's beneath, // such as a backdrop that closes it: tag becomes a handler for them, under // w's own. A tag nobody asks for events for isn't a handler, and lets // presses through. func opaque(gtx layout.Context, tag event.Tag, w layout.Widget) layout.Dimensions { for { if _, ok := gtx.Event(pointer.Filter{Target: tag, Kinds: pointer.Press}); !ok { break } } m := op.Record(gtx.Ops) dims := w(gtx) call := m.Stop() defer clip.Rect{Max: dims.Size}.Push(gtx.Ops).Pop() event.Op(gtx.Ops, tag) call.Add(gtx.Ops) return dims } // trackPresses notes where the pointer last pressed, in the window, so // that a menu a press opens appears beside it. func (u *UI) trackPresses(gtx layout.Context) { for { ev, ok := gtx.Event(pointer.Filter{Target: &u.pressTag, Kinds: pointer.Press}) if !ok { break } if e, ok := ev.(pointer.Event); ok { u.lastPress = e.Position.Round() } } } // layoutPressTracker covers the window with a handler for presses that // lets them through to what's beneath. It goes last, on top. func (u *UI) layoutPressTracker(gtx layout.Context) { defer clip.Rect{Max: gtx.Constraints.Max}.Push(gtx.Ops).Pop() defer pointer.PassOp{}.Push(gtx.Ops).Pop() event.Op(gtx.Ops, &u.pressTag) }