diff --git a/internal/rex/session.go b/internal/rex/session.go index a4d9fd6..7a0a148 100644 --- a/internal/rex/session.go +++ b/internal/rex/session.go @@ -37,6 +37,17 @@ func (v *View) Window(id string) *Window { return nil } +// WindowIndex returns the position of the window with the given ID in the +// window order, or -1. +func (v *View) WindowIndex(id string) int { + for i := range v.Windows { + if v.Windows[i].WindowID == id { + return i + } + } + return -1 +} + // Window is a tab within a session. type Window struct { WindowID string `json:"window_id"` diff --git a/internal/rexsession/session.go b/internal/rexsession/session.go index 6c2fc11..4b99d37 100644 --- a/internal/rexsession/session.go +++ b/internal/rexsession/session.go @@ -7,6 +7,7 @@ import ( "context" "encoding/json" "log" + "slices" "sync" "time" @@ -456,6 +457,44 @@ func (s *Session) FocusWindow(windowID string) { }) } +// MoveWindow moves a window to just before another in the session's window +// order, or to the end if beforeID is "". The view changes at once, before +// the server confirms. +func (s *Session) MoveWindow(windowID, beforeID string) { + if windowID == beforeID { + return + } + s.mu.Lock() + from := s.view.WindowIndex(windowID) + if from < 0 { + s.mu.Unlock() + return + } + v := cloneView(s.view) + w := v.Windows[from] + v.Windows = slices.Delete(v.Windows, from, from+1) + to := len(v.Windows) + if beforeID != "" { + if to = v.WindowIndex(beforeID); to < 0 { + s.mu.Unlock() + return + } + } + if to == from { + s.mu.Unlock() + return // already there + } + v.Windows = slices.Insert(v.Windows, to, w) + s.view = v + s.mu.Unlock() + s.notify() + args := map[string]any{"session_id": s.id, "window_id": windowID} + if beforeID != "" { + args["before_window_id"] = beforeID + } + s.call("session.move_window", args) +} + // cloneView copies the parts of v that a local change touches, so that a // Frame already handed out never changes under its reader. func cloneView(v rex.View) rex.View { diff --git a/internal/ui/tabs.go b/internal/ui/tabs.go new file mode 100644 index 0000000..c4b4c7e --- /dev/null +++ b/internal/ui/tabs.go @@ -0,0 +1,316 @@ +package ui + +import ( + "image" + + "gioui.org/f32" + "gioui.org/io/event" + "gioui.org/io/pointer" + "gioui.org/layout" + "gioui.org/op" + "gioui.org/op/clip" + "gioui.org/unit" + "gioui.org/widget" + + "100gex/internal/rex" + "100gex/internal/rexsession" + "100gex/internal/theme" +) + +// tabGap is the space between tabs. +const tabGap unit.Dp = 10 + +// dragSlop is how far the pointer must move, pressed, before a press on a +// tab becomes a drag rather than a click. +const dragSlop unit.Dp = 4 + +// tabDrag follows a press on a tab, and the drag it may become. Its +// positions are in the tab strip's coordinates, which don't move while the +// tabs do. +type tabDrag struct { + tag tag + pid pointer.ID + window string // the window whose tab was pressed, or "" for none + start f32.Point // where the press was + grab float32 // how far right of the tab's left edge it was + x float32 // where the pointer is now + active bool // past dragSlop: the tab follows the pointer +} + +// tabSlot is where a tab was drawn, in the strip's coordinates. +type tabSlot struct { + window string + rect image.Rectangle +} + +// laidTab is a tab laid out, but not yet drawn. +type laidTab struct { + id string + call op.CallOp + size image.Point +} + +// layoutTabs draws a tab for each window, filling the height of +// gtx.Constraints.Max, with its origin at origin in the window. Pressing a +// tab and dragging it sideways moves its window to another place in the +// order; clicking it switches to it. +func (u *UI) layoutTabs(gtx layout.Context, f rexsession.Frame, origin image.Point) layout.Dimensions { + var windows []rex.Window + if f.Window != nil { + windows = f.View.Windows + } + u.updateTabDrag(gtx, windows) + + tabs := make([]laidTab, len(windows)) + height := gtx.Constraints.Max.Y + gtx.Constraints.Min = image.Point{} + for i := range windows { + w := &windows[i] + click := u.tabs[w.WindowID] + if click == nil { + click = new(widget.Clickable) + u.tabs[w.WindowID] = click + } + if click.Clicked(gtx) && u.session != nil { + u.session.FocusWindow(w.WindowID) + } + m := op.Record(gtx.Ops) + dims := theme.Button{ + Theme: u.theme, Clickable: click, Label: u.tabLabel(f, w, i), + Selected: w.WindowID == f.View.ActiveWindowID, + }.Layout(gtx) + tabs[i] = laidTab{id: w.WindowID, call: m.Stop(), size: dims.Size} + } + + gap := gtx.Dp(tabGap) + natural := make([]int, len(tabs)) // each tab's left edge, undragged + width := 0 + for i, t := range tabs { + if i > 0 { + width += gap + } + natural[i] = width + width += t.size.X + } + + // Where each tab goes: in order, or, while one is dragged, the others + // in order with room for it where it would land, and it under the + // pointer. + xs := natural + dragged := -1 + if d := &u.tabDrag; d.active { + for i, t := range tabs { + if t.id == d.window { + dragged = i + } + } + } + var lifted int + if dragged >= 0 { + lifted = u.draggedTabX(tabs[dragged].size.X, width) + to := dropIndex(tabs, natural, dragged, lifted) + xs = make([]int, len(tabs)) + x := 0 + for k, i := 0, 0; i < len(tabs); i++ { + if i == dragged { + continue + } + if k == to { + x += tabs[dragged].size.X + gap + } + xs[i] = x + x += tabs[i].size.X + gap + k++ + } + xs[dragged] = lifted + } + + // The strip's drag handler is beneath the tabs, so that their + // Clickables get presses too, and see clicks that don't become drags. + // The area reaches past the strip for the lifted tab's shadow. + lift := gtx.Dp(theme.Shadow) + area := clip.Rect{Min: image.Pt(-lift, 0), Max: image.Pt(width+lift, height)}.Push(gtx.Ops) + event.Op(gtx.Ops, &u.tabDrag.tag) + if dragged >= 0 { + pointer.CursorGrabbing.Add(gtx.Ops) + } + u.tabSlots = u.tabSlots[:0] + clear(u.tabRects) + draw := func(i int) { + t := tabs[i] + pos := image.Pt(xs[i], (height-t.size.Y)/2) + if i == dragged { + // Lifted off the bar: up and to the left, with a deeper + // shadow than the button's own. + own := gtx.Dp(theme.Shadow) / 2 + pos = pos.Sub(image.Pt(lift-own, lift-own)) + face := t.size.Sub(image.Pt(own, own)) + theme.Fill(gtx, theme.Ink, image.Rectangle{Max: face}.Add(pos).Add(image.Pt(lift, lift))) + } + st := op.Offset(pos).Push(gtx.Ops) + t.call.Add(gtx.Ops) + st.Pop() + r := image.Rectangle{Min: pos, Max: pos.Add(t.size)} + u.tabSlots = append(u.tabSlots, tabSlot{window: t.id, rect: r}) + u.tabRects[t.id] = r.Add(origin) + } + for i := range tabs { + if i != dragged { + draw(i) + } + } + if dragged >= 0 { + draw(dragged) // on top + } + area.Pop() + + // Forget tabs for windows that have closed. + for id := range u.tabs { + if f.View.Window(id) == nil { + delete(u.tabs, id) + } + } + return layout.Dimensions{Size: image.Pt(width, height)} +} + +// draggedTabX is where the dragged tab's left edge is, kept within the +// strip, which is width wide. +func (u *UI) draggedTabX(tabWidth, width int) int { + d := &u.tabDrag + x := int(d.x - d.grab) + return max(0, min(x, width-tabWidth)) +} + +// dropIndex is the place among the other tabs where the dragged one would +// land if dropped with its left edge at x. A tab before it moves after it +// once its left edge passes the tab's middle; a tab after it, once its right +// edge does. So both ends can be reached, whatever the tabs' widths. +func dropIndex(tabs []laidTab, natural []int, dragged, x int) int { + to := 0 + for i, t := range tabs { + middle := natural[i] + t.size.X/2 + switch { + case i < dragged && x > middle: + to++ + case i > dragged && x+tabs[dragged].size.X > middle: + to++ + } + } + return to +} + +// updateTabDrag reads the pointer's events on the tab strip: a press on a +// tab, a drag past dragSlop that takes the pointer from the tab's button, +// and the release that drops it. +func (u *UI) updateTabDrag(gtx layout.Context, windows []rex.Window) { + d := &u.tabDrag + for { + ev, ok := gtx.Event(pointer.Filter{ + Target: &d.tag, + Kinds: pointer.Press | pointer.Drag | pointer.Release | pointer.Cancel, + }) + if !ok { + break + } + e, ok := ev.(pointer.Event) + if !ok { + continue + } + switch e.Kind { + case pointer.Press: + if d.window != "" || e.Source == pointer.Mouse && e.Buttons != pointer.ButtonPrimary { + continue + } + p := e.Position.Round() + for _, s := range u.tabSlots { + if p.In(s.rect) { + *d = tabDrag{pid: e.PointerID, window: s.window, start: e.Position, + grab: e.Position.X - float32(s.rect.Min.X), x: e.Position.X} + } + } + case pointer.Drag: + if d.window == "" || e.PointerID != d.pid { + continue + } + d.x = e.Position.X + if !d.active { + diff := e.Position.Sub(d.start) + slop := float32(gtx.Dp(dragSlop)) + if diff.X*diff.X+diff.Y*diff.Y > slop*slop { + // Taking the pointer cancels the button's click. + gtx.Execute(pointer.GrabCmd{Tag: &d.tag, ID: e.PointerID}) + d.active = true + } + } + case pointer.Release: + if e.PointerID == d.pid && d.active { + d.x = e.Position.X + u.dropTab(gtx, windows) + } + *d = tabDrag{} + case pointer.Cancel: + *d = tabDrag{} + } + } + // A window that closes while its tab is dragged ends the drag. + if d.window != "" { + found := false + for i := range windows { + found = found || windows[i].WindowID == d.window + } + if !found { + *d = tabDrag{} + } + } +} + +// dropTab moves the dragged tab's window to where the tab was dropped. +func (u *UI) dropTab(gtx layout.Context, windows []rex.Window) { + if u.session == nil { + return + } + d := &u.tabDrag + // The tabs as they were last drawn, in order, to place the drop + // among: their widths haven't changed since. + gap := gtx.Dp(tabGap) + tabs := make([]laidTab, len(windows)) + natural := make([]int, len(windows)) + dragged, width := -1, 0 + for i := range windows { + id := windows[i].WindowID + var size image.Point + for _, s := range u.tabSlots { + if s.window == id { + size = s.rect.Size() + } + } + if id == d.window { + dragged = i + } + if i > 0 { + width += gap + } + tabs[i], natural[i] = laidTab{id: id, size: size}, width + width += size.X + } + if dragged < 0 { + return + } + to := dropIndex(tabs, natural, dragged, u.draggedTabX(tabs[dragged].size.X, width)) + if to == dragged { + return // where it was + } + // The window that will come after it, counting without it. + before := "" + for k, i := 0, 0; i < len(windows); i++ { + if i == dragged { + continue + } + if k == to { + before = windows[i].WindowID + break + } + k++ + } + u.session.MoveWindow(d.window, before) +} diff --git a/internal/ui/tabs_test.go b/internal/ui/tabs_test.go new file mode 100644 index 0000000..b25df70 --- /dev/null +++ b/internal/ui/tabs_test.go @@ -0,0 +1,103 @@ +package ui + +import ( + "image" + "slices" + "testing" + + "gioui.org/f32" + "gioui.org/io/pointer" + + "100gex/internal/rex" + "100gex/internal/rex/rextest" + "100gex/internal/rexsession" +) + +// TestTabDrag drags tabs to new places in the window order, and checks that +// clicks, and presses that wobble less than dragSlop, still switch tabs. +func TestTabDrag(t *testing.T) { + srv := rextest.Start(t) + other := srv.Dial(t, "other-device") + sid, _ := rextest.NewSession(t, other, rextest.RawCat...) + for _, label := range []string{"two", "three"} { + rextest.Call(t, other, "session.new_window", map[string]any{ + "session_id": sid, "window_label": label, "layout": rextest.Block(rextest.RawCat...), "focus": false, + }, nil) + } + c := srv.Dial(t, "100gex-test") + h := startUI(t, srv, c, sid) + f := h.until("three tabs", func(f rexsession.Frame) bool { return len(f.View.Windows) == 3 && f.Ready() }) + ids := func(f rexsession.Frame) []string { + var out []string + for _, w := range f.View.Windows { + out = append(out, w.WindowID) + } + return out + } + first, second, third := ids(f)[0], ids(f)[1], ids(f)[2] + serverOrder := func() []string { + var v rex.View + rextest.Call(t, other, "session.view", map[string]any{"session_id": sid}, &v) + var out []string + for _, w := range v.Windows { + out = append(out, w.WindowID) + } + return out + } + + send := func(kind pointer.Kind, p image.Point) { + h.router.Queue(pointer.Event{Kind: kind, Source: pointer.Mouse, Position: f32.Pt(float32(p.X), float32(p.Y)), Buttons: pointer.ButtonPrimary}) + h.frame() + } + middle := func(id string) image.Point { + r := h.u.tabRects[id] + return r.Min.Add(r.Size().Div(2)) + } + // drag presses at from and moves to to in steps, a frame each, as a + // person's drag does, then lets go. + drag := func(from, to image.Point) { + send(pointer.Press, from) + const steps = 8 + for i := 1; i <= steps; i++ { + send(pointer.Move, from.Add(to.Sub(from).Mul(i).Div(steps))) + } + send(pointer.Release, to) + } + waitOrder := func(what string, want ...string) { + t.Helper() + // The view changes at once; the server, once the request is made. + h.until(what, func(f rexsession.Frame) bool { + return slices.Equal(ids(f), want) && slices.Equal(serverOrder(), want) + }) + } + + // The third tab, dropped over the first's left half, goes first. + drag(middle(third), h.u.tabRects[first].Min.Add(image.Pt(4, 10))) + waitOrder("the third tab moved first", third, first, second) + if h.u.tabDrag.active { + t.Error("the drag is still going after the release") + } + if got := h.frame().View.ActiveWindowID; got != first { + t.Errorf("dragging a tab switched to %s; the first window was active", got) + } + + // The tab now first, dragged past the end, goes last. + drag(middle(third), image.Pt(testWidth-100, middle(third).Y)) + waitOrder("the third tab moved last", first, second, third) + + // A short move, past the second's middle, swaps neighbours. + r := h.u.tabRects[second] + drag(middle(first), image.Pt(r.Max.X-2, middle(first).Y)) + waitOrder("the first tab moved after the second", second, first, third) + + // A press that wobbles less than dragSlop is a click: it switches to the tab + // and leaves the order be. + p := middle(third) + send(pointer.Press, p) + send(pointer.Move, p.Add(image.Pt(2, 1))) + send(pointer.Release, p.Add(image.Pt(2, 1))) + h.until("the click to switch to the third tab", func(f rexsession.Frame) bool { return f.View.ActiveWindowID == third }) + if got := ids(h.frame()); !slices.Equal(got, []string{second, first, third}) { + t.Errorf("a click moved tabs: %v", got) + } +} diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 95be420..cbdc96f 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -102,6 +102,9 @@ type UI struct { // 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 + srv *server // the server shown; conn and ws are its mu sync.Mutex // guards what other goroutines hand over @@ -379,36 +382,19 @@ func (u *UI) layoutTitlebar(gtx layout.Context, f rexsession.Frame, r image.Rect u.palette.toggle(paletteCommands) } - var windows []rex.Window - if f.Window != nil { - windows = f.View.Windows - } - gap := unit.Dp(10) - children := []layout.FlexChild{layout.Rigid(layout.Spacer{Width: theme.Gap}.Layout)} - clear(u.tabRects) - x := sidebar + gtx.Dp(theme.Gap) - for i := range windows { - w := &windows[i] - click := u.tabs[w.WindowID] - if click == nil { - click = new(widget.Clickable) - u.tabs[w.WindowID] = click - } - if click.Clicked(gtx) && u.session != nil { - u.session.FocusWindow(w.WindowID) - } - label := u.tabLabel(f, w, i) - active := w.WindowID == f.View.ActiveWindowID - id := w.WindowID - children = append(children, - layout.Rigid(func(gtx layout.Context) layout.Dimensions { - dims := theme.Button{Theme: u.theme, Clickable: click, Label: label, Selected: active}.Layout(gtx) - u.tabRects[id] = image.Rect(x, (gtx.Constraints.Max.Y-dims.Size.Y)/2, x+dims.Size.X, (gtx.Constraints.Max.Y+dims.Size.Y)/2) - x += dims.Size.X + gtx.Dp(gap) - return dims - }), - layout.Rigid(layout.Spacer{Width: gap}.Layout), - ) + gap := tabGap + children := []layout.FlexChild{ + layout.Rigid(layout.Spacer{Width: theme.Gap}.Layout), + 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), 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)) @@ -435,12 +421,6 @@ func (u *UI) layoutTitlebar(gtx layout.Context, f rexsession.Frame, r image.Rect return layout.Flex{Alignment: layout.Middle}.Layout(gtx, children...) }) - // Forget tabs for windows that have closed. - for id := range u.tabs { - if f.View.Window(id) == nil { - delete(u.tabs, id) - } - } } // defaultWindowLabel matches the labels the server gives windows, such as