package hypr import ( "bufio" "context" "errors" "fmt" "net" "os" "path/filepath" "strings" "time" ) // Control commands sent by hypridle hooks via `hypr-agent `. var Commands = map[string]bool{"idle": true, "resume": true, "lock": true, "unlock": true} // ControlEvent is a control command stamped with when it was received. type ControlEvent struct { Command string At time.Time } // ControlSocketPath is where the running agent listens for control commands. func ControlSocketPath() string { dir := os.Getenv("XDG_RUNTIME_DIR") if dir == "" { dir = os.TempDir() } return filepath.Join(dir, "hypr-agent.sock") } // ServeControl accepts one-line commands on the control socket until ctx is // cancelled. func ServeControl(ctx context.Context, out chan<- ControlEvent) error { path := ControlSocketPath() os.Remove(path) // stale socket from a previous run ln, err := net.Listen("unix", path) if err != nil { return err } go func() { <-ctx.Done() ln.Close() }() 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, _ := bufio.NewReader(conn).ReadString('\n') cmd := strings.TrimSpace(line) if !Commands[cmd] { fmt.Fprintf(conn, "unknown command %q\n", cmd) return } select { case out <- ControlEvent{Command: cmd, At: time.Now()}: fmt.Fprintln(conn, "ok") case <-ctx.Done(): // the agent stopped reading fmt.Fprintln(conn, "shutting down") } }() } } // SendControl sends a command to the running agent. func SendControl(cmd string) error { conn, err := net.DialTimeout("unix", ControlSocketPath(), 2*time.Second) if err != nil { return fmt.Errorf("is hypr-agent 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(reply) } return nil }