diff --git a/internal/ui/actions.go b/internal/ui/actions.go index f5dad31..e41bac1 100644 --- a/internal/ui/actions.go +++ b/internal/ui/actions.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "log" + "slices" "sort" "time" @@ -151,6 +152,18 @@ var actions = func() map[string]action { u.switchSession(-1) return nil }, true}, + {info("session.last", "Go to Last Session", "Session"), func(u *UI, _ actionArgs) error { + u.lastSession() + return nil + }, true}, + {info("session.goto", "Go to Session", "Session"), func(u *UI, a actionArgs) error { + u.gotoSession(a.Index) + return nil + }, true}, + {info("session.rename", "Rename Session…", "Session"), func(u *UI, _ actionArgs) error { + u.startRename(sessionKey{u.srv, u.session.ID()}) + return nil + }, false}, {info("client.close", "Close", "Window"), func(u *UI, _ actionArgs) error { u.session.ClosePane() return nil @@ -299,6 +312,16 @@ func defaultBindings() []rex.KeyBinding { bind("ctrl+shift+p", "client.palette.toggle", nil), bind("ctrl+shift+k", "session.switch", nil), bind("ctrl+shift+n", "session.new", nil), + bind("ctrl+shift+l", "session.last", nil), + bind("ctrl+alt+1", "session.goto", map[string]any{"index": 1}), + bind("ctrl+alt+2", "session.goto", map[string]any{"index": 2}), + bind("ctrl+alt+3", "session.goto", map[string]any{"index": 3}), + bind("ctrl+alt+4", "session.goto", map[string]any{"index": 4}), + bind("ctrl+alt+5", "session.goto", map[string]any{"index": 5}), + bind("ctrl+alt+6", "session.goto", map[string]any{"index": 6}), + bind("ctrl+alt+7", "session.goto", map[string]any{"index": 7}), + bind("ctrl+alt+8", "session.goto", map[string]any{"index": 8}), + bind("ctrl+alt+9", "session.goto", map[string]any{"index": 9}), bind("ctrl+=", "client.font.increase", nil), bind("ctrl+shift+=", "client.font.increase", nil), bind("ctrl+-", "client.font.decrease", nil), @@ -524,17 +547,57 @@ func spell(keys []string) string { return out } +// allSessions lists the sessions on every host connected to, in the +// sidebar's order. +func (u *UI) allSessions() []sessionKey { + var list []sessionKey + for _, e := range u.hosts() { + if e.srv == nil || e.state != hostOnline { + continue + } + for _, s := range e.srv.ws.Sessions() { + list = append(list, sessionKey{e.srv, s.SessionID}) + } + } + return list +} + // switchSession shows the session before or after the current one, in the -// server's order, wrapping round. +// sidebar's order, across hosts, wrapping round. func (u *UI) switchSession(step int) { - list := u.ws.Sessions() + list := u.allSessions() if len(list) < 2 || u.session == nil { return } - for i, s := range list { - if s.SessionID == u.session.ID() { - u.ws.Switch(list[(i+step+len(list))%len(list)].SessionID) + cur := sessionKey{u.srv, u.session.ID()} + for i, k := range list { + if k == cur { + next := list[(i+step+len(list))%len(list)] + u.switchTo(next.srv, next.id) return } } } + +// gotoSession shows the session at a 1-based position in the sidebar's +// order, or the last with -1. +func (u *UI) gotoSession(position int) { + list := u.allSessions() + if position == -1 { + position = len(list) + } + if position < 1 || position > len(list) { + return + } + k := list[position-1] + u.switchTo(k.srv, k.id) +} + +// lastSession goes back to the session shown before this one, on any host. +func (u *UI) lastSession() { + k := u.last + if k.srv == nil || !slices.Contains(u.servers, k.srv) { + return + } + u.switchTo(k.srv, k.id) +} diff --git a/internal/ui/palette.go b/internal/ui/palette.go index 6c8b733..6a4b639 100644 --- a/internal/ui/palette.go +++ b/internal/ui/palette.go @@ -99,7 +99,7 @@ func (p *palette) close() { func (u *UI) commandItems() []paletteItem { var items []paletteItem for _, a := range actions { - if a.Args != nil || a.Name == "client.tab.goto" || a.Name == "pane.send_key" || strings.HasPrefix(a.Name, "client.mode.enter") { + if a.Args != nil || a.Name == "client.tab.goto" || a.Name == "session.goto" || a.Name == "pane.send_key" || strings.HasPrefix(a.Name, "client.mode.enter") { continue // needs arguments the palette can't ask for } items = append(items, paletteItem{title: a.Title, detail: a.Category, keys: u.keysFor(a.Name), action: a.Name}) diff --git a/internal/ui/sessionmenu.go b/internal/ui/sessionmenu.go new file mode 100644 index 0000000..111b01b --- /dev/null +++ b/internal/ui/sessionmenu.go @@ -0,0 +1,233 @@ +package ui + +import ( + "context" + "fmt" + "image" + "strings" + "time" + + "gioui.org/font" + "gioui.org/io/event" + "gioui.org/io/key" + "gioui.org/io/pointer" + "gioui.org/layout" + "gioui.org/op" + "gioui.org/op/clip" + "gioui.org/widget" + "gioui.org/widget/material" + + "100gex/internal/theme" +) + +// sessionMenu is the card a right click on a session's row opens. +type sessionMenu struct { + open bool + key sessionKey + at image.Point + backdrop tag + card tag + rename widget.Clickable + close widget.Clickable + confirmClose bool // close was clicked once +} + +// sessionWidgets are the handlers of a session's row. +type sessionWidgets struct { + click widget.Clickable + menu tag // right clicks +} + +func (u *UI) sessionWidgets(k sessionKey) *sessionWidgets { + if u.side.sessions == nil { + u.side.sessions = make(map[sessionKey]*sessionWidgets) + } + w := u.side.sessions[k] + if w == nil { + w = new(sessionWidgets) + u.side.sessions[k] = w + } + return w +} + +// sessionLabel returns a session's label, if its server lists it. +func sessionLabel(k sessionKey) (string, bool) { + for _, s := range k.srv.ws.Sessions() { + if s.SessionID == k.id { + return s.Label, true + } + } + return "", false +} + +// renaming reports whether a session's label is being edited. +func (u *UI) renaming() bool { return u.side.renaming.srv != nil } + +// startRename edits a session's label in its row. +func (u *UI) startRename(k sessionKey) { + label, ok := sessionLabel(k) + if !ok { + return + } + u.side.collapsed = false + u.side.renaming = k + e := &u.side.renameEditor + e.SingleLine, e.Submit = true, true + e.SetText(label) + e.SetCaret(len([]rune(label)), 0) // all of it selected + u.side.renameFocus = true +} + +// finishRename sets the label being edited, unless save is false. +func (u *UI) finishRename(save bool) { + k := u.side.renaming + u.side.renaming = sessionKey{} + label := strings.TrimSpace(u.side.renameEditor.Text()) + if old, ok := sessionLabel(k); !save || !ok || label == old { + return + } + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := k.srv.conn.Call(ctx, "session.set_label", map[string]string{"session_id": k.id, "label": label}, nil); err != nil { + u.report(fmt.Errorf("rename session: %w", err)) + } + }() +} + +// renameField draws the editor for a session's label, in place of the +// label: Enter saves it, Escape gives up. +func (u *UI) renameField(gtx layout.Context) layout.Dimensions { + e := &u.side.renameEditor + for { + ev, ok := gtx.Event(key.Filter{Focus: e, Name: key.NameEscape}) + if !ok { + break + } + if ke, ok := ev.(key.Event); ok && ke.State == key.Press { + u.finishRename(false) + } + } + for { + ev, ok := e.Update(gtx) + if !ok { + break + } + if _, ok := ev.(widget.SubmitEvent); ok { + u.finishRename(true) + } + } + if u.side.renameFocus { + gtx.Execute(key.FocusCmd{Tag: e}) + u.side.renameFocus = false + } + ed := material.Editor(u.theme.Material, e, "Session name") + ed.Color, ed.HintColor, ed.SelectionColor = theme.Ink, theme.Muted, theme.Lavender + ed.TextSize = 14 + ed.Font.Weight = font.Bold + // A box like the palette's search field, so that it reads as one. + return theme.Box{Fill: theme.White, Padding: layout.Inset{Top: 2, Bottom: 2, Left: 4, Right: 4}}.Layout(gtx, func(gtx layout.Context) layout.Dimensions { + gtx.Constraints.Min.X = gtx.Constraints.Max.X + return ed.Layout(gtx) + }) +} + +// openSessionMenu opens a session's menu where the pointer last pressed. +func (u *UI) openSessionMenu(k sessionKey) { + u.smenu = sessionMenu{open: true, key: k, at: u.lastPress} +} + +// layoutSessionMenu draws the open session menu. A click outside closes +// it. +func (u *UI) layoutSessionMenu(gtx layout.Context) { + m := &u.smenu + if !m.open { + return + } + label, ok := sessionLabel(m.key) + if !ok { + m.open = false // the session 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.rename.Clicked(gtx) { + m.open = false + u.startRename(m.key) + return + } + if m.close.Clicked(gtx) { + if !m.confirmClose { + m.confirmClose = true + } else { + m.open = false + u.closeSession(m.key) + 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(300) + 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, func(gtx layout.Context) layout.Dimensions { + closeLabel, note := "Close session", "" + if m.confirmClose { + closeLabel, note = "Really close?", "Its programs stop, on every device." + } + children := []layout.FlexChild{ + layout.Rigid(func(gtx layout.Context) layout.Dimensions { + l := u.theme.Display(20, label, theme.Ink) + l.MaxLines = 1 + return theme.Highlighted(gtx, l) + }), + layout.Rigid(layout.Spacer{Height: 12}.Layout), + layout.Rigid(func(gtx layout.Context) layout.Dimensions { + return layout.Flex{}.Layout(gtx, + layout.Rigid(theme.Button{Theme: u.theme, Clickable: &m.rename, Label: "Rename"}.Layout), + layout.Rigid(layout.Spacer{Width: 8}.Layout), + layout.Rigid(theme.Button{Theme: u.theme, Clickable: &m.close, Label: closeLabel}.Layout), + ) + }), + } + if note != "" { + children = append(children, layout.Rigid(func(gtx layout.Context) layout.Dimensions { + l := u.theme.Label(12, note, theme.Red, font.SemiBold) + l.MaxLines = 2 + return layout.Inset{Top: 10}.Layout(gtx, l.Layout) + })) + } + return layout.Flex{Axis: layout.Vertical}.Layout(gtx, children...) + }) + }) + 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) +} + +// closeSession destroys a session, and every program in it. +func (u *UI) closeSession(k sessionKey) { + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if _, err := k.srv.conn.Call(ctx, "session.destroy", map[string]string{"session_id": k.id}, nil); err != nil { + u.report(fmt.Errorf("close session: %w", err)) + } + }() +} diff --git a/internal/ui/shots_test.go b/internal/ui/shots_test.go index e030daf..9b96cc1 100644 --- a/internal/ui/shots_test.go +++ b/internal/ui/shots_test.go @@ -147,6 +147,14 @@ func TestShots(t *testing.T) { save("menu") u.menu.open = false + u.startRename(sessionKey{u.srv, api}) + u.openSessionMenu(sessionKey{u.srv, api}) + u.smenu.at = image.Pt(120, 140) + u.smenu.confirmClose = true + save("session") + u.smenu.open = false + u.finishRename(false) + u.palette.toggle(paletteSessions) save("switcher") u.palette.close() diff --git a/internal/ui/sidebar.go b/internal/ui/sidebar.go index 224dd55..495dd72 100644 --- a/internal/ui/sidebar.go +++ b/internal/ui/sidebar.go @@ -39,8 +39,12 @@ type sidebar struct { jump widget.Clickable addHost widget.Clickable hosts map[string]*hostWidgets // by hostEntry.key - sessions map[sessionKey]*widget.Clickable - folded map[string]bool // hosts folded or unfolded by hand, by key + sessions map[sessionKey]*sessionWidgets + + renaming sessionKey // the session whose label is being edited + renameEditor widget.Editor + renameFocus bool // give the editor focus on the next frame + folded map[string]bool // hosts folded or unfolded by hand, by key } // hostWidgets are the clickables of one host's heading, or its rail @@ -76,18 +80,6 @@ func (u *UI) hostWidgets(key string) *hostWidgets { return w } -func (u *UI) sessionClick(k sessionKey) *widget.Clickable { - if u.side.sessions == nil { - u.side.sessions = make(map[sessionKey]*widget.Clickable) - } - c := u.side.sessions[k] - if c == nil { - c = new(widget.Clickable) - u.side.sessions[k] = c - } - return c -} - // isFolded reports whether a host's sessions are hidden: as folded by hand, // or else when it's offline. func (u *UI) isFolded(e hostEntry) bool { @@ -211,10 +203,39 @@ func (u *UI) layoutSidebar(gtx layout.Context, r image.Rectangle) { } } } + // A click shows a session, a double click renames it, and a right + // click opens its menu. + renamed := false for _, row := range rows { - if row.kind == rowSession && u.sessionClick(sessionKey{row.host.srv, row.session.SessionID}).Clicked(gtx) { - u.switchTo(row.host.srv, row.session.SessionID) + if row.kind != rowSession { + continue + } + k := sessionKey{row.host.srv, row.session.SessionID} + w := u.sessionWidgets(k) + for { + c, ok := w.click.Update(gtx) + if !ok { + break + } + if c.NumClicks >= 2 { + u.startRename(k) + } else if u.side.renaming != k { + u.switchTo(k.srv, k.id) + } } + for { + ev, ok := gtx.Event(pointer.Filter{Target: &w.menu, Kinds: pointer.Press}) + if !ok { + break + } + if pe, ok := ev.(pointer.Event); ok && pe.Buttons.Contain(pointer.ButtonSecondary) { + u.openSessionMenu(k) + } + } + renamed = renamed || u.side.renaming == k + } + if u.renaming() && !renamed { + u.side.renaming = sessionKey{} // the session is gone, or hidden } rows = u.sidebarRows(entries, gtx.Now) @@ -342,7 +363,9 @@ func stateSquare(gtx layout.Context, s hostState) layout.Dimensions { // it open, and a tag for what happened in it since it was last shown, or // what a program in it says. func (u *UI) sessionRow(gtx layout.Context, srv *server, s rex.Session, current bool) layout.Dimensions { - click := u.sessionClick(sessionKey{srv, s.SessionID}) + k := sessionKey{srv, s.SessionID} + w := u.sessionWidgets(k) + click := &w.click sum := srv.ws.Summary(s.SessionID) detail := strings.Join(sum.Programs, " · ") if len(sum.Elsewhere) > 0 { @@ -353,7 +376,8 @@ func (u *UI) sessionRow(gtx layout.Context, srv *server, s rex.Session, current detail += on } tag, tagFill, tagFg := sessionTag(sum) - return click.Layout(gtx, func(gtx layout.Context) layout.Dimensions { + rec := op.Record(gtx.Ops) + dims := click.Layout(gtx, func(gtx layout.Context) layout.Dimensions { gtx.Constraints.Min.X = gtx.Constraints.Max.X content := func(gtx layout.Context) layout.Dimensions { weight := font.Medium @@ -363,6 +387,9 @@ func (u *UI) sessionRow(gtx layout.Context, srv *server, s rex.Session, current label := u.theme.Label(14, s.Label, theme.Ink, weight) label.MaxLines = 1 top := []layout.FlexChild{layout.Flexed(1, label.Layout)} + if u.side.renaming == k { + top[0] = layout.Flexed(1, u.renameField) + } if tag != "" { top = append(top, layout.Rigid(func(gtx layout.Context) layout.Dimensions { return layout.Inset{Left: 6}.Layout(gtx, func(gtx layout.Context) layout.Dimensions { @@ -396,6 +423,11 @@ func (u *UI) sessionRow(gtx layout.Context, srv *server, s rex.Session, current call.Add(gtx.Ops) return dims }) + call := rec.Stop() + defer clip.Rect{Max: dims.Size}.Push(gtx.Ops).Pop() + event.Op(gtx.Ops, &w.menu) + call.Add(gtx.Ops) + return dims } // sessionTag is the tag on a session's row, for the most pressing thing diff --git a/internal/ui/sidebar_test.go b/internal/ui/sidebar_test.go index 0f01f9d..b39cea6 100644 --- a/internal/ui/sidebar_test.go +++ b/internal/ui/sidebar_test.go @@ -2,6 +2,7 @@ package ui import ( "context" + "encoding/json" "strings" "testing" "time" @@ -67,3 +68,71 @@ func TestSessionSummaries(t *testing.T) { rextest.Call(t, laptop, "session.detach", map[string]string{"session_id": sidA}, nil) h.until("A to be open nowhere else", func(rexsession.Frame) bool { return len(sum(sidA).Elsewhere) == 0 }) } + +// TestSessionKeys goes to sessions across hosts by position, in turn, and +// back to the last one, and renames and closes one from its menu. +func TestSessionKeys(t *testing.T) { + alpha := rextest.Start(t) + bravo := rextest.Start(t) + ac := alpha.Dial(t, "setup") + sidA1, _ := rextest.NewSession(t, ac, rextest.RawCat...) + sidA2, _ := rextest.NewSession(t, ac, rextest.RawCat...) + sidB, _ := rextest.NewSession(t, bravo.Dial(t, "setup"), rextest.RawCat...) + + h := startUI(t, alpha, alpha.Dial(t, "100gex-test"), sidA1) + h.until("A1", func(f rexsession.Frame) bool { return f.Ready() && f.View.SessionID == sidA1 }) + h.u.Connect(bravo.Endpoint.String()) + h.until("B", func(f rexsession.Frame) bool { return f.Ready() && f.View.SessionID == sidB }) + perform := func(action string, args map[string]any) { + t.Helper() + raw, _ := json.Marshal(args) + if args == nil { + raw = nil + } + if err := h.u.perform(action, raw, nil, nil); err != nil { + t.Fatal(err) + } + } + shows := func(what, sid string) { + t.Helper() + h.until(what, func(f rexsession.Frame) bool { return f.Ready() && f.View.SessionID == sid }) + } + + perform("session.goto", map[string]any{"index": 2}) + shows("the second session, A2", sidA2) + perform("session.next", nil) + shows("the next session, on the other host, B", sidB) + perform("session.last", nil) + shows("the last session, A2", sidA2) + perform("session.previous", nil) + shows("the previous session, A1", sidA1) + + // Renaming in place. + k := sessionKey{h.u.srv, sidA1} + perform("session.rename", nil) + if h.u.side.renaming != k { + t.Fatalf("renaming %v, want %v", h.u.side.renaming, k) + } + h.frame() + h.u.side.renameEditor.SetText("renamed") + h.u.finishRename(true) + h.until("the new label", func(rexsession.Frame) bool { + label, _ := sessionLabel(k) + return label == "renamed" + }) + + // Closing from the menu takes two clicks. + h.u.openSessionMenu(sessionKey{h.u.srv, sidA2}) + h.frame() + h.u.smenu.close.Click() + h.frame() + if !h.u.smenu.confirmClose || !h.u.smenu.open { + t.Fatal("one click on Close didn't ask to confirm") + } + h.u.smenu.close.Click() + h.frame() + h.until("A2 to close", func(rexsession.Frame) bool { + _, ok := sessionLabel(sessionKey{h.u.srv, sidA2}) + return !ok + }) +} diff --git a/internal/ui/ui.go b/internal/ui/ui.go index bd4ca67..344296b 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -96,7 +96,10 @@ type UI struct { 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 @@ -256,6 +259,11 @@ func (u *UI) Layout(gtx layout.Context) (rexsession.Frame, system.Action, error) 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 + } + } var f rexsession.Frame if u.session != nil { // The frame holds the terminals while it draws them; their output @@ -274,7 +282,7 @@ func (u *UI) Layout(gtx layout.Context) (rexsession.Frame, system.Action, error) // 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.keys.Layout(gtx, u.key, !u.palette.open && !u.renaming()) u.layoutPaste(gtx) titlebar, sidebar := gtx.Dp(theme.TitlebarHigh), u.sidebarWide(gtx) @@ -285,6 +293,7 @@ func (u *UI) Layout(gtx layout.Context) (rexsession.Frame, system.Action, error) 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)