mirror of
https://github.com/RustyRaptor/deckrotate.git
synced 2026-12-03 15:55:20 -07:00
Add deckrotate: Steam Deck screen rotation for Plasma
Go daemon reads the controller's accelerometer from hidraw (re-enabling the IMU that Steam switches off), debounces it into an orientation and rotates eDP-1 through kscreen-doctor in auto mode, or offers a layer-shell tap-to-rotate button in manual mode, with a persistent lock. Includes a D-Bus service, a CLI for global shortcuts (kglobalaccel service file), a Plasma system tray applet, a systemd user unit and hardware notes from probing the Deck OLED. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
81d2a986b6
53 files changed
+4422
No files matched your search
@@ -0,0 +1 @@
|
||||
bin/
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 RustyRaptor
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,135 @@
|
||||
# deckrotate
|
||||
|
||||
Screen rotation for the Steam Deck in KDE Plasma (Wayland) desktop mode:
|
||||
auto-rotate from the Deck's motion sensor, a tap-to-rotate button, a rotation
|
||||
lock, a system tray applet and global shortcuts.
|
||||
|
||||
SteamOS can't auto-rotate on its own: the Deck has no accelerometer the
|
||||
kernel knows about. deckrotate reads the one built into the controller
|
||||
instead (see [docs/hardware.md](docs/hardware.md)).
|
||||
|
||||
## Features
|
||||
|
||||
- **Auto mode**: the screen follows the Deck as soon as it settles in a new
|
||||
position (0.5 s).
|
||||
- **Manual mode**: turning the Deck shows a round button in the bottom-right
|
||||
corner, as you're now holding it, for 5 seconds. Tap it to rotate.
|
||||
- **Lock**: stops both modes reacting to the sensor. Explicit rotations from the
|
||||
applet, CLI or shortcuts still work.
|
||||
- **Tray applet**: pick any of the four orientations, rotate left/right, lock,
|
||||
and switch modes. Middle-click the tray icon to toggle the lock.
|
||||
- **Global shortcuts** for lock, rotate left/right/flip, each orientation,
|
||||
mode toggle, and "accept" for the manual-mode button.
|
||||
- Lying the Deck flat, or shaking it, never triggers a rotation.
|
||||
|
||||
## Install
|
||||
|
||||
Needs Go via [mise](https://mise.jdx.dev/) (`mise.toml` pins it). Everything
|
||||
installs under `$HOME`, so SteamOS's read-only root is untouched.
|
||||
|
||||
```sh
|
||||
mise run install
|
||||
systemctl --user enable --now deckrotate
|
||||
```
|
||||
|
||||
That installs:
|
||||
|
||||
| What | Where |
|
||||
|-------------------|-------------------------------------------------------------|
|
||||
| daemon + CLI | `~/.local/bin/deckrotate` |
|
||||
| overlay QML | `~/.local/share/deckrotate/ui/` |
|
||||
| tray applet | `~/.local/share/plasma/plasmoids/io.github.rustyraptor.deckrotate/` |
|
||||
| shortcut actions | `~/.local/share/kglobalaccel/io.github.rustyraptor.deckrotate.desktop` |
|
||||
| systemd user unit | `~/.config/systemd/user/deckrotate.service` |
|
||||
|
||||
The applet adds itself to the system tray. If it doesn't, right-click the tray,
|
||||
open **Configure System Tray → Entries** and set **Screen Rotation** to shown.
|
||||
|
||||
The shortcut actions appear under **System Settings → Keyboard → Shortcuts →
|
||||
Screen Rotation** after you next log in (KWin reads that directory at session
|
||||
start). None have a default key, so pick your own. With Steam Input you can
|
||||
bind a key combination to a Deck button combo.
|
||||
|
||||
`mise run uninstall` removes everything.
|
||||
|
||||
## CLI
|
||||
|
||||
```
|
||||
deckrotate status [--json]
|
||||
deckrotate lock | unlock | toggle-lock
|
||||
deckrotate mode auto|manual|toggle
|
||||
deckrotate rotate cw|ccw|flip
|
||||
deckrotate rotate landscape|portrait-cw|landscape-flipped|portrait-ccw
|
||||
deckrotate accept # take the manual-mode button's rotation
|
||||
deckrotate dismiss
|
||||
```
|
||||
|
||||
`portrait-cw` is the Deck turned clockwise (right grip down); `portrait-ccw`
|
||||
is left grip down. Settings persist in `~/.config/deckrotate/settings.json`.
|
||||
|
||||
## How it works
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
imu["/dev/hidrawN<br/>controller report 0x09"] -->|accel, 250 Hz| det["orient.Detector<br/>tilt + hysteresis + 0.5 s settle"]
|
||||
det -->|turned| core["core.Controller<br/>auto / manual / lock"]
|
||||
core -->|kscreen-doctor| kwin["KWin<br/>eDP-1 rotation"]
|
||||
core -->|spawn / kill| ov["overlay.qml<br/>layer-shell button"]
|
||||
ov -->|exit code 10 = tapped| core
|
||||
core <-->|D-Bus io.github.RustyRaptor.DeckRotate| applet["Plasma tray applet"]
|
||||
core <-->|D-Bus| cli["deckrotate CLI<br/>(global shortcuts)"]
|
||||
```
|
||||
|
||||
| Package | Role |
|
||||
|---------------------|---------------------------------------------------------------|
|
||||
| `internal/imu` | find the controller, decode reports, keep the IMU switched on |
|
||||
| `internal/orient` | accelerometer vector → orientation, debounced |
|
||||
| `internal/display` | read/set the panel rotation with `kscreen-doctor` |
|
||||
| `internal/core` | the mode/lock state machine |
|
||||
| `internal/overlay` | button placement maths and the overlay process |
|
||||
| `internal/service` | D-Bus object, properties and client |
|
||||
| `internal/daemon` | wiring; reopens the IMU after suspend/resume |
|
||||
| `ui/` | the manual-mode overlay (QML + LayerShellQt) |
|
||||
| `plasmoid/` | the tray applet (QML) |
|
||||
|
||||
The applet and overlay are QML because Plasma applets must be, and a Wayland
|
||||
corner overlay needs layer-shell, which has no pure-Go binding. Everything
|
||||
else is Go with CGO off.
|
||||
|
||||
### D-Bus API
|
||||
|
||||
Service and interface `io.github.RustyRaptor.DeckRotate`, object
|
||||
`/io/github/RustyRaptor/DeckRotate`.
|
||||
|
||||
| Property | Type | Notes |
|
||||
|------------------------|------|-----------------------------------------|
|
||||
| `Mode` | s | `auto` or `manual` |
|
||||
| `Locked` | b | |
|
||||
| `DeviceOrientation` | s | physical position, `unknown` until read |
|
||||
| `ScreenOrientation` | s | what the panel is rotated for |
|
||||
| `SuggestedOrientation` | s | manual-mode offer, empty when none |
|
||||
| `ImuAvailable` | b | |
|
||||
|
||||
Methods: `SetMode(s)`, `ToggleMode()`, `SetLocked(b)`, `ToggleLock()`,
|
||||
`RotateTo(s)`, `RotateBy(i quarterTurnsClockwise)`, `Accept()`, `Dismiss()`.
|
||||
Properties emit `PropertiesChanged`.
|
||||
|
||||
## Development
|
||||
|
||||
Written test-first. `mise run test` runs:
|
||||
|
||||
| Task | What |
|
||||
|-----------------|---------------------------------------------------------------------|
|
||||
| `test:go` | Go unit tests (private `dbus-daemon` for the service tests) |
|
||||
| `test:qml` | overlay QML tests, offscreen |
|
||||
| `test:plasmoid` | applet view and logic tests against a mock backend |
|
||||
| `test:dbus` | applet's real D-Bus backend against the Go service on a private bus |
|
||||
|
||||
`mise run test:hw` reads the real controller. The race detector needs cgo;
|
||||
on the Deck: `nix shell nixpkgs#gcc --command env CGO_ENABLED=1 go test -race ./...`.
|
||||
|
||||
Logs: `journalctl --user -u deckrotate -f`.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -0,0 +1,53 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseCommand(t *testing.T) {
|
||||
cases := []struct {
|
||||
args string
|
||||
method string
|
||||
params []any
|
||||
}{
|
||||
{"lock", "SetLocked", []any{true}},
|
||||
{"unlock", "SetLocked", []any{false}},
|
||||
{"toggle-lock", "ToggleLock", nil},
|
||||
{"mode auto", "SetMode", []any{"auto"}},
|
||||
{"mode manual", "SetMode", []any{"manual"}},
|
||||
{"mode toggle", "ToggleMode", nil},
|
||||
{"rotate cw", "RotateBy", []any{int32(1)}},
|
||||
{"rotate ccw", "RotateBy", []any{int32(-1)}},
|
||||
{"rotate flip", "RotateBy", []any{int32(2)}},
|
||||
{"rotate landscape", "RotateTo", []any{"landscape"}},
|
||||
{"rotate portrait-cw", "RotateTo", []any{"portrait-cw"}},
|
||||
{"rotate portrait-ccw", "RotateTo", []any{"portrait-ccw"}},
|
||||
{"rotate landscape-flipped", "RotateTo", []any{"landscape-flipped"}},
|
||||
{"accept", "Accept", nil},
|
||||
{"dismiss", "Dismiss", nil},
|
||||
}
|
||||
for _, c := range cases {
|
||||
m, p, err := parseCommand(strings.Fields(c.args))
|
||||
if err != nil || m != c.method || !reflect.DeepEqual(p, c.params) {
|
||||
t.Errorf("parseCommand(%q) = %q %v %v; want %q %v", c.args, m, p, err, c.method, c.params)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseCommandErrors(t *testing.T) {
|
||||
for _, args := range []string{"", "spin", "mode", "mode sometimes", "rotate", "rotate diagonal", "lock now"} {
|
||||
if _, _, err := parseCommand(strings.Fields(args)); err == nil {
|
||||
t.Errorf("parseCommand(%q) should fail", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatStatus(t *testing.T) {
|
||||
got := formatStatus(statusFixture)
|
||||
want := "mode: manual\nlocked: yes\ndevice: portrait-cw\nscreen: landscape\nsuggested: portrait-cw\nimu: ok\n"
|
||||
if got != want {
|
||||
t.Errorf("formatStatus =\n%s\nwant\n%s", got, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package main
|
||||
|
||||
import "github.com/RustyRaptor/deckrotate/internal/service"
|
||||
|
||||
var statusFixture = service.Status{
|
||||
Mode: "manual", Locked: true, Device: "portrait-cw",
|
||||
Screen: "landscape", Suggested: "portrait-cw", IMU: true,
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
// Command deckrotate rotates the Steam Deck screen in KDE Plasma desktop mode.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/godbus/dbus/v5"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/core"
|
||||
"github.com/RustyRaptor/deckrotate/internal/daemon"
|
||||
"github.com/RustyRaptor/deckrotate/internal/orient"
|
||||
"github.com/RustyRaptor/deckrotate/internal/service"
|
||||
)
|
||||
|
||||
const usage = `usage: deckrotate <command>
|
||||
|
||||
daemon [flags] run the orientation daemon (normally via systemd)
|
||||
status [--json] show mode, lock and orientations
|
||||
lock | unlock | toggle-lock
|
||||
mode auto|manual|toggle
|
||||
rotate cw|ccw|flip turn the screen from where it is now
|
||||
rotate landscape|portrait-cw|landscape-flipped|portrait-ccw
|
||||
accept take the rotation the manual-mode button offers
|
||||
dismiss hide the manual-mode button
|
||||
`
|
||||
|
||||
func main() {
|
||||
if err := run(os.Args[1:]); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "deckrotate:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(args []string) error {
|
||||
if len(args) == 0 || args[0] == "-h" || args[0] == "--help" || args[0] == "help" {
|
||||
fmt.Print(usage)
|
||||
return nil
|
||||
}
|
||||
switch args[0] {
|
||||
case "daemon":
|
||||
return runDaemon(args[1:])
|
||||
case "status":
|
||||
return runStatus(args[1:])
|
||||
}
|
||||
method, params, err := parseCommand(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cl, err := dial()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return cl.Call(method, params...)
|
||||
}
|
||||
|
||||
func parseCommand(args []string) (string, []any, error) {
|
||||
if len(args) == 0 {
|
||||
return "", nil, errors.New("no command (try --help)")
|
||||
}
|
||||
arg := func() (string, error) {
|
||||
if len(args) != 2 {
|
||||
return "", fmt.Errorf("%s takes exactly one argument", args[0])
|
||||
}
|
||||
return args[1], nil
|
||||
}
|
||||
noArgs := func(method string, params ...any) (string, []any, error) {
|
||||
if len(args) != 1 {
|
||||
return "", nil, fmt.Errorf("%s takes no arguments", args[0])
|
||||
}
|
||||
return method, params, nil
|
||||
}
|
||||
switch args[0] {
|
||||
case "lock":
|
||||
return noArgs("SetLocked", true)
|
||||
case "unlock":
|
||||
return noArgs("SetLocked", false)
|
||||
case "toggle-lock":
|
||||
return noArgs("ToggleLock")
|
||||
case "accept":
|
||||
return noArgs("Accept")
|
||||
case "dismiss":
|
||||
return noArgs("Dismiss")
|
||||
case "mode":
|
||||
m, err := arg()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if m == "toggle" {
|
||||
return "ToggleMode", nil, nil
|
||||
}
|
||||
if _, err := core.ParseMode(m); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return "SetMode", []any{m}, nil
|
||||
case "rotate":
|
||||
r, err := arg()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if turns, ok := map[string]int32{"cw": 1, "ccw": -1, "flip": 2}[r]; ok {
|
||||
return "RotateBy", []any{turns}, nil
|
||||
}
|
||||
if _, err := orient.Parse(r); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return "RotateTo", []any{r}, nil
|
||||
}
|
||||
return "", nil, fmt.Errorf("unknown command %q (try --help)", args[0])
|
||||
}
|
||||
|
||||
func dial() (*service.Client, error) {
|
||||
conn, err := dbus.ConnectSessionBus()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return service.NewClient(conn), nil
|
||||
}
|
||||
|
||||
func formatStatus(s service.Status) string {
|
||||
yn := map[bool]string{true: "yes", false: "no"}
|
||||
imu := map[bool]string{true: "ok", false: "unavailable"}
|
||||
sug := s.Suggested
|
||||
if sug == "" {
|
||||
sug = "-"
|
||||
}
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "mode: %s\nlocked: %s\ndevice: %s\nscreen: %s\nsuggested: %s\nimu: %s\n",
|
||||
s.Mode, yn[s.Locked], s.Device, s.Screen, sug, imu[s.IMU])
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func runStatus(args []string) error {
|
||||
fs := flag.NewFlagSet("status", flag.ContinueOnError)
|
||||
asJSON := fs.Bool("json", false, "print JSON")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
cl, err := dial()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s, err := cl.Status()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if *asJSON {
|
||||
return json.NewEncoder(os.Stdout).Encode(s)
|
||||
}
|
||||
fmt.Print(formatStatus(s))
|
||||
return nil
|
||||
}
|
||||
|
||||
func defaultUIDir() string {
|
||||
if exe, err := os.Executable(); err == nil {
|
||||
dir := filepath.Join(filepath.Dir(exe), "..", "share", "deckrotate", "ui")
|
||||
if _, err := os.Stat(filepath.Join(dir, "overlay.qml")); err == nil {
|
||||
return dir
|
||||
}
|
||||
}
|
||||
return filepath.Join(os.Getenv("HOME"), ".local", "share", "deckrotate", "ui")
|
||||
}
|
||||
|
||||
func runDaemon(args []string) error {
|
||||
fs := flag.NewFlagSet("daemon", flag.ContinueOnError)
|
||||
o := daemon.Options{SysRoot: "/sys"}
|
||||
fs.StringVar(&o.UIDir, "ui-dir", defaultUIDir(), "directory containing overlay.qml")
|
||||
fs.StringVar(&o.QMLBin, "qml", "/usr/lib/qt6/bin/qml", "QML runtime used for the overlay")
|
||||
fs.DurationVar(&o.Settle, "settle", 500*time.Millisecond, "how long an orientation must hold before it counts")
|
||||
fs.DurationVar(&o.PromptTimeout, "prompt-timeout", 5*time.Second, "how long the manual-mode button stays up")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
return daemon.Run(ctx, o)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Every global shortcut must run a command the CLI accepts.
|
||||
func TestShortcutFileActionsAreValidCommands(t *testing.T) {
|
||||
f, err := os.Open("../../packaging/kglobalaccel/io.github.rustyraptor.deckrotate.desktop")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
var declared []string
|
||||
actions := map[string]string{} // action id -> Exec
|
||||
section := ""
|
||||
sc := bufio.NewScanner(f)
|
||||
for sc.Scan() {
|
||||
line := strings.TrimSpace(sc.Text())
|
||||
switch {
|
||||
case strings.HasPrefix(line, "[Desktop Action "):
|
||||
section = strings.TrimSuffix(strings.TrimPrefix(line, "[Desktop Action "), "]")
|
||||
case strings.HasPrefix(line, "["):
|
||||
section = ""
|
||||
case section == "" && strings.HasPrefix(line, "Actions="):
|
||||
declared = strings.Split(strings.TrimSuffix(strings.TrimPrefix(line, "Actions="), ";"), ";")
|
||||
case section != "" && strings.HasPrefix(line, "Exec="):
|
||||
actions[section] = strings.TrimPrefix(line, "Exec=")
|
||||
}
|
||||
}
|
||||
if len(declared) < 5 {
|
||||
t.Fatalf("only %d actions declared: %v", len(declared), declared)
|
||||
}
|
||||
for _, id := range declared {
|
||||
exec, ok := actions[id]
|
||||
if !ok {
|
||||
t.Errorf("action %s has no Exec", id)
|
||||
continue
|
||||
}
|
||||
fields := strings.Fields(exec)
|
||||
if fields[0] != "@BINDIR@/deckrotate" {
|
||||
t.Errorf("%s: Exec should start with @BINDIR@/deckrotate, got %q", id, fields[0])
|
||||
}
|
||||
if _, _, err := parseCommand(fields[1:]); err != nil {
|
||||
t.Errorf("%s: %q is not a valid command: %v", id, exec, err)
|
||||
}
|
||||
}
|
||||
for _, must := range []string{"ToggleLock", "RotateCW", "RotateCCW", "ToggleMode", "Accept"} {
|
||||
if _, ok := actions[must]; !ok {
|
||||
t.Errorf("missing action %s", must)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
# Hardware notes
|
||||
|
||||
Findings from investigating orientation sensing on a Steam Deck OLED (DMI
|
||||
`Galileo`), SteamOS 3.9, Plasma 6.7 Wayland. Collected 2026-11-03.
|
||||
|
||||
## No kernel accelerometer
|
||||
|
||||
The kernel exposes only two ambient light sensors through IIO:
|
||||
|
||||
| IIO device | Driver | Use |
|
||||
|-----------------|------------|---------------------|
|
||||
| `iio:device0` | `ltrf216a` | ambient light |
|
||||
| `iio:device1` | `ltrf216a` | ambient light |
|
||||
|
||||
`iio-sensor-proxy` runs but `monitor-sensor` reports `No accelerometer`, so
|
||||
KWin's built-in auto-rotation (which uses iio-sensor-proxy) can never work.
|
||||
|
||||
## The controller IMU
|
||||
|
||||
The built-in controller (USB `28DE:1205`) has a BMI-class IMU whose data
|
||||
arrives in the controller's state report. Three hidraw interfaces belong to
|
||||
it; the state one is identified by a report descriptor starting with
|
||||
`06 ff ff` (vendor usage page 0xFFFF). Its `/dev/hidrawN` number changes
|
||||
between boots, so `imu.Find` looks it up through `/sys/class/hidraw`. The
|
||||
device node has a `uaccess` ACL, so the logged-in user can read it and send
|
||||
feature reports without root.
|
||||
|
||||
### Report 0x09 layout (64 bytes, little endian)
|
||||
|
||||
| Offset | Size | Field |
|
||||
|--------|------|--------------------------------|
|
||||
| 0 | 2 | report version (`01 00`) |
|
||||
| 2 | 1 | type, `0x09` = controller state |
|
||||
| 3 | 1 | length (`0x40`) |
|
||||
| 4 | 4 | packet number |
|
||||
| 8 | 8 | buttons |
|
||||
| 16 | 8 | trackpad X/Y left, right |
|
||||
| **24** | 6 | **accel X, Y, Z (int16)** |
|
||||
| 30 | 6 | gyro X, Y, Z (int16) |
|
||||
| 36 | 8 | orientation quaternion W,X,Y,Z |
|
||||
| 44 | 4 | raw triggers |
|
||||
| 48 | 8 | sticks |
|
||||
| 56 | 4 | trackpad pressure |
|
||||
|
||||
Reports arrive at about 250 Hz. Accelerometer scale is +/-2 g, so
|
||||
1 g = 16384 counts. Layout cross-checked against SDL's
|
||||
`src/joystick/hidapi/steam/controller_structs.h`.
|
||||
|
||||
### Steam turns the IMU off
|
||||
|
||||
With Steam running in desktop mode the accel and gyro fields read all zeros:
|
||||
the desktop controller config doesn't use the gyro, so Steam sets the IMU
|
||||
mode to off. One feature report turns raw data back on:
|
||||
|
||||
```
|
||||
report id 0x00
|
||||
0x87 ID_SET_SETTINGS_VALUES
|
||||
0x03 payload length: one {u8 register, u16 value} setting
|
||||
0x30 SETTING_IMU_MODE
|
||||
0x18 0x00 SEND_RAW_ACCEL (0x08) | SEND_RAW_GYRO (0x10)
|
||||
...zero padding to 64 bytes
|
||||
```
|
||||
|
||||
sent with `ioctl(fd, HIDIOCSFEATURE(65), buf)`. It stays on until Steam
|
||||
re-sends settings (for example after a config switch), so the reader re-sends
|
||||
it after about half a second of all-zero IMU fields.
|
||||
|
||||
### Axes
|
||||
|
||||
Measured by holding the Deck still in each position (values are the gravity
|
||||
reaction, i.e. the axis pointing up reads positive):
|
||||
|
||||
| Position | accel X | accel Y | accel Z |
|
||||
|--------------------------------|--------:|--------:|--------:|
|
||||
| Landscape, leaning back ~22° | +0.04 | +0.93 | +0.38 |
|
||||
| Upside down | -0.04 | -0.99 | +0.01 |
|
||||
| Left grip down (right edge up) | +0.99 | -0.01 | +0.03 |
|
||||
| Right grip down (left edge up) | -1.01 | +0.01 | +0.02 |
|
||||
| Flat, screen down | 0.00 | +0.30 | -0.95 |
|
||||
|
||||
So X points to the Deck's right edge, Y to its top edge, Z out of the screen,
|
||||
matching SDL's convention.
|
||||
|
||||
## The panel
|
||||
|
||||
The internal panel is `eDP-1` (kscreen output type 7), natively portrait
|
||||
800x1280 with its top at the Deck's left edge. kscreen rotations needed to
|
||||
look upright:
|
||||
|
||||
| Deck position | deckrotate name | kscreen rotation | value |
|
||||
|--------------------------------|---------------------|------------------|------:|
|
||||
| Landscape | `landscape` | `right` | 8 |
|
||||
| Right grip down | `portrait-cw` | `none` | 1 |
|
||||
| Upside down | `landscape-flipped` | `left` | 2 |
|
||||
| Left grip down | `portrait-ccw` | `inverted` | 4 |
|
||||
|
||||
`kscreen-doctor output.eDP-1.rotation.<name>` applies it; KWin remaps the
|
||||
touchscreen automatically.
|
||||
@@ -0,0 +1,7 @@
|
||||
module github.com/RustyRaptor/deckrotate
|
||||
|
||||
go 1.27.3
|
||||
|
||||
require github.com/godbus/dbus/v5 v5.2.4
|
||||
|
||||
require golang.org/x/sys v0.27.0 // indirect
|
||||
@@ -0,0 +1,4 @@
|
||||
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=
|
||||
@@ -0,0 +1,52 @@
|
||||
// Package config persists deckrotate's user settings as JSON.
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/core"
|
||||
)
|
||||
|
||||
type FileStore struct{ path string }
|
||||
|
||||
func NewFileStore(path string) *FileStore { return &FileStore{path: path} }
|
||||
|
||||
func DefaultPath() string {
|
||||
dir := os.Getenv("XDG_CONFIG_HOME")
|
||||
if dir == "" {
|
||||
dir = filepath.Join(os.Getenv("HOME"), ".config")
|
||||
}
|
||||
return filepath.Join(dir, "deckrotate", "settings.json")
|
||||
}
|
||||
|
||||
func (f *FileStore) Load() (core.Settings, error) {
|
||||
s := core.Settings{Mode: core.Auto}
|
||||
b, err := os.ReadFile(f.path)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return s, nil
|
||||
}
|
||||
if err != nil {
|
||||
return s, err
|
||||
}
|
||||
err = json.Unmarshal(b, &s)
|
||||
return s, err
|
||||
}
|
||||
|
||||
func (f *FileStore) Save(s core.Settings) error {
|
||||
b, err := json.MarshalIndent(s, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(f.path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := f.path + ".tmp"
|
||||
if err := os.WriteFile(tmp, append(b, '\n'), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, f.path)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/core"
|
||||
)
|
||||
|
||||
func TestMissingFileGivesDefaults(t *testing.T) {
|
||||
s, err := NewFileStore(filepath.Join(t.TempDir(), "nope", "settings.json")).Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s != (core.Settings{Mode: core.Auto}) {
|
||||
t.Errorf("defaults = %+v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveLoadRoundTrip(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "deckrotate", "settings.json")
|
||||
st := NewFileStore(path)
|
||||
want := core.Settings{Mode: core.Manual, Locked: true}
|
||||
if err := st.Save(want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := os.ReadFile(path)
|
||||
if string(b) != "{\n \"mode\": \"manual\",\n \"locked\": true\n}\n" {
|
||||
t.Errorf("file = %q", b)
|
||||
}
|
||||
got, err := NewFileStore(path).Load()
|
||||
if err != nil || got != want {
|
||||
t.Errorf("Load = %+v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCorruptFileIsAnError(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "settings.json")
|
||||
os.WriteFile(path, []byte(`{"mode":"sideways"}`), 0o644)
|
||||
if _, err := NewFileStore(path).Load(); err == nil {
|
||||
t.Error("expected error for bad mode")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultPathUsesXDG(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", "/cfg")
|
||||
if got := DefaultPath(); got != "/cfg/deckrotate/settings.json" {
|
||||
t.Errorf("DefaultPath = %q", got)
|
||||
}
|
||||
t.Setenv("XDG_CONFIG_HOME", "")
|
||||
t.Setenv("HOME", "/home/x")
|
||||
if got := DefaultPath(); got != "/home/x/.config/deckrotate/settings.json" {
|
||||
t.Errorf("DefaultPath = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
// Package core decides when the screen rotates: auto, manual (prompted) or locked.
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/orient"
|
||||
)
|
||||
|
||||
type Mode int
|
||||
|
||||
const (
|
||||
Auto Mode = iota
|
||||
Manual
|
||||
)
|
||||
|
||||
func (m Mode) String() string {
|
||||
if m == Manual {
|
||||
return "manual"
|
||||
}
|
||||
return "auto"
|
||||
}
|
||||
|
||||
func ParseMode(s string) (Mode, error) {
|
||||
switch s {
|
||||
case "auto":
|
||||
return Auto, nil
|
||||
case "manual":
|
||||
return Manual, nil
|
||||
}
|
||||
return Auto, fmt.Errorf("unknown mode %q (want auto or manual)", s)
|
||||
}
|
||||
|
||||
func (m Mode) MarshalText() ([]byte, error) { return []byte(m.String()), nil }
|
||||
|
||||
func (m *Mode) UnmarshalText(b []byte) (err error) {
|
||||
*m, err = ParseMode(string(b))
|
||||
return err
|
||||
}
|
||||
|
||||
// Settings are the user choices that survive restarts.
|
||||
type Settings struct {
|
||||
Mode Mode `json:"mode"`
|
||||
Locked bool `json:"locked"`
|
||||
}
|
||||
|
||||
type State struct {
|
||||
Mode Mode
|
||||
Locked bool
|
||||
Device orient.Orientation // physical orientation, Unknown until first reading
|
||||
Screen orient.Orientation // what the panel is rotated for
|
||||
Suggested orient.Orientation // manual-mode prompt target, Unknown when none
|
||||
IMU bool // accelerometer is delivering data
|
||||
}
|
||||
|
||||
type Screen interface {
|
||||
Current(ctx context.Context) (orient.Orientation, error)
|
||||
Apply(ctx context.Context, o orient.Orientation) error
|
||||
}
|
||||
|
||||
// Prompt shows the manual-mode "rotate to target" button. Implementations
|
||||
// must not block.
|
||||
type Prompt interface {
|
||||
Show(target, current orient.Orientation)
|
||||
Hide()
|
||||
}
|
||||
|
||||
type Store interface {
|
||||
Load() (Settings, error)
|
||||
Save(Settings) error
|
||||
}
|
||||
|
||||
type Timer interface{ Stop() bool }
|
||||
|
||||
type Deps struct {
|
||||
Screen Screen
|
||||
Prompt Prompt
|
||||
Store Store
|
||||
AfterFunc func(time.Duration, func()) Timer
|
||||
PromptTimeout time.Duration
|
||||
OnChange func(State)
|
||||
}
|
||||
|
||||
var ErrNothingToAccept = errors.New("no rotation is being offered")
|
||||
|
||||
type Controller struct {
|
||||
d Deps
|
||||
mu sync.Mutex
|
||||
st State
|
||||
timer Timer
|
||||
gen int // bumps on every prompt change so stale timeouts are ignored
|
||||
}
|
||||
|
||||
func New(d Deps) *Controller {
|
||||
if d.AfterFunc == nil {
|
||||
d.AfterFunc = func(t time.Duration, f func()) Timer { return time.AfterFunc(t, f) }
|
||||
}
|
||||
if d.OnChange == nil {
|
||||
d.OnChange = func(State) {}
|
||||
}
|
||||
return &Controller{d: d, st: State{Device: orient.Unknown, Screen: orient.Unknown, Suggested: orient.Unknown}}
|
||||
}
|
||||
|
||||
func (c *Controller) Init(ctx context.Context) error {
|
||||
s, err := c.d.Store.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.update(func() error {
|
||||
c.st.Mode, c.st.Locked = s.Mode, s.Locked
|
||||
return c.refreshScreen(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Controller) State() State {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.st
|
||||
}
|
||||
|
||||
// update runs f under the lock, then reports the resulting state.
|
||||
func (c *Controller) update(f func() error) error {
|
||||
c.mu.Lock()
|
||||
err := f()
|
||||
st := c.st
|
||||
c.mu.Unlock()
|
||||
c.d.OnChange(st)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Controller) refreshScreen(ctx context.Context) error {
|
||||
o, err := c.d.Screen.Current(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.st.Screen = o
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Controller) apply(ctx context.Context, o orient.Orientation) error {
|
||||
if err := c.d.Screen.Apply(ctx, o); err != nil {
|
||||
return err
|
||||
}
|
||||
c.st.Screen = o
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Controller) save() error {
|
||||
return c.d.Store.Save(Settings{Mode: c.st.Mode, Locked: c.st.Locked})
|
||||
}
|
||||
|
||||
func (c *Controller) withdraw() {
|
||||
if c.st.Suggested == orient.Unknown {
|
||||
return
|
||||
}
|
||||
c.gen++
|
||||
if c.timer != nil {
|
||||
c.timer.Stop()
|
||||
c.timer = nil
|
||||
}
|
||||
c.st.Suggested = orient.Unknown
|
||||
c.d.Prompt.Hide()
|
||||
}
|
||||
|
||||
func (c *Controller) offer(o orient.Orientation) {
|
||||
if c.st.Suggested == o {
|
||||
return
|
||||
}
|
||||
if c.timer != nil {
|
||||
c.timer.Stop()
|
||||
}
|
||||
c.gen++
|
||||
gen := c.gen
|
||||
c.st.Suggested = o
|
||||
c.d.Prompt.Show(o, c.st.Screen)
|
||||
c.timer = c.d.AfterFunc(c.d.PromptTimeout, func() {
|
||||
c.update(func() error {
|
||||
if c.gen == gen {
|
||||
c.withdraw()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// follow reacts to the current device orientation according to mode and lock.
|
||||
func (c *Controller) follow(ctx context.Context) error {
|
||||
dev := c.st.Device
|
||||
if c.st.Locked || dev == orient.Unknown || dev == c.st.Screen {
|
||||
c.withdraw()
|
||||
return nil
|
||||
}
|
||||
if c.st.Mode == Auto {
|
||||
c.withdraw()
|
||||
return c.apply(ctx, dev)
|
||||
}
|
||||
c.offer(dev)
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeviceTurned is called when the debounced physical orientation changes.
|
||||
func (c *Controller) DeviceTurned(ctx context.Context, o orient.Orientation) error {
|
||||
return c.update(func() error {
|
||||
c.st.Device = o
|
||||
if err := c.refreshScreen(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.follow(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Controller) SetIMUAvailable(ok bool) {
|
||||
c.update(func() error { c.st.IMU = ok; return nil })
|
||||
}
|
||||
|
||||
func (c *Controller) SetMode(ctx context.Context, m Mode) error {
|
||||
return c.update(func() error {
|
||||
c.st.Mode = m
|
||||
if err := c.save(); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.follow(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Controller) ToggleMode(ctx context.Context) error {
|
||||
m := Auto
|
||||
if c.State().Mode == Auto {
|
||||
m = Manual
|
||||
}
|
||||
return c.SetMode(ctx, m)
|
||||
}
|
||||
|
||||
func (c *Controller) SetLocked(ctx context.Context, locked bool) error {
|
||||
return c.update(func() error {
|
||||
c.st.Locked = locked
|
||||
if err := c.save(); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.follow(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Controller) ToggleLock(ctx context.Context) error {
|
||||
return c.SetLocked(ctx, !c.State().Locked)
|
||||
}
|
||||
|
||||
// RotateTo is an explicit user request; it works regardless of mode and lock.
|
||||
func (c *Controller) RotateTo(ctx context.Context, o orient.Orientation) error {
|
||||
return c.update(func() error {
|
||||
c.withdraw()
|
||||
return c.apply(ctx, o)
|
||||
})
|
||||
}
|
||||
|
||||
// RotateBy turns the screen by clockwise quarter turns from where it is now.
|
||||
func (c *Controller) RotateBy(ctx context.Context, turns int) error {
|
||||
return c.update(func() error {
|
||||
if err := c.refreshScreen(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
from := c.st.Screen
|
||||
if from == orient.Unknown {
|
||||
from = orient.Landscape
|
||||
}
|
||||
c.withdraw()
|
||||
return c.apply(ctx, from.Rotate(turns))
|
||||
})
|
||||
}
|
||||
|
||||
// Accept takes the rotation the manual-mode prompt is offering.
|
||||
func (c *Controller) Accept(ctx context.Context) error {
|
||||
return c.update(func() error {
|
||||
o := c.st.Suggested
|
||||
if o == orient.Unknown {
|
||||
return ErrNothingToAccept
|
||||
}
|
||||
c.withdraw()
|
||||
return c.apply(ctx, o)
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Controller) Dismiss() {
|
||||
c.update(func() error { c.withdraw(); return nil })
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/orient"
|
||||
)
|
||||
|
||||
type fakeScreen struct {
|
||||
cur orient.Orientation
|
||||
applied []orient.Orientation
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *fakeScreen) Current(context.Context) (orient.Orientation, error) { return s.cur, nil }
|
||||
func (s *fakeScreen) Apply(_ context.Context, o orient.Orientation) error {
|
||||
if s.err != nil {
|
||||
return s.err
|
||||
}
|
||||
s.applied = append(s.applied, o)
|
||||
s.cur = o
|
||||
return nil
|
||||
}
|
||||
|
||||
type promptCall struct {
|
||||
show bool
|
||||
target, current orient.Orientation
|
||||
}
|
||||
|
||||
type fakePrompt struct{ calls []promptCall }
|
||||
|
||||
func (p *fakePrompt) Show(target, current orient.Orientation) {
|
||||
p.calls = append(p.calls, promptCall{true, target, current})
|
||||
}
|
||||
func (p *fakePrompt) Hide() { p.calls = append(p.calls, promptCall{show: false}) }
|
||||
|
||||
func (p *fakePrompt) visible() bool {
|
||||
return len(p.calls) > 0 && p.calls[len(p.calls)-1].show
|
||||
}
|
||||
|
||||
type fakeStore struct {
|
||||
s Settings
|
||||
saved []Settings
|
||||
}
|
||||
|
||||
func (f *fakeStore) Load() (Settings, error) { return f.s, nil }
|
||||
func (f *fakeStore) Save(s Settings) error {
|
||||
f.saved = append(f.saved, s)
|
||||
f.s = s
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeTimer struct {
|
||||
d time.Duration
|
||||
f func()
|
||||
stopped bool
|
||||
}
|
||||
|
||||
func (t *fakeTimer) Stop() bool { t.stopped = true; return true }
|
||||
|
||||
type fakeClock struct{ timers []*fakeTimer }
|
||||
|
||||
func (c *fakeClock) AfterFunc(d time.Duration, f func()) Timer {
|
||||
t := &fakeTimer{d: d, f: f}
|
||||
c.timers = append(c.timers, t)
|
||||
return t
|
||||
}
|
||||
|
||||
func (c *fakeClock) fireLast() {
|
||||
t := c.timers[len(c.timers)-1]
|
||||
if !t.stopped {
|
||||
t.f()
|
||||
}
|
||||
}
|
||||
|
||||
type rig struct {
|
||||
c *Controller
|
||||
screen *fakeScreen
|
||||
prompt *fakePrompt
|
||||
store *fakeStore
|
||||
clock *fakeClock
|
||||
states []State
|
||||
}
|
||||
|
||||
func newRig(t *testing.T, s Settings) *rig {
|
||||
t.Helper()
|
||||
r := &rig{
|
||||
screen: &fakeScreen{cur: orient.Landscape},
|
||||
prompt: &fakePrompt{},
|
||||
store: &fakeStore{s: s},
|
||||
clock: &fakeClock{},
|
||||
}
|
||||
r.c = New(Deps{
|
||||
Screen: r.screen,
|
||||
Prompt: r.prompt,
|
||||
Store: r.store,
|
||||
AfterFunc: r.clock.AfterFunc,
|
||||
PromptTimeout: 5 * time.Second,
|
||||
OnChange: func(s State) { r.states = append(r.states, s) },
|
||||
})
|
||||
if err := r.c.Init(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
var ctx = context.Background()
|
||||
|
||||
func TestInitLoadsSettingsAndScreen(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Manual, Locked: true})
|
||||
got := r.c.State()
|
||||
want := State{Mode: Manual, Locked: true, Device: orient.Unknown, Screen: orient.Landscape, Suggested: orient.Unknown}
|
||||
if got != want {
|
||||
t.Errorf("State = %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoRotatesImmediately(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Auto})
|
||||
r.c.DeviceTurned(ctx, orient.PortraitCW)
|
||||
if !reflect.DeepEqual(r.screen.applied, []orient.Orientation{orient.PortraitCW}) {
|
||||
t.Errorf("applied = %v", r.screen.applied)
|
||||
}
|
||||
if s := r.c.State(); s.Screen != orient.PortraitCW || s.Device != orient.PortraitCW {
|
||||
t.Errorf("state = %+v", s)
|
||||
}
|
||||
if len(r.prompt.calls) != 0 {
|
||||
t.Errorf("auto mode must not prompt: %v", r.prompt.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoNoOpWhenAlreadyMatching(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Auto})
|
||||
r.c.DeviceTurned(ctx, orient.Landscape)
|
||||
if len(r.screen.applied) != 0 {
|
||||
t.Errorf("applied = %v", r.screen.applied)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockedIgnoresTurns(t *testing.T) {
|
||||
for _, m := range []Mode{Auto, Manual} {
|
||||
r := newRig(t, Settings{Mode: m, Locked: true})
|
||||
r.c.DeviceTurned(ctx, orient.PortraitCCW)
|
||||
if len(r.screen.applied) != 0 || len(r.prompt.calls) != 0 {
|
||||
t.Errorf("%v: locked but applied=%v prompt=%v", m, r.screen.applied, r.prompt.calls)
|
||||
}
|
||||
if r.c.State().Device != orient.PortraitCCW {
|
||||
t.Errorf("%v: device orientation should still be tracked", m)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualShowsPromptThenAccept(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Manual})
|
||||
r.c.DeviceTurned(ctx, orient.PortraitCCW)
|
||||
if len(r.screen.applied) != 0 {
|
||||
t.Fatalf("manual mode applied %v", r.screen.applied)
|
||||
}
|
||||
want := []promptCall{{true, orient.PortraitCCW, orient.Landscape}}
|
||||
if !reflect.DeepEqual(r.prompt.calls, want) {
|
||||
t.Fatalf("prompt = %v, want %v", r.prompt.calls, want)
|
||||
}
|
||||
if r.c.State().Suggested != orient.PortraitCCW {
|
||||
t.Errorf("Suggested = %v", r.c.State().Suggested)
|
||||
}
|
||||
|
||||
if err := r.c.Accept(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(r.screen.applied, []orient.Orientation{orient.PortraitCCW}) {
|
||||
t.Errorf("applied = %v", r.screen.applied)
|
||||
}
|
||||
if r.prompt.visible() || r.c.State().Suggested != orient.Unknown {
|
||||
t.Errorf("prompt should be gone after accept: %+v", r.c.State())
|
||||
}
|
||||
if !r.clock.timers[0].stopped {
|
||||
t.Error("prompt timeout should be cancelled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualPromptTimesOut(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Manual})
|
||||
r.c.DeviceTurned(ctx, orient.PortraitCW)
|
||||
if len(r.clock.timers) != 1 || r.clock.timers[0].d != 5*time.Second {
|
||||
t.Fatalf("timers = %+v", r.clock.timers)
|
||||
}
|
||||
r.clock.fireLast()
|
||||
if r.prompt.visible() || r.c.State().Suggested != orient.Unknown {
|
||||
t.Errorf("prompt still up after timeout")
|
||||
}
|
||||
if err := r.c.Accept(ctx); !errors.Is(err, ErrNothingToAccept) {
|
||||
t.Errorf("Accept after timeout = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualTurnBackHidesPrompt(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Manual})
|
||||
r.c.DeviceTurned(ctx, orient.PortraitCW)
|
||||
r.c.DeviceTurned(ctx, orient.Landscape)
|
||||
if r.prompt.visible() || r.c.State().Suggested != orient.Unknown {
|
||||
t.Errorf("turning back should withdraw the prompt: %v", r.prompt.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualSecondTurnReplacesPrompt(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Manual})
|
||||
r.c.DeviceTurned(ctx, orient.PortraitCW)
|
||||
r.c.DeviceTurned(ctx, orient.LandscapeFlipped)
|
||||
last := r.prompt.calls[len(r.prompt.calls)-1]
|
||||
if last != (promptCall{true, orient.LandscapeFlipped, orient.Landscape}) {
|
||||
t.Errorf("last prompt = %v", last)
|
||||
}
|
||||
if !r.clock.timers[0].stopped || len(r.clock.timers) != 2 {
|
||||
t.Errorf("old timeout must be replaced: %+v", r.clock.timers)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaleTimerDoesNotHideNewPrompt(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Manual})
|
||||
r.c.DeviceTurned(ctx, orient.PortraitCW)
|
||||
first := r.clock.timers[0]
|
||||
r.c.DeviceTurned(ctx, orient.LandscapeFlipped)
|
||||
first.f() // fires anyway, racing with Stop
|
||||
if r.c.State().Suggested != orient.LandscapeFlipped || !r.prompt.visible() {
|
||||
t.Errorf("stale timer hid the current prompt: %+v", r.c.State())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockingHidesPrompt(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Manual})
|
||||
r.c.DeviceTurned(ctx, orient.PortraitCW)
|
||||
r.c.SetLocked(ctx, true)
|
||||
if r.prompt.visible() || r.c.State().Suggested != orient.Unknown {
|
||||
t.Error("lock should withdraw the prompt")
|
||||
}
|
||||
if got := r.store.s; !got.Locked || got.Mode != Manual {
|
||||
t.Errorf("saved %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnlockCatchesUp(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Auto, Locked: true})
|
||||
r.c.DeviceTurned(ctx, orient.PortraitCW)
|
||||
r.c.SetLocked(ctx, false)
|
||||
if !reflect.DeepEqual(r.screen.applied, []orient.Orientation{orient.PortraitCW}) {
|
||||
t.Errorf("auto unlock should rotate to the device: %v", r.screen.applied)
|
||||
}
|
||||
|
||||
r = newRig(t, Settings{Mode: Manual, Locked: true})
|
||||
r.c.DeviceTurned(ctx, orient.PortraitCW)
|
||||
r.c.ToggleLock(ctx)
|
||||
if !r.prompt.visible() {
|
||||
t.Error("manual unlock should offer the device orientation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSwitchingToAutoCatchesUp(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Manual})
|
||||
r.c.DeviceTurned(ctx, orient.LandscapeFlipped)
|
||||
r.c.SetMode(ctx, Auto)
|
||||
if !reflect.DeepEqual(r.screen.applied, []orient.Orientation{orient.LandscapeFlipped}) {
|
||||
t.Errorf("applied = %v", r.screen.applied)
|
||||
}
|
||||
if r.prompt.visible() {
|
||||
t.Error("prompt should be gone in auto mode")
|
||||
}
|
||||
if r.store.s.Mode != Auto {
|
||||
t.Errorf("mode not saved: %+v", r.store.s)
|
||||
}
|
||||
r.c.ToggleMode(ctx)
|
||||
if r.c.State().Mode != Manual {
|
||||
t.Errorf("ToggleMode -> %v", r.c.State().Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExplicitRotateWorksWhileLocked(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Auto, Locked: true})
|
||||
if err := r.c.RotateTo(ctx, orient.PortraitCCW); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.c.RotateBy(ctx, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []orient.Orientation{orient.PortraitCCW, orient.Landscape}
|
||||
if !reflect.DeepEqual(r.screen.applied, want) {
|
||||
t.Errorf("applied = %v, want %v", r.screen.applied, want)
|
||||
}
|
||||
if !r.c.State().Locked {
|
||||
t.Error("explicit rotation must not change the lock")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRotateRefreshesScreenFirst(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Auto, Locked: true})
|
||||
r.screen.cur = orient.PortraitCW // changed behind our back in System Settings
|
||||
r.c.RotateBy(ctx, 1)
|
||||
if last := r.screen.applied[len(r.screen.applied)-1]; last != orient.LandscapeFlipped {
|
||||
t.Errorf("RotateBy(1) from portrait-cw applied %v", last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyErrorKeepsState(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Auto, Locked: true})
|
||||
r.screen.err = errors.New("kscreen-doctor missing")
|
||||
if err := r.c.RotateTo(ctx, orient.PortraitCW); err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
if r.c.State().Screen != orient.Landscape {
|
||||
t.Errorf("Screen = %v after failed apply", r.c.State().Screen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnChangeFires(t *testing.T) {
|
||||
r := newRig(t, Settings{Mode: Auto})
|
||||
n := len(r.states)
|
||||
r.c.DeviceTurned(ctx, orient.PortraitCW)
|
||||
if len(r.states) == n {
|
||||
t.Fatal("OnChange not called")
|
||||
}
|
||||
if last := r.states[len(r.states)-1]; last.Screen != orient.PortraitCW {
|
||||
t.Errorf("last state = %+v", last)
|
||||
}
|
||||
r.c.SetIMUAvailable(true)
|
||||
if !r.states[len(r.states)-1].IMU {
|
||||
t.Error("IMU flag not reported")
|
||||
}
|
||||
}
|
||||
|
||||
func TestModeStrings(t *testing.T) {
|
||||
for _, m := range []Mode{Auto, Manual} {
|
||||
got, err := ParseMode(m.String())
|
||||
if err != nil || got != m {
|
||||
t.Errorf("ParseMode(%q) = %v, %v", m.String(), got, err)
|
||||
}
|
||||
}
|
||||
if _, err := ParseMode("sometimes"); err == nil {
|
||||
t.Error("ParseMode(sometimes) should fail")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/godbus/dbus/v5"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/config"
|
||||
"github.com/RustyRaptor/deckrotate/internal/core"
|
||||
"github.com/RustyRaptor/deckrotate/internal/display"
|
||||
"github.com/RustyRaptor/deckrotate/internal/imu"
|
||||
"github.com/RustyRaptor/deckrotate/internal/overlay"
|
||||
"github.com/RustyRaptor/deckrotate/internal/service"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
UIDir string // holds overlay.qml
|
||||
QMLBin string
|
||||
Settle time.Duration
|
||||
PromptTimeout time.Duration
|
||||
SysRoot string
|
||||
}
|
||||
|
||||
func Run(ctx context.Context, o Options) error {
|
||||
conn, err := dbus.ConnectSessionBus()
|
||||
if err != nil {
|
||||
return fmt.Errorf("session bus: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
var svc atomic.Pointer[service.Service]
|
||||
var ctrl *core.Controller
|
||||
prompt := overlay.NewProcessPrompt(
|
||||
func(ctx context.Context, p overlay.Placement) *exec.Cmd {
|
||||
args := append([]string{filepath.Join(o.UIDir, "overlay.qml"), "--"}, p.Args()...)
|
||||
cmd := exec.CommandContext(ctx, o.QMLBin, args...)
|
||||
cmd.Stderr = os.Stderr
|
||||
return cmd
|
||||
},
|
||||
func() {
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := ctrl.Accept(c); err != nil {
|
||||
log.Printf("accept: %v", err)
|
||||
}
|
||||
},
|
||||
)
|
||||
ctrl = core.New(core.Deps{
|
||||
Screen: display.NewKScreen(display.ExecRunner),
|
||||
Prompt: prompt,
|
||||
Store: config.NewFileStore(config.DefaultPath()),
|
||||
PromptTimeout: o.PromptTimeout,
|
||||
OnChange: func(st core.State) {
|
||||
if s := svc.Load(); s != nil {
|
||||
s.Publish(st)
|
||||
}
|
||||
},
|
||||
})
|
||||
if err := ctrl.Init(ctx); err != nil {
|
||||
return fmt.Errorf("init: %w", err)
|
||||
}
|
||||
s, err := service.Export(conn, ctrl)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
svc.Store(s)
|
||||
s.Publish(ctrl.State())
|
||||
st := ctrl.State()
|
||||
log.Printf("deckrotate running: mode=%v locked=%v screen=%v", st.Mode, st.Locked, st.Screen)
|
||||
|
||||
go readIMU(ctx, o.SysRoot, NewTracker(ctrl, o.Settle))
|
||||
<-ctx.Done()
|
||||
prompt.Hide()
|
||||
return nil
|
||||
}
|
||||
|
||||
// readIMU keeps a reader running, reopening the device after suspend/resume
|
||||
// or any other read failure.
|
||||
func readIMU(ctx context.Context, sysRoot string, tr *Tracker) {
|
||||
const retry = 2 * time.Second
|
||||
for ctx.Err() == nil {
|
||||
if err := readOnce(ctx, sysRoot, tr); err != nil && ctx.Err() == nil {
|
||||
log.Printf("imu: %v (retrying in %v)", err, retry)
|
||||
}
|
||||
tr.Lost()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(retry):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func readOnce(ctx context.Context, sysRoot string, tr *Tracker) error {
|
||||
path, err := imu.Find(sysRoot)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dev, err := imu.OpenHIDRaw(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
stop := context.AfterFunc(ctx, func() { dev.Close() })
|
||||
defer stop()
|
||||
defer dev.Close()
|
||||
// ~250 reports/s: re-enable after half a second without IMU data.
|
||||
return imu.NewReader(dev, 125).Run(func(s imu.Sample) { tr.Sample(time.Now(), s) })
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Package daemon wires the IMU, orientation detector, controller, overlay
|
||||
// and D-Bus service together.
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/imu"
|
||||
"github.com/RustyRaptor/deckrotate/internal/orient"
|
||||
)
|
||||
|
||||
type Sink interface {
|
||||
DeviceTurned(context.Context, orient.Orientation) error
|
||||
SetIMUAvailable(bool)
|
||||
}
|
||||
|
||||
// Tracker turns raw IMU samples into settled orientation changes. It is not
|
||||
// safe for concurrent use; feed it from the single IMU reader goroutine.
|
||||
type Tracker struct {
|
||||
sink Sink
|
||||
det *orient.Detector
|
||||
alive bool
|
||||
}
|
||||
|
||||
func NewTracker(sink Sink, settle time.Duration) *Tracker {
|
||||
return &Tracker{sink: sink, det: orient.NewDetector(settle)}
|
||||
}
|
||||
|
||||
func (t *Tracker) Sample(at time.Time, s imu.Sample) {
|
||||
if !t.alive {
|
||||
t.alive = true
|
||||
t.sink.SetIMUAvailable(true)
|
||||
}
|
||||
if o, changed := t.det.Update(at, s.Vec()); changed {
|
||||
log.Printf("deck turned to %v", o)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
if err := t.sink.DeviceTurned(ctx, o); err != nil {
|
||||
log.Printf("rotate to %v: %v", o, err)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
// Lost records that the IMU stopped delivering (device gone, read error).
|
||||
func (t *Tracker) Lost() {
|
||||
if t.alive {
|
||||
t.alive = false
|
||||
t.sink.SetIMUAvailable(false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/imu"
|
||||
"github.com/RustyRaptor/deckrotate/internal/orient"
|
||||
)
|
||||
|
||||
type fakeSink struct {
|
||||
turns []orient.Orientation
|
||||
imu []bool
|
||||
}
|
||||
|
||||
func (f *fakeSink) DeviceTurned(_ context.Context, o orient.Orientation) error {
|
||||
f.turns = append(f.turns, o)
|
||||
return nil
|
||||
}
|
||||
func (f *fakeSink) SetIMUAvailable(ok bool) { f.imu = append(f.imu, ok) }
|
||||
|
||||
var (
|
||||
landscape = imu.Sample{Accel: [3]int16{660, 15228, 6174}} // recorded on hardware
|
||||
leftGripDn = imu.Sample{Accel: [3]int16{16176, -88, 520}} // right edge up
|
||||
flat = imu.Sample{Accel: [3]int16{46, 4839, -15603}} // face down on a table
|
||||
)
|
||||
|
||||
func TestTrackerFeedsSettledTurns(t *testing.T) {
|
||||
sink := &fakeSink{}
|
||||
tr := NewTracker(sink, 300*time.Millisecond)
|
||||
t0 := time.Unix(0, 0)
|
||||
feed := func(s imu.Sample, from, to time.Duration) {
|
||||
for d := from; d <= to; d += 4 * time.Millisecond {
|
||||
tr.Sample(t0.Add(d), s)
|
||||
}
|
||||
}
|
||||
feed(landscape, 0, 400*time.Millisecond)
|
||||
feed(leftGripDn, 500*time.Millisecond, 900*time.Millisecond)
|
||||
feed(flat, time.Second, 2*time.Second)
|
||||
|
||||
want := []orient.Orientation{orient.Landscape, orient.PortraitCCW}
|
||||
if len(sink.turns) != 2 || sink.turns[0] != want[0] || sink.turns[1] != want[1] {
|
||||
t.Errorf("turns = %v, want %v", sink.turns, want)
|
||||
}
|
||||
if len(sink.imu) != 1 || !sink.imu[0] {
|
||||
t.Errorf("imu availability = %v, want one true", sink.imu)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrackerReportsLostIMU(t *testing.T) {
|
||||
sink := &fakeSink{}
|
||||
tr := NewTracker(sink, 300*time.Millisecond)
|
||||
tr.Sample(time.Unix(0, 0), landscape)
|
||||
tr.Lost()
|
||||
tr.Lost()
|
||||
tr.Sample(time.Unix(1, 0), landscape)
|
||||
want := []bool{true, false, true}
|
||||
if len(sink.imu) != 3 || sink.imu[0] != want[0] || sink.imu[1] != want[1] || sink.imu[2] != want[2] {
|
||||
t.Errorf("imu = %v, want %v", sink.imu, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Package display reads and sets the Deck panel's rotation through kscreen-doctor.
|
||||
package display
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/orient"
|
||||
)
|
||||
|
||||
var ErrNoPanel = errors.New("display: no internal panel found")
|
||||
|
||||
// The Deck's panel is natively portrait with its top at the Deck's left edge.
|
||||
var rotationFor = map[orient.Orientation]string{
|
||||
orient.Landscape: "right",
|
||||
orient.PortraitCW: "none",
|
||||
orient.LandscapeFlipped: "left",
|
||||
orient.PortraitCCW: "inverted",
|
||||
}
|
||||
|
||||
// KScreen::Output::Rotation values as they appear in kscreen-doctor -j.
|
||||
var kscreenValue = map[string]int{"none": 1, "left": 2, "inverted": 4, "right": 8}
|
||||
|
||||
const kscreenPanelType = 7
|
||||
|
||||
// RotationFor is the kscreen rotation that shows content upright when the
|
||||
// Deck is physically in orientation o.
|
||||
func RotationFor(o orient.Orientation) string { return rotationFor[o] }
|
||||
|
||||
func orientationForKScreen(v int) orient.Orientation {
|
||||
for o, name := range rotationFor {
|
||||
if kscreenValue[name] == v {
|
||||
return o
|
||||
}
|
||||
}
|
||||
return orient.Unknown
|
||||
}
|
||||
|
||||
type Runner func(ctx context.Context, name string, args ...string) ([]byte, error)
|
||||
|
||||
// ExecRunner runs a real command and returns its stdout.
|
||||
func ExecRunner(ctx context.Context, name string, args ...string) ([]byte, error) {
|
||||
out, err := exec.CommandContext(ctx, name, args...).Output()
|
||||
if ee, ok := err.(*exec.ExitError); ok {
|
||||
return out, fmt.Errorf("%s: %w: %s", name, err, strings.TrimSpace(string(ee.Stderr)))
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
|
||||
type KScreen struct {
|
||||
run Runner
|
||||
mu sync.Mutex
|
||||
panel string
|
||||
}
|
||||
|
||||
func NewKScreen(run Runner) *KScreen { return &KScreen{run: run} }
|
||||
|
||||
type output struct {
|
||||
Name string `json:"name"`
|
||||
Type int `json:"type"`
|
||||
Rotation int `json:"rotation"`
|
||||
}
|
||||
|
||||
func (k *KScreen) panelOutput(ctx context.Context) (output, error) {
|
||||
out, err := k.run(ctx, "kscreen-doctor", "-j")
|
||||
if err != nil {
|
||||
return output{}, err
|
||||
}
|
||||
var cfg struct {
|
||||
Outputs []output `json:"outputs"`
|
||||
}
|
||||
if err := json.Unmarshal(out, &cfg); err != nil {
|
||||
return output{}, fmt.Errorf("display: parse kscreen-doctor: %w", err)
|
||||
}
|
||||
for _, o := range cfg.Outputs {
|
||||
if o.Type == kscreenPanelType || strings.HasPrefix(o.Name, "eDP") {
|
||||
return o, nil
|
||||
}
|
||||
}
|
||||
return output{}, ErrNoPanel
|
||||
}
|
||||
|
||||
// Current returns the physical orientation the panel's rotation is set for.
|
||||
func (k *KScreen) Current(ctx context.Context) (orient.Orientation, error) {
|
||||
o, err := k.panelOutput(ctx)
|
||||
if err != nil {
|
||||
return orient.Unknown, err
|
||||
}
|
||||
k.mu.Lock()
|
||||
k.panel = o.Name
|
||||
k.mu.Unlock()
|
||||
return orientationForKScreen(o.Rotation), nil
|
||||
}
|
||||
|
||||
// Apply rotates the panel so content is upright in orientation o.
|
||||
func (k *KScreen) Apply(ctx context.Context, o orient.Orientation) error {
|
||||
rot, ok := rotationFor[o]
|
||||
if !ok {
|
||||
return fmt.Errorf("display: cannot apply %v", o)
|
||||
}
|
||||
k.mu.Lock()
|
||||
name := k.panel
|
||||
k.mu.Unlock()
|
||||
if name == "" {
|
||||
out, err := k.panelOutput(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name = out.Name
|
||||
k.mu.Lock()
|
||||
k.panel = name
|
||||
k.mu.Unlock()
|
||||
}
|
||||
_, err := k.run(ctx, "kscreen-doctor", "output."+name+".rotation."+rot)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package display
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/orient"
|
||||
)
|
||||
|
||||
func TestRotationMappingRoundTrips(t *testing.T) {
|
||||
// Verified on hardware: the Deck's panel is natively portrait with its top
|
||||
// at the Deck's left edge, so "none" is upright with the right grip down.
|
||||
want := map[orient.Orientation]string{
|
||||
orient.Landscape: "right",
|
||||
orient.PortraitCW: "none",
|
||||
orient.LandscapeFlipped: "left",
|
||||
orient.PortraitCCW: "inverted",
|
||||
}
|
||||
for o, name := range want {
|
||||
if got := RotationFor(o); got != name {
|
||||
t.Errorf("RotationFor(%v) = %q, want %q", o, got, name)
|
||||
}
|
||||
if got := orientationForKScreen(kscreenValue[name]); got != o {
|
||||
t.Errorf("orientationForKScreen(%q) = %v, want %v", name, got, o)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type call struct {
|
||||
name string
|
||||
args []string
|
||||
}
|
||||
|
||||
type fakeRunner struct {
|
||||
calls []call
|
||||
out []byte
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeRunner) run(_ context.Context, name string, args ...string) ([]byte, error) {
|
||||
f.calls = append(f.calls, call{name, args})
|
||||
return f.out, f.err
|
||||
}
|
||||
|
||||
func TestCurrentReadsInternalPanel(t *testing.T) {
|
||||
out, err := os.ReadFile(filepath.Join("testdata", "kscreen_handheld.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := &fakeRunner{out: out}
|
||||
k := NewKScreen(f.run)
|
||||
o, err := k.Current(context.Background())
|
||||
if err != nil || o != orient.Landscape {
|
||||
t.Fatalf("Current = %v, %v; want landscape", o, err)
|
||||
}
|
||||
if !reflect.DeepEqual(f.calls, []call{{"kscreen-doctor", []string{"-j"}}}) {
|
||||
t.Errorf("calls = %v", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
const dockedJSON = `{"outputs":[
|
||||
{"name":"DP-1","type":14,"enabled":true,"connected":true,"rotation":1},
|
||||
{"name":"eDP-1","type":7,"enabled":true,"connected":true,"rotation":2}
|
||||
]}`
|
||||
|
||||
func TestCurrentIgnoresExternalMonitors(t *testing.T) {
|
||||
k := NewKScreen((&fakeRunner{out: []byte(dockedJSON)}).run)
|
||||
o, err := k.Current(context.Background())
|
||||
if err != nil || o != orient.LandscapeFlipped {
|
||||
t.Fatalf("Current = %v, %v; want landscape-flipped", o, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentNoPanel(t *testing.T) {
|
||||
k := NewKScreen((&fakeRunner{out: []byte(`{"outputs":[{"name":"DP-1","type":14,"rotation":1}]}`)}).run)
|
||||
if _, err := k.Current(context.Background()); !errors.Is(err, ErrNoPanel) {
|
||||
t.Fatalf("err = %v, want ErrNoPanel", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyUsesPanelName(t *testing.T) {
|
||||
f := &fakeRunner{out: []byte(dockedJSON)}
|
||||
k := NewKScreen(f.run)
|
||||
if err := k.Apply(context.Background(), orient.PortraitCCW); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := call{"kscreen-doctor", []string{"output.eDP-1.rotation.inverted"}}
|
||||
if len(f.calls) != 2 || !reflect.DeepEqual(f.calls[1], want) {
|
||||
t.Errorf("calls = %v, want lookup then %v", f.calls, want)
|
||||
}
|
||||
// The panel name is cached after the first lookup.
|
||||
k.Apply(context.Background(), orient.Landscape)
|
||||
if len(f.calls) != 3 {
|
||||
t.Errorf("expected a single extra call, got %v", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyRejectsUnknown(t *testing.T) {
|
||||
k := NewKScreen((&fakeRunner{out: []byte(dockedJSON)}).run)
|
||||
if err := k.Apply(context.Background(), orient.Unknown); err == nil {
|
||||
t.Error("Apply(Unknown) should fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerErrorsPropagate(t *testing.T) {
|
||||
k := NewKScreen((&fakeRunner{err: errors.New("boom")}).run)
|
||||
if _, err := k.Current(context.Background()); err == nil {
|
||||
t.Error("expected error")
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"features": 255,
|
||||
"outputs": [
|
||||
{
|
||||
"brightness": 0.7,
|
||||
"clones": [
|
||||
],
|
||||
"connected": true,
|
||||
"currentModeId": "1",
|
||||
"edrPolicy": 0,
|
||||
"enabled": true,
|
||||
"followPreferredMode": false,
|
||||
"iccProfilePath": "",
|
||||
"icon": "",
|
||||
"id": 1,
|
||||
"maxBpc": 0,
|
||||
"modes": [
|
||||
{
|
||||
"id": "1",
|
||||
"name": "800x1280@90",
|
||||
"refreshRate": 90.06099700927734,
|
||||
"size": {
|
||||
"height": 1280,
|
||||
"width": 800
|
||||
}
|
||||
}
|
||||
],
|
||||
"name": "eDP-1",
|
||||
"overscan": 0,
|
||||
"pos": {
|
||||
"x": 0,
|
||||
"y": 0
|
||||
},
|
||||
"preferredModes": [
|
||||
"1"
|
||||
],
|
||||
"priority": 1,
|
||||
"replicationSource": 0,
|
||||
"rotation": 8,
|
||||
"scale": 1,
|
||||
"size": {
|
||||
"height": 800,
|
||||
"width": 1280
|
||||
},
|
||||
"sizeMM": {
|
||||
"height": 160,
|
||||
"width": 100
|
||||
},
|
||||
"type": 7
|
||||
}
|
||||
],
|
||||
"screen": {
|
||||
"currentSize": {
|
||||
"height": 1280,
|
||||
"width": 800
|
||||
},
|
||||
"id": 0,
|
||||
"maxActiveOutputsCount": 1,
|
||||
"maxSize": {
|
||||
"height": 64000,
|
||||
"width": 64000
|
||||
},
|
||||
"minSize": {
|
||||
"height": 0,
|
||||
"width": 0
|
||||
}
|
||||
},
|
||||
"tabletModeAvailable": true,
|
||||
"tabletModeEngaged": false
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package imu
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func hidiocsfeature(n int) uintptr {
|
||||
const iocRead, iocWrite = 2, 1
|
||||
return uintptr((iocRead|iocWrite)<<30 | n<<16 | 'H'<<8 | 0x06)
|
||||
}
|
||||
|
||||
// HIDRaw is a /dev/hidrawN device.
|
||||
type HIDRaw struct{ f *os.File }
|
||||
|
||||
func OpenHIDRaw(path string) (*HIDRaw, error) {
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &HIDRaw{f: f}, nil
|
||||
}
|
||||
|
||||
func (h *HIDRaw) Read(p []byte) (int, error) { return h.f.Read(p) }
|
||||
func (h *HIDRaw) Close() error { return h.f.Close() }
|
||||
|
||||
func (h *HIDRaw) SetFeature(report []byte) error {
|
||||
rc, err := h.f.SyscallConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var errno syscall.Errno
|
||||
err = rc.Control(func(fd uintptr) {
|
||||
_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, fd, hidiocsfeature(len(report)), uintptr(unsafe.Pointer(&report[0])))
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if errno != 0 {
|
||||
return errno
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package imu
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHIDIOCSFEATURE(t *testing.T) {
|
||||
// From <linux/hidraw.h>: _IOC(_IOC_WRITE|_IOC_READ, 'H', 0x06, len)
|
||||
if got := hidiocsfeature(65); got != 0xC0414806 {
|
||||
t.Errorf("hidiocsfeature(65) = %#x, want 0xc0414806", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHardwareSample runs only on a Deck with DECKROTATE_HW=1.
|
||||
func TestHardwareSample(t *testing.T) {
|
||||
if os.Getenv("DECKROTATE_HW") == "" {
|
||||
t.Skip("set DECKROTATE_HW=1 to read the real controller")
|
||||
}
|
||||
path, err := Find("/sys")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dev, err := OpenHIDRaw(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer dev.Close()
|
||||
n := 0
|
||||
err = NewReader(dev, 250).Run(func(s Sample) {
|
||||
if n++; n == 50 {
|
||||
dev.Close()
|
||||
}
|
||||
if v := s.Vec(); v.X*v.X+v.Y*v.Y+v.Z*v.Z < 0.5 {
|
||||
t.Errorf("implausible gravity %+v", v)
|
||||
}
|
||||
})
|
||||
if n < 50 {
|
||||
t.Fatalf("got %d samples before error %v", n, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// Package imu reads the Steam Deck controller's accelerometer from hidraw.
|
||||
package imu
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/orient"
|
||||
)
|
||||
|
||||
const (
|
||||
ReportSize = 64
|
||||
FeatureReportSize = 64
|
||||
|
||||
deckHIDID = "0003:000028DE:00001205"
|
||||
reportTypeState = 0x09
|
||||
accelOffset = 24 // after header(4), packet num(4), buttons(8), pads(8)
|
||||
gyroOffset = 30
|
||||
countsPerG = 16384.0 // +/-2 g range
|
||||
|
||||
cmdSetSettings = 0x87
|
||||
settingIMUMode = 0x30
|
||||
imuRawAccelGyro = 0x0008 | 0x0010
|
||||
)
|
||||
|
||||
var ErrNotState = errors.New("imu: not a controller state report")
|
||||
|
||||
// vendorUsagePage prefixes the report descriptor of the interface carrying
|
||||
// controller state; the other Deck interfaces are lizard-mode mouse/keyboard.
|
||||
var vendorUsagePage = []byte{0x06, 0xff, 0xff}
|
||||
|
||||
type Sample struct {
|
||||
Accel [3]int16
|
||||
Gyro [3]int16
|
||||
}
|
||||
|
||||
// Off reports whether the controller is sending no IMU data, which is what
|
||||
// Steam leaves it in when the active config doesn't use the gyro.
|
||||
func (s Sample) Off() bool {
|
||||
return s.Accel == [3]int16{} && s.Gyro == [3]int16{}
|
||||
}
|
||||
|
||||
func (s Sample) Vec() orient.Vec {
|
||||
return orient.Vec{
|
||||
X: float64(s.Accel[0]) / countsPerG,
|
||||
Y: float64(s.Accel[1]) / countsPerG,
|
||||
Z: float64(s.Accel[2]) / countsPerG,
|
||||
}
|
||||
}
|
||||
|
||||
func Decode(r []byte) (Sample, error) {
|
||||
if len(r) < ReportSize {
|
||||
return Sample{}, fmt.Errorf("imu: short report (%d bytes)", len(r))
|
||||
}
|
||||
if r[2] != reportTypeState {
|
||||
return Sample{}, ErrNotState
|
||||
}
|
||||
var s Sample
|
||||
for i := range 3 {
|
||||
s.Accel[i] = int16(binary.LittleEndian.Uint16(r[accelOffset+2*i:]))
|
||||
s.Gyro[i] = int16(binary.LittleEndian.Uint16(r[gyroOffset+2*i:]))
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// EnableReport is the hidraw feature report (leading report ID 0) that
|
||||
// switches the controller to streaming raw accelerometer and gyro data.
|
||||
func EnableReport() []byte {
|
||||
b := make([]byte, FeatureReportSize+1)
|
||||
b[1] = cmdSetSettings
|
||||
b[2] = 3 // one {u8 register, u16 value} setting
|
||||
b[3] = settingIMUMode
|
||||
binary.LittleEndian.PutUint16(b[4:], imuRawAccelGyro)
|
||||
return b
|
||||
}
|
||||
|
||||
// Find returns the /dev path of the Deck controller's state interface.
|
||||
// sysRoot is normally "/sys".
|
||||
func Find(sysRoot string) (string, error) {
|
||||
dirs, err := filepath.Glob(filepath.Join(sysRoot, "class", "hidraw", "hidraw*"))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, d := range dirs {
|
||||
uevent, err := os.ReadFile(filepath.Join(d, "device", "uevent"))
|
||||
if err != nil || !strings.Contains(strings.ToUpper(string(uevent)), "HID_ID="+deckHIDID) {
|
||||
continue
|
||||
}
|
||||
desc, err := os.ReadFile(filepath.Join(d, "device", "report_descriptor"))
|
||||
if err != nil || !bytes.HasPrefix(desc, vendorUsagePage) {
|
||||
continue
|
||||
}
|
||||
return "/dev/" + filepath.Base(d), nil
|
||||
}
|
||||
return "", fmt.Errorf("imu: no Steam Deck controller found under %s", sysRoot)
|
||||
}
|
||||
|
||||
type Device interface {
|
||||
Read(p []byte) (int, error)
|
||||
SetFeature(report []byte) error
|
||||
}
|
||||
|
||||
// Reader streams samples and keeps the IMU switched on.
|
||||
type Reader struct {
|
||||
dev Device
|
||||
reenableAfter int
|
||||
}
|
||||
|
||||
// NewReader re-sends the enable report after reenableAfter consecutive
|
||||
// samples without IMU data (the controller reports at about 250 Hz).
|
||||
func NewReader(dev Device, reenableAfter int) *Reader {
|
||||
return &Reader{dev: dev, reenableAfter: reenableAfter}
|
||||
}
|
||||
|
||||
// Run calls f for every sample that carries IMU data until a read fails.
|
||||
func (r *Reader) Run(f func(Sample)) error {
|
||||
if err := r.dev.SetFeature(EnableReport()); err != nil {
|
||||
return fmt.Errorf("imu: enable: %w", err)
|
||||
}
|
||||
buf := make([]byte, ReportSize)
|
||||
empty := 0
|
||||
for {
|
||||
n, err := r.dev.Read(buf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s, err := Decode(buf[:n])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if !s.Off() {
|
||||
empty = 0
|
||||
f(s)
|
||||
continue
|
||||
}
|
||||
if empty++; empty >= r.reenableAfter {
|
||||
empty = 0
|
||||
if err := r.dev.SetFeature(EnableReport()); err != nil {
|
||||
return fmt.Errorf("imu: re-enable: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package imu
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func fixture(t *testing.T, name string) []byte {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(filepath.Join("testdata", name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func TestDecodeRealReport(t *testing.T) {
|
||||
s, err := Decode(fixture(t, "report_imu_on.bin"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.Accel != [3]int16{690, 15104, 6079} {
|
||||
t.Errorf("Accel = %v", s.Accel)
|
||||
}
|
||||
if s.Off() {
|
||||
t.Error("report with accel data reported as Off")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeIMUOffReport(t *testing.T) {
|
||||
s, err := Decode(fixture(t, "report_imu_off.bin"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !s.Off() {
|
||||
t.Errorf("all-zero IMU should be Off, got %+v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeRejectsOtherReports(t *testing.T) {
|
||||
r := make([]byte, ReportSize)
|
||||
r[0], r[2] = 0x01, 0x04 // battery/status report type
|
||||
if _, err := Decode(r); !errors.Is(err, ErrNotState) {
|
||||
t.Errorf("err = %v, want ErrNotState", err)
|
||||
}
|
||||
if _, err := Decode(make([]byte, 10)); err == nil || errors.Is(err, ErrNotState) {
|
||||
t.Errorf("short report err = %v, want a size error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSampleVecInG(t *testing.T) {
|
||||
v := Sample{Accel: [3]int16{-16384, 8192, 0}}.Vec()
|
||||
if math.Abs(v.X+1) > 1e-9 || math.Abs(v.Y-0.5) > 1e-9 || v.Z != 0 {
|
||||
t.Errorf("Vec = %+v", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnableReport(t *testing.T) {
|
||||
got := EnableReport()
|
||||
if len(got) != FeatureReportSize+1 {
|
||||
t.Fatalf("len = %d, want %d", len(got), FeatureReportSize+1)
|
||||
}
|
||||
// report ID 0, ID_SET_SETTINGS_VALUES, 3 bytes, SETTING_IMU_MODE = raw accel|gyro (LE u16)
|
||||
want := []byte{0x00, 0x87, 0x03, 0x30, 0x18, 0x00}
|
||||
if !bytes.Equal(got[:len(want)], want) {
|
||||
t.Errorf("prefix = % x, want % x", got[:len(want)], want)
|
||||
}
|
||||
for i, b := range got[len(want):] {
|
||||
if b != 0 {
|
||||
t.Fatalf("byte %d = %#x, want zero padding", len(want)+i, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindPicksVendorInterface(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
mk := func(name, hidID string, desc []byte) {
|
||||
d := filepath.Join(root, "class", "hidraw", name, "device")
|
||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.WriteFile(filepath.Join(d, "uevent"), []byte("DRIVER=hid-steam\nHID_ID="+hidID+"\n"), 0o644)
|
||||
os.WriteFile(filepath.Join(d, "report_descriptor"), desc, 0o644)
|
||||
}
|
||||
mk("hidraw0", "0003:000028DE:00001205", []byte{0x05, 0x01, 0x09, 0x02}) // lizard mouse
|
||||
mk("hidraw2", "0018:00002808:00001015", []byte{0x06, 0xff, 0xff}) // touchscreen
|
||||
mk("hidraw3", "0003:000028DE:00001205", []byte{0x06, 0xff, 0xff, 0x09}) // controller state
|
||||
|
||||
got, err := Find(root)
|
||||
if err != nil || got != "/dev/hidraw3" {
|
||||
t.Errorf("Find = %q, %v; want /dev/hidraw3", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindNoDeck(t *testing.T) {
|
||||
if _, err := Find(t.TempDir()); err == nil {
|
||||
t.Error("expected an error with no devices")
|
||||
}
|
||||
}
|
||||
|
||||
// fakeDev feeds canned reports and records feature reports written to it.
|
||||
type fakeDev struct {
|
||||
reports [][]byte
|
||||
features [][]byte
|
||||
}
|
||||
|
||||
func (f *fakeDev) Read(p []byte) (int, error) {
|
||||
if len(f.reports) == 0 {
|
||||
return 0, errors.New("EOF")
|
||||
}
|
||||
n := copy(p, f.reports[0])
|
||||
f.reports = f.reports[1:]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (f *fakeDev) SetFeature(b []byte) error {
|
||||
f.features = append(f.features, append([]byte(nil), b...))
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestReaderReEnablesIMUWhenSteamTurnsItOff(t *testing.T) {
|
||||
on := fixture(t, "report_imu_on.bin")
|
||||
off := fixture(t, "report_imu_off.bin")
|
||||
dev := &fakeDev{}
|
||||
for i := 0; i < 3; i++ {
|
||||
dev.reports = append(dev.reports, on)
|
||||
}
|
||||
for i := 0; i < 30; i++ {
|
||||
dev.reports = append(dev.reports, off)
|
||||
}
|
||||
r := NewReader(dev, 10) // re-enable after 10 consecutive empty samples
|
||||
|
||||
var got []Sample
|
||||
err := r.Run(func(s Sample) { got = append(got, s) })
|
||||
if err == nil || err.Error() != "EOF" {
|
||||
t.Fatalf("Run err = %v", err)
|
||||
}
|
||||
if len(got) != 3 {
|
||||
t.Errorf("delivered %d samples, want only the 3 with IMU data", len(got))
|
||||
}
|
||||
// Once at start, then once per 10 empty samples (30 / 10 = 3).
|
||||
if len(dev.features) != 4 {
|
||||
t.Errorf("sent %d enable reports, want 4", len(dev.features))
|
||||
}
|
||||
for _, f := range dev.features {
|
||||
if !bytes.Equal(f, EnableReport()) {
|
||||
t.Errorf("unexpected feature report % x", f[:8])
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,128 @@
|
||||
// Package orient turns accelerometer readings into a physical Deck orientation.
|
||||
package orient
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Orientation is how far the Deck is physically turned clockwise from normal
|
||||
// landscape, in quarter turns, as seen from the front.
|
||||
type Orientation int
|
||||
|
||||
const (
|
||||
Unknown Orientation = -1
|
||||
Landscape Orientation = 0 // top edge up
|
||||
PortraitCW Orientation = 1 // left edge up, right grip down
|
||||
LandscapeFlipped Orientation = 2 // bottom edge up
|
||||
PortraitCCW Orientation = 3 // right edge up, left grip down
|
||||
)
|
||||
|
||||
var All = []Orientation{Landscape, PortraitCW, LandscapeFlipped, PortraitCCW}
|
||||
|
||||
var names = map[Orientation]string{
|
||||
Unknown: "unknown",
|
||||
Landscape: "landscape",
|
||||
PortraitCW: "portrait-cw",
|
||||
LandscapeFlipped: "landscape-flipped",
|
||||
PortraitCCW: "portrait-ccw",
|
||||
}
|
||||
|
||||
func (o Orientation) String() string {
|
||||
if n, ok := names[o]; ok {
|
||||
return n
|
||||
}
|
||||
return fmt.Sprintf("orientation(%d)", int(o))
|
||||
}
|
||||
|
||||
func Parse(s string) (Orientation, error) {
|
||||
for _, o := range All {
|
||||
if names[o] == s {
|
||||
return o, nil
|
||||
}
|
||||
}
|
||||
return Unknown, fmt.Errorf("unknown orientation %q", s)
|
||||
}
|
||||
|
||||
// Rotate turns o by the given number of clockwise quarter turns (negative is
|
||||
// counter-clockwise).
|
||||
func (o Orientation) Rotate(turns int) Orientation {
|
||||
return Orientation(((int(o)+turns)%4 + 4) % 4)
|
||||
}
|
||||
|
||||
// Vec is a gravity reaction vector in g, in Deck coordinates: X toward the
|
||||
// right edge, Y toward the top edge, Z out of the screen.
|
||||
type Vec struct{ X, Y, Z float64 }
|
||||
|
||||
const (
|
||||
minMagnitude = 0.6 // below this the Deck is being swung or dropped
|
||||
maxMagnitude = 1.4 // above this it is being shaken
|
||||
minPlane = 0.45 // ~27 degrees from flat; flatter than this has no "up"
|
||||
stickyDeg = 65.0 // stay in the current orientation within this angle
|
||||
)
|
||||
|
||||
// Classify returns the orientation v points to, or Unknown when the Deck is
|
||||
// too flat or moving too much to tell. current adds hysteresis: a reading has
|
||||
// to be well past the 45 degree midpoint before it leaves current.
|
||||
func Classify(current Orientation, v Vec) Orientation {
|
||||
mag := math.Sqrt(v.X*v.X + v.Y*v.Y + v.Z*v.Z)
|
||||
if mag < minMagnitude || mag > maxMagnitude {
|
||||
return Unknown
|
||||
}
|
||||
if math.Hypot(v.X, v.Y) < minPlane {
|
||||
return Unknown
|
||||
}
|
||||
// 0 = top edge up, increasing as the Deck turns clockwise.
|
||||
deg := math.Atan2(-v.X, v.Y) * 180 / math.Pi
|
||||
if current != Unknown && angleDist(deg, float64(current)*90) <= stickyDeg {
|
||||
return current
|
||||
}
|
||||
return Orientation(int(math.Round(deg / 90))).Rotate(0)
|
||||
}
|
||||
|
||||
func angleDist(a, b float64) float64 {
|
||||
d := math.Mod(math.Abs(a-b), 360)
|
||||
if d > 180 {
|
||||
d = 360 - d
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// Detector debounces Classify: an orientation is reported only after every
|
||||
// sample for settle time agrees on it.
|
||||
type Detector struct {
|
||||
settle time.Duration
|
||||
current Orientation
|
||||
candidate Orientation
|
||||
since time.Time
|
||||
}
|
||||
|
||||
func NewDetector(settle time.Duration) *Detector {
|
||||
return &Detector{settle: settle, current: Unknown, candidate: Unknown}
|
||||
}
|
||||
|
||||
// Current is the last reported orientation, or Unknown before the first.
|
||||
func (d *Detector) Current() Orientation { return d.current }
|
||||
|
||||
// Update feeds one sample taken at t. It returns the new orientation and true
|
||||
// when the settled orientation changes.
|
||||
func (d *Detector) Update(t time.Time, v Vec) (Orientation, bool) {
|
||||
ref := d.candidate
|
||||
if ref == Unknown {
|
||||
ref = d.current
|
||||
}
|
||||
o := Classify(ref, v)
|
||||
if o == Unknown || o == d.current {
|
||||
d.candidate = Unknown
|
||||
return d.current, false
|
||||
}
|
||||
if o != d.candidate {
|
||||
d.candidate, d.since = o, t
|
||||
}
|
||||
if t.Sub(d.since) < d.settle {
|
||||
return d.current, false
|
||||
}
|
||||
d.current, d.candidate = o, Unknown
|
||||
return o, true
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package orient
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestOrientationStringRoundTrip(t *testing.T) {
|
||||
for _, o := range All {
|
||||
got, err := Parse(o.String())
|
||||
if err != nil || got != o {
|
||||
t.Errorf("Parse(%q) = %v, %v; want %v", o.String(), got, err, o)
|
||||
}
|
||||
}
|
||||
if _, err := Parse("sideways"); err == nil {
|
||||
t.Error("Parse(sideways) should fail")
|
||||
}
|
||||
if Unknown.String() != "unknown" {
|
||||
t.Errorf("Unknown.String() = %q", Unknown.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRotate(t *testing.T) {
|
||||
cases := []struct {
|
||||
o Orientation
|
||||
turns int
|
||||
want Orientation
|
||||
}{
|
||||
{Landscape, 1, PortraitCW},
|
||||
{PortraitCW, 1, LandscapeFlipped},
|
||||
{PortraitCCW, 1, Landscape},
|
||||
{Landscape, -1, PortraitCCW},
|
||||
{Landscape, 2, LandscapeFlipped},
|
||||
{PortraitCW, -5, Landscape},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := c.o.Rotate(c.turns); got != c.want {
|
||||
t.Errorf("%v.Rotate(%d) = %v, want %v", c.o, c.turns, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// vec builds a 1 g screen-plane vector for a Deck turned deg degrees
|
||||
// clockwise from landscape (0 = top edge up, 90 = left edge up).
|
||||
func vec(deg float64) Vec {
|
||||
r := deg * math.Pi / 180
|
||||
return Vec{X: -math.Sin(r), Y: math.Cos(r)}
|
||||
}
|
||||
|
||||
func TestClassifyCardinal(t *testing.T) {
|
||||
cases := []struct {
|
||||
v Vec
|
||||
want Orientation
|
||||
}{
|
||||
{Vec{X: 0, Y: 1}, Landscape},
|
||||
{Vec{X: -1, Y: 0}, PortraitCW},
|
||||
{Vec{X: 0, Y: -1}, LandscapeFlipped},
|
||||
{Vec{X: 1, Y: 0}, PortraitCCW},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := Classify(Unknown, c.v); got != c.want {
|
||||
t.Errorf("Classify(%+v) = %v, want %v", c.v, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyFlatIsUnknown(t *testing.T) {
|
||||
// Lying flat: gravity is almost entirely through the screen.
|
||||
flat := Vec{X: 0.1, Y: 0.2, Z: 0.97}
|
||||
if got := Classify(Landscape, flat); got != Unknown {
|
||||
t.Errorf("flat = %v, want unknown", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyRejectsShaking(t *testing.T) {
|
||||
// 2.5 g along +Y is a jolt, not a steady pose.
|
||||
if got := Classify(Unknown, Vec{Y: 2.5}); got != Unknown {
|
||||
t.Errorf("jolt = %v, want unknown", got)
|
||||
}
|
||||
if got := Classify(Unknown, Vec{Y: 0.3}); got != Unknown {
|
||||
t.Errorf("free-fall-ish = %v, want unknown", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyTiltedBackStillLandscape(t *testing.T) {
|
||||
// Real reading from the Deck held upright, leaning back ~22 degrees.
|
||||
if got := Classify(Unknown, Vec{X: 0.04, Y: 0.93, Z: 0.38}); got != Landscape {
|
||||
t.Errorf("got %v, want landscape", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyHysteresis(t *testing.T) {
|
||||
// 50 degrees toward PortraitCW: past the 45 degree midpoint, but inside
|
||||
// the hysteresis band, so the current orientation sticks.
|
||||
if got := Classify(Landscape, vec(50)); got != Landscape {
|
||||
t.Errorf("50deg from landscape = %v, want landscape (hysteresis)", got)
|
||||
}
|
||||
// With no current orientation the nearest one wins.
|
||||
if got := Classify(Unknown, vec(50)); got != PortraitCW {
|
||||
t.Errorf("50deg fresh = %v, want portrait-cw", got)
|
||||
}
|
||||
// Well past the band it switches.
|
||||
if got := Classify(Landscape, vec(70)); got != PortraitCW {
|
||||
t.Errorf("70deg from landscape = %v, want portrait-cw", got)
|
||||
}
|
||||
// Hysteresis works across the 0/360 wrap too.
|
||||
if got := Classify(Landscape, vec(-50)); got != Landscape {
|
||||
t.Errorf("-50deg from landscape = %v, want landscape", got)
|
||||
}
|
||||
if got := Classify(PortraitCCW, vec(-40)); got != PortraitCCW {
|
||||
t.Errorf("-40deg from portrait-ccw = %v, want portrait-ccw", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectorNeedsSettleTime(t *testing.T) {
|
||||
d := NewDetector(400 * time.Millisecond)
|
||||
t0 := time.Unix(1000, 0)
|
||||
|
||||
if _, ok := d.Update(t0, vec(0)); ok {
|
||||
t.Fatal("first sample must not report a change yet")
|
||||
}
|
||||
if _, ok := d.Update(t0.Add(300*time.Millisecond), vec(0)); ok {
|
||||
t.Fatal("reported before settle time")
|
||||
}
|
||||
o, ok := d.Update(t0.Add(400*time.Millisecond), vec(0))
|
||||
if !ok || o != Landscape {
|
||||
t.Fatalf("got %v,%v; want landscape,true", o, ok)
|
||||
}
|
||||
if _, ok := d.Update(t0.Add(500*time.Millisecond), vec(0)); ok {
|
||||
t.Fatal("must report each orientation once")
|
||||
}
|
||||
if d.Current() != Landscape {
|
||||
t.Fatalf("Current() = %v", d.Current())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectorIgnoresBriefWobble(t *testing.T) {
|
||||
d := NewDetector(400 * time.Millisecond)
|
||||
t0 := time.Unix(1000, 0)
|
||||
d.Update(t0, vec(0))
|
||||
d.Update(t0.Add(400*time.Millisecond), vec(0))
|
||||
|
||||
at := t0.Add(time.Second)
|
||||
d.Update(at, vec(90)) // starts turning
|
||||
d.Update(at.Add(200*time.Millisecond), vec(90)) // not long enough
|
||||
d.Update(at.Add(300*time.Millisecond), vec(0)) // came back
|
||||
if _, ok := d.Update(at.Add(800*time.Millisecond), vec(0)); ok {
|
||||
t.Fatal("returning to the same orientation is not a change")
|
||||
}
|
||||
if d.Current() != Landscape {
|
||||
t.Fatalf("Current() = %v", d.Current())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectorReportsTurn(t *testing.T) {
|
||||
d := NewDetector(400 * time.Millisecond)
|
||||
t0 := time.Unix(1000, 0)
|
||||
d.Update(t0, vec(0))
|
||||
d.Update(t0.Add(400*time.Millisecond), vec(0))
|
||||
|
||||
at := t0.Add(time.Second)
|
||||
d.Update(at, vec(-90))
|
||||
o, ok := d.Update(at.Add(450*time.Millisecond), vec(-88))
|
||||
if !ok || o != PortraitCCW {
|
||||
t.Fatalf("got %v,%v; want portrait-ccw,true", o, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectorFlatKeepsOrientationAndResetsCandidate(t *testing.T) {
|
||||
d := NewDetector(400 * time.Millisecond)
|
||||
t0 := time.Unix(1000, 0)
|
||||
d.Update(t0, vec(0))
|
||||
d.Update(t0.Add(400*time.Millisecond), vec(0))
|
||||
|
||||
at := t0.Add(time.Second)
|
||||
d.Update(at, vec(90))
|
||||
d.Update(at.Add(200*time.Millisecond), Vec{Z: 1}) // laid flat mid-turn
|
||||
if _, ok := d.Update(at.Add(450*time.Millisecond), vec(90)); ok {
|
||||
t.Fatal("flat sample must restart the settle timer")
|
||||
}
|
||||
if d.Current() != Landscape {
|
||||
t.Fatalf("Current() = %v", d.Current())
|
||||
}
|
||||
if o, ok := d.Update(at.Add(850*time.Millisecond), vec(90)); !ok || o != PortraitCW {
|
||||
t.Fatalf("got %v,%v; want portrait-cw,true", o, ok)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// Package overlay runs the manual-mode "rotate" button as a separate QML process.
|
||||
package overlay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/orient"
|
||||
)
|
||||
|
||||
// Placement says where the button goes on the screen as it is currently
|
||||
// rotated, and how far (clockwise degrees) to turn its icon so it looks
|
||||
// upright to someone holding the Deck in the new orientation.
|
||||
type Placement struct {
|
||||
Vertical string // top or bottom
|
||||
Horizontal string // left or right
|
||||
Angle int
|
||||
}
|
||||
|
||||
var direction = [4]string{"top", "right", "bottom", "left"}
|
||||
|
||||
// PlacementFor puts the button in the bottom-right corner as seen by someone
|
||||
// holding the Deck in target, while the content is still drawn for current.
|
||||
func PlacementFor(target, current orient.Orientation) Placement {
|
||||
d := ((int(target)-int(current))%4 + 4) % 4
|
||||
userRight := direction[(1-d+4)%4]
|
||||
userDown := direction[(2-d+4)%4]
|
||||
p := Placement{Angle: (360 - 90*d) % 360}
|
||||
if userDown == "top" || userDown == "bottom" {
|
||||
p.Vertical, p.Horizontal = userDown, userRight
|
||||
} else {
|
||||
p.Vertical, p.Horizontal = userRight, userDown
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (p Placement) Args() []string {
|
||||
return []string{"--vertical", p.Vertical, "--horizontal", p.Horizontal, "--angle", strconv.Itoa(p.Angle)}
|
||||
}
|
||||
|
||||
type CommandFunc func(ctx context.Context, p Placement) *exec.Cmd
|
||||
|
||||
// AcceptExitCode is how the overlay reports a tap; QML has no clean stdout.
|
||||
const AcceptExitCode = 10
|
||||
|
||||
// ProcessPrompt implements core.Prompt by starting the overlay command on
|
||||
// Show and killing it on Hide.
|
||||
type ProcessPrompt struct {
|
||||
command CommandFunc
|
||||
onAccept func()
|
||||
|
||||
mu sync.Mutex
|
||||
cancel context.CancelFunc
|
||||
gen int
|
||||
live int
|
||||
}
|
||||
|
||||
func NewProcessPrompt(command CommandFunc, onAccept func()) *ProcessPrompt {
|
||||
return &ProcessPrompt{command: command, onAccept: onAccept}
|
||||
}
|
||||
|
||||
func (p *ProcessPrompt) Show(target, current orient.Orientation) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.stopLocked()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cmd := p.command(ctx, PlacementFor(target, current))
|
||||
if err := cmd.Start(); err != nil {
|
||||
cancel()
|
||||
log.Printf("overlay: start: %v", err)
|
||||
return
|
||||
}
|
||||
p.cancel = cancel
|
||||
p.gen++
|
||||
gen := p.gen
|
||||
p.live++
|
||||
go func() {
|
||||
err := cmd.Wait()
|
||||
cancel()
|
||||
var ee *exec.ExitError
|
||||
accepted := errors.As(err, &ee) && ee.ExitCode() == AcceptExitCode
|
||||
p.mu.Lock()
|
||||
p.live--
|
||||
current := p.gen == gen
|
||||
p.mu.Unlock()
|
||||
if accepted && current {
|
||||
p.onAccept()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (p *ProcessPrompt) Hide() {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.stopLocked()
|
||||
}
|
||||
|
||||
func (p *ProcessPrompt) stopLocked() {
|
||||
if p.cancel != nil {
|
||||
p.cancel()
|
||||
p.cancel = nil
|
||||
p.gen++
|
||||
}
|
||||
}
|
||||
|
||||
func (p *ProcessPrompt) running() bool {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.live > 0
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package overlay
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/orient"
|
||||
)
|
||||
|
||||
func TestPlacement(t *testing.T) {
|
||||
cases := []struct {
|
||||
target, current orient.Orientation
|
||||
want Placement
|
||||
}{
|
||||
// Not rotated relative to the content: plain bottom-right, upright.
|
||||
{orient.Landscape, orient.Landscape, Placement{"bottom", "right", 0}},
|
||||
// Turned clockwise (right grip down): the user's bottom-right is the
|
||||
// content's top-right, and the icon must turn counter-clockwise.
|
||||
{orient.PortraitCW, orient.Landscape, Placement{"top", "right", 270}},
|
||||
// Turned counter-clockwise (left grip down).
|
||||
{orient.PortraitCCW, orient.Landscape, Placement{"bottom", "left", 90}},
|
||||
// Upside down.
|
||||
{orient.LandscapeFlipped, orient.Landscape, Placement{"top", "left", 180}},
|
||||
// Relative turns are what matter, not absolute ones.
|
||||
{orient.Landscape, orient.PortraitCCW, Placement{"top", "right", 270}},
|
||||
{orient.PortraitCW, orient.LandscapeFlipped, Placement{"bottom", "left", 90}},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := PlacementFor(c.target, c.current); got != c.want {
|
||||
t.Errorf("PlacementFor(%v, %v) = %+v, want %+v", c.target, c.current, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlacementArgs(t *testing.T) {
|
||||
got := Placement{"top", "left", 180}.Args()
|
||||
want := []string{"--vertical", "top", "--horizontal", "left", "--angle", "180"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Args = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHelperOverlay is not a real test: the process tests below re-run the
|
||||
// test binary as a stand-in for the QML overlay.
|
||||
func TestHelperOverlay(t *testing.T) {
|
||||
mode := os.Getenv("DECKROTATE_HELPER")
|
||||
if mode == "" {
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "args=%v\n", os.Args)
|
||||
switch mode {
|
||||
case "accept":
|
||||
os.Exit(AcceptExitCode)
|
||||
case "fail":
|
||||
os.Exit(1)
|
||||
case "wait":
|
||||
bufio.NewReader(os.Stdin).ReadString('\n')
|
||||
time.Sleep(time.Minute)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
func helper(mode string, seen *[][]string, mu *sync.Mutex) CommandFunc {
|
||||
return func(ctx context.Context, p Placement) *exec.Cmd {
|
||||
mu.Lock()
|
||||
*seen = append(*seen, p.Args())
|
||||
mu.Unlock()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=TestHelperOverlay")
|
||||
cmd.Env = append(os.Environ(), "DECKROTATE_HELPER="+mode)
|
||||
return cmd
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessPromptAccept(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var seen [][]string
|
||||
accepted := make(chan struct{}, 1)
|
||||
p := NewProcessPrompt(helper("accept", &seen, &mu), func() { accepted <- struct{}{} })
|
||||
p.Show(orient.PortraitCW, orient.Landscape)
|
||||
select {
|
||||
case <-accepted:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("OnAccept not called")
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(seen) != 1 || strings.Join(seen[0], " ") != "--vertical top --horizontal right --angle 270" {
|
||||
t.Errorf("args = %v", seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessPromptOtherExitIsNotAccept(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var seen [][]string
|
||||
accepted := make(chan struct{}, 1)
|
||||
p := NewProcessPrompt(helper("fail", &seen, &mu), func() { accepted <- struct{}{} })
|
||||
p.Show(orient.PortraitCW, orient.Landscape)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for p.running() && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
select {
|
||||
case <-accepted:
|
||||
t.Fatal("a failing overlay must not count as accept")
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessPromptHideKills(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var seen [][]string
|
||||
p := NewProcessPrompt(helper("wait", &seen, &mu), func() { t.Error("unexpected accept") })
|
||||
p.Show(orient.PortraitCW, orient.Landscape)
|
||||
if !p.running() {
|
||||
t.Fatal("overlay not running after Show")
|
||||
}
|
||||
p.Show(orient.PortraitCCW, orient.Landscape) // replaces the first
|
||||
p.Hide()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for p.running() && time.Now().Before(deadline) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if p.running() {
|
||||
t.Fatal("overlay still running after Hide")
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(seen) != 2 {
|
||||
t.Errorf("started %d overlays, want 2", len(seen))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/godbus/dbus/v5"
|
||||
)
|
||||
|
||||
// Client talks to a running daemon.
|
||||
type Client struct{ conn *dbus.Conn }
|
||||
|
||||
func NewClient(conn *dbus.Conn) *Client { return &Client{conn: conn} }
|
||||
|
||||
func (c *Client) obj() dbus.BusObject { return c.conn.Object(BusName, ObjectPath) }
|
||||
|
||||
func (c *Client) Call(method string, args ...any) error {
|
||||
return c.obj().Call(Interface+"."+method, 0, args...).Err
|
||||
}
|
||||
|
||||
func (c *Client) Status() (Status, error) {
|
||||
var all map[string]dbus.Variant
|
||||
if err := c.obj().Call("org.freedesktop.DBus.Properties.GetAll", 0, Interface).Store(&all); err != nil {
|
||||
return Status{}, err
|
||||
}
|
||||
var s Status
|
||||
for name, dst := range map[string]any{
|
||||
"Mode": &s.Mode, "Locked": &s.Locked,
|
||||
"DeviceOrientation": &s.Device, "ScreenOrientation": &s.Screen,
|
||||
"SuggestedOrientation": &s.Suggested, "ImuAvailable": &s.IMU,
|
||||
} {
|
||||
v, ok := all[name]
|
||||
if !ok {
|
||||
return s, fmt.Errorf("daemon did not report %s", name)
|
||||
}
|
||||
if err := v.Store(dst); err != nil {
|
||||
return s, fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
// Package service exposes the controller on the D-Bus session bus.
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/godbus/dbus/v5"
|
||||
"github.com/godbus/dbus/v5/introspect"
|
||||
"github.com/godbus/dbus/v5/prop"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/core"
|
||||
"github.com/RustyRaptor/deckrotate/internal/orient"
|
||||
)
|
||||
|
||||
const (
|
||||
BusName = "io.github.RustyRaptor.DeckRotate"
|
||||
Interface = BusName
|
||||
ObjectPath = dbus.ObjectPath("/io/github/RustyRaptor/DeckRotate")
|
||||
|
||||
callTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
var ErrAlreadyRunning = errors.New("service: another deckrotate daemon owns the bus name")
|
||||
|
||||
type Controller interface {
|
||||
State() core.State
|
||||
SetMode(context.Context, core.Mode) error
|
||||
ToggleMode(context.Context) error
|
||||
SetLocked(context.Context, bool) error
|
||||
ToggleLock(context.Context) error
|
||||
RotateTo(context.Context, orient.Orientation) error
|
||||
RotateBy(context.Context, int) error
|
||||
Accept(context.Context) error
|
||||
Dismiss()
|
||||
}
|
||||
|
||||
// Status is the property set as plain values.
|
||||
type Status struct {
|
||||
Mode string
|
||||
Locked bool
|
||||
Device string
|
||||
Screen string
|
||||
Suggested string // empty when nothing is being offered
|
||||
IMU bool
|
||||
}
|
||||
|
||||
func statusOf(s core.State) Status {
|
||||
sug := ""
|
||||
if s.Suggested != orient.Unknown {
|
||||
sug = s.Suggested.String()
|
||||
}
|
||||
return Status{
|
||||
Mode: s.Mode.String(), Locked: s.Locked,
|
||||
Device: s.Device.String(), Screen: s.Screen.String(),
|
||||
Suggested: sug, IMU: s.IMU,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Status) props() map[string]any {
|
||||
return map[string]any{
|
||||
"Mode": s.Mode,
|
||||
"Locked": s.Locked,
|
||||
"DeviceOrientation": s.Device,
|
||||
"ScreenOrientation": s.Screen,
|
||||
"SuggestedOrientation": s.Suggested,
|
||||
"ImuAvailable": s.IMU,
|
||||
}
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
props *prop.Properties
|
||||
mu sync.Mutex
|
||||
last Status
|
||||
}
|
||||
|
||||
// object holds the exported methods; godbus exports every method of it.
|
||||
type object struct{ c Controller }
|
||||
|
||||
func fail(err error) *dbus.Error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return dbus.MakeFailedError(err)
|
||||
}
|
||||
|
||||
func ctx() (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(context.Background(), callTimeout)
|
||||
}
|
||||
|
||||
func (o object) SetMode(m string) *dbus.Error {
|
||||
mode, err := core.ParseMode(m)
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
c, cancel := ctx()
|
||||
defer cancel()
|
||||
return fail(o.c.SetMode(c, mode))
|
||||
}
|
||||
|
||||
func (o object) ToggleMode() *dbus.Error {
|
||||
c, cancel := ctx()
|
||||
defer cancel()
|
||||
return fail(o.c.ToggleMode(c))
|
||||
}
|
||||
|
||||
func (o object) SetLocked(locked bool) *dbus.Error {
|
||||
c, cancel := ctx()
|
||||
defer cancel()
|
||||
return fail(o.c.SetLocked(c, locked))
|
||||
}
|
||||
|
||||
func (o object) ToggleLock() *dbus.Error {
|
||||
c, cancel := ctx()
|
||||
defer cancel()
|
||||
return fail(o.c.ToggleLock(c))
|
||||
}
|
||||
|
||||
func (o object) RotateTo(name string) *dbus.Error {
|
||||
or, err := orient.Parse(name)
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
c, cancel := ctx()
|
||||
defer cancel()
|
||||
return fail(o.c.RotateTo(c, or))
|
||||
}
|
||||
|
||||
func (o object) RotateBy(turns int32) *dbus.Error {
|
||||
c, cancel := ctx()
|
||||
defer cancel()
|
||||
return fail(o.c.RotateBy(c, int(turns)))
|
||||
}
|
||||
|
||||
func (o object) Accept() *dbus.Error {
|
||||
c, cancel := ctx()
|
||||
defer cancel()
|
||||
return fail(o.c.Accept(c))
|
||||
}
|
||||
|
||||
func (o object) Dismiss() *dbus.Error {
|
||||
o.c.Dismiss()
|
||||
return nil
|
||||
}
|
||||
|
||||
var methods = []introspect.Method{
|
||||
{Name: "SetMode", Args: []introspect.Arg{{Name: "mode", Type: "s", Direction: "in"}}},
|
||||
{Name: "ToggleMode"},
|
||||
{Name: "SetLocked", Args: []introspect.Arg{{Name: "locked", Type: "b", Direction: "in"}}},
|
||||
{Name: "ToggleLock"},
|
||||
{Name: "RotateTo", Args: []introspect.Arg{{Name: "orientation", Type: "s", Direction: "in"}}},
|
||||
{Name: "RotateBy", Args: []introspect.Arg{{Name: "quarterTurnsClockwise", Type: "i", Direction: "in"}}},
|
||||
{Name: "Accept"},
|
||||
{Name: "Dismiss"},
|
||||
}
|
||||
|
||||
// Export publishes c on conn and claims the well-known bus name.
|
||||
func Export(conn *dbus.Conn, c Controller) (*Service, error) {
|
||||
if err := conn.Export(object{c}, ObjectPath, Interface); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st := statusOf(c.State())
|
||||
spec := map[string]*prop.Prop{}
|
||||
for name, v := range st.props() {
|
||||
spec[name] = &prop.Prop{Value: v, Emit: prop.EmitTrue}
|
||||
}
|
||||
props, err := prop.Export(conn, ObjectPath, prop.Map{Interface: spec})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node := &introspect.Node{
|
||||
Name: string(ObjectPath),
|
||||
Interfaces: []introspect.Interface{
|
||||
introspect.IntrospectData,
|
||||
prop.IntrospectData,
|
||||
{Name: Interface, Methods: methods, Properties: props.Introspection(Interface)},
|
||||
},
|
||||
}
|
||||
if err := conn.Export(introspect.NewIntrospectable(node), ObjectPath, "org.freedesktop.DBus.Introspectable"); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reply, err := conn.RequestName(BusName, dbus.NameFlagDoNotQueue)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if reply != dbus.RequestNameReplyPrimaryOwner {
|
||||
return nil, ErrAlreadyRunning
|
||||
}
|
||||
return &Service{props: props, last: st}, nil
|
||||
}
|
||||
|
||||
// Publish updates the properties, emitting PropertiesChanged for each one
|
||||
// whose value actually changed.
|
||||
func (s *Service) Publish(st core.State) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
next := statusOf(st)
|
||||
prev := s.last.props()
|
||||
for name, v := range next.props() {
|
||||
if prev[name] != v {
|
||||
s.props.SetMust(Interface, name, v)
|
||||
}
|
||||
}
|
||||
s.last = next
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"os/exec"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/godbus/dbus/v5"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/core"
|
||||
"github.com/RustyRaptor/deckrotate/internal/orient"
|
||||
)
|
||||
|
||||
// privateBus starts a throwaway session bus and returns its address.
|
||||
func privateBus(t *testing.T) string {
|
||||
t.Helper()
|
||||
path, err := exec.LookPath("dbus-daemon")
|
||||
if err != nil {
|
||||
t.Skip("dbus-daemon not available")
|
||||
}
|
||||
cmd := exec.Command(path, "--session", "--nofork", "--print-address=1")
|
||||
out, _ := cmd.StdoutPipe()
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() })
|
||||
addr, err := bufio.NewReader(out).ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return strings.TrimSpace(addr)
|
||||
}
|
||||
|
||||
func connect(t *testing.T, addr string) *dbus.Conn {
|
||||
t.Helper()
|
||||
conn, err := dbus.Connect(addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { conn.Close() })
|
||||
return conn
|
||||
}
|
||||
|
||||
type fakeController struct {
|
||||
mu sync.Mutex
|
||||
calls []string
|
||||
st core.State
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeController) rec(s string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.calls = append(f.calls, s)
|
||||
return f.err
|
||||
}
|
||||
|
||||
func (f *fakeController) recorded() []string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]string(nil), f.calls...)
|
||||
}
|
||||
|
||||
func (f *fakeController) setErr(err error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.err = err
|
||||
}
|
||||
|
||||
func (f *fakeController) State() core.State { return f.st }
|
||||
func (f *fakeController) SetMode(_ context.Context, m core.Mode) error {
|
||||
return f.rec("mode " + m.String())
|
||||
}
|
||||
func (f *fakeController) ToggleMode(context.Context) error { return f.rec("toggle-mode") }
|
||||
func (f *fakeController) SetLocked(_ context.Context, l bool) error {
|
||||
if l {
|
||||
return f.rec("lock")
|
||||
}
|
||||
return f.rec("unlock")
|
||||
}
|
||||
func (f *fakeController) ToggleLock(context.Context) error { return f.rec("toggle-lock") }
|
||||
func (f *fakeController) RotateTo(_ context.Context, o orient.Orientation) error {
|
||||
return f.rec("to " + o.String())
|
||||
}
|
||||
func (f *fakeController) RotateBy(_ context.Context, n int) error {
|
||||
return f.rec("by " + map[int]string{1: "1", -1: "-1"}[n])
|
||||
}
|
||||
func (f *fakeController) Accept(context.Context) error { return f.rec("accept") }
|
||||
func (f *fakeController) Dismiss() { f.rec("dismiss") }
|
||||
|
||||
func setup(t *testing.T) (*fakeController, *Service, *Client) {
|
||||
t.Helper()
|
||||
addr := privateBus(t)
|
||||
fc := &fakeController{st: core.State{
|
||||
Mode: core.Manual, Locked: true, Device: orient.PortraitCW,
|
||||
Screen: orient.Landscape, Suggested: orient.Unknown, IMU: true,
|
||||
}}
|
||||
svc, err := Export(connect(t, addr), fc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return fc, svc, NewClient(connect(t, addr))
|
||||
}
|
||||
|
||||
func TestMethodsReachController(t *testing.T) {
|
||||
fc, _, cl := setup(t)
|
||||
steps := []struct {
|
||||
method string
|
||||
args []any
|
||||
}{
|
||||
{"SetMode", []any{"auto"}},
|
||||
{"ToggleMode", nil},
|
||||
{"SetLocked", []any{true}},
|
||||
{"SetLocked", []any{false}},
|
||||
{"ToggleLock", nil},
|
||||
{"RotateTo", []any{"portrait-ccw"}},
|
||||
{"RotateBy", []any{int32(1)}},
|
||||
{"RotateBy", []any{int32(-1)}},
|
||||
{"Accept", nil},
|
||||
{"Dismiss", nil},
|
||||
}
|
||||
for _, s := range steps {
|
||||
if err := cl.Call(s.method, s.args...); err != nil {
|
||||
t.Fatalf("%s: %v", s.method, err)
|
||||
}
|
||||
}
|
||||
want := []string{"mode auto", "toggle-mode", "lock", "unlock", "toggle-lock",
|
||||
"to portrait-ccw", "by 1", "by -1", "accept", "dismiss"}
|
||||
if got := fc.recorded(); !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("calls = %v\nwant %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadArgumentsAreDBusErrors(t *testing.T) {
|
||||
fc, _, cl := setup(t)
|
||||
if err := cl.Call("SetMode", "sometimes"); err == nil {
|
||||
t.Error("SetMode(sometimes) should fail")
|
||||
}
|
||||
if err := cl.Call("RotateTo", "diagonal"); err == nil {
|
||||
t.Error("RotateTo(diagonal) should fail")
|
||||
}
|
||||
if got := fc.recorded(); len(got) != 0 {
|
||||
t.Errorf("controller called with bad args: %v", got)
|
||||
}
|
||||
fc.setErr(errors.New("kscreen-doctor exploded"))
|
||||
err := cl.Call("ToggleLock")
|
||||
if err == nil || !strings.Contains(err.Error(), "kscreen-doctor exploded") {
|
||||
t.Errorf("controller error not forwarded: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitialPropertiesAndStatus(t *testing.T) {
|
||||
_, _, cl := setup(t)
|
||||
got, err := cl.Status()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := Status{Mode: "manual", Locked: true, Device: "portrait-cw", Screen: "landscape", Suggested: "", IMU: true}
|
||||
if got != want {
|
||||
t.Errorf("Status = %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishEmitsPropertiesChanged(t *testing.T) {
|
||||
addr := privateBus(t)
|
||||
svc, err := Export(connect(t, addr), &fakeController{st: core.State{Device: orient.Unknown, Screen: orient.Landscape, Suggested: orient.Unknown}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
watcher := connect(t, addr)
|
||||
if err := watcher.AddMatchSignal(dbus.WithMatchInterface("org.freedesktop.DBus.Properties"), dbus.WithMatchMember("PropertiesChanged")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ch := make(chan *dbus.Signal, 16)
|
||||
watcher.Signal(ch)
|
||||
|
||||
svc.Publish(core.State{Mode: core.Auto, Device: orient.PortraitCCW, Screen: orient.Landscape, Suggested: orient.PortraitCCW, IMU: true})
|
||||
|
||||
changed := map[string]any{}
|
||||
deadline := time.After(3 * time.Second)
|
||||
for len(changed) < 3 {
|
||||
select {
|
||||
case sig := <-ch:
|
||||
if sig.Body[0] != Interface {
|
||||
continue
|
||||
}
|
||||
for k, v := range sig.Body[1].(map[string]dbus.Variant) {
|
||||
changed[k] = v.Value()
|
||||
}
|
||||
case <-deadline:
|
||||
t.Fatalf("only saw %v", changed)
|
||||
}
|
||||
}
|
||||
want := map[string]any{"DeviceOrientation": "portrait-ccw", "SuggestedOrientation": "portrait-ccw", "ImuAvailable": true}
|
||||
if !reflect.DeepEqual(changed, want) {
|
||||
t.Errorf("changed = %v, want %v", changed, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecondInstanceRefused(t *testing.T) {
|
||||
addr := privateBus(t)
|
||||
if _, err := Export(connect(t, addr), &fakeController{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Export(connect(t, addr), &fakeController{}); !errors.Is(err, ErrAlreadyRunning) {
|
||||
t.Errorf("second Export err = %v, want ErrAlreadyRunning", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntrospectionListsMethods(t *testing.T) {
|
||||
_, _, cl := setup(t)
|
||||
var xml string
|
||||
if err := cl.conn.Object(BusName, ObjectPath).Call("org.freedesktop.DBus.Introspectable.Introspect", 0).Store(&xml); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, m := range []string{"ToggleLock", "RotateBy", "Accept", "ScreenOrientation"} {
|
||||
if !strings.Contains(xml, `"`+m+`"`) {
|
||||
t.Errorf("introspection is missing %s", m)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// Command testservice serves a real controller with an in-memory screen on
|
||||
// the session bus, for the plasmoid's D-Bus integration tests.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/godbus/dbus/v5"
|
||||
|
||||
"github.com/RustyRaptor/deckrotate/internal/core"
|
||||
"github.com/RustyRaptor/deckrotate/internal/orient"
|
||||
"github.com/RustyRaptor/deckrotate/internal/service"
|
||||
)
|
||||
|
||||
type memScreen struct{ o orient.Orientation }
|
||||
|
||||
func (m *memScreen) Current(context.Context) (orient.Orientation, error) { return m.o, nil }
|
||||
func (m *memScreen) Apply(_ context.Context, o orient.Orientation) error {
|
||||
m.o = o
|
||||
return nil
|
||||
}
|
||||
|
||||
type noPrompt struct{}
|
||||
|
||||
func (noPrompt) Show(_, _ orient.Orientation) {}
|
||||
func (noPrompt) Hide() {}
|
||||
|
||||
type memStore struct{ s core.Settings }
|
||||
|
||||
func (m *memStore) Load() (core.Settings, error) { return m.s, nil }
|
||||
func (m *memStore) Save(s core.Settings) error { m.s = s; return nil }
|
||||
|
||||
func main() {
|
||||
conn, err := dbus.ConnectSessionBus()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
var svc *service.Service
|
||||
ctrl := core.New(core.Deps{
|
||||
Screen: &memScreen{o: orient.Landscape},
|
||||
Prompt: noPrompt{},
|
||||
Store: &memStore{},
|
||||
OnChange: func(st core.State) {
|
||||
if svc != nil {
|
||||
svc.Publish(st)
|
||||
}
|
||||
},
|
||||
})
|
||||
if err := ctrl.Init(ctx); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
ctrl.SetIMUAvailable(true)
|
||||
ctrl.SetLocked(ctx, true) // don't let the device report rotate the screen
|
||||
ctrl.DeviceTurned(ctx, orient.Landscape)
|
||||
ctrl.SetLocked(ctx, false)
|
||||
if svc, err = service.Export(conn, ctrl); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Fprintln(os.Stdout, "ready")
|
||||
<-ctx.Done()
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
[tools]
|
||||
go = "1.27.3"
|
||||
|
||||
[env]
|
||||
CGO_ENABLED = "0"
|
||||
|
||||
[tasks.test]
|
||||
description = "Run all tests"
|
||||
depends = ["test:go", "test:qml", "test:plasmoid", "test:dbus"]
|
||||
|
||||
[tasks."test:go"]
|
||||
description = "Run Go tests"
|
||||
run = "go test ./..."
|
||||
|
||||
[tasks."test:qml"]
|
||||
description = "Run QML tests offscreen"
|
||||
run = "QT_QPA_PLATFORM=offscreen QT_FORCE_STDERR_LOGGING=1 /usr/lib/qt6/bin/qmltestrunner -input ui/tests"
|
||||
|
||||
[tasks.check]
|
||||
description = "Vet and format check"
|
||||
run = ["go vet ./...", "test -z \"$(gofmt -l .)\""]
|
||||
|
||||
[tasks.build]
|
||||
description = "Build the deckrotate binary"
|
||||
run = "go build -o bin/deckrotate ./cmd/deckrotate"
|
||||
|
||||
[tasks."test:dbus"]
|
||||
description = "Run the applet's D-Bus backend against the real Go service on a private bus"
|
||||
run = "./scripts/test-dbus.sh"
|
||||
|
||||
[tasks."test:plasmoid"]
|
||||
description = "Run the applet's QML tests offscreen"
|
||||
run = "QT_QPA_PLATFORM=offscreen /usr/lib/qt6/bin/qmltestrunner -input plasmoid/tests"
|
||||
|
||||
[tasks."test:hw"]
|
||||
description = "Run tests that read the real Deck controller"
|
||||
run = "DECKROTATE_HW=1 go test ./internal/imu/ -run Hardware -v"
|
||||
|
||||
[tasks.install]
|
||||
description = "Install the daemon, overlay, applet, shortcuts and systemd unit under $HOME"
|
||||
depends = ["build"]
|
||||
run = [
|
||||
"install -Dm755 bin/deckrotate ~/.local/bin/deckrotate",
|
||||
"rm -rf ~/.local/share/deckrotate/ui && mkdir -p ~/.local/share/deckrotate && cp -r ui ~/.local/share/deckrotate/ui && rm -rf ~/.local/share/deckrotate/ui/tests",
|
||||
"install -Dm644 packaging/systemd/deckrotate.service ~/.config/systemd/user/deckrotate.service",
|
||||
"mkdir -p ~/.local/share/kglobalaccel && sed \"s|@BINDIR@|$HOME/.local/bin|g\" packaging/kglobalaccel/io.github.rustyraptor.deckrotate.desktop > ~/.local/share/kglobalaccel/io.github.rustyraptor.deckrotate.desktop",
|
||||
"kpackagetool6 -t Plasma/Applet -u plasmoid/package 2>/dev/null || kpackagetool6 -t Plasma/Applet -i plasmoid/package",
|
||||
"systemctl --user daemon-reload",
|
||||
"echo 'installed; enable with: systemctl --user enable --now deckrotate'",
|
||||
]
|
||||
|
||||
[tasks.uninstall]
|
||||
description = "Stop and remove deckrotate from $HOME"
|
||||
run = [
|
||||
"systemctl --user disable --now deckrotate || true",
|
||||
"rm -f ~/.local/bin/deckrotate ~/.config/systemd/user/deckrotate.service ~/.local/share/kglobalaccel/io.github.rustyraptor.deckrotate.desktop",
|
||||
"rm -rf ~/.local/share/deckrotate",
|
||||
"kpackagetool6 -t Plasma/Applet -r io.github.rustyraptor.deckrotate || true",
|
||||
"systemctl --user daemon-reload",
|
||||
]
|
||||
@@ -0,0 +1,59 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Screen Rotation
|
||||
Comment=Rotate, auto-rotate and lock the Steam Deck screen
|
||||
Icon=transform-rotate
|
||||
NoDisplay=true
|
||||
StartupNotify=false
|
||||
X-KDE-GlobalShortcutType=Service
|
||||
Actions=ToggleLock;RotateCW;RotateCCW;Flip;ToggleMode;Accept;Landscape;PortraitCW;PortraitCCW;LandscapeFlipped;
|
||||
|
||||
[Desktop Action ToggleLock]
|
||||
Name=Lock/Unlock Screen Rotation
|
||||
Exec=@BINDIR@/deckrotate toggle-lock
|
||||
X-KDE-Shortcuts=
|
||||
|
||||
[Desktop Action RotateCW]
|
||||
Name=Rotate Screen Right
|
||||
Exec=@BINDIR@/deckrotate rotate cw
|
||||
X-KDE-Shortcuts=
|
||||
|
||||
[Desktop Action RotateCCW]
|
||||
Name=Rotate Screen Left
|
||||
Exec=@BINDIR@/deckrotate rotate ccw
|
||||
X-KDE-Shortcuts=
|
||||
|
||||
[Desktop Action Flip]
|
||||
Name=Flip Screen Upside Down
|
||||
Exec=@BINDIR@/deckrotate rotate flip
|
||||
X-KDE-Shortcuts=
|
||||
|
||||
[Desktop Action ToggleMode]
|
||||
Name=Switch Auto/Manual Rotation
|
||||
Exec=@BINDIR@/deckrotate mode toggle
|
||||
X-KDE-Shortcuts=
|
||||
|
||||
[Desktop Action Accept]
|
||||
Name=Rotate to Match the Deck
|
||||
Exec=@BINDIR@/deckrotate accept
|
||||
X-KDE-Shortcuts=
|
||||
|
||||
[Desktop Action Landscape]
|
||||
Name=Screen Orientation: Landscape
|
||||
Exec=@BINDIR@/deckrotate rotate landscape
|
||||
X-KDE-Shortcuts=
|
||||
|
||||
[Desktop Action PortraitCW]
|
||||
Name=Screen Orientation: Portrait (right grip down)
|
||||
Exec=@BINDIR@/deckrotate rotate portrait-cw
|
||||
X-KDE-Shortcuts=
|
||||
|
||||
[Desktop Action PortraitCCW]
|
||||
Name=Screen Orientation: Portrait (left grip down)
|
||||
Exec=@BINDIR@/deckrotate rotate portrait-ccw
|
||||
X-KDE-Shortcuts=
|
||||
|
||||
[Desktop Action LandscapeFlipped]
|
||||
Name=Screen Orientation: Landscape (flipped)
|
||||
Exec=@BINDIR@/deckrotate rotate landscape-flipped
|
||||
X-KDE-Shortcuts=
|
||||
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=deckrotate: Steam Deck screen rotation for Plasma
|
||||
Documentation=https://github.com/RustyRaptor/deckrotate
|
||||
PartOf=graphical-session.target
|
||||
After=plasma-workspace.target
|
||||
|
||||
[Service]
|
||||
ExecStart=%h/.local/bin/deckrotate daemon
|
||||
Restart=on-failure
|
||||
RestartSec=3
|
||||
|
||||
[Install]
|
||||
WantedBy=plasma-workspace.target
|
||||
@@ -0,0 +1,59 @@
|
||||
import QtQuick
|
||||
import QtTest
|
||||
import "../package/contents/ui"
|
||||
|
||||
// Runs against internal/service/testservice on a private bus (scripts/test-dbus.sh).
|
||||
Item {
|
||||
id: root
|
||||
|
||||
DBusBackend {
|
||||
id: backend
|
||||
}
|
||||
|
||||
TestCase {
|
||||
name: "DBusBackend"
|
||||
|
||||
function initTestCase() {
|
||||
tryCompare(backend, "available", true, 5000)
|
||||
}
|
||||
|
||||
function test_1_initial_state() {
|
||||
tryCompare(backend, "mode", "auto")
|
||||
compare(backend.locked, false)
|
||||
compare(backend.imu, true)
|
||||
compare(backend.device, "landscape")
|
||||
compare(backend.screen, "landscape")
|
||||
compare(backend.suggested, "")
|
||||
}
|
||||
|
||||
function test_2_lock() {
|
||||
backend.setLocked(true)
|
||||
tryCompare(backend, "locked", true)
|
||||
backend.setLocked(false)
|
||||
tryCompare(backend, "locked", false)
|
||||
}
|
||||
|
||||
function test_3_rotate() {
|
||||
backend.rotateTo("portrait-ccw")
|
||||
tryCompare(backend, "screen", "portrait-ccw")
|
||||
backend.rotateBy(1)
|
||||
tryCompare(backend, "screen", "landscape")
|
||||
backend.rotateBy(-1)
|
||||
tryCompare(backend, "screen", "portrait-ccw")
|
||||
backend.rotateTo("landscape")
|
||||
tryCompare(backend, "screen", "landscape")
|
||||
}
|
||||
|
||||
function test_4_mode() {
|
||||
backend.setMode("manual")
|
||||
tryCompare(backend, "mode", "manual")
|
||||
backend.setMode("auto")
|
||||
tryCompare(backend, "mode", "auto")
|
||||
}
|
||||
|
||||
function test_5_types_are_plain() {
|
||||
compare(typeof backend.mode, "string")
|
||||
compare(typeof backend.locked, "boolean")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import QtQuick
|
||||
import org.kde.plasma.workspace.dbus as DBus
|
||||
|
||||
// The deckrotate daemon as seen over the session bus. Same API as MockBackend.
|
||||
QtObject {
|
||||
id: backend
|
||||
|
||||
readonly property string service: "io.github.RustyRaptor.DeckRotate"
|
||||
readonly property string objectPath: "/io/github/RustyRaptor/DeckRotate"
|
||||
|
||||
readonly property bool available: watcher.registered
|
||||
readonly property bool imu: available && props.properties.ImuAvailable === true
|
||||
readonly property string mode: text(props.properties.Mode, "auto")
|
||||
readonly property bool locked: available && props.properties.Locked === true
|
||||
readonly property string device: text(props.properties.DeviceOrientation, "unknown")
|
||||
readonly property string screen: text(props.properties.ScreenOrientation, "unknown")
|
||||
readonly property string suggested: text(props.properties.SuggestedOrientation, "")
|
||||
|
||||
property DBus.DBusServiceWatcher watcher: DBus.DBusServiceWatcher {
|
||||
busType: DBus.BusType.Session
|
||||
watchedService: backend.service
|
||||
// The daemon may start after the applet, or restart.
|
||||
onRegisteredChanged: if (registered) backend.props.updateAll()
|
||||
}
|
||||
|
||||
property DBus.Properties props: DBus.Properties {
|
||||
busType: DBus.BusType.Session
|
||||
service: backend.service
|
||||
path: backend.objectPath
|
||||
iface: backend.service
|
||||
}
|
||||
|
||||
// Strings arrive as String objects; make them plain for === comparisons.
|
||||
function text(v, fallback) {
|
||||
return available && v !== undefined && v !== null ? String(v) : fallback
|
||||
}
|
||||
|
||||
// No signature: the module rejects explicit ones but infers types correctly.
|
||||
function call(member, args) {
|
||||
const reply = DBus.SessionBus.asyncCall({
|
||||
service: service,
|
||||
path: objectPath,
|
||||
iface: service,
|
||||
member: member,
|
||||
arguments: args
|
||||
})
|
||||
reply.finished.connect(() => {
|
||||
if (reply.isError)
|
||||
console.warn("deckrotate:", member, "failed:", reply.error.message)
|
||||
})
|
||||
}
|
||||
|
||||
function setMode(m) { call("SetMode", [m]) }
|
||||
function setLocked(l) { call("SetLocked", [l]) }
|
||||
function rotateTo(o) { call("RotateTo", [o]) }
|
||||
function rotateBy(n) { call("RotateBy", [new DBus.int32(n)]) }
|
||||
function accept() { call("Accept", []) }
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import QtQuick
|
||||
import QtQuick.Layouts
|
||||
import org.kde.kirigami as Kirigami
|
||||
import org.kde.plasma.components as PlasmaComponents3
|
||||
import org.kde.plasma.extras as PlasmaExtras
|
||||
import "logic.js" as Logic
|
||||
|
||||
Item {
|
||||
id: view
|
||||
|
||||
// DBusBackend in the applet, MockBackend in tests.
|
||||
property var backend
|
||||
|
||||
implicitWidth: Kirigami.Units.gridUnit * 18
|
||||
implicitHeight: content.implicitHeight + Kirigami.Units.largeSpacing * 2
|
||||
|
||||
PlasmaExtras.PlaceholderMessage {
|
||||
objectName: "notRunning"
|
||||
anchors.centerIn: parent
|
||||
width: parent.width - Kirigami.Units.largeSpacing * 4
|
||||
visible: !view.backend.available
|
||||
iconName: "transform-rotate"
|
||||
text: tr("Rotation service is not running")
|
||||
explanation: tr("Start it with: systemctl --user start deckrotate")
|
||||
}
|
||||
|
||||
ColumnLayout {
|
||||
id: content
|
||||
objectName: "controls"
|
||||
visible: view.backend.available
|
||||
anchors.fill: parent
|
||||
anchors.margins: Kirigami.Units.largeSpacing
|
||||
spacing: Kirigami.Units.smallSpacing
|
||||
|
||||
Kirigami.InlineMessage {
|
||||
objectName: "suggestion"
|
||||
Layout.fillWidth: true
|
||||
visible: view.backend.suggested !== ""
|
||||
type: Kirigami.MessageType.Information
|
||||
text: tr("The Deck is turned to %1", Logic.label(view.backend.suggested))
|
||||
actions: [
|
||||
Kirigami.Action {
|
||||
id: acceptAction
|
||||
text: tr("Rotate")
|
||||
icon.name: "object-rotate-right"
|
||||
onTriggered: view.backend.accept()
|
||||
}
|
||||
]
|
||||
}
|
||||
// Mirrors acceptAction as a plain button tests and keyboards can reach.
|
||||
PlasmaComponents3.Button {
|
||||
objectName: "acceptSuggestion"
|
||||
visible: view.backend.suggested !== ""
|
||||
Layout.alignment: Qt.AlignRight
|
||||
action: acceptAction
|
||||
}
|
||||
|
||||
Kirigami.InlineMessage {
|
||||
objectName: "noSensor"
|
||||
Layout.fillWidth: true
|
||||
visible: !view.backend.imu
|
||||
type: Kirigami.MessageType.Warning
|
||||
text: tr("Orientation sensor unavailable; rotate manually.")
|
||||
}
|
||||
|
||||
PlasmaExtras.Heading {
|
||||
level: 5
|
||||
text: tr("Screen orientation")
|
||||
}
|
||||
|
||||
GridLayout {
|
||||
Layout.fillWidth: true
|
||||
columns: 2
|
||||
columnSpacing: Kirigami.Units.smallSpacing
|
||||
rowSpacing: Kirigami.Units.smallSpacing
|
||||
|
||||
Repeater {
|
||||
model: Logic.orientations
|
||||
delegate: PlasmaComponents3.ToolButton {
|
||||
required property string modelData
|
||||
objectName: "orientation-" + modelData
|
||||
Layout.fillWidth: true
|
||||
checkable: true
|
||||
checked: view.backend.screen === modelData
|
||||
// Leave `checked` to the binding; the daemon's reply updates it.
|
||||
onClicked: {
|
||||
checked = Qt.binding(() => view.backend.screen === modelData)
|
||||
view.backend.rotateTo(modelData)
|
||||
}
|
||||
contentItem: RowLayout {
|
||||
spacing: Kirigami.Units.smallSpacing
|
||||
OrientationGlyph {
|
||||
angle: Logic.angle(modelData)
|
||||
}
|
||||
PlasmaComponents3.Label {
|
||||
Layout.fillWidth: true
|
||||
text: Logic.label(modelData)
|
||||
wrapMode: Text.Wrap
|
||||
}
|
||||
}
|
||||
Accessible.name: Logic.label(modelData)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
RowLayout {
|
||||
Layout.fillWidth: true
|
||||
PlasmaComponents3.Button {
|
||||
objectName: "rotateCCW"
|
||||
Layout.fillWidth: true
|
||||
icon.name: "object-rotate-left"
|
||||
text: tr("Rotate left")
|
||||
onClicked: view.backend.rotateBy(-1)
|
||||
}
|
||||
PlasmaComponents3.Button {
|
||||
objectName: "rotateCW"
|
||||
Layout.fillWidth: true
|
||||
icon.name: "object-rotate-right"
|
||||
text: tr("Rotate right")
|
||||
onClicked: view.backend.rotateBy(1)
|
||||
}
|
||||
}
|
||||
|
||||
Kirigami.Separator {
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: Kirigami.Units.smallSpacing
|
||||
Layout.bottomMargin: Kirigami.Units.smallSpacing
|
||||
}
|
||||
|
||||
PlasmaComponents3.Switch {
|
||||
objectName: "lockSwitch"
|
||||
Layout.fillWidth: true
|
||||
text: tr("Lock rotation")
|
||||
checked: view.backend.locked
|
||||
onToggled: {
|
||||
const want = checked
|
||||
checked = Qt.binding(() => view.backend.locked)
|
||||
view.backend.setLocked(want)
|
||||
}
|
||||
}
|
||||
|
||||
PlasmaExtras.Heading {
|
||||
level: 5
|
||||
text: tr("When the Deck is turned")
|
||||
}
|
||||
|
||||
PlasmaComponents3.RadioButton {
|
||||
objectName: "modeAuto"
|
||||
enabled: view.backend.imu
|
||||
text: tr("Rotate automatically")
|
||||
checked: view.backend.mode === "auto"
|
||||
onClicked: {
|
||||
checked = Qt.binding(() => view.backend.mode === "auto")
|
||||
view.backend.setMode("auto")
|
||||
}
|
||||
}
|
||||
PlasmaComponents3.RadioButton {
|
||||
objectName: "modeManual"
|
||||
enabled: view.backend.imu
|
||||
text: tr("Show a rotate button")
|
||||
checked: view.backend.mode === "manual"
|
||||
onClicked: {
|
||||
checked = Qt.binding(() => view.backend.mode === "manual")
|
||||
view.backend.setMode("manual")
|
||||
}
|
||||
}
|
||||
|
||||
PlasmaComponents3.Label {
|
||||
objectName: "deviceLabel"
|
||||
Layout.fillWidth: true
|
||||
Layout.topMargin: Kirigami.Units.smallSpacing
|
||||
opacity: 0.7
|
||||
font: Kirigami.Theme.smallFont
|
||||
wrapMode: Text.Wrap
|
||||
text: tr("Deck is held: %1", Logic.label(view.backend.device))
|
||||
}
|
||||
|
||||
Item {
|
||||
Layout.fillHeight: true
|
||||
}
|
||||
}
|
||||
|
||||
function tr(s, arg) {
|
||||
if (typeof i18nd === "function")
|
||||
return arg === undefined ? i18nd(Logic.domain, s) : i18nd(Logic.domain, s, arg)
|
||||
return arg === undefined ? s : s.replace("%1", arg)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import QtQuick
|
||||
import org.kde.kirigami as Kirigami
|
||||
|
||||
// A tiny Deck silhouette turned to `angle`; the bar marks the Deck's top edge.
|
||||
Item {
|
||||
id: glyph
|
||||
|
||||
property int angle: 0
|
||||
property color color: Kirigami.Theme.textColor
|
||||
|
||||
implicitWidth: Kirigami.Units.iconSizes.medium
|
||||
implicitHeight: Kirigami.Units.iconSizes.medium
|
||||
|
||||
Item {
|
||||
anchors.centerIn: parent
|
||||
width: glyph.width * 0.9
|
||||
height: width * 0.5
|
||||
rotation: glyph.angle
|
||||
|
||||
Rectangle {
|
||||
anchors.fill: parent
|
||||
radius: height * 0.25
|
||||
color: "transparent"
|
||||
border.color: glyph.color
|
||||
border.width: 1.5
|
||||
}
|
||||
// Screen.
|
||||
Rectangle {
|
||||
anchors.centerIn: parent
|
||||
width: parent.width * 0.5
|
||||
height: parent.height * 0.6
|
||||
color: Qt.alpha(glyph.color, 0.35)
|
||||
}
|
||||
// Top edge marker.
|
||||
Rectangle {
|
||||
anchors.horizontalCenter: parent.horizontalCenter
|
||||
anchors.top: parent.top
|
||||
anchors.topMargin: -3
|
||||
width: parent.width * 0.5
|
||||
height: 2
|
||||
radius: 1
|
||||
color: Kirigami.Theme.highlightColor
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
.pragma library
|
||||
|
||||
const pluginId = "io.github.rustyraptor.deckrotate"
|
||||
const domain = "plasma_applet_" + pluginId
|
||||
|
||||
// Clockwise quarter turns from normal landscape, matching the daemon's names.
|
||||
const orientations = ["landscape", "portrait-cw", "landscape-flipped", "portrait-ccw"]
|
||||
|
||||
const labels = {
|
||||
"landscape": "Landscape",
|
||||
"portrait-cw": "Portrait (right grip down)",
|
||||
"landscape-flipped": "Landscape (flipped)",
|
||||
"portrait-ccw": "Portrait (left grip down)"
|
||||
}
|
||||
|
||||
function label(o) {
|
||||
return labels[o] ?? "Unknown"
|
||||
}
|
||||
|
||||
function angle(o) {
|
||||
const i = orientations.indexOf(o)
|
||||
return i < 0 ? 0 : i * 90
|
||||
}
|
||||
|
||||
function iconName(b) {
|
||||
return b.available && b.locked ? "object-locked-symbolic" : "transform-rotate-symbolic"
|
||||
}
|
||||
|
||||
function summary(b) {
|
||||
if (!b.available)
|
||||
return "Rotation service is not running"
|
||||
let state
|
||||
if (b.locked)
|
||||
state = "Locked"
|
||||
else if (!b.imu)
|
||||
state = "No orientation sensor"
|
||||
else
|
||||
state = b.mode === "manual" ? "Manual" : "Auto-rotate"
|
||||
return state + " · " + label(b.screen)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import QtQuick
|
||||
import QtQuick.Layouts
|
||||
import org.kde.plasma.plasmoid
|
||||
import org.kde.plasma.core as PlasmaCore
|
||||
import org.kde.kirigami as Kirigami
|
||||
import "logic.js" as Logic
|
||||
|
||||
PlasmoidItem {
|
||||
id: root
|
||||
|
||||
readonly property DBusBackend backend: DBusBackend {}
|
||||
|
||||
Plasmoid.icon: Logic.iconName(backend)
|
||||
Plasmoid.status: PlasmaCore.Types.ActiveStatus
|
||||
toolTipMainText: i18n("Screen Rotation")
|
||||
toolTipSubText: Logic.summary(backend)
|
||||
|
||||
// Left click opens the panel, middle click toggles the lock.
|
||||
compactRepresentation: MouseArea {
|
||||
acceptedButtons: Qt.LeftButton | Qt.MiddleButton
|
||||
hoverEnabled: true
|
||||
onClicked: (mouse) => {
|
||||
if (mouse.button === Qt.MiddleButton)
|
||||
root.backend.setLocked(!root.backend.locked)
|
||||
else
|
||||
root.expanded = !root.expanded
|
||||
}
|
||||
|
||||
Kirigami.Icon {
|
||||
anchors.fill: parent
|
||||
source: Plasmoid.icon
|
||||
active: parent.containsMouse
|
||||
}
|
||||
}
|
||||
|
||||
fullRepresentation: FullView {
|
||||
backend: root.backend
|
||||
Layout.minimumWidth: Kirigami.Units.gridUnit * 16
|
||||
Layout.minimumHeight: implicitHeight
|
||||
Layout.preferredWidth: implicitWidth
|
||||
Layout.preferredHeight: implicitHeight
|
||||
}
|
||||
|
||||
Plasmoid.contextualActions: [
|
||||
PlasmaCore.Action {
|
||||
text: i18n("Lock Rotation")
|
||||
icon.name: "object-locked"
|
||||
checkable: true
|
||||
checked: root.backend.locked
|
||||
enabled: root.backend.available
|
||||
onTriggered: root.backend.setLocked(checked)
|
||||
},
|
||||
PlasmaCore.Action {
|
||||
text: i18n("Rotate Right")
|
||||
icon.name: "object-rotate-right"
|
||||
enabled: root.backend.available
|
||||
onTriggered: root.backend.rotateBy(1)
|
||||
},
|
||||
PlasmaCore.Action {
|
||||
text: i18n("Rotate Left")
|
||||
icon.name: "object-rotate-left"
|
||||
enabled: root.backend.available
|
||||
onTriggered: root.backend.rotateBy(-1)
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"KPackageStructure": "Plasma/Applet",
|
||||
"KPlugin": {
|
||||
"Authors": [
|
||||
{
|
||||
"Name": "RustyRaptor"
|
||||
}
|
||||
],
|
||||
"Category": "System Information",
|
||||
"Description": "Rotate, auto-rotate and lock the Steam Deck screen",
|
||||
"EnabledByDefault": true,
|
||||
"Icon": "transform-rotate",
|
||||
"Id": "io.github.rustyraptor.deckrotate",
|
||||
"License": "MIT",
|
||||
"Name": "Screen Rotation",
|
||||
"Version": "0.1.0",
|
||||
"Website": "https://github.com/RustyRaptor/deckrotate"
|
||||
},
|
||||
"X-Plasma-API-Minimum-Version": "6.0",
|
||||
"X-Plasma-NotificationArea": "true",
|
||||
"X-Plasma-NotificationAreaCategory": "Hardware"
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import QtQuick
|
||||
|
||||
// Stands in for DBusBackend; records every call.
|
||||
QtObject {
|
||||
property bool available: true
|
||||
property bool imu: true
|
||||
property string mode: "auto"
|
||||
property bool locked: false
|
||||
property string device: "landscape"
|
||||
property string screen: "landscape"
|
||||
property string suggested: ""
|
||||
|
||||
property var calls: []
|
||||
|
||||
function record(c) {
|
||||
calls = calls.concat([c])
|
||||
}
|
||||
|
||||
function setMode(m) { record("setMode " + m) }
|
||||
function setLocked(l) { record("setLocked " + l) }
|
||||
function rotateTo(o) { record("rotateTo " + o) }
|
||||
function rotateBy(n) { record("rotateBy " + n) }
|
||||
function accept() { record("accept") }
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import QtQuick
|
||||
import QtTest
|
||||
import "../package/contents/ui"
|
||||
|
||||
Item {
|
||||
id: root
|
||||
width: 420
|
||||
height: 560
|
||||
|
||||
// The mock lives inside the view so teardown never leaves it dangling.
|
||||
Component {
|
||||
id: viewComponent
|
||||
FullView {
|
||||
anchors.fill: parent
|
||||
backend: MockBackend {}
|
||||
}
|
||||
}
|
||||
|
||||
TestCase {
|
||||
name: "FullView"
|
||||
when: windowShown
|
||||
|
||||
function make(props) {
|
||||
const view = createTemporaryObject(viewComponent, root)
|
||||
verify(view)
|
||||
for (const k in props || {})
|
||||
view.backend[k] = props[k]
|
||||
return { backend: view.backend, view: view }
|
||||
}
|
||||
|
||||
function child(view, name) {
|
||||
const c = findChild(view, name)
|
||||
verify(c, "missing " + name)
|
||||
return c
|
||||
}
|
||||
|
||||
function test_unavailable_shows_placeholder() {
|
||||
const t = make({ available: false })
|
||||
verify(child(t.view, "notRunning").visible)
|
||||
verify(!child(t.view, "controls").visible)
|
||||
}
|
||||
|
||||
function test_available_hides_placeholder() {
|
||||
const t = make()
|
||||
verify(!child(t.view, "notRunning").visible)
|
||||
verify(child(t.view, "controls").visible)
|
||||
}
|
||||
|
||||
function test_current_orientation_checked() {
|
||||
const t = make({ screen: "portrait-ccw" })
|
||||
verify(child(t.view, "orientation-portrait-ccw").checked)
|
||||
verify(!child(t.view, "orientation-landscape").checked)
|
||||
t.backend.screen = "landscape"
|
||||
verify(child(t.view, "orientation-landscape").checked)
|
||||
verify(!child(t.view, "orientation-portrait-ccw").checked)
|
||||
}
|
||||
|
||||
function test_orientation_buttons_rotate_data() {
|
||||
return ["landscape", "portrait-cw", "landscape-flipped", "portrait-ccw"].map(o => ({ tag: o, o: o }))
|
||||
}
|
||||
|
||||
function test_orientation_buttons_rotate(data) {
|
||||
const t = make({ screen: "unknown" })
|
||||
mouseClick(child(t.view, "orientation-" + data.o))
|
||||
compare(t.backend.calls, ["rotateTo " + data.o])
|
||||
}
|
||||
|
||||
function test_rotate_cw_ccw() {
|
||||
const t = make()
|
||||
mouseClick(child(t.view, "rotateCW"))
|
||||
mouseClick(child(t.view, "rotateCCW"))
|
||||
compare(t.backend.calls, ["rotateBy 1", "rotateBy -1"])
|
||||
}
|
||||
|
||||
function test_lock_switch() {
|
||||
const t = make({ locked: false })
|
||||
const sw = child(t.view, "lockSwitch")
|
||||
verify(!sw.checked)
|
||||
mouseClick(sw)
|
||||
compare(t.backend.calls, ["setLocked true"])
|
||||
t.backend.locked = true
|
||||
verify(sw.checked)
|
||||
}
|
||||
|
||||
function test_mode_radios() {
|
||||
const t = make({ mode: "auto" })
|
||||
verify(child(t.view, "modeAuto").checked)
|
||||
verify(!child(t.view, "modeManual").checked)
|
||||
mouseClick(child(t.view, "modeManual"))
|
||||
compare(t.backend.calls, ["setMode manual"])
|
||||
t.backend.mode = "manual"
|
||||
verify(child(t.view, "modeManual").checked)
|
||||
verify(!child(t.view, "modeAuto").checked)
|
||||
}
|
||||
|
||||
function test_no_imu_disables_modes_but_not_buttons() {
|
||||
const t = make({ imu: false })
|
||||
verify(child(t.view, "noSensor").visible)
|
||||
verify(!child(t.view, "modeAuto").enabled)
|
||||
verify(!child(t.view, "modeManual").enabled)
|
||||
verify(child(t.view, "rotateCW").enabled)
|
||||
verify(child(t.view, "lockSwitch").enabled)
|
||||
}
|
||||
|
||||
function test_suggestion_banner() {
|
||||
const t = make({ suggested: "" })
|
||||
verify(!child(t.view, "suggestion").visible)
|
||||
t.backend.suggested = "portrait-cw"
|
||||
verify(child(t.view, "suggestion").visible)
|
||||
mouseClick(child(t.view, "acceptSuggestion"))
|
||||
compare(t.backend.calls, ["accept"])
|
||||
}
|
||||
|
||||
function test_device_orientation_shown() {
|
||||
const t = make({ device: "portrait-cw" })
|
||||
verify(child(t.view, "deviceLabel").text.indexOf("Portrait (right grip down)") >= 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import QtQuick
|
||||
import QtTest
|
||||
import "../package/contents/ui/logic.js" as Logic
|
||||
|
||||
TestCase {
|
||||
name: "Logic"
|
||||
|
||||
function test_orientations_order() {
|
||||
compare(Logic.orientations, ["landscape", "portrait-cw", "landscape-flipped", "portrait-ccw"])
|
||||
}
|
||||
|
||||
function test_labels_data() {
|
||||
return [
|
||||
{ tag: "landscape", o: "landscape", want: "Landscape" },
|
||||
{ tag: "portrait-cw", o: "portrait-cw", want: "Portrait (right grip down)" },
|
||||
{ tag: "flipped", o: "landscape-flipped", want: "Landscape (flipped)" },
|
||||
{ tag: "portrait-ccw", o: "portrait-ccw", want: "Portrait (left grip down)" },
|
||||
{ tag: "unknown", o: "unknown", want: "Unknown" },
|
||||
{ tag: "empty", o: "", want: "Unknown" }
|
||||
]
|
||||
}
|
||||
|
||||
function test_labels(data) {
|
||||
compare(Logic.label(data.o), data.want)
|
||||
}
|
||||
|
||||
function test_angles() {
|
||||
compare(Logic.orientations.map(Logic.angle), [0, 90, 180, 270])
|
||||
compare(Logic.angle("unknown"), 0)
|
||||
}
|
||||
|
||||
function test_icon() {
|
||||
compare(Logic.iconName({ available: true, locked: false }), "transform-rotate-symbolic")
|
||||
compare(Logic.iconName({ available: true, locked: true }), "object-locked-symbolic")
|
||||
compare(Logic.iconName({ available: false, locked: false }), "transform-rotate-symbolic")
|
||||
}
|
||||
|
||||
function test_summary_data() {
|
||||
return [
|
||||
{ tag: "down", b: { available: false }, want: "Rotation service is not running" },
|
||||
{ tag: "auto", b: { available: true, imu: true, locked: false, mode: "auto", screen: "landscape" }, want: "Auto-rotate · Landscape" },
|
||||
{ tag: "manual", b: { available: true, imu: true, locked: false, mode: "manual", screen: "portrait-ccw" }, want: "Manual · Portrait (left grip down)" },
|
||||
{ tag: "locked", b: { available: true, imu: true, locked: true, mode: "auto", screen: "landscape-flipped" }, want: "Locked · Landscape (flipped)" },
|
||||
{ tag: "no-imu", b: { available: true, imu: false, locked: false, mode: "auto", screen: "landscape" }, want: "No orientation sensor · Landscape" }
|
||||
]
|
||||
}
|
||||
|
||||
function test_summary(data) {
|
||||
compare(Logic.summary(data.b), data.want)
|
||||
}
|
||||
}
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
# Runs the plasmoid's DBusBackend against the real Go service on a private bus.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
if [[ -z "${DECKROTATE_IN_PRIVATE_BUS:-}" ]]; then
|
||||
exec env DECKROTATE_IN_PRIVATE_BUS=1 dbus-run-session -- "$0" "$@"
|
||||
fi
|
||||
|
||||
bin=$(mktemp -d)
|
||||
trap 'kill "${svc:-}" 2>/dev/null || true; rm -rf "$bin"' EXIT
|
||||
go build -o "$bin/testservice" ./internal/service/testservice
|
||||
|
||||
coproc SVC { exec "$bin/testservice"; }
|
||||
svc=$SVC_PID
|
||||
read -r -t 10 line <&"${SVC[0]}"
|
||||
[[ "$line" == ready ]] || { echo "testservice did not start" >&2; exit 1; }
|
||||
|
||||
QT_QPA_PLATFORM=offscreen /usr/lib/qt6/bin/qmltestrunner -input plasmoid/itests 2>&1 | grep -v Fontconfig
|
||||
exit "${PIPESTATUS[0]}"
|
||||
@@ -0,0 +1,62 @@
|
||||
import QtQuick
|
||||
import org.kde.kirigami as Kirigami
|
||||
|
||||
// Round "rotate to match the Deck" button for the manual-mode overlay.
|
||||
Item {
|
||||
id: button
|
||||
|
||||
property int angle: 0
|
||||
readonly property alias iconRotation: icon.rotation
|
||||
signal accepted
|
||||
|
||||
implicitWidth: 64
|
||||
implicitHeight: 64
|
||||
width: implicitWidth
|
||||
height: implicitHeight
|
||||
|
||||
Accessible.role: Accessible.Button
|
||||
Accessible.name: qsTr("Rotate screen to match the Deck")
|
||||
Accessible.onPressAction: button.accepted()
|
||||
|
||||
Rectangle {
|
||||
id: disc
|
||||
anchors.fill: parent
|
||||
radius: width / 2
|
||||
color: Qt.alpha(Kirigami.Theme.backgroundColor, tap.pressed ? 0.95 : 0.85)
|
||||
border.color: Kirigami.Theme.highlightColor
|
||||
border.width: 2
|
||||
scale: tap.pressed ? 0.92 : 1
|
||||
|
||||
Behavior on scale {
|
||||
NumberAnimation { duration: 80 }
|
||||
}
|
||||
|
||||
Kirigami.Icon {
|
||||
id: icon
|
||||
anchors.centerIn: parent
|
||||
width: parent.width * 0.55
|
||||
height: width
|
||||
source: "object-rotate-right"
|
||||
rotation: button.angle
|
||||
}
|
||||
}
|
||||
|
||||
TapHandler {
|
||||
id: tap
|
||||
// Only taps on the disc itself, not the square's corners.
|
||||
onTapped: (point) => {
|
||||
const dx = point.position.x - button.width / 2
|
||||
const dy = point.position.y - button.height / 2
|
||||
if (dx * dx + dy * dy <= (button.width / 2) * (button.width / 2))
|
||||
button.accepted()
|
||||
}
|
||||
}
|
||||
|
||||
// Pop in so the button catches the eye after the Deck is turned.
|
||||
NumberAnimation on opacity {
|
||||
from: 0
|
||||
to: 1
|
||||
duration: 150
|
||||
running: true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
.pragma library
|
||||
|
||||
// Parses the overlay's command line: --vertical top|bottom --horizontal left|right --angle 0|90|180|270
|
||||
function parse(argv) {
|
||||
const out = { vertical: "bottom", horizontal: "right", angle: 0 }
|
||||
for (let i = 0; i + 1 < argv.length; i++) {
|
||||
const v = argv[i + 1]
|
||||
switch (argv[i]) {
|
||||
case "--vertical":
|
||||
if (v === "top" || v === "bottom") out.vertical = v
|
||||
break
|
||||
case "--horizontal":
|
||||
if (v === "left" || v === "right") out.horizontal = v
|
||||
break
|
||||
case "--angle": {
|
||||
const n = Number(v)
|
||||
if ([0, 90, 180, 270].includes(n)) out.angle = n
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// The Deck's built-in panel, so the button never lands on an external monitor.
|
||||
function panelScreen(screens) {
|
||||
return screens.find(s => s.name.startsWith("eDP")) ?? screens[0] ?? null
|
||||
}
|
||||
|
||||
function edges(opts) {
|
||||
return {
|
||||
top: opts.vertical === "top",
|
||||
bottom: opts.vertical === "bottom",
|
||||
left: opts.horizontal === "left",
|
||||
right: opts.horizontal === "right"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import QtQuick
|
||||
import org.kde.layershell as LayerShell
|
||||
import "components"
|
||||
import "js/args.js" as Args
|
||||
|
||||
// Manual-mode prompt. Usage:
|
||||
// qml overlay.qml -- --vertical top|bottom --horizontal left|right --angle 0|90|180|270
|
||||
// Exits with code 10 when tapped; the daemon kills it on timeout.
|
||||
Window {
|
||||
id: window
|
||||
|
||||
readonly property var opts: Args.parse(Qt.application.arguments)
|
||||
readonly property var edges: Args.edges(opts)
|
||||
readonly property int inset: 20
|
||||
|
||||
screen: Args.panelScreen(Qt.application.screens)
|
||||
width: button.width + inset
|
||||
height: button.height + inset
|
||||
visible: true
|
||||
color: "transparent"
|
||||
flags: Qt.FramelessWindowHint | Qt.WindowDoesNotAcceptFocus
|
||||
title: "deckrotate"
|
||||
|
||||
LayerShell.Window.scope: "deckrotate"
|
||||
LayerShell.Window.layer: LayerShell.Window.LayerOverlay
|
||||
LayerShell.Window.anchors: (edges.top ? LayerShell.Window.AnchorTop : LayerShell.Window.AnchorBottom)
|
||||
| (edges.left ? LayerShell.Window.AnchorLeft : LayerShell.Window.AnchorRight)
|
||||
LayerShell.Window.keyboardInteractivity: LayerShell.Window.KeyboardInteractivityNone
|
||||
LayerShell.Window.exclusionZone: -1
|
||||
|
||||
RotateButton {
|
||||
id: button
|
||||
x: window.edges.left ? window.inset : 0
|
||||
y: window.edges.top ? window.inset : 0
|
||||
angle: window.opts.angle
|
||||
onAccepted: Qt.exit(10)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import QtQuick
|
||||
import QtTest
|
||||
import "../js/args.js" as Args
|
||||
|
||||
TestCase {
|
||||
name: "OverlayArgs"
|
||||
|
||||
function test_defaults() {
|
||||
const o = Args.parse(["/usr/lib/qt6/bin/qml", "overlay.qml", "--"])
|
||||
compare(o.vertical, "bottom")
|
||||
compare(o.horizontal, "right")
|
||||
compare(o.angle, 0)
|
||||
}
|
||||
|
||||
function test_parse() {
|
||||
const o = Args.parse(["qml", "overlay.qml", "--", "--vertical", "top", "--horizontal", "left", "--angle", "270"])
|
||||
compare(o.vertical, "top")
|
||||
compare(o.horizontal, "left")
|
||||
compare(o.angle, 270)
|
||||
}
|
||||
|
||||
function test_rejects_junk_data() {
|
||||
return [
|
||||
{ tag: "vertical", args: ["--vertical", "middle"], key: "vertical", want: "bottom" },
|
||||
{ tag: "horizontal", args: ["--horizontal", "up"], key: "horizontal", want: "right" },
|
||||
{ tag: "angle", args: ["--angle", "45"], key: "angle", want: 0 },
|
||||
{ tag: "angle-nan", args: ["--angle", "lots"], key: "angle", want: 0 },
|
||||
{ tag: "dangling", args: ["--angle"], key: "angle", want: 0 }
|
||||
]
|
||||
}
|
||||
|
||||
function test_rejects_junk(data) {
|
||||
compare(Args.parse(data.args)[data.key], data.want)
|
||||
}
|
||||
|
||||
function test_panel_screen() {
|
||||
const ext = { name: "DP-1" }
|
||||
const panel = { name: "eDP-1" }
|
||||
compare(Args.panelScreen([ext, panel]), panel)
|
||||
compare(Args.panelScreen([ext]), ext)
|
||||
compare(Args.panelScreen([]), null)
|
||||
}
|
||||
|
||||
function test_anchor_edges() {
|
||||
compare(Args.edges({ vertical: "top", horizontal: "left" }), { top: true, bottom: false, left: true, right: false })
|
||||
compare(Args.edges({ vertical: "bottom", horizontal: "right" }), { top: false, bottom: true, left: false, right: true })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import QtQuick
|
||||
import QtTest
|
||||
import "../components"
|
||||
|
||||
Item {
|
||||
id: root
|
||||
width: 200
|
||||
height: 200
|
||||
|
||||
Component {
|
||||
id: buttonComponent
|
||||
RotateButton {}
|
||||
}
|
||||
|
||||
SignalSpy {
|
||||
id: spy
|
||||
signalName: "accepted"
|
||||
}
|
||||
|
||||
TestCase {
|
||||
name: "RotateButton"
|
||||
when: windowShown
|
||||
|
||||
function init() {
|
||||
spy.clear()
|
||||
}
|
||||
|
||||
function test_icon_follows_angle_data() {
|
||||
return [0, 90, 180, 270].map(a => ({ tag: String(a), angle: a }))
|
||||
}
|
||||
|
||||
function test_icon_follows_angle(data) {
|
||||
const b = createTemporaryObject(buttonComponent, root, { angle: data.angle })
|
||||
compare(b.iconRotation, data.angle)
|
||||
}
|
||||
|
||||
function test_tap_accepts() {
|
||||
const b = createTemporaryObject(buttonComponent, root)
|
||||
spy.target = b
|
||||
mouseClick(b)
|
||||
compare(spy.count, 1)
|
||||
}
|
||||
|
||||
function test_touch_accepts() {
|
||||
const b = createTemporaryObject(buttonComponent, root)
|
||||
spy.target = b
|
||||
const touch = touchEvent(b)
|
||||
touch.press(0, b, b.width / 2, b.height / 2).commit()
|
||||
touch.release(0, b, b.width / 2, b.height / 2).commit()
|
||||
compare(spy.count, 1)
|
||||
}
|
||||
|
||||
function test_tap_outside_circle_ignored() {
|
||||
const b = createTemporaryObject(buttonComponent, root)
|
||||
spy.target = b
|
||||
mouseClick(b, 1, 1) // square corner, outside the round button
|
||||
compare(spy.count, 0)
|
||||
}
|
||||
|
||||
function test_is_finger_sized() {
|
||||
const b = createTemporaryObject(buttonComponent, root)
|
||||
verify(b.width >= 56 && b.height >= 56, "button should be at least 56px for touch")
|
||||
}
|
||||
|
||||
function test_accessible() {
|
||||
const b = createTemporaryObject(buttonComponent, root)
|
||||
compare(b.Accessible.role, Accessible.Button)
|
||||
verify(b.Accessible.name.length > 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user