diff --git a/cmd/deckhudd/main.go b/cmd/deckhudd/main.go index a4b0a2c..1b31cb1 100644 --- a/cmd/deckhudd/main.go +++ b/cmd/deckhudd/main.go @@ -16,6 +16,7 @@ import ( "github.com/RustyRaptor/deckhud/internal/appwatch" "github.com/RustyRaptor/deckhud/internal/binding" + "github.com/RustyRaptor/deckhud/internal/control" "github.com/RustyRaptor/deckhud/internal/hid" "github.com/RustyRaptor/deckhud/internal/steamcfg" ) @@ -27,6 +28,8 @@ commands: (default: ../share/deckhud/ui next to the binary) events run without the overlay, printing events as JSON lines demo [ui-dir] play a scripted session through the overlay (no controller needed) + peek toggle the cheat sheet in the running daemon + (bind it to a KDE shortcut, then map a Steam button to that) find print the Deck controller hidraw device dump print the active Steam Input config as deckhud sees it monitor print button changes and stick angles live @@ -57,6 +60,8 @@ func main() { err = demo(ctx, dir) case "events": err = run(ctx, runOpts{print: true}) + case "peek": + err = control.Send(control.DefaultPath(), "peek") case "find": var dev string if dev, err = hid.Find("/sys"); err == nil { diff --git a/cmd/deckhudd/run.go b/cmd/deckhudd/run.go index 4505b32..8d6a005 100644 --- a/cmd/deckhudd/run.go +++ b/cmd/deckhudd/run.go @@ -17,6 +17,7 @@ import ( "github.com/RustyRaptor/deckhud/internal/accent" "github.com/RustyRaptor/deckhud/internal/appwatch" + "github.com/RustyRaptor/deckhud/internal/control" "github.com/RustyRaptor/deckhud/internal/engine" "github.com/RustyRaptor/deckhud/internal/hid" "github.com/RustyRaptor/deckhud/internal/ipc" @@ -47,6 +48,15 @@ type daemon struct { func run(ctx context.Context, opts runOpts) error { d := &daemon{opts: opts} + ctx, cancel := context.WithCancel(ctx) + defer cancel() + ready, served := make(chan struct{}), make(chan error, 1) + go func() { served <- control.Serve(ctx, control.DefaultPath(), ready, d.command) }() + select { + case <-ready: + case err := <-served: + return err + } token := randomToken() d.hub = ipc.NewHub(token, d.greeting) @@ -69,7 +79,6 @@ func run(ctx context.Context, opts runOpts) error { 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 if opts.uiDir != "" { @@ -106,6 +115,16 @@ func (d *daemon) greeting() []any { return msgs } +// command handles control-socket commands from 'deckhudd peek' and friends. +func (d *daemon) command(cmd string) error { + switch cmd { + case "peek": + d.emit(map[string]any{"type": "peek"}) + return nil + } + return control.ErrUnknown +} + func accentMsg(hex string) map[string]any { return map[string]any{"type": "accent", "color": hex} } func (d *daemon) configMsg() map[string]any { diff --git a/internal/control/control.go b/internal/control/control.go new file mode 100644 index 0000000..25f36c9 --- /dev/null +++ b/internal/control/control.go @@ -0,0 +1,98 @@ +// Package control is a tiny line-based command channel to a running daemon +// over a Unix socket (e.g. "peek" to toggle the cheat sheet). Inside a Flatpak +// the socket lives in the app's shared runtime dir, which every instance of +// the app can reach; loopback TCP is not shared between instances. +package control + +import ( + "bufio" + "context" + "errors" + "fmt" + "net" + "os" + "path/filepath" + "strings" + "time" +) + +// ErrUnknown is returned by handlers for commands they don't support. +var ErrUnknown = errors.New("unknown command") + +// SocketPath returns where the daemon listens. +func SocketPath(runtimeDir, flatpakID string) string { + if flatpakID != "" { + return filepath.Join(runtimeDir, "app", flatpakID, "control.sock") + } + return filepath.Join(runtimeDir, "deckhud", "control.sock") +} + +// DefaultPath derives SocketPath from the environment. +func DefaultPath() string { + rt := os.Getenv("XDG_RUNTIME_DIR") + if rt == "" { + rt = filepath.Join(os.TempDir(), fmt.Sprintf("deckhud-%d", os.Getuid())) + } + return SocketPath(rt, os.Getenv("FLATPAK_ID")) +} + +// Serve accepts commands until ctx ends. ready is closed once listening. +func Serve(ctx context.Context, path string, ready chan<- struct{}, handle func(cmd string) error) error { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + if c, err := net.Dial("unix", path); err == nil { + c.Close() + return fmt.Errorf("control: another daemon is listening on %s", path) + } + os.Remove(path) // stale socket from a crashed daemon + ln, err := net.Listen("unix", path) + if err != nil { + return err + } + go func() { <-ctx.Done(); ln.Close() }() + close(ready) + for { + conn, err := ln.Accept() + if err != nil { + if ctx.Err() != nil { + return nil + } + return err + } + go func() { + defer conn.Close() + conn.SetDeadline(time.Now().Add(2 * time.Second)) + line, err := bufio.NewReader(conn).ReadString('\n') + if err != nil { + return + } + if err := handle(strings.TrimSpace(line)); err != nil { + fmt.Fprintf(conn, "error: %v\n", err) + return + } + fmt.Fprintln(conn, "ok") + }() + } +} + +// Send delivers one command and waits for the reply. +func Send(path, cmd string) error { + conn, err := net.DialTimeout("unix", path, time.Second) + if err != nil { + return fmt.Errorf("control: is deckhudd running? %w", err) + } + defer conn.Close() + conn.SetDeadline(time.Now().Add(2 * time.Second)) + if _, err := fmt.Fprintln(conn, cmd); err != nil { + return err + } + reply, err := bufio.NewReader(conn).ReadString('\n') + if err != nil { + return err + } + if reply = strings.TrimSpace(reply); reply != "ok" { + return errors.New(strings.TrimPrefix(reply, "error: ")) + } + return nil +} diff --git a/internal/control/control_test.go b/internal/control/control_test.go new file mode 100644 index 0000000..85fe93f --- /dev/null +++ b/internal/control/control_test.go @@ -0,0 +1,80 @@ +package control + +import ( + "context" + "path/filepath" + "testing" + "time" +) + +func TestSendReachesHandler(t *testing.T) { + path := filepath.Join(t.TempDir(), "control.sock") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + got := make(chan string, 1) + ready := make(chan struct{}) + go func() { + if err := Serve(ctx, path, ready, func(cmd string) error { got <- cmd; return nil }); err != nil { + t.Errorf("Serve: %v", err) + } + }() + <-ready + if err := Send(path, "peek"); err != nil { + t.Fatalf("Send: %v", err) + } + select { + case cmd := <-got: + if cmd != "peek" { + t.Errorf("cmd = %q", cmd) + } + case <-time.After(2 * time.Second): + t.Fatal("handler not called") + } +} + +func TestUnknownCommandErrors(t *testing.T) { + path := filepath.Join(t.TempDir(), "control.sock") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + ready := make(chan struct{}) + go Serve(ctx, path, ready, func(cmd string) error { return ErrUnknown }) + <-ready + if err := Send(path, "nope"); err == nil { + t.Error("expected an error for an unknown command") + } +} + +func TestSendWithoutDaemon(t *testing.T) { + if err := Send(filepath.Join(t.TempDir(), "none.sock"), "peek"); err == nil { + t.Error("expected error when no daemon is listening") + } +} + +func TestStaleSocketIsReplaced(t *testing.T) { + path := filepath.Join(t.TempDir(), "control.sock") + for i := 0; i < 2; i++ { // second Serve must not fail on the leftover file + ctx, cancel := context.WithCancel(context.Background()) + ready := make(chan struct{}) + done := make(chan error, 1) + go func() { done <- Serve(ctx, path, ready, func(string) error { return nil }) }() + select { + case <-ready: + case err := <-done: + t.Fatalf("round %d: %v", i, err) + } + cancel() + <-done + } +} + +func TestSocketPath(t *testing.T) { + cases := []struct{ runtime, flatpakID, want string }{ + {"/run/user/1000", "", "/run/user/1000/deckhud/control.sock"}, + {"/run/user/1000", "io.github.RustyRaptor.deckhud", "/run/user/1000/app/io.github.RustyRaptor.deckhud/control.sock"}, + } + for _, c := range cases { + if got := SocketPath(c.runtime, c.flatpakID); got != c.want { + t.Errorf("SocketPath(%q,%q) = %q, want %q", c.runtime, c.flatpakID, got, c.want) + } + } +}