diff --git a/cmd/deckhudd/run.go b/cmd/deckhudd/run.go index c734147..4505b32 100644 --- a/cmd/deckhudd/run.go +++ b/cmd/deckhudd/run.go @@ -15,6 +15,7 @@ import ( "syscall" "time" + "github.com/RustyRaptor/deckhud/internal/accent" "github.com/RustyRaptor/deckhud/internal/appwatch" "github.com/RustyRaptor/deckhud/internal/engine" "github.com/RustyRaptor/deckhud/internal/hid" @@ -41,6 +42,7 @@ type daemon struct { cfgPath string cfgMod time.Time app appwatch.State + accent string } func run(ctx context.Context, opts runOpts) error { @@ -61,6 +63,12 @@ func run(ctx context.Context, opts runOpts) error { fmt.Fprintln(os.Stderr, "deckhudd: config:", err) } go d.watchConfig(ctx) + go accent.Watch(ctx, func(hex string) { + d.mu.Lock() + d.accent = hex + d.mu.Unlock() + d.emit(accentMsg(hex)) + }) ctx, cancel := context.WithCancel(ctx) var ui sync.WaitGroup defer func() { cancel(); ui.Wait() }() // never leave an orphaned overlay @@ -87,14 +95,19 @@ func (d *daemon) greeting() []any { d.mu.Lock() defer d.mu.Unlock() msgs := []any{map[string]any{"type": "hello", "version": protocolVersion}} + if d.accent != "" { + msgs = append(msgs, accentMsg(d.accent)) + } if d.eng != nil { msgs = append(msgs, d.configMsg()) - st := d.eng.State() - msgs = append(msgs, engine.Event{Type: "state", State: &st}) + st, sh := d.eng.State(), d.eng.Sheet() + msgs = append(msgs, engine.Event{Type: "state", State: &st, Sheet: &sh}) } return msgs } +func accentMsg(hex string) map[string]any { return map[string]any{"type": "accent", "color": hex} } + func (d *daemon) configMsg() map[string]any { return map[string]any{"type": "config", "app": d.app.App, "title": d.cfg.Title} } @@ -143,11 +156,11 @@ func (d *daemon) reload(full bool) error { } d.cfg, d.cfgPath, d.cfgMod = cfg, path, st.ModTime() d.eng = engine.New(cfg, engine.Options{}) - st2 := d.eng.State() + st2, sh := d.eng.State(), d.eng.Sheet() go func(cfgMsg map[string]any, state engine.Event) { // emit outside the lock d.emit(cfgMsg) d.emit(state) - }(d.configMsg(), engine.Event{Type: "state", State: &st2}) + }(d.configMsg(), engine.Event{Type: "state", State: &st2, Sheet: &sh}) return nil } diff --git a/docs/research/flatpak-spike.md b/docs/research/flatpak-spike.md new file mode 100644 index 0000000..71a63e7 --- /dev/null +++ b/docs/research/flatpak-spike.md @@ -0,0 +1,35 @@ +# Spike: Flatpak packaging (2026-10-30) + +**Result: viable.** Built with `org.flatpak.Builder` against `org.kde.Platform//6.11`. + +| Question | Finding | +|---|---| +| Does KWin let a sandboxed client use `wlr-layer-shell`? | **Yes.** Overlay layer, transparent, above windows, same as on the host | +| LayerShellQt in the runtime? | **No.** Built `invent.kde.org/plasma/layer-shell-qt` tag `v6.7.3` as a module, unmodified (cmake-ninja, `-DBUILD_TESTING=OFF`) | +| `qml` runner in the runtime? | **No** (SDK only). A ~10-line C++ launcher (`QGuiApplication` + `QQmlApplicationEngine`) replaces it | +| Kirigami / QtWebSockets / QtQuick.Shapes in runtime? | Yes | +| Controller access | `--device=all` → `/dev/hidraw2` readable inside the sandbox (report `0x09` streams) | +| Steam files | `--filesystem=~/.local/share/Steam:ro` exposes `logs/controller.txt`, configs, binding icons | +| Loopback WebSocket | Works inside one sandbox instance without `--share=network`. **Separate `flatpak run` instances do not share loopback**, so a CLI → daemon control channel must use a Unix socket under `$XDG_RUNTIME_DIR/app//` | +| `--filesystem=` on `flatpak run` | Did not expose a hidden dir under `~/Projects`; `home:ro` did. `~/.cache` is never exposed | + +## Accent colour: Kirigami is not reliable, the portal is + +Plasma here derives the accent from a wallpaper **slideshow that changes every ~10 s**, which made single +readings misleading. Sampling host `qml`, sandboxed launcher and `kdeglobals` side by side for 60 s: + +- **Neither** process's `Kirigami.Theme` colour followed live changes (both stayed on their start value). +- The sandbox's start value equalled `[Colors:Selection] BackgroundNormal`; the host `qml` runner's did not + match the file at all. + +`org.freedesktop.portal.Settings` works on the host session bus and from sandboxes by default: + +```sh +busctl --user call org.freedesktop.portal.Desktop /org/freedesktop/portal/desktop \ + org.freedesktop.portal.Settings ReadOne ss org.freedesktop.appearance accent-color +# v (ddd) 0.941176 0.611765 0.792157 +``` + +and emits `SettingChanged(org.freedesktop.appearance, accent-color, (ddd))` on every slideshow change. +**Decision:** `deckhudd` reads the accent from the portal (fallback: `kdeglobals [General] AccentColor`) +and pushes it to the UI as an `accent` message. Kirigami is no longer used for colour. diff --git a/go.mod b/go.mod index c73e25d..842d265 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,9 @@ module github.com/RustyRaptor/deckhud go 1.27.3 -require github.com/coder/websocket v1.8.15 +require ( + github.com/coder/websocket v1.8.15 + github.com/godbus/dbus/v5 v5.2.4 +) + +require golang.org/x/sys v0.27.0 // indirect diff --git a/go.sum b/go.sum index 4e0a48d..4e90007 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,6 @@ github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA= github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= +github.com/godbus/dbus/v5 v5.2.4 h1:F2gUCy++NMIxGmo9J+z5le/+ZC8W1OgeR51P4i9ZB/U= +github.com/godbus/dbus/v5 v5.2.4/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= +golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s= +golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= diff --git a/internal/accent/accent.go b/internal/accent/accent.go new file mode 100644 index 0000000..f7cda85 --- /dev/null +++ b/internal/accent/accent.go @@ -0,0 +1,196 @@ +// Package accent tracks the desktop accent colour. +// +// The source of truth is the XDG settings portal (org.freedesktop.appearance +// accent-color), which works the same on the host and inside a Flatpak and +// signals every change, even when Plasma derives the accent from a wallpaper +// slideshow. kdeglobals is read as a fallback when no portal answers. +package accent + +import ( + "bufio" + "context" + "fmt" + "io" + "math" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/godbus/dbus/v5" +) + +// FromPortal converts the portal's (r, g, b) doubles in 0..1 to "#rrggbb". +// Out-of-range values mean "no accent set". +func FromPortal(rgb []float64) (string, error) { + if len(rgb) != 3 { + return "", fmt.Errorf("accent: want 3 components, got %d", len(rgb)) + } + var c [3]int + for i, v := range rgb { + if v < 0 || v > 1 || math.IsNaN(v) { + return "", fmt.Errorf("accent: component %v out of range", v) + } + c[i] = int(math.Round(v * 255)) + } + return fmt.Sprintf("#%02x%02x%02x", c[0], c[1], c[2]), nil +} + +// FromKdeglobals reads [General] AccentColor, falling back to the colour +// scheme's selection background. +func FromKdeglobals(r io.Reader) (string, error) { + var group, accent, selection string + sc := bufio.NewScanner(r) + for sc.Scan() { + line := strings.TrimSpace(sc.Text()) + if strings.HasPrefix(line, "[") { + group = line + continue + } + k, v, ok := strings.Cut(line, "=") + switch { + case !ok: + case group == "[General]" && k == "AccentColor": + accent = v + case group == "[Colors:Selection]" && k == "BackgroundNormal": + selection = v + } + } + for _, v := range []string{accent, selection} { + if hex, err := fromRGBList(v); err == nil { + return hex, nil + } + } + return "", fmt.Errorf("accent: no AccentColor or selection colour in kdeglobals") +} + +func fromRGBList(s string) (string, error) { + parts := strings.Split(s, ",") + if len(parts) < 3 { + return "", fmt.Errorf("accent: bad colour %q", s) + } + var c [3]int + for i := range c { + n, err := strconv.Atoi(strings.TrimSpace(parts[i])) + if err != nil || n < 0 || n > 255 { + return "", fmt.Errorf("accent: bad colour %q", s) + } + c[i] = n + } + return fmt.Sprintf("#%02x%02x%02x", c[0], c[1], c[2]), nil +} + +const ( + portalDest = "org.freedesktop.portal.Desktop" + portalPath = "/org/freedesktop/portal/desktop" + settingsIfc = "org.freedesktop.portal.Settings" + namespace = "org.freedesktop.appearance" + key = "accent-color" +) + +// Watch calls f with the current accent and again whenever it changes, until +// ctx ends. It prefers the portal and falls back to polling kdeglobals. +func Watch(ctx context.Context, f func(hex string)) { + last := "" + emit := func(hex string) { + if hex != "" && hex != last { + last = hex + f(hex) + } + } + if err := watchPortal(ctx, emit); err == nil || ctx.Err() != nil { + return + } + pollKdeglobals(ctx, emit) +} + +func watchPortal(ctx context.Context, emit func(string)) error { + conn, err := dbus.ConnectSessionBus() + if err != nil { + return err + } + defer conn.Close() + + obj := conn.Object(portalDest, portalPath) + var v dbus.Variant + if err := obj.CallWithContext(ctx, settingsIfc+".ReadOne", 0, namespace, key).Store(&v); err != nil { + return err + } + if hex, err := portalValue(v); err == nil { + emit(hex) + } + + if err := conn.AddMatchSignalContext(ctx, + dbus.WithMatchObjectPath(portalPath), + dbus.WithMatchInterface(settingsIfc), + dbus.WithMatchMember("SettingChanged"), + dbus.WithMatchArg(0, namespace), + dbus.WithMatchArg(1, key), + ); err != nil { + return err + } + signals := make(chan *dbus.Signal, 16) + conn.Signal(signals) + for { + select { + case <-ctx.Done(): + return nil + case s, ok := <-signals: + if !ok { + return fmt.Errorf("accent: bus closed") + } + if len(s.Body) == 3 { + if v, ok := s.Body[2].(dbus.Variant); ok { + if hex, err := portalValue(v); err == nil { + emit(hex) + } + } + } + } + } +} + +// portalValue unwraps the (ddd) struct, which godbus decodes as []any. +func portalValue(v dbus.Variant) (string, error) { + if inner, ok := v.Value().(dbus.Variant); ok { // older portals double-wrap + v = inner + } + fields, ok := v.Value().([]any) + if !ok { + return "", fmt.Errorf("accent: unexpected portal value %v", v) + } + rgb := make([]float64, 0, 3) + for _, x := range fields { + d, ok := x.(float64) + if !ok { + return "", fmt.Errorf("accent: unexpected portal value %v", v) + } + rgb = append(rgb, d) + } + return FromPortal(rgb) +} + +func pollKdeglobals(ctx context.Context, emit func(string)) { + dir := os.Getenv("XDG_CONFIG_HOME") + if dir == "" { + home, _ := os.UserHomeDir() + dir = filepath.Join(home, ".config") + } + path := filepath.Join(dir, "kdeglobals") + t := time.NewTicker(time.Second) + defer t.Stop() + for { + if f, err := os.Open(path); err == nil { + if hex, err := FromKdeglobals(f); err == nil { + emit(hex) + } + f.Close() + } + select { + case <-ctx.Done(): + return + case <-t.C: + } + } +} diff --git a/internal/accent/accent_test.go b/internal/accent/accent_test.go new file mode 100644 index 0000000..6f341c7 --- /dev/null +++ b/internal/accent/accent_test.go @@ -0,0 +1,74 @@ +package accent + +import ( + "context" + "os" + "strings" + "testing" + "time" +) + +func TestFromPortal(t *testing.T) { + cases := []struct { + in []float64 + want string + wantErr bool + }{ + {[]float64{0.941176, 0.611765, 0.792157}, "#f09cca", false}, + {[]float64{0, 0, 0}, "#000000", false}, + {[]float64{1, 1, 1}, "#ffffff", false}, + {[]float64{-1, -1, -1}, "", true}, // portal's "no accent set" + {[]float64{0.5, 2, 0.5}, "", true}, + {[]float64{0.5, 0.5}, "", true}, + } + for _, c := range cases { + got, err := FromPortal(c.in) + if (err != nil) != c.wantErr || got != c.want { + t.Errorf("FromPortal(%v) = %q, %v; want %q, err=%v", c.in, got, err, c.want, c.wantErr) + } + } +} + +func TestFromKdeglobals(t *testing.T) { + src := `[ColorEffects:Disabled] +AccentColor=1,2,3 + +[Colors:Selection] +BackgroundNormal=126,196,124 + +[General] +AccentColor=243,121,185 +accentColorFromWallpaper=true +` + got, err := FromKdeglobals(strings.NewReader(src)) + if err != nil || got != "#f379b9" { + t.Errorf("got %q, %v; want #f379b9 from [General] only", got, err) + } + + noAccent := "[Colors:Selection]\nBackgroundNormal=61,174,233\n" + if got, err := FromKdeglobals(strings.NewReader(noAccent)); err != nil || got != "#3daee9" { + t.Errorf("selection fallback = %q, %v", got, err) + } + if _, err := FromKdeglobals(strings.NewReader("[General]\nfoo=bar\n")); err == nil { + t.Error("expected error with no colour at all") + } +} + +// TestWatchLivePortal talks to the real session portal; skipped without one. +func TestWatchLivePortal(t *testing.T) { + if os.Getenv("DBUS_SESSION_BUS_ADDRESS") == "" { + t.Skip("no session bus") + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + got := make(chan string, 8) + go Watch(ctx, func(hex string) { got <- hex }) + select { + case c := <-got: + if len(c) != 7 || c[0] != '#' { + t.Errorf("bad colour %q", c) + } + case <-ctx.Done(): + t.Skip("portal did not answer (no xdg-desktop-portal?)") + } +} diff --git a/internal/engine/sheet.go b/internal/engine/sheet.go index 110e2a2..5e889e6 100644 --- a/internal/engine/sheet.go +++ b/internal/engine/sheet.go @@ -86,7 +86,7 @@ func (e *Engine) control(glyph, source, input string, layers []*steamcfg.Set, sh if g == nil { return nil } - c := &Control{Glyph: glyph, Source: source, Mode: g.Mode} + c := &Control{Glyph: glyph, Source: source, Mode: g.Mode, Entries: []Entry{}} if input != "" { c.Entries = entries("", e.cfg.Activators(e.base, layers, shifted, source, input)) if len(c.Entries) == 0 { diff --git a/internal/engine/sheet_test.go b/internal/engine/sheet_test.go index 6807d03..1f4d7ca 100644 --- a/internal/engine/sheet_test.go +++ b/internal/engine/sheet_test.go @@ -1,7 +1,9 @@ package engine import ( + "encoding/json" "reflect" + "strings" "testing" "time" @@ -112,3 +114,14 @@ func TestStateEventsCarryTheSheet(t *testing.T) { } t.Fatal("no state event") } + +func TestSheetJSONHasNoNullEntries(t *testing.T) { + s := newSim(t, "desktop_neptune.vdf") + data, err := json.Marshal(s.e.Sheet()) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(data), `"entries":null`) { + t.Errorf("controls without inputs must encode entries as [], got %s", data) + } +} diff --git a/ui/components/Hud.qml b/ui/components/Hud.qml index 0b04725..67db08a 100644 --- a/ui/components/Hud.qml +++ b/ui/components/Hud.qml @@ -5,6 +5,7 @@ Item { id: hud property color accent: "#9a93e3" + Behavior on accent { ColorAnimation { duration: 400 } } property string iconDir: "" property bool quietNextState: false property var lastSheet: null @@ -27,6 +28,10 @@ Item { function handle(msg) { switch (msg.type) { + case "accent": + if (/^#[0-9a-fA-F]{6}$/.test(msg.color ?? "")) + accent = msg.color + break case "hello": quietNextState = true break diff --git a/ui/main.qml b/ui/main.qml index e58fecb..7e0b896 100644 --- a/ui/main.qml +++ b/ui/main.qml @@ -1,7 +1,6 @@ import QtQuick import QtCore import QtWebSockets -import org.kde.kirigami as Kirigami import org.kde.layershell as LayerShell import "components" @@ -27,10 +26,8 @@ Window { Hud { id: hud anchors.fill: parent - accent: Kirigami.Theme.highlightColor iconDir: StandardPaths.writableLocation(StandardPaths.GenericDataLocation) + "/Steam/tenfoot/resource/images/library/controller/binding_icons" - Behavior on accent { ColorAnimation { duration: 400 } } } WebSocket { diff --git a/ui/tests/tst_hud.qml b/ui/tests/tst_hud.qml index 2746fc6..1153b0e 100644 --- a/ui/tests/tst_hud.qml +++ b/ui/tests/tst_hud.qml @@ -66,5 +66,14 @@ Item { h.handle({ type: "bogus" }) compare(h.toasts.count, 1) } + + function test_accentMessage() { + const h = createTemporaryObject(hudComponent, root) + h.handle({ type: "accent", color: "#f09cca" }) + tryCompare(h, "accent", Qt.color("#f09cca"), 2000) + h.handle({ type: "accent", color: "not a colour" }) + wait(600) + compare(h.accent, Qt.color("#f09cca"), "invalid colours are ignored") + } } }