gui: on niri the tray panel opens under the bar beside the clicked icon, not in the middle of the screen (#1670, Kenoia)
A Wayland window can't place itself. Under niri the panel opened where niri floats a new window, the middle of the output. Hyprland already had an adapter (omarchy/hypr.go); niri now has one too. niri (checked in niri v26.04's source, niri-ipc/src/lib.rs and src/ipc/server.rs) can't add window rules at runtime and doesn't report the pointer over IPC. So omarchy.NiriPanel watches niri's event stream ($NIRI_SOCKET, one line of JSON per message) and moves each window of magpie's pid titled "magpie panel" once as it opens: MoveWindowToFloating if it was tiled, then MoveFloatingWindow with SetFixed x/y, which count from the working area's top-left (below the bar). It goes 6 px under the bar, centred on the x that the tray host passed to the SNI Activate(x, y), kept inside the output. Wails' Linux tray keeps that x in private fields (lastClickX/lastClickY), read the same way trayProps already reads props; TestTrayClickIsWails reads Wails' source to fail if they move. Noctalia passes bar-surface-local coordinates, so the x is taken across the focused output. With no click (`magpie panel`), or with one off the output, it goes to the top right. Wails' HideOnFocusLost closes it when another window takes the focus. What was run: - go test -race ./internal/omarchy/, go test ./internal/gui/ (sandbox HOME, pinned GOMODCACHE/GOCACHE). The IPC fixtures are built from niri-ipc 26.4.0's Window/Output/Event/Reply types, quoted in the test. - Broke it by hand: dropping the placed-once map fails TestWatchWindows (placed [7 7 9 9 9]); dropping the right-edge clamp fails TestPanelSpot. - gofmt -l; go vet (darwin), GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...; linux nogui and windows builds. - A nested niri 26.04 (winit backend on Xvfb, scale 1.5, Fedora 43 container, magpie built with -tags gtk3), with SNI Activate sent via dbus-send. Activate(300, 14) put the panel at [58, 6] (300 - 484/2). A second Activate closed it. `magpie panel` reopened it at the top right (853 - 484 - 6 = 363). Activate(800, 14) clamped it to 363. `magpie gui` taking the focus closed it. Not tried: a real niri desktop, Noctalia or another real tray host (Waybar, ironbar), more than one monitor, a bar at the bottom or the side (not accounted for), focus-follows-mouse. The panel still opens in the middle and slides up; how visible that is on real hardware wasn't seen. Not from this change: omarchy's TestCurrent fails with -count=2 on main (it passes with -count=1).
This commit is contained in:
@@ -159,6 +159,7 @@ retry after a failed read. See `TestRecentCallBodiesOnDemand` and
|
||||
- The Providers page has a search box over its list (#1614, `findProviders` in [`app.js`](../../internal/gui/assets/app.js)): the words typed keep the rows, on and off, whose text or data say them all: name, id, preset, addresses, every model's id and name, the account's user and plan and each login's, account names and key names. The Turned off fold stays open while searching; Escape or clearing the box shows every row and the fold as it was. A row that is on reorders by dragging its logo, Alt+↑/↓, Alt+Shift+↑/↓ (top, bottom) or its right-click menu (`openProviderMenu`: Move to top, Move up, Move down, Move to bottom). While searching, a step or a drop moves it among the rows shown (it takes the place of the row it passes, `stepProvider`, `shownToOn`) and the hidden ones keep their order; Move to top and Move to bottom go to the ends of the whole list. Every move saves the whole order through `POST /api/providers/arrange`. See `provider-find.test.cjs` and `provider-order.test.cjs`.
|
||||
- The page must work in Chromium (Windows' WebView2) and WebKit (macOS, and WebKitGTK on Linux). GUI tests run in both engines.
|
||||
- On Linux the panel is frameless and the main window has a hidden title bar (`plainTitlebar`). GTK 3 asks KDE's Wayland session (KWin's decoration protocol) for a frame drawn by KWin on any window without client-side decorations, an undecorated one too, so `ownFrame` tells KWin the panel draws its own on each realize (#1283). GTK 4 builds ask for none themselves. With no KWin title bar, and with a Wayland window placed by the compositor rather than by the icon, the panel's header is its drag handle on Linux, as the window's is (`--wails-draggable` in `app.js`; `panel-drag-linux.test.cjs`); on the Mac and Windows the panel isn't dragged (#1430).
|
||||
- A Wayland window can't place itself, so under Hyprland and niri the compositor is asked to put the panel under the bar. Under Hyprland `placePanel` gives it a window rule at the cursor (`omarchy.PlacePanel`) and closes it on a click outside (`omarchy.ReportClicks`). niri (`omarchy.Niri`, `NIRI_SOCKET` set) takes no rules at runtime and doesn't report the cursor. There `omarchy.NiriPanel` watches niri's event stream and moves the panel each time it opens: the window of magpie's pid titled `panelTitle`, moved with `MoveFloatingWindow` (after `MoveWindowToFloating` if it was tiled). It goes 6 px under the working area's top, centred on the x the tray host passed to `Activate(x, y)`. Wails keeps that x in its Linux tray (`trayClick`, `TestTrayClickIsWails`), and it is taken across the bar, since that's all a Wayland bar knows. With no click (`magpie panel`), or with one off the output, it goes top right. Wails' `HideOnFocusLost` closes it, since a click on another window takes niri's focus. It still opens in the middle and slides up, and a bar at the bottom or the side isn't accounted for (#1670).
|
||||
- Wails calls the tray's click handler both for the icon's click (`Activate`) and when the tray host opens the icon's menu (dbusmenu's "opened" event). KDE opens the menu on a right-click, and the panel that click opened took the focus and shut the menu on Wayland. On Linux the handler ignores the call when it comes from the menu opening (`menuOpening` in [`trayclick.go`](../../internal/gui/trayclick.go), which looks for Wails' `(*linuxSystemTray).Event` among its callers; `TestTrayMenuOpenFrameIsWails` fails if Wails renames it or stops calling the handler there) (#1430).
|
||||
- On GTK 3 builds, the app gives GDK a font DPI before the first webview when it has none (`fontDPI`, [`fontdpi_gtk3.h`](../../internal/gui/fontdpi_gtk3.h)). GDK's unset value is -1, and WebKitGTK 2.54's GTK 3 settings reader multiplies it by 1024 unchecked, so every page lays out at a negative width with a 9000000px font (#1371). An unset DPI takes `gtk-xft-dpi`, or 96, times a valid `GDK_DPI_SCALE`; a positive one is left alone. Wails initialises GTK (its GtkApplication) only inside `Run` and makes each window from a default-idle-priority callback on the main loop, so `fontDPI`, called just before `Run`, queues the check as a `G_PRIORITY_HIGH` idle: it runs on the main thread after GTK's own start, before the first window. `TestFontDPIUnset` opens a real WebKitGTK page through `magpie_font_dpi` and needs a display (Xvfb).
|
||||
- Tests never touch a live agent config. The package's `TestMain` runs under `testenv`'s home of its own. A macOS test that shows windows runs them in a process of its own through `runAppKit` ([`appkit_darwin_test.go`](../../internal/gui/appkit_darwin_test.go)). AppKit and WebKit take their home from the account, not from HOME, so `runAppKit` gives them a temporary one with `CFFIXED_USER_HOME`; appearance, contrast and languages still come from the account. The test fails when that process leaves a folder in the real `~/Library/WebKit` or `~/Library/Caches`. Playwright tests serve `assets/` with isolated `/api` fixtures.
|
||||
|
||||
+18
-2
@@ -83,6 +83,13 @@ type host struct {
|
||||
barTray atomic.Int64 // the newest setTrayInBar; older ones stop
|
||||
query string // what the windows' URLs carry (a forced theme)
|
||||
|
||||
// niri places the panel as it opens (#1670): niriWatch starts its
|
||||
// watch once, and iconX is where the tray icon was just clicked
|
||||
// across its bar
|
||||
niri omarchy.NiriPanel
|
||||
niriWatch sync.Once
|
||||
iconX atomic.Pointer[int]
|
||||
|
||||
// closing is set while a full-screen main window, closed, leaves full
|
||||
// screen; it is hidden once it has
|
||||
closing atomic.Bool
|
||||
@@ -159,8 +166,8 @@ func (h *host) ChooseFolder(title string) (string, error) {
|
||||
return d.PromptForSingleSelection()
|
||||
}
|
||||
|
||||
// panelTitle names the panel for Hyprland's rule, which places it (the
|
||||
// main window is "magpie")
|
||||
// panelTitle names the panel for Hyprland's rule, which places it, and
|
||||
// for niri, which finds it by it (the main window is "magpie")
|
||||
const panelTitle = "magpie panel"
|
||||
|
||||
// FitPanel grows or shrinks the panel to its content and keeps it anchored
|
||||
@@ -483,6 +490,9 @@ func Run(version string, showMain bool, link string) error {
|
||||
h.ShowMain("")
|
||||
return
|
||||
}
|
||||
if x, ok := trayClick(h.tray); ok {
|
||||
h.iconX.Store(&x)
|
||||
}
|
||||
h.togglePanel()
|
||||
})
|
||||
|
||||
@@ -679,6 +689,12 @@ func (h *host) togglePanelNow() {
|
||||
}
|
||||
h.placePanel()
|
||||
}
|
||||
// niri places it as it opens (see omarchy.NiriPanel), by the click
|
||||
// that opened it, if a click did
|
||||
if x := h.iconX.Swap(nil); omarchy.Niri() && !h.panel.IsVisible() {
|
||||
h.niriWatch.Do(func() { go h.niri.Watch(panelTitle) })
|
||||
h.niri.Opening(x)
|
||||
}
|
||||
if runtime.GOOS == "darwin" {
|
||||
// Wails' ToggleWindow goes by IsVisible, which on the Mac is the
|
||||
// window's occlusion: under a window over the whole screen (a
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// menuOpenFrame is the Wails function that tells the tray's click handler
|
||||
@@ -39,3 +41,41 @@ func openedBy(callers []string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// trayImpl is the struct behind a Wails SystemTray's impl, the platform's
|
||||
// tray (Linux's linuxSystemTray), given the SystemTray itself; not valid
|
||||
// once a Wails version keeps it elsewhere.
|
||||
func trayImpl(tray reflect.Value) (impl reflect.Value) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
impl = reflect.Value{}
|
||||
}
|
||||
}()
|
||||
i := tray.FieldByName("impl")
|
||||
if !i.IsValid() || i.Kind() != reflect.Interface || i.IsNil() {
|
||||
return reflect.Value{}
|
||||
}
|
||||
p := i.Elem()
|
||||
if p.Kind() != reflect.Pointer || p.IsNil() || p.Elem().Kind() != reflect.Struct {
|
||||
return reflect.Value{}
|
||||
}
|
||||
return p.Elem()
|
||||
}
|
||||
|
||||
// clickIn reads the click Wails' Linux tray keeps from the tray host's
|
||||
// Activate(x, y), lastClickX and lastClickY, given the SystemTray. (0, 0)
|
||||
// is no click, as Wails reads it too: a host that passes no coordinates
|
||||
// sends that.
|
||||
func clickIn(tray reflect.Value) (x int, ok bool) {
|
||||
impl := trayImpl(tray)
|
||||
if !impl.IsValid() {
|
||||
return 0, false
|
||||
}
|
||||
fx, fy := impl.FieldByName("lastClickX"), impl.FieldByName("lastClickY")
|
||||
if !fx.IsValid() || !fy.IsValid() || fx.Kind() != reflect.Int || fy.Kind() != reflect.Int || !fx.CanAddr() {
|
||||
return 0, false
|
||||
}
|
||||
x = *(*int)(unsafe.Pointer(fx.UnsafeAddr()))
|
||||
y := *(*int)(unsafe.Pointer(fy.UnsafeAddr()))
|
||||
return x, x != 0 || y != 0
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
@@ -65,3 +66,68 @@ func TestTrayMenuOpenFrameIsWails(t *testing.T) {
|
||||
t.Fatalf("Wails' Event no longer calls the click handler on \"opened\"; see menuOpening:\n%s", fn)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeTray is the shape clickIn reads in Wails' SystemTray: impl, an
|
||||
// interface holding a pointer to the platform's tray.
|
||||
type fakeTray struct{ impl any }
|
||||
|
||||
type fakeLinuxTray struct {
|
||||
label string
|
||||
lastClickX, lastClickY int
|
||||
}
|
||||
|
||||
// niri places the panel by where the tray host said the icon was clicked,
|
||||
// which Wails keeps from Activate(x, y) and gives the click handler no way
|
||||
// to ask for (#1670).
|
||||
func TestTrayClickIn(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
tray fakeTray
|
||||
x int
|
||||
ok bool
|
||||
}{
|
||||
{"clicked", fakeTray{&fakeLinuxTray{lastClickX: 1490, lastClickY: 14}}, 1490, true},
|
||||
{"clicked at the bar's left end", fakeTray{&fakeLinuxTray{lastClickX: 0, lastClickY: 14}}, 0, true},
|
||||
{"no coordinates from the host", fakeTray{&fakeLinuxTray{}}, 0, false},
|
||||
{"no tray yet", fakeTray{}, 0, false},
|
||||
{"fields gone in a later Wails", fakeTray{&struct{ lastClickX string }{"x"}}, 0, false},
|
||||
{"not a pointer", fakeTray{fakeLinuxTray{lastClickX: 5}}, 0, false},
|
||||
} {
|
||||
x, ok := clickIn(reflect.ValueOf(&c.tray).Elem())
|
||||
if x != c.x || ok != c.ok {
|
||||
t.Errorf("%s: %d %v, want %d %v", c.name, x, ok, c.x, c.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// clickIn reads the fields Wails' Activate fills before it calls the click
|
||||
// handler; an upgrade that renames them or stops keeping the click fails
|
||||
// here.
|
||||
func TestTrayClickIsWails(t *testing.T) {
|
||||
out, err := exec.Command("go", "mod", "download", "-json", "github.com/wailsapp/wails/v3").Output()
|
||||
if err != nil {
|
||||
t.Skip("go mod download:", err)
|
||||
}
|
||||
var mod struct{ Dir string }
|
||||
if err := json.Unmarshal(out, &mod); err != nil || mod.Dir == "" {
|
||||
t.Fatalf("go mod download named no folder: %s", out)
|
||||
}
|
||||
app := filepath.Join(mod.Dir, "pkg", "application")
|
||||
src, err := os.ReadFile(filepath.Join(app, "systemtray_linux.go"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !regexp.MustCompile(`(?s)type linuxSystemTray struct \{.*?\n\s*lastClickX int\n\s*lastClickY int\n`).Match(src) {
|
||||
t.Fatal("Wails' linuxSystemTray has no lastClickX, lastClickY int; see clickIn")
|
||||
}
|
||||
if !regexp.MustCompile(`(?s)func \(s \*linuxSystemTray\) Activate\(x int32, y int32\) \(err \*dbus\.Error\) \{\s*s\.lastClickX = int\(x\)\s*s\.lastClickY = int\(y\).*?s\.parent\.clickHandler\(\)`).Match(src) {
|
||||
t.Fatal("Wails' Activate no longer keeps the click before calling the click handler; see clickIn")
|
||||
}
|
||||
src, err = os.ReadFile(filepath.Join(app, "systemtray.go"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !regexp.MustCompile(`(?s)type SystemTray struct \{.*?\n\s*impl\s+systemTrayImpl\n`).Match(src) {
|
||||
t.Fatal("Wails' SystemTray keeps its platform tray in no impl; see trayImpl")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,21 +56,28 @@ func trayProps(tray *application.SystemTray) (props *prop.Properties) {
|
||||
if tray == nil {
|
||||
return nil
|
||||
}
|
||||
impl := reflect.ValueOf(tray).Elem().FieldByName("impl")
|
||||
if !impl.IsValid() || impl.Kind() != reflect.Interface || impl.IsNil() {
|
||||
impl := trayImpl(reflect.ValueOf(tray).Elem())
|
||||
if !impl.IsValid() {
|
||||
return nil
|
||||
}
|
||||
p := impl.Elem()
|
||||
if p.Kind() != reflect.Pointer || p.IsNil() || p.Elem().Kind() != reflect.Struct {
|
||||
return nil
|
||||
}
|
||||
f := p.Elem().FieldByName("props")
|
||||
f := impl.FieldByName("props")
|
||||
if !f.IsValid() || f.Type() != reflect.TypeOf((*prop.Properties)(nil)) {
|
||||
return nil
|
||||
}
|
||||
return *(**prop.Properties)(unsafe.Pointer(f.UnsafeAddr()))
|
||||
}
|
||||
|
||||
// trayClick is where the tray host said the icon was clicked, across its
|
||||
// bar: Wails' Linux tray keeps Activate(x, y)'s coordinates
|
||||
// (SystemTray.impl.lastClickX) and passes the click handler none. ok is
|
||||
// false when they aren't there to read.
|
||||
func trayClick(tray *application.SystemTray) (x int, ok bool) {
|
||||
if tray == nil {
|
||||
return 0, false
|
||||
}
|
||||
return clickIn(reflect.ValueOf(tray).Elem())
|
||||
}
|
||||
|
||||
// setTrayPassive takes the tray's StatusNotifierItem out of the bar's tray
|
||||
// (Status "Passive") while magpie's icon is in Omarchy's bar as its widget,
|
||||
// and puts it back ("Active") when it isn't. Omarchy's tray and waybar's both
|
||||
|
||||
@@ -9,3 +9,6 @@ func setTrayTip(*application.SystemTray, string) bool { return true }
|
||||
|
||||
// setTrayPassive: only Linux has Omarchy's bar to put the icon in instead.
|
||||
func setTrayPassive(*application.SystemTray, bool) bool { return true }
|
||||
|
||||
// trayClick: Wails places the panel by the click itself here.
|
||||
func trayClick(*application.SystemTray) (int, bool) { return 0, false }
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
package omarchy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"os"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Niri is whether magpie runs under niri. As under Hyprland, a Wayland
|
||||
// window can't place itself, so the tray panel opened where niri floats a
|
||||
// new window: the middle of the screen (#1670).
|
||||
func Niri() bool {
|
||||
return runtime.GOOS == "linux" && os.Getenv("NIRI_SOCKET") != ""
|
||||
}
|
||||
|
||||
// NiriPanel puts the panel under niri's bar, beside the icon clicked, each
|
||||
// time it opens. niri has no rule a program can add while it runs and
|
||||
// doesn't tell where the pointer is, so the panel is found by its title
|
||||
// among the windows niri announces, made floating and moved there; it
|
||||
// still opens in the middle and slides up. A click on another window takes
|
||||
// niri's focus from it, and Wails' HideOnFocusLost closes it then.
|
||||
type NiriPanel struct {
|
||||
mu sync.Mutex
|
||||
iconX int // where the icon was clicked across its bar
|
||||
known bool // whether iconX is known: not when `magpie panel` opened it
|
||||
}
|
||||
|
||||
// Opening says the panel is about to open, from a click at x across the
|
||||
// tray's bar (the tray host's Activate(x, y)), or with x nil from anything
|
||||
// else, when it goes to the top right.
|
||||
func (p *NiriPanel) Opening(x *int) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.known = x != nil
|
||||
if x != nil {
|
||||
p.iconX = *x
|
||||
}
|
||||
}
|
||||
|
||||
// take is the click Opening was told of, once.
|
||||
func (p *NiriPanel) take() (x int, known bool) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
x, known = p.iconX, p.known
|
||||
p.known = false
|
||||
return x, known
|
||||
}
|
||||
|
||||
// Watch places each window of this process titled title as it opens, for
|
||||
// as long as magpie runs, reconnecting when niri restarts.
|
||||
func (p *NiriPanel) Watch(title string) {
|
||||
for {
|
||||
if c, err := niriDial(); err == nil {
|
||||
_ = watchWindows(c, title, os.Getpid(), p.place)
|
||||
c.Close()
|
||||
}
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
// niriWindow is what magpie reads of niri-ipc's Window.
|
||||
type niriWindow struct {
|
||||
ID uint64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
PID int `json:"pid"`
|
||||
IsFloating bool `json:"is_floating"`
|
||||
Layout struct {
|
||||
TileSize [2]float64 `json:"tile_size"` // the window and its border, as placed
|
||||
} `json:"layout"`
|
||||
}
|
||||
|
||||
// watchWindows reads niri's event stream on c and calls place once for
|
||||
// each window of pid titled title: when the stream starts (the panel may
|
||||
// have opened before it did) and whenever one opens or takes the title.
|
||||
// A window placed isn't placed again, so one dragged stays where it went.
|
||||
func watchWindows(c io.ReadWriter, title string, pid int, place func(niriWindow)) error {
|
||||
if _, err := io.WriteString(c, `"EventStream"`+"\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
sc := bufio.NewScanner(c)
|
||||
sc.Buffer(nil, 16<<20) // the first event lists every window
|
||||
if !sc.Scan() {
|
||||
return cmpErr(sc.Err(), io.EOF)
|
||||
}
|
||||
if err := niriReply(sc.Bytes(), nil); err != nil {
|
||||
return err
|
||||
}
|
||||
placed := map[uint64]bool{}
|
||||
see := func(w niriWindow) {
|
||||
if w.Title == title && (w.PID == 0 || w.PID == pid) && !placed[w.ID] {
|
||||
placed[w.ID] = true
|
||||
place(w)
|
||||
}
|
||||
}
|
||||
for sc.Scan() {
|
||||
var ev struct {
|
||||
WindowsChanged *struct {
|
||||
Windows []niriWindow `json:"windows"`
|
||||
}
|
||||
WindowOpenedOrChanged *struct {
|
||||
Window niriWindow `json:"window"`
|
||||
}
|
||||
WindowClosed *struct {
|
||||
ID uint64 `json:"id"`
|
||||
}
|
||||
}
|
||||
if json.Unmarshal(sc.Bytes(), &ev) != nil {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case ev.WindowsChanged != nil:
|
||||
open := map[uint64]bool{}
|
||||
for _, w := range ev.WindowsChanged.Windows {
|
||||
open[w.ID] = true
|
||||
}
|
||||
for id := range placed {
|
||||
if !open[id] {
|
||||
delete(placed, id)
|
||||
}
|
||||
}
|
||||
for _, w := range ev.WindowsChanged.Windows {
|
||||
see(w)
|
||||
}
|
||||
case ev.WindowOpenedOrChanged != nil:
|
||||
see(ev.WindowOpenedOrChanged.Window)
|
||||
case ev.WindowClosed != nil:
|
||||
delete(placed, ev.WindowClosed.ID)
|
||||
}
|
||||
}
|
||||
return cmpErr(sc.Err(), io.EOF)
|
||||
}
|
||||
|
||||
// place moves the panel w, just opened, under the bar of the output it
|
||||
// opened on (the focused one: it has just taken the focus).
|
||||
func (p *NiriPanel) place(w niriWindow) {
|
||||
x, known := p.take()
|
||||
var out struct {
|
||||
FocusedOutput *struct {
|
||||
Logical *struct {
|
||||
Width float64 `json:"width"`
|
||||
} `json:"logical"`
|
||||
}
|
||||
}
|
||||
if niriRequest("FocusedOutput", &out) != nil || out.FocusedOutput == nil || out.FocusedOutput.Logical == nil {
|
||||
return
|
||||
}
|
||||
px, py := panelSpot(x, known, w.Layout.TileSize[0], out.FocusedOutput.Logical.Width)
|
||||
if !w.IsFloating {
|
||||
_ = niriRequest(niriAction("MoveWindowToFloating", map[string]any{"id": w.ID}), nil)
|
||||
}
|
||||
_ = niriRequest(moveTo(w.ID, px, py), nil)
|
||||
}
|
||||
|
||||
// panelSpot is where a panel width wide goes in niri's working area (the
|
||||
// output less the bar), whose top left a floating window's position counts
|
||||
// from: PanelGap under the bar, its middle at the click, kept PanelGap
|
||||
// inside the output's sides; at the top right when the click isn't known.
|
||||
// A tray host on Wayland knows only its own bar's coordinates, so a click
|
||||
// counts across the output; one off it (a host giving coordinates across
|
||||
// every output) is taken as not known. outW is the output's logical width.
|
||||
func panelSpot(clickX int, known bool, width, outW float64) (x, y float64) {
|
||||
right := outW - width - PanelGap
|
||||
x = right
|
||||
if cx := float64(clickX); known && cx >= 0 && cx < outW {
|
||||
x = min(right, cx-width/2)
|
||||
}
|
||||
return math.Round(max(PanelGap, x)), PanelGap
|
||||
}
|
||||
|
||||
// moveTo is niri-ipc's MoveFloatingWindow, to x, y in the working area.
|
||||
func moveTo(id uint64, x, y float64) any {
|
||||
return niriAction("MoveFloatingWindow", map[string]any{
|
||||
"id": id,
|
||||
"x": map[string]float64{"SetFixed": x},
|
||||
"y": map[string]float64{"SetFixed": y},
|
||||
})
|
||||
}
|
||||
|
||||
func niriAction(name string, args map[string]any) any {
|
||||
return map[string]any{"Action": map[string]any{name: args}}
|
||||
}
|
||||
|
||||
func niriDial() (net.Conn, error) {
|
||||
sock := os.Getenv("NIRI_SOCKET")
|
||||
if sock == "" {
|
||||
return nil, errors.New("niri: NIRI_SOCKET is not set")
|
||||
}
|
||||
return net.DialTimeout("unix", sock, time.Second)
|
||||
}
|
||||
|
||||
// niriRequest sends niri one request, a line of JSON, and reads its reply
|
||||
// into v, the Ok side of niri-ipc's Reply.
|
||||
func niriRequest(req, v any) error {
|
||||
c, err := niriDial()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer c.Close()
|
||||
_ = c.SetDeadline(time.Now().Add(time.Second))
|
||||
b, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := c.Write(append(b, '\n')); err != nil {
|
||||
return err
|
||||
}
|
||||
sc := bufio.NewScanner(c)
|
||||
sc.Buffer(nil, 16<<20)
|
||||
if !sc.Scan() {
|
||||
return cmpErr(sc.Err(), io.EOF)
|
||||
}
|
||||
return niriReply(sc.Bytes(), v)
|
||||
}
|
||||
|
||||
// niriReply reads niri-ipc's Reply, {"Ok": …} or {"Err": "…"}, into v.
|
||||
func niriReply(line []byte, v any) error {
|
||||
var r struct {
|
||||
Ok json.RawMessage
|
||||
Err *string
|
||||
}
|
||||
if err := json.Unmarshal(line, &r); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Err != nil {
|
||||
return errors.New("niri: " + *r.Err)
|
||||
}
|
||||
if r.Ok == nil {
|
||||
return errors.New("niri: a reply with neither Ok nor Err")
|
||||
}
|
||||
if v == nil {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(r.Ok, v)
|
||||
}
|
||||
|
||||
func cmpErr(err, otherwise error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return otherwise
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package omarchy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The JSON below is niri's own, as niri-ipc 26.4.0 (niri v26.04,
|
||||
// niri-ipc/src/lib.rs) serializes it with serde's defaults: Reply is a
|
||||
// Result ({"Ok": …} / {"Err": "…"}), Response, Event, Action and
|
||||
// PositionChange are externally tagged enums, Window's Option fields are
|
||||
// null when unset and WindowLayout's pairs are arrays.
|
||||
|
||||
// panelJSON is a Window as niri-ipc's Window and WindowLayout have it.
|
||||
func panelJSON(id, pid int, title string, floating bool) string {
|
||||
return `{"id":` + itoa(id) + `,"title":` + quote(title) + `,"app_id":"magpie","pid":` + itoa(pid) +
|
||||
`,"workspace_id":1,"is_focused":true,"is_floating":` + map[bool]string{true: "true", false: "false"}[floating] +
|
||||
`,"is_urgent":false,"layout":{"pos_in_scrolling_layout":null,"tile_size":[440.0,520.0],"window_size":[440,520],` +
|
||||
`"tile_pos_in_workspace_view":[633.0,273.5],"window_offset_in_tile":[0.0,0.0]},"focus_timestamp":{"secs":12,"nanos":5000}}`
|
||||
}
|
||||
|
||||
// focusedOutput is niri's reply to "FocusedOutput": the reporter's 1.5
|
||||
// scale, a 2560x1600 panel at 1707x1067 logical.
|
||||
const focusedOutput = `{"Ok":{"FocusedOutput":{"name":"eDP-1","make":"BOE","model":"0x0BCA","serial":null,` +
|
||||
`"physical_size":[300,190],"modes":[{"width":2560,"height":1600,"refresh_rate":60000,"is_preferred":true}],` +
|
||||
`"current_mode":0,"is_custom_mode":false,"vrr_supported":false,"vrr_enabled":false,` +
|
||||
`"logical":{"x":0,"y":0,"width":1707,"height":1067,"scale":1.5,"transform":"Normal"}}}}`
|
||||
|
||||
func itoa(n int) string { b, _ := json.Marshal(n); return string(b) }
|
||||
|
||||
func quote(s string) string { b, _ := json.Marshal(s); return string(b) }
|
||||
|
||||
func TestPanelSpot(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
click int
|
||||
known bool
|
||||
x, y float64
|
||||
width float64
|
||||
output float64
|
||||
}{
|
||||
{"under the icon", 1200, true, 1200 - 220, 6, 440, 1707},
|
||||
{"icon near the right edge", 1690, true, 1707 - 6 - 440, 6, 440, 1707},
|
||||
{"icon near the left edge", 30, true, 6, 6, 440, 1707},
|
||||
{"not clicked: top right", 0, false, 1707 - 6 - 440, 6, 440, 1707},
|
||||
{"a click off the output: top right", 2100, true, 1707 - 6 - 440, 6, 440, 1707},
|
||||
{"a negative click: top right", -4, true, 1707 - 6 - 440, 6, 440, 1707},
|
||||
{"an output narrower than the panel", 200, true, 6, 6, 440, 400},
|
||||
{"half pixels round", 1001, true, 781, 6, 441, 1707},
|
||||
} {
|
||||
x, y := panelSpot(c.click, c.known, c.width, c.output)
|
||||
if x != c.x || y != c.y {
|
||||
t.Errorf("%s: %v,%v; want %v,%v", c.name, x, y, c.x, c.y)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The panel is placed once as it opens, whether it opened before the
|
||||
// stream started or after, and not again while it stays open; other
|
||||
// windows, another process's and the main window are left alone.
|
||||
func TestWatchWindows(t *testing.T) {
|
||||
const pid = 4242
|
||||
stream := strings.Join([]string{
|
||||
`{"Ok":"Handled"}`,
|
||||
`{"WorkspacesChanged":{"workspaces":[]}}`,
|
||||
`{"WindowsChanged":{"windows":[` + panelJSON(3, pid, "magpie", false) + `,` + panelJSON(7, pid, "magpie panel", true) + `,` + panelJSON(8, 99, "magpie panel", true) + `]}}`,
|
||||
`{"WindowFocusChanged":{"id":7}}`,
|
||||
`{"WindowOpenedOrChanged":{"window":` + panelJSON(7, pid, "magpie panel", true) + `}}`,
|
||||
`{"WindowLayoutsChanged":{"changes":[[7,{"pos_in_scrolling_layout":null,"tile_size":[440.0,520.0],"window_size":[440,520],"tile_pos_in_workspace_view":[1000.0,6.0],"window_offset_in_tile":[0.0,0.0]}]]}}`,
|
||||
`{"WindowClosed":{"id":7}}`,
|
||||
`{"WindowOpenedOrChanged":{"window":` + panelJSON(9, pid, "magpie", false) + `}}`,
|
||||
`{"WindowOpenedOrChanged":{"window":` + panelJSON(9, pid, "magpie panel", false) + `}}`,
|
||||
`{"WindowOpenedOrChanged":{"window":` + panelJSON(9, pid, "magpie panel", false) + `}}`,
|
||||
`{"SomeEventNiriAddsLater":{"x":1}}`,
|
||||
`{"WindowsChanged":{"windows":[` + panelJSON(9, pid, "magpie panel", false) + `]}}`,
|
||||
``,
|
||||
}, "\n")
|
||||
var sent bytes.Buffer
|
||||
c := struct {
|
||||
io.Reader
|
||||
io.Writer
|
||||
}{strings.NewReader(stream), &sent}
|
||||
var placed []uint64
|
||||
if err := watchWindows(c, "magpie panel", pid, func(w niriWindow) { placed = append(placed, w.ID) }); err != io.EOF {
|
||||
t.Fatalf("watchWindows: %v, want EOF at the stream's end", err)
|
||||
}
|
||||
if sent.String() != "\"EventStream\"\n" {
|
||||
t.Fatalf("asked %q, want niri-ipc's Request::EventStream", sent.String())
|
||||
}
|
||||
if want := []uint64{7, 9}; len(placed) != 2 || placed[0] != want[0] || placed[1] != want[1] {
|
||||
t.Fatalf("placed %v, want %v", placed, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWatchWindowsRefused(t *testing.T) {
|
||||
c := struct {
|
||||
io.Reader
|
||||
io.Writer
|
||||
}{strings.NewReader(`{"Err":"unknown request"}` + "\n"), io.Discard}
|
||||
if err := watchWindows(c, "magpie panel", 1, func(niriWindow) { t.Fatal("placed") }); err == nil || !strings.Contains(err.Error(), "unknown request") {
|
||||
t.Fatalf("watchWindows: %v, want niri's error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// fakeNiri answers on NIRI_SOCKET as niri does, one request a line, and
|
||||
// keeps the requests.
|
||||
func fakeNiri(t *testing.T, answer func(req string) string) (sent func() []string) {
|
||||
dir, err := os.MkdirTemp("", "niri") // a socket path fits in 104 bytes
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sock := filepath.Join(dir, "niri.sock")
|
||||
l, err := net.Listen("unix", sock)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var mu sync.Mutex
|
||||
var got []string
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
sc := bufio.NewScanner(c)
|
||||
for sc.Scan() {
|
||||
mu.Lock()
|
||||
got = append(got, sc.Text())
|
||||
mu.Unlock()
|
||||
io.WriteString(c, answer(sc.Text())+"\n")
|
||||
}
|
||||
c.Close()
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
l.Close()
|
||||
wg.Wait()
|
||||
os.RemoveAll(dir)
|
||||
})
|
||||
t.Setenv("NIRI_SOCKET", sock)
|
||||
return func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return append([]string(nil), got...)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlacePanel(t *testing.T) {
|
||||
answer := func(req string) string {
|
||||
if req == `"FocusedOutput"` {
|
||||
return focusedOutput
|
||||
}
|
||||
return `{"Ok":"Handled"}`
|
||||
}
|
||||
x := 1200
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
click *int
|
||||
floating bool
|
||||
want []string
|
||||
}{
|
||||
{"clicked, already floating", &x, true, []string{
|
||||
`"FocusedOutput"`,
|
||||
`{"Action":{"MoveFloatingWindow":{"id":7,"x":{"SetFixed":980},"y":{"SetFixed":6}}}}`,
|
||||
}},
|
||||
{"opened by magpie panel, tiled", nil, false, []string{
|
||||
`"FocusedOutput"`,
|
||||
`{"Action":{"MoveWindowToFloating":{"id":7}}}`,
|
||||
`{"Action":{"MoveFloatingWindow":{"id":7,"x":{"SetFixed":1261},"y":{"SetFixed":6}}}}`,
|
||||
}},
|
||||
} {
|
||||
got := fakeNiri(t, answer)
|
||||
var w niriWindow
|
||||
if err := json.Unmarshal([]byte(panelJSON(7, 1, "magpie panel", c.floating)), &w); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var p NiriPanel
|
||||
p.Opening(c.click)
|
||||
p.place(w)
|
||||
if sent := strings.Join(got(), "\n"); sent != strings.Join(c.want, "\n") {
|
||||
t.Errorf("%s: sent\n%s\nwant\n%s", c.name, sent, strings.Join(c.want, "\n"))
|
||||
}
|
||||
// the click is used once: the next opening, not clicked, goes top right
|
||||
if _, known := p.take(); known {
|
||||
t.Errorf("%s: the click was kept for the next opening", c.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A niri that can't say its focused output gets no move at all.
|
||||
func TestPlacePanelNoOutput(t *testing.T) {
|
||||
got := fakeNiri(t, func(req string) string {
|
||||
if req == `"FocusedOutput"` {
|
||||
return `{"Ok":{"FocusedOutput":null}}`
|
||||
}
|
||||
return `{"Ok":"Handled"}`
|
||||
})
|
||||
var p NiriPanel
|
||||
p.place(niriWindow{ID: 7})
|
||||
if sent := got(); len(sent) != 1 {
|
||||
t.Fatalf("sent %q, want only the question", sent)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user