diff --git a/.ensemblr/settings.toml b/.ensemblr/settings.toml new file mode 100644 index 0000000..f938504 --- /dev/null +++ b/.ensemblr/settings.toml @@ -0,0 +1,35 @@ +#:schema https://www.ensemblr.dev/schemas/settings.schema.json + +# Every command runs against this worktree's flake (`.`). + +[scripts] +# Build the dev shell and fill the Go module cache, so a new workspace's first +# build or lint does not wait on downloads. +setup = "nix develop -c go mod download" + +# Build and test the package for this machine and evaluate the other systems. +[scripts.run.check] +command = "nix flake check" +icon = "shield-check" +default = true + +# Build the package into ./result. +[scripts.run.build] +command = "nix build" +icon = "hammer" + +# Drive the attached Stream Deck from decks/test.deck until stopped. -verbose +# prints every key press and the output of the exec key. +[scripts.run.deck] +command = "nix run . -- -deck decks/test.deck -verbose" +icon = "play" + +# Lint the Go sources with golangci-lint and .golangci.yml, in the dev shell. +[scripts.run.lint] +command = "nix develop -c golangci-lint run ./..." +icon = "list-checks" + +# Format every Nix file with alejandra, the flake's formatter. +[scripts.run.format] +command = "nix fmt -- ." +icon = "paintbrush" diff --git a/.gitignore b/.gitignore index 0a568d2..e6d507b 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,6 @@ dist/ # direnv .envrc + +# nix build +result diff --git a/.golangci.yml b/.golangci.yml index a5a91d0..c5bed7c 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,22 +1,9 @@ +version: "2" run: tests: false - -issues: - include: - - EXC0001 - - EXC0005 - - EXC0011 - - EXC0012 - - EXC0013 - - max-issues-per-linter: 0 - max-same-issues: 0 - linters: enable: - bodyclose - - exportloopref - - goimports - gosec - nilerr - predeclared @@ -27,3 +14,23 @@ linters: - unconvert - unparam - whitespace + exclusions: + generated: lax + presets: + - common-false-positives + paths: + - third_party$ + - builtin$ + - examples$ +issues: + max-issues-per-linter: 0 + max-same-issues: 0 +formatters: + enable: + - goimports + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/README.md b/README.md index 25cdaa2..ea87249 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ [![Build Status](https://img.shields.io/github/actions/workflow/status/muesli/deckmaster/build.yml?branch=master&style=for-the-badge)](https://github.com/muesli/deckmaster/actions) [![Go ReportCard](https://goreportcard.com/badge/github.com/muesli/deckmaster?style=for-the-badge)](https://goreportcard.com/report/muesli/deckmaster) -An application to control your Elgato Stream Deck on Linux +An application to control your Elgato Stream Deck on Linux and macOS ## Features @@ -18,10 +18,12 @@ An application to control your Elgato Stream Deck on Linux - Comes with a collection of widgets: - Buttons - Time (with formatting) - - CPU/Mem usage + - CPU/Mem/GPU usage + - Temperature sensors - Weather - Command output - Recently used windows (X11-only) + - Several widgets on one key, switched with a tap - Lets you trigger several actions: - Run commands - Emulate a key-press @@ -36,6 +38,16 @@ An application to control your Elgato Stream Deck on Linux - [Packages](https://github.com/muesli/deckmaster/releases) in Alpine, Debian & RPM formats - [Binaries](https://github.com/muesli/deckmaster/releases) for various architectures +### Nix + +This repository is a flake for x86_64-linux, aarch64-linux and aarch64-darwin: + + nix run github:psoldunov/deckmaster -- -deck path/to/main.deck + +`packages..default` is the package, and `overlays.default` replaces +`pkgs.deckmaster` with it. `nix develop` opens a shell with Go, gopls and +golangci-lint. + ### From source Make sure you have a working Go environment (Go 1.17 or higher is required). @@ -47,6 +59,11 @@ To install deckmaster, simply run: cd deckmaster go build +deckmaster draws its text in Roboto. On macOS it only looks for the font in +`~/Library/Fonts`, `/Library/Fonts` and `/System/Library/Fonts`, so install +Roboto there before running a binary built with `go build`. The Nix package +points the binary at Roboto in the Nix store instead. + ## System Setup On Linux you need to set up some `udev` rules to be able to access the device as @@ -108,6 +125,39 @@ systemctl --user enable streamdeck.path systemctl --user start streamdeck.path ``` +### macOS + +macOS needs no device rules. Quit Elgato's Stream Deck app first, since the two +can't drive the deck at the same time. + +`keycode` and `paste` actions post keyboard events, which macOS drops until +deckmaster is allowed in System Settings → Privacy & Security → Accessibility. +deckmaster logs a warning at startup while that permission is missing, and +another line for every key it can't post. The permission belongs to the +process macOS holds responsible: the terminal app when you start deckmaster +from a terminal, and the deckmaster binary itself when a launchd agent starts +it. + +macOS ties the grant to that exact binary, so every rebuild loses it, and a +Nix rebuild also moves the binary to a new store path. After each rebuild, +remove the old entry from the Accessibility list and add the new binary, whose +path `readlink -f "$(command -v deckmaster)"` prints. + +A few things work differently on macOS: + +- `keycode` takes the same key names and numbers as on Linux, translated to + Mac keys. `Leftmeta` and `Rightmeta` are Command, `Leftalt` and + `Rightalt` are Option, `Insert` is Help, and Print Screen, Scroll Lock and + Pause are F13 to F15, the way macOS maps a PC keyboard. `Playpause`, + `Nextsong`, `Previoussong`, `Volumeup`, `Volumedown`, `Mute` and the other + media keys act like the keys on an Apple keyboard. A key with no Mac + equivalent, such as 248 (`KEY_MICMUTE`), is logged and skipped. +- `paste` presses Command-V instead of Ctrl-V. +- `dbus` actions log that they aren't supported. +- The `recentWindow` widget stays empty, since there is no X11. +- The `gpu` and `vram` modes of the `top` widget and the `temp` widget read + Linux's sysfs, so on a Mac they draw an empty bar with a dash. + ## Usage Start `deckmaster` with the initial deck configuration you want to load: @@ -174,6 +224,7 @@ A simple button that can display an image and/or a label. id = "button" [keys.widget.config] icon = "/some/image.png" # optional + iconCommand = "~/bin/player-icon" # optional label = "My Button" # optional fontsize = 10.0 # optional color = "#fefefe" # optional @@ -182,6 +233,12 @@ A simple button that can display an image and/or a label. If `flatten` is `true` all opaque pixels of the icon will have the color `color`. +`iconCommand` is a shell command that deckmaster runs on every update of the +widget, once a second unless the widget sets its own `interval`. The command +prints the path of the image to show, either absolute or relative to the deck +file. `icon` is shown until the command first answers. When the command fails +or prints a path that can't be loaded, the key keeps its current icon. + #### Recent Window (requires X11) Displays the icon of a recently used window/application. Pressing the button @@ -235,7 +292,7 @@ Values for `format` are: #### Top -This widget shows the current CPU or memory utilization as a bar graph. +This widget shows the current CPU, memory or GPU utilization as a bar graph. ```toml [keys.widget] @@ -246,7 +303,63 @@ This widget shows the current CPU or memory utilization as a bar graph. fillColor = "#d497de" # optional ``` -There are two values for `mode`: `cpu` and `memory`. +There are four values for `mode`: + +| mode | shows | +| -------- | -------------------------------------- | +| `cpu` | CPU usage | +| `memory` | memory usage | +| `gpu` | how busy the GPU is | +| `vram` | how much of the GPU's memory is in use | + +`gpu` and `vram` read the amdgpu card with the most VRAM from +`/sys/class/drm`, so they need Linux and an AMD GPU. When an integrated GPU +sits beside a discrete one, that picks the discrete card. Without an amdgpu +card the bar is drawn empty. + +`mode` can hold several modes split on `;`, which share the key as columns +side by side. `fillColor` splits the same way, one color per column in the same +order, and a column without a color of its own gets the default fill: + +```toml +[keys.widget] + id = "top" + [keys.widget.config] + mode = "gpu;vram" + fillColor = "#d497de;#9bb6de" # optional +``` + +#### Temp + +This widget shows one hwmon temperature sensor in the same bar as `top`. The +bar fills towards the sensor's critical temperature. + +```toml +[keys.widget] + id = "temp" + [keys.widget.config] + chip = "k10temp" + sensor = "Tctl" # optional + device = "nvme0" # optional + label = "CPU" # optional + warn = 80 # optional + crit = 95 # optional + color = "#fefefe" # optional + fillColor = "#d497de" # optional +``` + +`chip` is the `name` of a chip in `/sys/class/hwmon`, and `sensor` is the +`temp*_label` of a sensor on it. Leave `sensor` out to pick a chip's unlabelled +sensor. When two chips share a name, as two NVMe drives do, `device` picks the +one whose resolved sysfs device path contains it. `label` is drawn under the +bar and defaults to `sensor`. + +`warn` and `crit` are in °C. Without them the widget uses the sensor's own +`temp*_max` and `temp*_crit`, and a sensor without a critical temperature fills +the bar at 100 °C. The bar turns orange at the warning temperature and red at +the critical one. A sensor that can't be read shows a dash and is looked up +again on the next update, once a second unless the widget sets its own +`interval`. #### Command @@ -284,6 +397,29 @@ corresponding icons with correct names need to be placed in `~/.local/share/deckmaster/themes/[theme]`. The default icons with their respective names can be found [here](https://github.com/muesli/deckmaster/tree/master/assets/weather). +#### Toggle + +A widget that holds several widgets on one key and shows one at a time. A tap +switches to the next one. + +```toml +[keys.widget] + id = "toggle" + [[keys.widget.config.widgets]] + id = "clock" + [[keys.widget.config.widgets]] + id = "top" + interval = 1000 # optional + [keys.widget.config.widgets.config] + mode = "cpu;memory" +``` + +Each entry in `widgets` takes the same `id`, `interval` and `config` as a key's +own `widget` table, and a toggle needs at least two. Every entry is built when +the deck loads, so switching back keeps what a widget has already fetched. A +tap switches only on a key without an `action` of its own, and holding the key +doesn't switch. + ### Actions You can hook up any key with several actions. A regular keypress will trigger @@ -320,6 +456,20 @@ Emulate a series of key-presses with delay in between: A list of available `keycodes` can be found here: [keycodes](https://github.com/muesli/deckmaster/blob/master/keycodes.go) +#### Repeat while held + +Any action can repeat while its key is held: + +```toml +[keys.action] + keycode = "Volumeup" + repeat = 100 +``` + +Once the key is held past a long press (350 ms), the action fires every +`repeat` milliseconds until the key is released. A repeating key never fires +its `keys.action_hold`. A short tap still fires the action once. + #### Paste to clipboard ```toml diff --git a/config.go b/config.go index e21add0..e6710b3 100644 --- a/config.go +++ b/config.go @@ -31,6 +31,8 @@ type ActionConfig struct { Paste string `toml:"paste,omitempty"` Device string `toml:"device,omitempty"` DBus DBusConfig `toml:"dbus,omitempty"` + // Repeat, in milliseconds, re-triggers the action while its key is held. + Repeat uint `toml:"repeat,omitempty"` } // WidgetConfig describes configuration data for widgets. diff --git a/deck.go b/deck.go index a260afb..d6d23ce 100644 --- a/deck.go +++ b/deck.go @@ -1,6 +1,7 @@ package main import ( + "errors" "fmt" "image" "image/draw" @@ -155,10 +156,12 @@ func emulateKeyPress(keys string) { } if i+1 < len(kk) { - _ = keyboard.KeyDown(kc) + if err := keyboard.KeyDown(kc); err != nil { + fmt.Fprintf(os.Stderr, "Can't emulate keycode %d: %s\n", kc, err) + } defer keyboard.KeyUp(kc) //nolint:errcheck - } else { - _ = keyboard.KeyPress(kc) + } else if err := keyboard.KeyPress(kc); err != nil { + fmt.Fprintf(os.Stderr, "Can't emulate keycode %d: %s\n", kc, err) } } } @@ -171,11 +174,16 @@ func emulateClipboard(text string) { } // paste the string - emulateKeyPress("29-47") // ctrl-v + emulateKeyPress(pasteKeys) } // executes a dbus method. func executeDBusMethod(object, path, method, args string) { + if dbusConn == nil { + fmt.Fprintf(os.Stderr, "Can't run dbus action: %s\n", dbusErr) + return + } + call := dbusConn.Object(object, dbus.ObjectPath(path)).Call(method, 0, args) if call.Err != nil { fmt.Fprintf(os.Stderr, "dbus call failed: %s\n", call.Err) @@ -205,6 +213,51 @@ func executeCommand(cmd string) { } } +// repeatInterval returns how often a held key repeats its action, or 0 if it +// does not repeat. +func (d *Deck) repeatInterval(index uint8) time.Duration { + for _, w := range d.Widgets { + if w.Key() == index && w.Action() != nil { + return time.Duration(w.Action().Repeat) * time.Millisecond + } + } + return 0 +} + +// repeatAction has the event loop trigger a key's action every interval until +// released closes. +func repeatAction(dev *streamdeck.Device, index uint8, interval time.Duration, released <-chan struct{}, actions chan<- func()) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + + for { + select { + case <-released: + return + case actions <- func() { deck.triggerAction(dev, index, false) }: + } + + select { + case <-released: + return + case <-ticker.C: + } + } +} + +// deviceFailed handles an error from the Stream Deck and reports whether the +// deck is gone. A deck that is gone stops deckmaster, so its service manager +// starts it again once the deck is back; any other failure is logged and +// deckmaster carries on. +func deviceFailed(err error) bool { + fmt.Fprintf(os.Stderr, "error: %v\n", err) + if errors.Is(err, streamdeck.ErrDisconnected) { + fatal(streamdeck.ErrDisconnected) + return true + } + return false +} + // triggerAction triggers an action. func (d *Deck) triggerAction(dev *streamdeck.Device, index uint8, hold bool) { for _, w := range d.Widgets { @@ -230,8 +283,7 @@ func (d *Deck) triggerAction(dev *streamdeck.Device, index uint8, hold bool) { fmt.Fprintln(os.Stderr, "Can't load deck:", err) return } - if err := dev.Clear(); err != nil { - fatal(err) + if err := dev.Clear(); err != nil && deviceFailed(err) { return } @@ -254,7 +306,7 @@ func (d *Deck) triggerAction(dev *streamdeck.Device, index uint8, hold bool) { switch { case a.Device == "sleep": if err := dev.Sleep(); err != nil { - fatalf("error: %v\n", err) + deviceFailed(err) } case strings.HasPrefix(a.Device, "brightness"): @@ -276,7 +328,15 @@ func (d *Deck) updateWidgets() { // fmt.Println("Repaint", w.Key()) if err := w.Update(); err != nil { - fatalf("error: %v", err) + var de drawError + if !errors.As(err, &de) { + fatalf("error: %v", err) + return + } + // The key draws again on the next update. + if deviceFailed(err) { + return + } } } } @@ -323,7 +383,8 @@ func (d *Deck) adjustBrightness(dev *streamdeck.Device, value string) { v = 100 } if err := dev.SetBrightness(uint8(v)); err != nil { - fatalf("error: %v\n", err) + deviceFailed(err) + return } *brightness = uint(v) diff --git a/deck_test.go b/deck_test.go new file mode 100644 index 0000000..015da05 --- /dev/null +++ b/deck_test.go @@ -0,0 +1,87 @@ +package main + +import ( + "errors" + "fmt" + "testing" + "time" + + "github.com/muesli/streamdeck" +) + +// failingWidget fails to draw the way BaseWidget.render does: it asks to be +// drawn again and returns a drawError. +type failingWidget struct { + *BaseWidget + err error + updates int +} + +func (w *failingWidget) Update() error { + w.updates++ + if w.err == nil { + w.lastUpdate = time.Now() + return nil + } + w.Repaint() + return w.err +} + +func newFailingWidget(key uint8, err error) *failingWidget { + return &failingWidget{BaseWidget: &BaseWidget{key: key}, err: err} +} + +// shutdownRequested reports whether something asked deckmaster to exit. +func shutdownRequested(t *testing.T) bool { + t.Helper() + select { + case err := <-shutdown: + t.Logf("shutdown: %v", err) + return true + case <-time.After(50 * time.Millisecond): + return false + } +} + +func TestFailedDrawIsLoggedAndRetried(t *testing.T) { + broken := newFailingWidget(1, drawError{key: 1, err: errors.New("IOHIDDeviceSetReport failed")}) + fine := newFailingWidget(2, nil) + d := &Deck{Widgets: []Widget{broken, fine}} + + d.updateWidgets() + if shutdownRequested(t) { + t.Fatal("a failed draw stopped deckmaster") + } + if fine.updates != 1 { + t.Errorf("the key after the failing one was drawn %d times, want 1", fine.updates) + } + + broken.err = nil + d.updateWidgets() + if broken.updates != 2 { + t.Errorf("the failed key was drawn %d times, want 2", broken.updates) + } + d.updateWidgets() + if broken.updates != 2 || fine.updates != 1 { + t.Errorf("keys without an interval drew again: %d, %d", broken.updates, fine.updates) + } +} + +func TestGoneDeckStopsDeckmaster(t *testing.T) { + gone := fmt.Errorf("%w: write failed", streamdeck.ErrDisconnected) + d := &Deck{Widgets: []Widget{newFailingWidget(0, drawError{key: 0, err: gone})}} + + d.updateWidgets() + if !shutdownRequested(t) { + t.Fatal("a gone deck did not stop deckmaster") + } +} + +func TestWidgetErrorStillStopsDeckmaster(t *testing.T) { + d := &Deck{Widgets: []Widget{newFailingWidget(0, errors.New("top widget needs a mode"))}} + + d.updateWidgets() + if !shutdownRequested(t) { + t.Fatal("a widget error no longer stops deckmaster") + } +} diff --git a/decks/test.deck b/decks/test.deck new file mode 100644 index 0000000..4fe1381 --- /dev/null +++ b/decks/test.deck @@ -0,0 +1,160 @@ +# A deck that exercises every widget and action on a 15-key Stream Deck: +# +# nix run . -- -deck decks/test.deck -verbose +# +# -verbose prints each key press and the output of the exec key. + +# CPU and memory as two columns +[[keys]] + index = 0 + [keys.widget] + id = "top" + [keys.widget.config] + mode = "cpu;memory" + fillColor = "#d497de;#9bb6de" + +# amdgpu only: the bars stay empty elsewhere +[[keys]] + index = 1 + [keys.widget] + id = "top" + [keys.widget.config] + mode = "gpu;vram" + +# hwmon only: shows a dash elsewhere +[[keys]] + index = 2 + [keys.widget] + id = "temp" + [keys.widget.config] + chip = "k10temp" + sensor = "Tctl" + label = "CPU" + +# a tap switches between the clock and the date +[[keys]] + index = 3 + [keys.widget] + id = "toggle" + [[keys.widget.config.widgets]] + id = "clock" + [[keys.widget.config.widgets]] + id = "date" + +# the icon flips every two seconds +[[keys]] + index = 4 + [keys.widget] + id = "button" + interval = 500 + [keys.widget.config] + icon = "assets/go-previous.png" + iconCommand = "[ $(( $(date +%s) / 2 % 2 )) -eq 0 ] && echo assets/go-previous.png || echo assets/go-next.png" + label = "iconCommand" + fontsize = 8 + +[[keys]] + index = 5 + [keys.widget] + id = "button" + [keys.widget.config] + icon = "assets/volume-low.png" + label = "Vol -" + fontsize = 8 + [keys.action] + keycode = "Volumedown" + repeat = 150 + +[[keys]] + index = 6 + [keys.widget] + id = "button" + [keys.widget.config] + icon = "assets/volume-high.png" + label = "Vol +" + fontsize = 8 + [keys.action] + keycode = "Volumeup" + repeat = 150 + +[[keys]] + index = 7 + [keys.widget] + id = "button" + [keys.widget.config] + label = "Mute" + [keys.action] + keycode = "Mute" + +[[keys]] + index = 8 + [keys.widget] + id = "button" + [keys.widget.config] + label = "Prev" + [keys.action] + keycode = "Previoussong" + +[[keys]] + index = 9 + [keys.widget] + id = "button" + [keys.widget.config] + label = "Play" + [keys.action] + keycode = "Playpause" + +[[keys]] + index = 10 + [keys.widget] + id = "button" + [keys.widget.config] + label = "Next" + [keys.action] + keycode = "Nextsong" + +[[keys]] + index = 11 + [keys.widget] + id = "button" + [keys.widget.config] + label = "exec" + [keys.action] + exec = "echo deckmaster ran the exec key" + +# pastes into the focused window: ctrl-v on Linux, cmd-v on macOS +[[keys]] + index = 12 + [keys.widget] + id = "button" + [keys.widget.config] + label = "Paste" + [keys.action] + paste = "pasted by deckmaster" + +# fails with a log line on macOS, which has no session bus +[[keys]] + index = 13 + [keys.widget] + id = "button" + [keys.widget.config] + label = "dbus" + [keys.action] + [keys.action.dbus] + object = "org.freedesktop.DBus" + path = "/org/freedesktop/DBus" + method = "org.freedesktop.DBus.GetNameOwner" + value = "org.freedesktop.DBus" + +[[keys]] + index = 14 + [keys.widget] + id = "button" + [keys.widget.config] + icon = "assets/go-more.png" + label = "Dim" + fontsize = 8 + [keys.action] + device = "brightness-10" + [keys.action_hold] + device = "brightness+10" diff --git a/desktop_darwin.go b/desktop_darwin.go new file mode 100644 index 0000000..4053c56 --- /dev/null +++ b/desktop_darwin.go @@ -0,0 +1,37 @@ +//go:build darwin +// +build darwin + +package main + +import ( + "errors" + "time" +) + +// errNoX11 is what window tracking answers on macOS, which has no X server, so +// the recentWindow widget stays empty there. +var errNoX11 = errors.New("there is no X server on macOS") + +// Xorg stands in for the X11 session the Linux build tracks windows through. +type Xorg struct{} + +// Connect fails on macOS. +func Connect(_ string) (*Xorg, error) { + return nil, errNoX11 +} + +// Close does nothing on macOS. +func (x Xorg) Close() {} + +// TrackWindows does nothing on macOS. +func (x *Xorg) TrackWindows(_ chan interface{}, _ time.Duration) {} + +// RequestActivation fails on macOS. +func (x Xorg) RequestActivation(_ Window) error { + return errNoX11 +} + +// CloseWindow fails on macOS. +func (x Xorg) CloseWindow(_ Window) error { + return errNoX11 +} diff --git a/desktop_unix.go b/desktop_unix.go index c6ed231..4721d88 100644 --- a/desktop_unix.go +++ b/desktop_unix.go @@ -31,24 +31,6 @@ type Xorg struct { activeWindow Window } -// ActiveWindowChangedEvent gets emitted when the active window changes. -type ActiveWindowChangedEvent struct { - Window Window -} - -// WindowClosedEvent gets emitted when a window gets closed. -type WindowClosedEvent struct { - Window Window -} - -// Window describes an X11 window. -type Window struct { - ID uint32 - Class string - Name string - Icon image.Image -} - // Connect establishes a connection with an Xorg display. func Connect(display string) (*Xorg, error) { var x Xorg diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..908bdd1 --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1793110635, + "narHash": "sha256-dhoW6VgFWlaodSY5jrBn+CF2FLmaUvDVgM7+C7T2+NM=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "31ecbaca1bdefa45dffc409f0250bd8039ea0010", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..94eba32 --- /dev/null +++ b/flake.nix @@ -0,0 +1,46 @@ +{ + description = "Deckmaster: control an Elgato Stream Deck on Linux and macOS"; + + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + + outputs = { + self, + nixpkgs, + }: let + inherit (nixpkgs) lib; + + systems = ["x86_64-linux" "aarch64-linux" "aarch64-darwin"]; + forAllSystems = f: lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system}); + + date = self.lastModifiedDate or "19700101"; + deckmaster = pkgs: + pkgs.callPackage ./package.nix { + version = "0.9.0-unstable-${lib.substring 0 4 date}-${lib.substring 4 2 date}-${lib.substring 6 2 date}"; + commit = self.rev or self.dirtyRev or ""; + }; + in { + packages = forAllSystems (pkgs: { + deckmaster = deckmaster pkgs; + default = self.packages.${pkgs.stdenv.hostPlatform.system}.deckmaster; + }); + + overlays.default = final: _prev: {deckmaster = deckmaster final;}; + + devShells = forAllSystems (pkgs: let + package = self.packages.${pkgs.stdenv.hostPlatform.system}.deckmaster; + in { + default = pkgs.mkShell { + inputsFrom = [package]; + packages = [pkgs.go pkgs.gopls pkgs.golangci-lint pkgs.alejandra]; + # `go run`, `go build` and `go test` find Roboto the way the package does. + GOFLAGS = "'-ldflags=-X main.fontDir=${package.fontDir} -X github.com/muesli/deckmaster.fontDir=${package.fontDir}'"; + }; + }); + + formatter = forAllSystems (pkgs: pkgs.alejandra); + + checks = forAllSystems (pkgs: { + deckmaster = self.packages.${pkgs.stdenv.hostPlatform.system}.deckmaster; + }); + }; +} diff --git a/fonts.go b/fonts.go index 7773d26..ee2e7a7 100644 --- a/fonts.go +++ b/fonts.go @@ -6,6 +6,7 @@ import ( "image/color" "io/ioutil" "os" + "path/filepath" "github.com/flopp/go-findfont" "github.com/golang/freetype" @@ -17,6 +18,11 @@ var ( ttfFont *truetype.Font ttfThinFont *truetype.Font ttfBoldFont *truetype.Font + + // fontDir is searched for fonts before the system's font directories. The + // Nix package sets it with -ldflags "-X main.fontDir=...", so the binary + // finds Roboto in the store on any platform. + fontDir string ) // maxPointSize returns the maximum point size we can use to fit text inside @@ -70,8 +76,19 @@ func ftContext(img *image.RGBA, ttf *truetype.Font, dpi uint, fontsize float64) return c } +// findFont returns the path of a font file, looking in fontDir first. +func findFont(name string) (string, error) { + if fontDir != "" { + path := filepath.Join(fontDir, name) + if _, err := os.Stat(path); err == nil { + return path, nil + } + } + return findfont.Find(name) +} + func loadFont(name string) (*truetype.Font, error) { - fontPath, err := findfont.Find(name) + fontPath, err := findFont(name) if err != nil { return nil, err } diff --git a/go.mod b/go.mod index bf198a4..e7fed07 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.17 require ( github.com/BurntSushi/toml v1.2.1 github.com/atotto/clipboard v0.1.4 - github.com/bendahl/uinput v1.6.1 + github.com/bendahl/uinput v1.6.2 github.com/flopp/go-findfont v0.1.0 github.com/godbus/dbus v4.1.0+incompatible github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 @@ -22,6 +22,7 @@ require ( require ( github.com/BurntSushi/freetype-go v0.0.0-20160129220410-b763ddbfe298 // indirect github.com/BurntSushi/graphics-go v0.0.0-20160129215708-b43f31a4a966 // indirect + github.com/bearsh/hid v1.6.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/go-ole/go-ole v1.2.6 // indirect github.com/karalabe/hid v1.0.1-0.20190806082151-9c14560f9ee8 // indirect @@ -30,5 +31,9 @@ require ( github.com/tklauser/go-sysconf v0.3.9 // indirect github.com/tklauser/numcpus v0.3.0 // indirect github.com/yusufpapurcu/wmi v1.2.2 // indirect - golang.org/x/sys v0.5.0 // indirect + golang.org/x/sys v0.23.0 // indirect ) + +// macOS needs a newer hidapi than karalabe/hid bundles; see +// third_party/streamdeck/hid_darwin.go. +replace github.com/muesli/streamdeck => ./third_party/streamdeck diff --git a/go.sum b/go.sum index 7bf1e95..e3a40f4 100644 --- a/go.sum +++ b/go.sum @@ -6,9 +6,10 @@ github.com/BurntSushi/toml v1.2.1 h1:9F2/+DoOYIOksmaJFPw1tGFy1eDnIJXg+UHjuD8lTak github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= -github.com/bendahl/uinput v1.6.1 h1:A8b6mtqC3E7ZkpLdQWNeyZNmLPhqxGS+fScrim3TV/k= -github.com/bendahl/uinput v1.6.1/go.mod h1:Np7w3DINc9wB83p12fTAM3DPPhFnAKP0WTXRqCQJ6Z8= -github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/bearsh/hid v1.6.0 h1:eOBSuF2pg+SCytKGuGjOzZx73xQ72gevJ5IlFvzgfGE= +github.com/bearsh/hid v1.6.0/go.mod h1:7JhM3r/tm4ALu4WWFqshda+Q6aIcnGRpUR08sx/dHdc= +github.com/bendahl/uinput v1.6.2 h1:tIz52QyKDx1i1nObUkts3AZa/bULfLhPA5a+xKGlRPI= +github.com/bendahl/uinput v1.6.2/go.mod h1:Np7w3DINc9wB83p12fTAM3DPPhFnAKP0WTXRqCQJ6Z8= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/flopp/go-findfont v0.1.0 h1:lPn0BymDUtJo+ZkV01VS3661HL6F4qFlkhcJN55u6mU= @@ -19,7 +20,6 @@ github.com/godbus/dbus v4.1.0+incompatible h1:WqqLRTsQic3apZUK9qC5sGNfXthmPXzUZ7 github.com/godbus/dbus v4.1.0+incompatible/go.mod h1:/YcGZj5zSblfDWMMoOzV4fas9FZnQYTkDnsGvmh2Grw= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= -github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jezek/xgb v1.1.0 h1:wnpxJzP1+rkbGclEkmwpVFQWpuE2PUGNUzP8SbfFobk= github.com/jezek/xgb v1.1.0/go.mod h1:nrhwO0FX/enq75I7Y7G8iN1ubpSGZEiA3v9e9GyRFlk= github.com/jezek/xgbutil v0.0.0-20210302171758-530099784e66 h1:+wPhoJD8EH0/bXipIq8Lc2z477jfox9zkXPCJdhvHj8= @@ -30,17 +30,12 @@ github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69 github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/muesli/coral v1.0.0/go.mod h1:bf91M/dkp7iHQw73HOoR9PekdTJMTD6ihJgWoDitde8= -github.com/muesli/streamdeck v0.4.0 h1:kBV1RCLFz3dYfVlBvCPG0cWxTFK7IOdcc1Jw2T4Qz4E= -github.com/muesli/streamdeck v0.4.0/go.mod h1:6Fjt/9so3B22BtraQLRTPHu33c7yVgUIcDPiZqzSHfE= github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ= github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/tklauser/go-sysconf v0.3.9 h1:JeUVdAOWhhxVcU6Eqr/ATFHgXk/mmiItdKeJPev3vTo= @@ -52,7 +47,6 @@ github.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPR github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/image v0.6.0/go.mod h1:MXLdDR43H7cDJq5GEGXEVeeNhPgi+YYEQ2pC1byI1x0= golang.org/x/image v0.7.0 h1:gzS29xtG1J5ybQlv0PuyfE3nmc6R4qB73m6LUUmvFuw= golang.org/x/image v0.7.0/go.mod h1:nd/q4ef1AKKYl/4kft7g+6UyGbdiqWqTP1ZAbRoV7Rg= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= @@ -71,8 +65,9 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.23.0 h1:YfKFowiIMvtgl1UERQoTPPToxltDeZfbj4H7dVUCwmM= +golang.org/x/sys v0.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -80,12 +75,9 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= diff --git a/keyboard_darwin.go b/keyboard_darwin.go new file mode 100644 index 0000000..bafd511 --- /dev/null +++ b/keyboard_darwin.go @@ -0,0 +1,127 @@ +//go:build darwin +// +build darwin + +package main + +/* +#cgo CFLAGS: -x objective-c +#cgo LDFLAGS: -framework ApplicationServices -framework AppKit + +#import +#include + +// postKey posts a key down or up event for a macOS virtual key code, carrying +// the modifiers held down. +static bool postKey(CGKeyCode code, bool down, CGEventFlags flags) { + CGEventRef event = CGEventCreateKeyboardEvent(NULL, code, down); + if (event == NULL) { + return false; + } + CGEventSetFlags(event, flags); + CGEventPost(kCGHIDEventTap, event); + CFRelease(event); + return true; +} + +// postSystemKey posts a media key down or up. macOS delivers media keys as +// NX_SYSDEFINED events of subtype 8 instead of key codes. +static bool postSystemKey(int key, bool down, CGEventFlags flags) { + @autoreleasepool { + NSInteger state = down ? 0xa : 0xb; + NSEvent *event = [NSEvent otherEventWithType:NSEventTypeSystemDefined + location:NSZeroPoint + modifierFlags:flags | (state << 8) + timestamp:0 + windowNumber:0 + context:nil + subtype:8 + data1:(key << 16) | (state << 8) + data2:-1]; + CGEventRef cgEvent = [event CGEvent]; + if (cgEvent == NULL) { + return false; + } + CGEventPost(kCGHIDEventTap, cgEvent); + return true; + } +} +*/ +import "C" + +import ( + "errors" + "fmt" + "sync" +) + +var errNoAccessibility = errors.New("macOS drops emulated key events until deckmaster, or the terminal app that starts it, " + + "is allowed in System Settings → Privacy & Security → Accessibility") + +// accessibilityTrusted reports whether macOS lets deckmaster post key events. +func accessibilityTrusted() bool { + return C.AXIsProcessTrusted() != 0 +} + +// cgKeyboard emulates key presses by posting CoreGraphics events for the evdev +// key codes the Linux build hands to uinput. +type cgKeyboard struct { + mu sync.Mutex + // modifiers held down with KeyDown, set on every event posted after it + flags C.CGEventFlags +} + +// KeyPress presses a key and releases it. +func (k *cgKeyboard) KeyPress(key int) error { + if err := k.KeyDown(key); err != nil { + return err + } + return k.KeyUp(key) +} + +// KeyDown presses a key until KeyUp releases it. +func (k *cgKeyboard) KeyDown(key int) error { + return k.post(key, true) +} + +// KeyUp releases a key. +func (k *cgKeyboard) KeyUp(key int) error { + return k.post(key, false) +} + +// Close does nothing: there is no device to release. +func (k *cgKeyboard) Close() error { + return nil +} + +func (k *cgKeyboard) post(key int, down bool) error { + code, isKey := macKeycodes[key] + system, isSystem := macSystemKeys[key] + if !isKey && !isSystem { + return fmt.Errorf("keycode %d has no macOS equivalent", key) + } + if !accessibilityTrusted() { + return errNoAccessibility + } + + k.mu.Lock() + defer k.mu.Unlock() + + if isSystem { + if !C.postSystemKey(C.int(system), C.bool(down), k.flags) { + return fmt.Errorf("can't create a system event for keycode %d", key) + } + return nil + } + + if flag := C.CGEventFlags(macModifiers[code]); flag != 0 { + if down { + k.flags |= flag + } else { + k.flags &^= flag + } + } + if !C.postKey(C.CGKeyCode(code), C.bool(down), k.flags) { + return fmt.Errorf("can't create a key event for keycode %d", key) + } + return nil +} diff --git a/keycodes_darwin.go b/keycodes_darwin.go new file mode 100644 index 0000000..1a6806b --- /dev/null +++ b/keycodes_darwin.go @@ -0,0 +1,163 @@ +//go:build darwin +// +build darwin + +package main + +// macKeycodes maps Linux evdev key codes to macOS virtual key codes (kVK_* in +// HIToolbox/Events.h). Keys a PC keyboard has and a Mac keyboard lacks map the +// way macOS maps them from a USB keyboard: Insert is Help, and Print Screen, +// Scroll Lock and Pause are F13 to F15. +var macKeycodes = map[int]uint16{ + 1: 0x35, // Esc + 2: 0x12, // Num1 + 3: 0x13, // Num2 + 4: 0x14, // Num3 + 5: 0x15, // Num4 + 6: 0x17, // Num5 + 7: 0x16, // Num6 + 8: 0x1A, // Num7 + 9: 0x1C, // Num8 + 10: 0x19, // Num9 + 11: 0x1D, // Num0 + 12: 0x1B, // Minus + 13: 0x18, // Equal + 14: 0x33, // Backspace + 15: 0x30, // Tab + 16: 0x0C, // Q + 17: 0x0D, // W + 18: 0x0E, // E + 19: 0x0F, // R + 20: 0x11, // T + 21: 0x10, // Y + 22: 0x20, // U + 23: 0x22, // I + 24: 0x1F, // O + 25: 0x23, // P + 26: 0x21, // Leftbrace + 27: 0x1E, // Rightbrace + 28: 0x24, // Enter + 29: 0x3B, // Leftctrl + 30: 0x00, // A + 31: 0x01, // S + 32: 0x02, // D + 33: 0x03, // F + 34: 0x05, // G + 35: 0x04, // H + 36: 0x26, // J + 37: 0x28, // K + 38: 0x25, // L + 39: 0x29, // Semicolon + 40: 0x27, // Apostrophe + 41: 0x32, // Grave + 42: 0x38, // Leftshift + 43: 0x2A, // Backslash + 44: 0x06, // Z + 45: 0x07, // X + 46: 0x08, // C + 47: 0x09, // V + 48: 0x0B, // B + 49: 0x2D, // N + 50: 0x2E, // M + 51: 0x2B, // Comma + 52: 0x2F, // Dot + 53: 0x2C, // Slash + 54: 0x3C, // Rightshift + 55: 0x43, // Kpasterisk + 56: 0x3A, // Leftalt: Option + 57: 0x31, // Space + 58: 0x39, // Capslock + 59: 0x7A, // F1 + 60: 0x78, // F2 + 61: 0x63, // F3 + 62: 0x76, // F4 + 63: 0x60, // F5 + 64: 0x61, // F6 + 65: 0x62, // F7 + 66: 0x64, // F8 + 67: 0x65, // F9 + 68: 0x6D, // F10 + 69: 0x47, // Numlock: Clear + 70: 0x6B, // Scrolllock: F14 + 71: 0x59, // Kp7 + 72: 0x5B, // Kp8 + 73: 0x5C, // Kp9 + 74: 0x4E, // Kpminus + 75: 0x56, // Kp4 + 76: 0x57, // Kp5 + 77: 0x58, // Kp6 + 78: 0x45, // Kpplus + 79: 0x53, // Kp1 + 80: 0x54, // Kp2 + 81: 0x55, // Kp3 + 82: 0x52, // Kp0 + 83: 0x41, // Kpdot + 86: 0x0A, // 102Nd: the ISO key beside left shift + 87: 0x67, // F11 + 88: 0x6F, // F12 + 89: 0x5E, // Ro: JIS underscore + 96: 0x4C, // Kpenter + 97: 0x3E, // Rightctrl + 98: 0x4B, // Kpslash + 99: 0x69, // Sysrq: F13 + 100: 0x3D, // Rightalt: right Option + 102: 0x73, // Home + 103: 0x7E, // Up + 104: 0x74, // Pageup + 105: 0x7B, // Left + 106: 0x7C, // Right + 107: 0x77, // End + 108: 0x7D, // Down + 109: 0x79, // Pagedown + 110: 0x72, // Insert: Help + 111: 0x75, // Delete: forward delete + 117: 0x51, // Kpequal + 119: 0x71, // Pause: F15 + 121: 0x5F, // Kpcomma: JIS keypad comma + 122: 0x68, // Hangeul: JIS Kana + 123: 0x66, // Hanja: JIS Eisu + 124: 0x5D, // Yen + 125: 0x37, // Leftmeta: Command + 126: 0x36, // Rightmeta: right Command + 138: 0x72, // Help + 183: 0x69, // F13 + 184: 0x6B, // F14 + 185: 0x71, // F15 + 186: 0x6A, // F16 + 187: 0x40, // F17 + 188: 0x4F, // F18 + 189: 0x50, // F19 + 190: 0x5A, // F20 +} + +// macSystemKeys maps Linux evdev key codes of media keys to the NX_KEYTYPE_* +// values (IOKit/hidsystem/ev_keymap.h) macOS posts them as. +var macSystemKeys = map[int]int{ + 113: 7, // Mute + 114: 1, // Volumedown + 115: 0, // Volumeup + 116: 6, // Power + 161: 14, // Ejectcd + 163: 17, // Nextsong + 164: 16, // Playpause + 165: 18, // Previoussong + 168: 20, // Rewind + 208: 19, // Fastforward + 224: 3, // Brightnessdown + 225: 2, // Brightnessup + 228: 23, // Kbdillumtoggle + 229: 22, // Kbdillumdown + 230: 21, // Kbdillumup +} + +// macModifiers maps the virtual key codes of modifier keys to the CGEventFlags +// mask each one sets while held. +var macModifiers = map[uint16]uint64{ + 0x38: 0x20000, // Shift + 0x3C: 0x20000, // right Shift + 0x3B: 0x40000, // Control + 0x3E: 0x40000, // right Control + 0x3A: 0x80000, // Option + 0x3D: 0x80000, // right Option + 0x37: 0x100000, // Command + 0x36: 0x100000, // right Command +} diff --git a/keycodes_darwin_test.go b/keycodes_darwin_test.go new file mode 100644 index 0000000..0a449d4 --- /dev/null +++ b/keycodes_darwin_test.go @@ -0,0 +1,68 @@ +//go:build darwin +// +build darwin + +package main + +import ( + "strconv" + "testing" +) + +func evdevCode(t *testing.T, name string) int { + t.Helper() + code, err := strconv.Atoi(formatKeycodes(name)) + if err != nil { + t.Fatalf("%s is not a known key name", name) + } + return code +} + +func TestMacKeycodes(t *testing.T) { + for name, want := range map[string]uint16{ + "A": 0x00, + "Num1": 0x12, + "V": 0x09, + "Enter": 0x24, + "Leftctrl": 0x3B, + "Leftmeta": 0x37, + "Rightmeta": 0x36, + "F1": 0x7A, + "Up": 0x7E, + } { + if got, ok := macKeycodes[evdevCode(t, name)]; !ok || got != want { + t.Errorf("%s: got 0x%02X (mapped: %t), want 0x%02X", name, got, ok, want) + } + } +} + +func TestMacSystemKeys(t *testing.T) { + for name, want := range map[string]int{ + "Volumeup": 0, + "Volumedown": 1, + "Mute": 7, + "Playpause": 16, + "Nextsong": 17, + "Previoussong": 18, + } { + code := evdevCode(t, name) + if got, ok := macSystemKeys[code]; !ok || got != want { + t.Errorf("%s: got %d (mapped: %t), want %d", name, got, ok, want) + } + if _, ok := macKeycodes[code]; ok { + t.Errorf("%s is mapped both as a key and as a system key", name) + } + } +} + +func TestNoMacEquivalent(t *testing.T) { + // KEY_MICMUTE has no key on a Mac. + if err := (&cgKeyboard{}).KeyPress(248); err == nil { + t.Error("keycode 248 posted an event, want an error") + } +} + +func TestPasteIsCommandV(t *testing.T) { + if pasteKeys != strconv.Itoa(evdevCode(t, "Leftmeta"))+"-"+strconv.Itoa(evdevCode(t, "V")) { + t.Errorf("pasteKeys = %q, want Leftmeta-V", pasteKeys) + } +} diff --git a/main.go b/main.go index c808619..07fe06a 100644 --- a/main.go +++ b/main.go @@ -11,7 +11,6 @@ import ( "syscall" "time" - "github.com/bendahl/uinput" "github.com/godbus/dbus" "github.com/mitchellh/go-homedir" "github.com/muesli/streamdeck" @@ -29,7 +28,8 @@ var ( deck *Deck dbusConn *dbus.Conn - keyboard uinput.Keyboard + dbusErr error + keyboard virtualKeyboard shutdown = make(chan error) xorg *Xorg @@ -43,6 +43,15 @@ var ( version = flag.Bool("version", false, "display version") ) +// virtualKeyboard emulates key presses. It takes Linux evdev key codes on every +// platform, so a deck's keycodes work unchanged on macOS. +type virtualKeyboard interface { + KeyPress(key int) error + KeyDown(key int) error + KeyUp(key int) error + Close() error +} + const ( fadeDuration = 250 * time.Millisecond longPressDuration = 350 * time.Millisecond @@ -90,6 +99,11 @@ func eventLoop(dev *streamdeck.Device, tch chan interface{}) error { var keyStates sync.Map keyTimestamps := make(map[uint8]time.Time) + // closed when the key is released, which ends a repeating action + keyReleased := make(map[uint8]chan struct{}) + // Long presses and repeats run here, on the one goroutine that touches + // the deck and its widgets. + actions := make(chan func()) kch, err := dev.ReadKeys() if err != nil { @@ -100,12 +114,14 @@ func eventLoop(dev *streamdeck.Device, tch chan interface{}) error { case <-time.After(100 * time.Millisecond): deck.updateWidgets() + case action := <-actions: + action() + case k, ok := <-kch: if !ok { - if err = dev.Open(); err != nil { - return err - } - continue + // The reader follows the device across a reopen, so a closed + // channel means the deck is gone. + return streamdeck.ErrDisconnected } var state bool @@ -116,6 +132,10 @@ func eventLoop(dev *streamdeck.Device, tch chan interface{}) error { if state && !k.Pressed { // key was released + if released, ok := keyReleased[k.Index]; ok { + close(released) + delete(keyReleased, k.Index) + } if time.Since(keyTimestamps[k.Index]) < longPressDuration { verbosef("Triggering short action for key %d", k.Index) deck.triggerAction(dev, k.Index, false) @@ -123,16 +143,25 @@ func eventLoop(dev *streamdeck.Device, tch chan interface{}) error { } if !state && k.Pressed { // key was pressed - go func() { - // launch timer to observe keystate - time.Sleep(longPressDuration) - - if state, ok := keyStates.Load(k.Index); ok && state.(bool) { - // key still pressed - verbosef("Triggering long action for key %d", k.Index) - deck.triggerAction(dev, k.Index, true) + released := make(chan struct{}) + keyReleased[k.Index] = released + index := k.Index + longPress := func() { + state, ok := keyStates.Load(index) + if !ok || !state.(bool) { + return + } + // key still pressed + if interval := deck.repeatInterval(index); interval > 0 { + verbosef("Repeating action for key %d", index) + go repeatAction(dev, index, interval, released, actions) + return } - }() + verbosef("Triggering long action for key %d", index) + deck.triggerAction(dev, index, true) + } + // launch timer to observe keystate + time.AfterFunc(longPressDuration, func() { actions <- longPress }) } keyTimestamps[k.Index] = time.Now() @@ -170,10 +199,10 @@ func eventLoop(dev *streamdeck.Device, tch chan interface{}) error { func closeDevice(dev *streamdeck.Device) { if err := dev.Reset(); err != nil { - fmt.Fprintln(os.Stderr, "Unable to reset Stream Deck") + fmt.Fprintln(os.Stderr, "Unable to reset Stream Deck:", err) } if err := dev.Close(); err != nil { - fmt.Fprintln(os.Stderr, "Unable to close Stream Deck") + fmt.Fprintln(os.Stderr, "Unable to close Stream Deck:", err) } } @@ -199,7 +228,7 @@ func initDevice() (*streamdeck.Device, error) { if !found { fmt.Fprintln(os.Stderr, "Can't find device. Available devices:") for _, v := range d { - fmt.Fprintf(os.Stderr, "Serial %s (%d buttons)\n", v.Serial, dev.Keys) + fmt.Fprintf(os.Stderr, "Serial %s (%d buttons)\n", v.Serial, v.Keys) } os.Exit(1) } @@ -250,9 +279,10 @@ func run() error { } // initialize dbus connection - dbusConn, err = dbus.SessionBus() - if err != nil { - return fmt.Errorf("Unable to connect to dbus: %s", err) + dbusConn, dbusErr = connectDBus() + if dbusErr != nil { + fmt.Fprintf(os.Stderr, "Could not connect to dbus: %s\n", dbusErr) + fmt.Fprintln(os.Stderr, "dbus actions will be disabled!") } // initialize xorg connection and track window focus @@ -267,9 +297,9 @@ func run() error { } // initialize virtual keyboard - keyboard, err = uinput.CreateKeyboard("/dev/uinput", []byte("Deckmaster")) + keyboard, err = newKeyboard() if err != nil { - fmt.Fprintf(os.Stderr, "Could not create virtual input device (/dev/uinput): %s\n", err) + fmt.Fprintf(os.Stderr, "Could not create virtual keyboard: %s\n", err) fmt.Fprintln(os.Stderr, "Emulating keyboard events will be disabled!") } else { defer keyboard.Close() //nolint:errcheck diff --git a/package.nix b/package.nix new file mode 100644 index 0000000..b601cf7 --- /dev/null +++ b/package.nix @@ -0,0 +1,60 @@ +{ + lib, + buildGoModule, + roboto, + version ? "0.9.0-unstable", + commit ? "", +}: let + fontDir = "${roboto}/share/fonts/truetype"; +in + buildGoModule { + pname = "deckmaster"; + inherit version; + + src = lib.fileset.toSource { + root = ./.; + fileset = lib.fileset.unions [ + ./go.mod + ./go.sum + ./assets + ./third_party + (lib.fileset.fileFilter (file: file.hasExt "go") ./.) + ]; + }; + + vendorHash = "sha256-swuA8pYAcmZcnVZiW3OJO1gCA0A0ypuFXRV6KhmvQmM="; + + proxyVendor = true; + + # third_party/streamdeck is a module of its own, pulled in by a replace. + subPackages = ["."]; + + # subPackages cannot reach that module's tests, so run them by import path. + postCheck = '' + go test github.com/muesli/streamdeck + ''; + + # The binary looks for Roboto in the store itself instead of through a + # wrapper that sets XDG_DATA_DIRS: go-findfont ignores that variable on + # macOS, and a wrapper script at bin/deckmaster is not a binary macOS can + # grant Accessibility to. `go test` links package main under its import + # path, so the tests need the second -X. + ldflags = [ + "-s" + "-w" + "-X main.Version=${version}" + "-X main.CommitSHA=${commit}" + "-X main.fontDir=${fontDir}" + "-X github.com/muesli/deckmaster.fontDir=${fontDir}" + ]; + + passthru = {inherit fontDir;}; + + meta = { + description = "Application to control your Elgato Stream Deck on Linux and macOS"; + mainProgram = "deckmaster"; + homepage = "https://github.com/psoldunov/deckmaster"; + license = lib.licenses.mit; + platforms = lib.platforms.linux ++ lib.platforms.darwin; + }; + } diff --git a/platform_darwin.go b/platform_darwin.go new file mode 100644 index 0000000..b3089dd --- /dev/null +++ b/platform_darwin.go @@ -0,0 +1,30 @@ +//go:build darwin +// +build darwin + +package main + +import ( + "errors" + "fmt" + "os" + + "github.com/godbus/dbus" +) + +// pasteKeys pastes the clipboard: cmd-v. +const pasteKeys = "125-47" + +// newKeyboard creates a keyboard that posts CoreGraphics events. macOS drops +// those events until the binary has Accessibility permission, which can be +// granted while deckmaster runs, so a missing grant is only reported here. +func newKeyboard() (virtualKeyboard, error) { + if !accessibilityTrusted() { + fmt.Fprintf(os.Stderr, "Emulating keyboard events needs Accessibility permission: %s\n", errNoAccessibility) + } + return &cgKeyboard{}, nil +} + +// connectDBus fails on macOS, which has no session bus for dbus actions. +func connectDBus() (*dbus.Conn, error) { + return nil, errors.New("dbus actions are not supported on macOS") +} diff --git a/platform_linux.go b/platform_linux.go new file mode 100644 index 0000000..24b82f8 --- /dev/null +++ b/platform_linux.go @@ -0,0 +1,28 @@ +//go:build linux +// +build linux + +package main + +import ( + "fmt" + + "github.com/bendahl/uinput" + "github.com/godbus/dbus" +) + +// pasteKeys pastes the clipboard: ctrl-v. +const pasteKeys = "29-47" + +// newKeyboard creates a virtual keyboard through /dev/uinput. +func newKeyboard() (virtualKeyboard, error) { + keyboard, err := uinput.CreateKeyboard("/dev/uinput", []byte("Deckmaster")) + if err != nil { + return nil, fmt.Errorf("can't create virtual input device (/dev/uinput): %w", err) + } + return keyboard, nil +} + +// connectDBus connects to the session bus that dbus actions call. +func connectDBus() (*dbus.Conn, error) { + return dbus.SessionBus() +} diff --git a/third_party/streamdeck/LICENSE b/third_party/streamdeck/LICENSE new file mode 100644 index 0000000..8532c45 --- /dev/null +++ b/third_party/streamdeck/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Christian Muehlhaeuser + +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. diff --git a/third_party/streamdeck/fault.go b/third_party/streamdeck/fault.go new file mode 100644 index 0000000..e14b103 --- /dev/null +++ b/third_party/streamdeck/fault.go @@ -0,0 +1,95 @@ +//go:build streamdeck_fault +// +build streamdeck_fault + +package streamdeck + +import ( + "errors" + "fmt" + "os" + "strconv" + "sync" + "time" +) + +// A build with -tags streamdeck_fault fails writes to a real deck on purpose, +// to show what the retry, reopen and disconnect paths do: +// +// STREAMDECK_FAULT_EVERY=n every nth write starts a run of failures +// STREAMDECK_FAULT_RUN=m that many writes fail in a row (default 1) +// STREAMDECK_FAULT_GONE=d after duration d every write and every reopen +// fails, as if the deck had been unplugged +var fault struct { + sync.Mutex + every, run int + writes, failing int + failed map[byte]time.Time // keys whose image failed, by key + gone time.Time +} + +var errInjected = errors.New("injected write failure") + +func init() { + fault.every, _ = strconv.Atoi(os.Getenv("STREAMDECK_FAULT_EVERY")) + fault.run = 1 + fault.failed = map[byte]time.Time{} + if n, err := strconv.Atoi(os.Getenv("STREAMDECK_FAULT_RUN")); err == nil { + fault.run = n + } + if d, err := time.ParseDuration(os.Getenv("STREAMDECK_FAULT_GONE")); err == nil { + fault.gone = time.Now().Add(d) + } + + wrapOpen = func(open func() (hidHandle, error)) func() (hidHandle, error) { + return func() (hidHandle, error) { + if gone() { + return nil, errors.New("injected: device is gone") + } + h, err := open() + if err != nil { + return nil, err + } + return faultyHandle{h}, nil + } + } +} + +func gone() bool { + return !fault.gone.IsZero() && time.Now().After(fault.gone) +} + +type faultyHandle struct { + hidHandle +} + +func (h faultyHandle) Write(b []byte) (int, error) { + fault.Lock() + fault.writes++ + if fault.every > 0 && fault.writes%fault.every == 0 { + fault.failing = fault.run + } + fail := fault.failing > 0 || gone() + if fault.failing > 0 { + fault.failing-- + } + // b is an image page; with the 8-byte headers of the MK.2 and the XL, + // b[2] is the key and b[6] the page. + key, firstPage := b[2], b[6] == 0 + failedAt, redraw := fault.failed[key] + if fail { + fault.failed[key] = time.Now() + } else if redraw && firstPage { + delete(fault.failed, key) + } + fault.Unlock() + + if fail { + os.Stderr.WriteString("streamdeck: injecting a write failure\n") //nolint:errcheck + return 0, errInjected + } + if redraw && firstPage { + fmt.Fprintf(os.Stderr, "streamdeck: key %d drawn again %s after its last injected failure\n", + key, time.Since(failedAt).Round(time.Millisecond)) + } + return h.hidHandle.Write(b) +} diff --git a/third_party/streamdeck/go.mod b/third_party/streamdeck/go.mod new file mode 100644 index 0000000..54b2317 --- /dev/null +++ b/third_party/streamdeck/go.mod @@ -0,0 +1,11 @@ +// muesli/streamdeck v0.4.0, carried here so macOS can drive the deck through +// bearsh/hid while every other platform keeps karalabe/hid (see hid_darwin.go). +module github.com/muesli/streamdeck + +go 1.14 + +require ( + github.com/bearsh/hid v1.6.0 + github.com/karalabe/hid v1.0.1-0.20190806082151-9c14560f9ee8 + golang.org/x/image v0.7.0 +) diff --git a/third_party/streamdeck/hid.go b/third_party/streamdeck/hid.go new file mode 100644 index 0000000..9ba82e3 --- /dev/null +++ b/third_party/streamdeck/hid.go @@ -0,0 +1,10 @@ +//go:build !darwin +// +build !darwin + +package streamdeck + +import "github.com/karalabe/hid" + +type hidDeviceInfo = hid.DeviceInfo + +var hidEnumerate = hid.Enumerate diff --git a/third_party/streamdeck/hid_darwin.go b/third_party/streamdeck/hid_darwin.go new file mode 100644 index 0000000..0a482a2 --- /dev/null +++ b/third_party/streamdeck/hid_darwin.go @@ -0,0 +1,17 @@ +//go:build darwin +// +build darwin + +package streamdeck + +// karalabe/hid bundles a 2019 hidapi that names macOS devices by their +// IOService path. On Apple Silicon those paths run up against the 512-byte +// io_string_t, IORegistryEntryGetPath fails, and every Stream Deck enumerates +// with an empty path and is skipped. bearsh/hid keeps karalabe/hid's API on +// hidapi 0.14, which names devices by registry entry ID instead, and whose +// errors carry the IOReturn code; hidapi before 0.13 answered every macOS +// failure with "hid_error is not implemented yet". +import "github.com/bearsh/hid" + +type hidDeviceInfo = hid.DeviceInfo + +var hidEnumerate = hid.Enumerate diff --git a/third_party/streamdeck/streamdeck.go b/third_party/streamdeck/streamdeck.go new file mode 100644 index 0000000..7606dcb --- /dev/null +++ b/third_party/streamdeck/streamdeck.go @@ -0,0 +1,856 @@ +package streamdeck + +import ( + "bytes" + "context" + "errors" + "fmt" + "image" + "image/color" + "image/jpeg" + "math" + "sync" + "time" + + "golang.org/x/image/draw" +) + +const ( + // 30 fps fade animation. + fadeDelay = time.Second / 30 + + // A write or feature report that fails is tried ioAttempts times on the + // open handle, ioRetryDelay apart, then as often again on a reopened one. + // macOS rejects the odd transfer to a Stream Deck MK.2 with + // kIOReturnError (0xE00002BC), about once a minute under a busy deck and + // with or without other transfers in flight; the next attempt goes through. + ioAttempts = 3 + ioRetryDelay = 20 * time.Millisecond +) + +// ErrDisconnected is returned once the device has no open handle: it kept +// failing and could not be opened again, which is what an unplugged deck +// looks like, or it was closed. Every later call returns it as well. +var ErrDisconnected = errors.New("stream deck disconnected") + +// hidHandle is the part of an open HID device a Stream Deck uses. The tests +// stand in for it. +type hidHandle interface { + Read(b []byte) (int, error) + Write(b []byte) (int, error) + SendFeatureReport(b []byte) (int, error) + GetFeatureReport(b []byte) (int, error) + Close() error +} + +// Stream Deck Vendor & Product IDs. +// +//nolint:revive +const ( + VID_ELGATO = 0x0fd9 + PID_STREAMDECK = 0x0060 + PID_STREAMDECK_V2 = 0x006d + PID_STREAMDECK_MK2 = 0x0080 + PID_STREAMDECK_MINI = 0x0063 + PID_STREAMDECK_MINI_MK2 = 0x0090 + PID_STREAMDECK_XL = 0x006c +) + +// Firmware command IDs. +// +//nolint:revive +var ( + c_REV1_FIRMWARE = []byte{0x04} + c_REV1_RESET = []byte{0x0b, 0x63} + c_REV1_BRIGHTNESS = []byte{0x05, 0x55, 0xaa, 0xd1, 0x01} + + c_REV2_FIRMWARE = []byte{0x05} + c_REV2_RESET = []byte{0x03, 0x02} + c_REV2_BRIGHTNESS = []byte{0x03, 0x08} +) + +// Device represents a single Stream Deck device. +type Device struct { + ID string + Serial string + + Columns uint8 + Rows uint8 + Keys uint8 + Pixels uint + DPI uint + Padding uint + + featureReportSize int + firmwareOffset int + keyStateOffset int + translateKeyIndex func(index, columns uint8) uint8 + imagePageSize int + imagePageHeaderSize int + flipImage func(image.Image) image.Image + toImageFormat func(image.Image) ([]byte, error) + imagePageHeader func(pageIndex int, keyIndex uint8, payloadLength int, lastPage bool) []byte + + getFirmwareCommand []byte + resetCommand []byte + setBrightnessCommand []byte + + keyState []byte + + // ioMutex guards device and serializes every write, feature report, + // reopen and close, so the pages of an image go out back to back. + // Overlapping transfers also make macOS reject them far more often. + ioMutex *sync.Mutex + device hidHandle + open func() (hidHandle, error) + + // sleepMutex guards everything from here down. + lastActionTime time.Time + asleep bool + sleepCancel context.CancelFunc + sleepMutex *sync.RWMutex + fadeDuration time.Duration + + brightness uint8 + preSleepBrightness uint8 +} + +// Key holds the current status of a key on the device. +type Key struct { + Index uint8 + Pressed bool +} + +// Devices returns all attached Stream Decks. +func Devices() ([]Device, error) { + dd := []Device{} + + devs := hidEnumerate(VID_ELGATO, 0) + for _, d := range devs { + var dev Device + + switch { + case d.VendorID == VID_ELGATO && d.ProductID == PID_STREAMDECK: + dev = Device{ + ID: d.Path, + Serial: d.Serial, + Columns: 5, + Rows: 3, + Keys: 15, + Pixels: 72, + DPI: 124, + Padding: 16, + featureReportSize: 17, + firmwareOffset: 5, + keyStateOffset: 1, + translateKeyIndex: translateRightToLeft, + imagePageSize: 7819, + imagePageHeaderSize: 16, + imagePageHeader: rev1ImagePageHeader, + flipImage: flipHorizontally, + toImageFormat: toBMP, + getFirmwareCommand: c_REV1_FIRMWARE, + resetCommand: c_REV1_RESET, + setBrightnessCommand: c_REV1_BRIGHTNESS, + } + case d.VendorID == VID_ELGATO && (d.ProductID == PID_STREAMDECK_MINI || d.ProductID == PID_STREAMDECK_MINI_MK2): + dev = Device{ + ID: d.Path, + Serial: d.Serial, + Columns: 3, + Rows: 2, + Keys: 6, + Pixels: 80, + DPI: 138, + Padding: 16, + featureReportSize: 17, + firmwareOffset: 5, + keyStateOffset: 1, + translateKeyIndex: identity, + imagePageSize: 1024, + imagePageHeaderSize: 16, + imagePageHeader: miniImagePageHeader, + flipImage: rotateCounterclockwise, + toImageFormat: toBMP, + getFirmwareCommand: c_REV1_FIRMWARE, + resetCommand: c_REV1_RESET, + setBrightnessCommand: c_REV1_BRIGHTNESS, + } + case d.VendorID == VID_ELGATO && (d.ProductID == PID_STREAMDECK_V2 || d.ProductID == PID_STREAMDECK_MK2): + dev = Device{ + ID: d.Path, + Serial: d.Serial, + Columns: 5, + Rows: 3, + Keys: 15, + Pixels: 72, + DPI: 124, + Padding: 16, + featureReportSize: 32, + firmwareOffset: 6, + keyStateOffset: 4, + translateKeyIndex: identity, + imagePageSize: 1024, + imagePageHeaderSize: 8, + imagePageHeader: rev2ImagePageHeader, + flipImage: flipHorizontallyAndVertically, + toImageFormat: toJPEG, + getFirmwareCommand: c_REV2_FIRMWARE, + resetCommand: c_REV2_RESET, + setBrightnessCommand: c_REV2_BRIGHTNESS, + } + case d.VendorID == VID_ELGATO && d.ProductID == PID_STREAMDECK_XL: + dev = Device{ + ID: d.Path, + Serial: d.Serial, + Columns: 8, + Rows: 4, + Keys: 32, + Pixels: 96, + DPI: 166, + Padding: 16, + featureReportSize: 32, + firmwareOffset: 6, + keyStateOffset: 4, + translateKeyIndex: identity, + imagePageSize: 1024, + imagePageHeaderSize: 8, + imagePageHeader: rev2ImagePageHeader, + flipImage: flipHorizontallyAndVertically, + toImageFormat: toJPEG, + getFirmwareCommand: c_REV2_FIRMWARE, + resetCommand: c_REV2_RESET, + setBrightnessCommand: c_REV2_BRIGHTNESS, + } + } + + if dev.ID != "" { + dev.keyState = make([]byte, dev.Columns*dev.Rows) + dev.ioMutex = &sync.Mutex{} + dev.sleepMutex = &sync.RWMutex{} + dev.open = wrapOpen(opener(d)) + dd = append(dd, dev) + } + } + + return dd, nil +} + +// wrapOpen lets a build with -tags streamdeck_fault stand between a deck and +// its handles; see fault.go. +var wrapOpen = func(open func() (hidHandle, error)) func() (hidHandle, error) { return open } + +// opener opens the device by the path it was enumerated under. A replugged +// deck comes back under a new path, so it cannot be reopened this way. +func opener(info hidDeviceInfo) func() (hidHandle, error) { + return func() (hidHandle, error) { + device, err := info.Open() + if err != nil { + return nil, err + } + return device, nil + } +} + +// Open the device for input/output. This must be called before trying to +// communicate with the device. +func (d *Device) Open() error { + d.sleepMutex.Lock() + d.lastActionTime = time.Now() + d.sleepMutex.Unlock() + + d.ioMutex.Lock() + defer d.ioMutex.Unlock() + return d.reopen() +} + +// Close the connection with the device. +func (d *Device) Close() error { + d.cancelSleepTimer() + + d.ioMutex.Lock() + defer d.ioMutex.Unlock() + if d.device == nil { + return nil + } + err := d.device.Close() + d.device = nil + return err +} + +// reopen closes the handle, if there is one, and opens the device again. +// The caller holds ioMutex. On failure the device is left closed. +func (d *Device) reopen() error { + if d.device != nil { + _ = d.device.Close() + d.device = nil + } + device, err := d.open() + if err != nil { + return err + } + d.device = device + return nil +} + +// do runs op on the open handle under ioMutex, so no other write, feature +// report or reopen comes in between. An op that keeps failing is run again on +// a reopened handle; a device that cannot be reopened stays closed and the +// error wraps ErrDisconnected. +func (d *Device) do(op func(hidHandle) error) error { + d.ioMutex.Lock() + defer d.ioMutex.Unlock() + + if d.device == nil { + return ErrDisconnected + } + err := d.attempt(op) + if err == nil { + return nil + } + if rerr := d.reopen(); rerr != nil { + return fmt.Errorf("%w: %v, then reopening it failed: %v", ErrDisconnected, err, rerr) + } + return d.attempt(op) +} + +// attempt runs op up to ioAttempts times on the open handle. +func (d *Device) attempt(op func(hidHandle) error) error { + var err error + for i := 0; i < ioAttempts; i++ { + if i > 0 { + time.Sleep(ioRetryDelay) + } + if err = op(d.device); err == nil { + return nil + } + } + return err +} + +// FirmwareVersion returns the firmware version of the device. +func (d *Device) FirmwareVersion() (string, error) { + result, err := d.getFeatureReport(d.getFirmwareCommand) + if err != nil { + return "", err + } + return string(result[d.firmwareOffset:]), nil +} + +// Resets the Stream Deck, clears all button images and shows the standby image. +func (d *Device) Reset() error { + return d.sendFeatureReport(d.resetCommand) +} + +// Clears the Stream Deck, setting a black image on all buttons. +func (d *Device) Clear() error { + img := image.NewRGBA(image.Rect(0, 0, int(d.Pixels), int(d.Pixels))) + draw.Draw(img, img.Bounds(), image.NewUniform(color.RGBA{0, 0, 0, 255}), image.Point{}, draw.Src) + for i := uint8(0); i < d.Keys; i++ { + if err := d.SetImage(i, img); err != nil { + return err + } + } + + return nil +} + +// ReadKeys returns a channel, which it will use to emit key presses/releases. +// The channel is closed once the device is closed or gone. +func (d *Device) ReadKeys() (chan Key, error) { + kch := make(chan Key) + keyBuffer := make([]byte, d.keyStateOffset+len(d.keyState)) + go func() { + defer close(kch) + for { + copy(d.keyState, keyBuffer[d.keyStateOffset:]) + + if !d.read(keyBuffer) { + return + } + + // don't trigger a key event if the device is asleep, but wake it + if d.Asleep() { + _ = d.Wake() + + // reset state so no spurious key events get triggered + for i := d.keyStateOffset; i < len(keyBuffer); i++ { + keyBuffer[i] = 0 + } + continue + } + + d.sleepMutex.Lock() + d.lastActionTime = time.Now() + d.sleepMutex.Unlock() + + for i := d.keyStateOffset; i < len(keyBuffer); i++ { + keyIndex := uint8(i - d.keyStateOffset) + if keyBuffer[i] != d.keyState[keyIndex] { + kch <- Key{ + Index: d.translateKeyIndex(keyIndex, d.Columns), + Pressed: keyBuffer[i] == 1, + } + } + } + } + }() + + return kch, nil +} + +// read waits for the next input report. It carries on across a reopen, which +// closes the handle under a blocked read, and returns false once the device +// is closed or gone. +func (d *Device) read(b []byte) bool { + for { + d.ioMutex.Lock() + device := d.device + d.ioMutex.Unlock() + if device == nil { + return false + } + + if _, err := device.Read(b); err == nil { + return true + } + + // Locking waits out a reopen that is still under way. + d.ioMutex.Lock() + reopened := d.device != nil && d.device != device + d.ioMutex.Unlock() + if !reopened { + return false + } + } +} + +// Sleep puts the device asleep, waiting for a key event to wake it up. +func (d *Device) Sleep() error { + d.sleepMutex.Lock() + defer d.sleepMutex.Unlock() + + d.preSleepBrightness = d.brightness + + if err := d.fade(d.brightness, 0, d.fadeDuration); err != nil { + return err + } + + d.asleep = true + return d.setBrightness(0) +} + +// Wake wakes the device from sleep. +func (d *Device) Wake() error { + d.sleepMutex.Lock() + defer d.sleepMutex.Unlock() + + d.asleep = false + if err := d.fade(0, d.preSleepBrightness, d.fadeDuration); err != nil { + return err + } + + d.lastActionTime = time.Now() + return d.setBrightness(d.preSleepBrightness) +} + +// Asleep returns true if the device is asleep. +func (d *Device) Asleep() bool { + d.sleepMutex.RLock() + defer d.sleepMutex.RUnlock() + return d.asleep +} + +func (d *Device) cancelSleepTimer() { + if d.sleepCancel == nil { + return + } + + d.sleepCancel() + d.sleepCancel = nil +} + +// SetSleepFadeDuration sets the duration of the fading animation when the +// device is put to sleep or wakes up. +func (d *Device) SetSleepFadeDuration(t time.Duration) { + d.fadeDuration = t +} + +// SetSleepTimeout sets the time after which the device will sleep if no key +// events are received. +func (d *Device) SetSleepTimeout(t time.Duration) { + d.cancelSleepTimer() + if t == 0 { + return + } + + var ctx context.Context + ctx, d.sleepCancel = context.WithCancel(context.Background()) + + go func() { + for { + select { + case <-time.After(time.Second): + d.sleepMutex.RLock() + since := time.Since(d.lastActionTime) + asleep := d.asleep + d.sleepMutex.RUnlock() + + if !asleep && since >= t { + _ = d.Sleep() + } + + case <-ctx.Done(): + return + } + } + }() +} + +// Fade fades the brightness in or out. +func (d *Device) Fade(start uint8, end uint8, duration time.Duration) error { + d.sleepMutex.Lock() + defer d.sleepMutex.Unlock() + return d.fade(start, end, duration) +} + +// fade is Fade for a caller holding sleepMutex. +func (d *Device) fade(start uint8, end uint8, duration time.Duration) error { + step := (float64(end) - float64(start)) / float64(duration/fadeDelay) + if step == math.Inf(1) || step == math.Inf(-1) { + return nil + } + + for current := float64(start); ; current += step { + if !((start < end && int8(current) < int8(end)) || + (start > end && int8(current) > int8(end))) { + break + } + if err := d.setBrightness(uint8(current)); err != nil { + return err + } + + time.Sleep(fadeDelay) + } + return nil +} + +// SetBrightness sets the background lighting brightness from 0 to 100 percent. +func (d *Device) SetBrightness(percent uint8) error { + d.sleepMutex.Lock() + defer d.sleepMutex.Unlock() + return d.setBrightness(percent) +} + +// setBrightness is SetBrightness for a caller holding sleepMutex. +func (d *Device) setBrightness(percent uint8) error { + if percent > 100 { + percent = 100 + } + + d.brightness = percent + if d.asleep && percent > 0 { + // if the device is asleep, remember the brightness, but don't set it + d.preSleepBrightness = percent + return nil + } + + report := make([]byte, len(d.setBrightnessCommand)+1) + copy(report, d.setBrightnessCommand) + report[len(report)-1] = percent + + return d.sendFeatureReport(report) +} + +// SetImage sets the image of a button on the Stream Deck. The provided image +// needs to be in the correct resolution for the device. The index starts with +// 0 being the top-left button. +func (d *Device) SetImage(index uint8, img image.Image) error { + if img.Bounds().Dy() != int(d.Pixels) || + img.Bounds().Dx() != int(d.Pixels) { + return fmt.Errorf("supplied image has wrong dimensions, expected %[1]dx%[1]d pixels", d.Pixels) + } + + imageBytes, err := d.toImageFormat(d.flipImage(img)) + if err != nil { + return fmt.Errorf("cannot convert image data: %v", err) + } + imageData := imageData{ + image: imageBytes, + pageSize: d.imagePageSize - d.imagePageHeaderSize, + } + key := d.translateKeyIndex(index, d.Columns) + + // A retry starts over from page 0. + return d.do(func(device hidHandle) error { + return d.writeImage(device, key, imageData) + }) +} + +// writeImage sends every page of an image to the device. +func (d *Device) writeImage(device hidHandle, key uint8, imageData imageData) error { + data := make([]byte, d.imagePageSize) + + var page int + var lastPage bool + for !lastPage { + var payload []byte + payload, lastPage = imageData.Page(page) + header := d.imagePageHeader(page, key, len(payload), lastPage) + + copy(data, header) + copy(data[len(header):], payload) + + _, err := device.Write(data) + if err != nil { + return fmt.Errorf("cannot write image page %d of %d (%d image bytes) %d bytes: %w", + page, imageData.PageCount(), imageData.Length(), len(data), err) + } + + page++ + } + + return nil +} + +// getFeatureReport from the device without worries about the correct payload +// size. +func (d *Device) getFeatureReport(payload []byte) ([]byte, error) { + b := make([]byte, d.featureReportSize) + err := d.do(func(device hidHandle) error { + copy(b, payload) + _, err := device.GetFeatureReport(b) + return err + }) + if err != nil { + return nil, err + } + return b, nil +} + +// sendFeatureReport to the device without worries about the correct payload +// size. +func (d *Device) sendFeatureReport(payload []byte) error { + b := make([]byte, d.featureReportSize) + copy(b, payload) + return d.do(func(device hidHandle) error { + _, err := device.SendFeatureReport(b) + return err + }) +} + +// translateRightToLeft translates the given key index from right-to-left to +// left-to-right, based on the given number of columns. +func translateRightToLeft(index, columns uint8) uint8 { + keyCol := index % columns + return (index - keyCol) + (columns - 1) - keyCol +} + +// identity returns the given key index as it is. +func identity(index, _ uint8) uint8 { + return index +} + +// toRGBA converts an image.Image to an image.RGBA. +func toRGBA(img image.Image) *image.RGBA { + switch img := img.(type) { + case *image.RGBA: + return img + } + out := image.NewRGBA(img.Bounds()) + draw.Copy(out, image.Pt(0, 0), img, img.Bounds(), draw.Src, nil) + return out +} + +// flipHorizontally returns the given image horizontally flipped. +func flipHorizontally(img image.Image) image.Image { + flipped := image.NewRGBA(img.Bounds()) + draw.Copy(flipped, image.Point{}, img, img.Bounds(), draw.Src, nil) + for y := 0; y < flipped.Bounds().Dy(); y++ { + for x := 0; x < flipped.Bounds().Dx()/2; x++ { + xx := flipped.Bounds().Max.X - x - 1 + c := flipped.RGBAAt(x, y) + flipped.SetRGBA(x, y, flipped.RGBAAt(xx, y)) + flipped.SetRGBA(xx, y, c) + } + } + return flipped +} + +// flipHorizontallyAndVertically returns the given image horizontally and +// vertically flipped. +func flipHorizontallyAndVertically(img image.Image) image.Image { + flipped := image.NewRGBA(img.Bounds()) + draw.Copy(flipped, image.Point{}, img, img.Bounds(), draw.Src, nil) + for y := 0; y < flipped.Bounds().Dy()/2; y++ { + yy := flipped.Bounds().Max.Y - y - 1 + for x := 0; x < flipped.Bounds().Dx(); x++ { + xx := flipped.Bounds().Max.X - x - 1 + c := flipped.RGBAAt(x, y) + flipped.SetRGBA(x, y, flipped.RGBAAt(xx, yy)) + flipped.SetRGBA(xx, yy, c) + } + } + return flipped +} + +// rotateCounterclockwise returns the given image rotated counterclockwise. +func rotateCounterclockwise(img image.Image) image.Image { + flipped := image.NewRGBA(img.Bounds()) + draw.Copy(flipped, image.Point{}, img, img.Bounds(), draw.Src, nil) + for y := 0; y < flipped.Bounds().Dy(); y++ { + for x := y + 1; x < flipped.Bounds().Dx(); x++ { + c := flipped.RGBAAt(x, y) + flipped.SetRGBA(x, y, flipped.RGBAAt(y, x)) + flipped.SetRGBA(y, x, c) + } + } + for y := 0; y < flipped.Bounds().Dy()/2; y++ { + yy := flipped.Bounds().Max.Y - y - 1 + for x := 0; x < flipped.Bounds().Dx(); x++ { + c := flipped.RGBAAt(x, y) + flipped.SetRGBA(x, y, flipped.RGBAAt(x, yy)) + flipped.SetRGBA(x, yy, c) + } + } + return flipped +} + +// toBMP returns the raw bytes of the given image in BMP format. +func toBMP(img image.Image) ([]byte, error) { + rgba := toRGBA(img) + + // this is a BMP file header followed by a BPM bitmap info header + // find more information here: https://en.wikipedia.org/wiki/BMP_file_format + header := []byte{ + 0x42, 0x4d, 0xf6, 0x3c, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x28, 0x00, + 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x48, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x18, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xc0, 0x3c, 0x00, 0x00, 0xc4, 0x0e, + 0x00, 0x00, 0xc4, 0x0e, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + } + + buffer := make([]byte, len(header)+rgba.Bounds().Dx()*rgba.Bounds().Dy()*3) + copy(buffer, header) + + i := len(header) + for y := 0; y < rgba.Bounds().Dy(); y++ { + for x := 0; x < rgba.Bounds().Dx(); x++ { + c := rgba.RGBAAt(x, y) + buffer[i] = c.B + buffer[i+1] = c.G + buffer[i+2] = c.R + i += 3 + } + } + return buffer, nil +} + +// toJPEG returns the raw bytes of the given image in JPEG format. +func toJPEG(img image.Image) ([]byte, error) { + buffer := bytes.NewBuffer([]byte{}) + opts := jpeg.Options{ + Quality: 100, + } + err := jpeg.Encode(buffer, img, &opts) + if err != nil { + return nil, err + } + return buffer.Bytes(), err +} + +// rev1ImagePageHeader returns the image page header sequence used by the +// Stream Deck v1. +func rev1ImagePageHeader(pageIndex int, keyIndex uint8, payloadLength int, lastPage bool) []byte { + var lastPageByte byte + if lastPage { + lastPageByte = 1 + } + return []byte{ + 0x02, 0x01, + byte(pageIndex + 1), 0x00, + lastPageByte, + keyIndex + 1, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + } +} + +// miniImagePageHeader returns the image page header sequence used by the +// Stream Deck Mini. +func miniImagePageHeader(pageIndex int, keyIndex uint8, payloadLength int, lastPage bool) []byte { + var lastPageByte byte + if lastPage { + lastPageByte = 1 + } + return []byte{ + 0x02, 0x01, + byte(pageIndex), 0x00, + lastPageByte, + keyIndex + 1, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + } +} + +// rev2ImagePageHeader returns the image page header sequence used by Stream +// Deck XL and Stream Deck v2. +func rev2ImagePageHeader(pageIndex int, keyIndex uint8, payloadLength int, lastPage bool) []byte { + var lastPageByte byte + if lastPage { + lastPageByte = 1 + } + return []byte{ + 0x02, 0x07, keyIndex, lastPageByte, + byte(payloadLength), byte(payloadLength >> 8), + byte(pageIndex), byte(pageIndex >> 8), + } +} + +// imageData allows to access raw image data in a byte array through pages of a +// given size. +type imageData struct { + image []byte + pageSize int +} + +// Page returns the page with the given index and an indication if this is the +// last page. +func (d imageData) Page(pageIndex int) ([]byte, bool) { + offset := pageIndex * d.pageSize + if offset >= len(d.image) { + return []byte{}, true + } + + length := d.pageLength(pageIndex) + if offset+length > len(d.image) { + length = len(d.image) - offset + } + + return d.image[offset : offset+length], pageIndex == d.PageCount()-1 +} + +func (d imageData) pageLength(pageIndex int) int { + remaining := len(d.image) - (pageIndex * d.pageSize) + if remaining > d.pageSize { + return d.pageSize + } + if remaining > 0 { + return remaining + } + return 0 +} + +// PageCount returns the total number of pages. +func (d imageData) PageCount() int { + count := len(d.image) / d.pageSize + if len(d.image)%d.pageSize != 0 { + return count + 1 + } + return count +} + +// Length of the raw image data in bytes. +func (d imageData) Length() int { + return len(d.image) +} diff --git a/third_party/streamdeck/streamdeck_test.go b/third_party/streamdeck/streamdeck_test.go new file mode 100644 index 0000000..d6a9547 --- /dev/null +++ b/third_party/streamdeck/streamdeck_test.go @@ -0,0 +1,444 @@ +package streamdeck + +import ( + "errors" + "image" + "image/color" + "math/rand" + "sync" + "sync/atomic" + "testing" + "time" +) + +var errFake = errors.New("fake write failure") + +// report is one transfer that reached the fake deck. +type report struct { + feature bool + data []byte +} + +// fakeDeck records what reaches it through every handle it hands out, and +// notices when two transfers overlap. +type fakeDeck struct { + mu sync.Mutex + reports []report + handles []*fakeHandle + // failWrites is how many writes each new handle fails, -1 for all. + failWrites int + openErr error + + busy int32 + overlap int32 +} + +func (f *fakeDeck) open() (hidHandle, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.openErr != nil { + return nil, f.openErr + } + h := &fakeHandle{ + deck: f, + failWrites: f.failWrites, + input: make(chan []byte, 1), + closed: make(chan struct{}), + } + f.handles = append(f.handles, h) + return h, nil +} + +func (f *fakeDeck) transfer(feature bool, b []byte) { + if atomic.AddInt32(&f.busy, 1) > 1 { + atomic.StoreInt32(&f.overlap, 1) + } + time.Sleep(20 * time.Microsecond) // widen the window for an overlap + f.mu.Lock() + f.reports = append(f.reports, report{feature: feature, data: append([]byte(nil), b...)}) + f.mu.Unlock() + atomic.AddInt32(&f.busy, -1) +} + +func (f *fakeDeck) log() []report { + f.mu.Lock() + defer f.mu.Unlock() + return append([]report(nil), f.reports...) +} + +type fakeHandle struct { + deck *fakeDeck + failWrites int + input chan []byte + closed chan struct{} + closeOnce sync.Once +} + +func (h *fakeHandle) Read(b []byte) (int, error) { + select { + case r := <-h.input: + return copy(b, r), nil + case <-h.closed: + return 0, errors.New("closed") + } +} + +func (h *fakeHandle) Write(b []byte) (int, error) { + h.deck.mu.Lock() + fail := h.failWrites != 0 + if h.failWrites > 0 { + h.failWrites-- + } + h.deck.mu.Unlock() + if fail { + return 0, errFake + } + h.deck.transfer(false, b) + return len(b), nil +} + +func (h *fakeHandle) SendFeatureReport(b []byte) (int, error) { + h.deck.transfer(true, b) + return len(b), nil +} + +func (h *fakeHandle) GetFeatureReport(b []byte) (int, error) { + h.deck.transfer(true, b) + return len(b), nil +} + +func (h *fakeHandle) Close() error { + h.closeOnce.Do(func() { close(h.closed) }) + return nil +} + +func (h *fakeHandle) isClosed() bool { + select { + case <-h.closed: + return true + default: + return false + } +} + +// newFakeMK2 returns an open Stream Deck MK.2 wired to a fake deck. +func newFakeMK2(t *testing.T, f *fakeDeck) *Device { + t.Helper() + enumerate := hidEnumerate + hidEnumerate = func(uint16, uint16) []hidDeviceInfo { + return []hidDeviceInfo{{Path: "fake", VendorID: VID_ELGATO, ProductID: PID_STREAMDECK_MK2, Serial: "FAKE"}} + } + t.Cleanup(func() { hidEnumerate = enumerate }) + + devs, err := Devices() + if err != nil || len(devs) != 1 { + t.Fatalf("Devices() = %d devices, %v", len(devs), err) + } + dev := &devs[0] + dev.open = f.open + if err := dev.Open(); err != nil { + t.Fatal(err) + } + return dev +} + +// noise returns an image that encodes to several pages. +func noise(size int, seed int64) image.Image { + r := rand.New(rand.NewSource(seed)) //nolint:gosec // test pattern + img := image.NewRGBA(image.Rect(0, 0, size, size)) + for y := 0; y < size; y++ { + for x := 0; x < size; x++ { + img.SetRGBA(x, y, color.RGBA{uint8(r.Intn(256)), uint8(r.Intn(256)), uint8(r.Intn(256)), 255}) + } + } + return img +} + +// page decodes an MK.2 image page header. +type page struct { + key uint8 + last bool + index int +} + +func decodePage(b []byte) page { + return page{key: b[2], last: b[3] == 1, index: int(b[6]) | int(b[7])<<8} +} + +// checkContiguous fails unless every image in log went out page after page, +// with nothing in between, and returns how many complete images it saw. +func checkContiguous(t *testing.T, log []report) int { + t.Helper() + images := 0 + for i := 0; i < len(log); { + if log[i].feature { + i++ + continue + } + first := decodePage(log[i].data) + if first.index != 0 { + t.Fatalf("report %d: image for key %d starts at page %d", i, first.key, first.index) + } + for n := 0; ; n++ { + if i >= len(log) || log[i].feature { + t.Fatalf("report %d: image for key %d cut off after page %d", i, first.key, n-1) + } + p := decodePage(log[i].data) + if p.key != first.key || p.index != n { + t.Fatalf("report %d: page %d of key %d inside page %d of key %d", i, p.index, p.key, n, first.key) + } + i++ + if p.last { + break + } + } + images++ + } + return images +} + +func TestConcurrentImagesStayWhole(t *testing.T) { + f := &fakeDeck{} + dev := newFakeMK2(t, f) + + var wg sync.WaitGroup + for w := 0; w < 4; w++ { + wg.Add(1) + go func(w int) { + defer wg.Done() + for i := 0; i < 20; i++ { + if err := dev.SetImage(uint8(w), noise(int(dev.Pixels), int64(w*100+i))); err != nil { + t.Error(err) + return + } + } + }(w) + } + wg.Add(2) + go func() { + defer wg.Done() + for i := 0; i < 50; i++ { + if err := dev.SetBrightness(uint8(i)); err != nil { + t.Error(err) + return + } + } + }() + go func() { + defer wg.Done() + if err := dev.Fade(100, 0, 100*time.Millisecond); err != nil { + t.Error(err) + } + }() + wg.Wait() + + if atomic.LoadInt32(&f.overlap) != 0 { + t.Error("two transfers reached the device at once") + } + if images := checkContiguous(t, f.log()); images != 80 { + t.Errorf("saw %d whole images, want 80", images) + } +} + +func TestFailedImageStartsOverFromFirstPage(t *testing.T) { + f := &fakeDeck{} + dev := newFakeMK2(t, f) + img := noise(int(dev.Pixels), 1) + if err := dev.SetImage(3, img); err != nil { + t.Fatal(err) + } + pages := len(f.log()) + if pages < 2 { + t.Fatalf("image went out in %d pages, want several", pages) + } + + // Let page 0 through, then fail page 1 once. + h := f.handles[0] + f.mu.Lock() + f.reports = nil + f.mu.Unlock() + dev.ioMutex.Lock() + dev.device = &secondWriteFails{fakeHandle: h} + dev.ioMutex.Unlock() + + if err := dev.SetImage(3, img); err != nil { + t.Fatal(err) + } + log := f.log() + if len(log) != 1+pages { + t.Fatalf("got %d pages, want page 0 and then the %d pages again", len(log), pages) + } + checkContiguous(t, log[1:]) + if len(f.handles) != 1 { + t.Errorf("a single failure reopened the device") + } +} + +// secondWriteFails fails its second write. +type secondWriteFails struct { + *fakeHandle + writes int +} + +func (h *secondWriteFails) Write(b []byte) (int, error) { + h.writes++ + if h.writes == 2 { + return 0, errFake + } + return h.fakeHandle.Write(b) +} + +func TestFailingHandleIsReopened(t *testing.T) { + f := &fakeDeck{failWrites: -1} + dev := newFakeMK2(t, f) + f.mu.Lock() + f.failWrites = 0 // the reopened handle works + f.mu.Unlock() + + if err := dev.SetImage(0, noise(int(dev.Pixels), 2)); err != nil { + t.Fatal(err) + } + if len(f.handles) != 2 { + t.Fatalf("opened %d handles, want 2", len(f.handles)) + } + if !f.handles[0].isClosed() { + t.Error("the failing handle was left open") + } + if images := checkContiguous(t, f.log()); images != 1 { + t.Errorf("saw %d whole images, want 1", images) + } +} + +func TestKeyStillFailingAfterReopen(t *testing.T) { + f := &fakeDeck{failWrites: -1} + dev := newFakeMK2(t, f) + + err := dev.SetImage(0, noise(int(dev.Pixels), 3)) + if !errors.Is(err, errFake) || errors.Is(err, ErrDisconnected) { + t.Fatalf("SetImage() = %v, want the write error", err) + } + if len(f.handles) != 2 { + t.Errorf("opened %d handles, want 2", len(f.handles)) + } + // The device stays open and the next call tries again. + f.mu.Lock() + f.handles[1].failWrites = 0 + f.mu.Unlock() + if err := dev.SetImage(0, noise(int(dev.Pixels), 3)); err != nil { + t.Fatal(err) + } +} + +func TestGoneWhenReopenFails(t *testing.T) { + f := &fakeDeck{failWrites: -1} + dev := newFakeMK2(t, f) + keys, err := dev.ReadKeys() + if err != nil { + t.Fatal(err) + } + f.mu.Lock() + f.openErr = errors.New("no such device") + f.mu.Unlock() + + if err := dev.SetImage(0, noise(int(dev.Pixels), 4)); !errors.Is(err, ErrDisconnected) { + t.Fatalf("SetImage() = %v, want ErrDisconnected", err) + } + if err := dev.SetBrightness(50); !errors.Is(err, ErrDisconnected) { + t.Fatalf("SetBrightness() = %v, want ErrDisconnected", err) + } + select { + case _, ok := <-keys: + if ok { + t.Fatal("got a key from a gone device") + } + case <-time.After(time.Second): + t.Fatal("key channel still open") + } +} + +func TestReadErrorClosesKeys(t *testing.T) { + f := &fakeDeck{} + dev := newFakeMK2(t, f) + keys, err := dev.ReadKeys() + if err != nil { + t.Fatal(err) + } + // What an unplug looks like to the reader. + _ = f.handles[0].Close() + + select { + case _, ok := <-keys: + if ok { + t.Fatal("got a key from an unplugged device") + } + case <-time.After(time.Second): + t.Fatal("key channel still open") + } +} + +func TestReaderFollowsReopen(t *testing.T) { + f := &fakeDeck{failWrites: -1} + dev := newFakeMK2(t, f) + keys, err := dev.ReadKeys() + if err != nil { + t.Fatal(err) + } + f.mu.Lock() + f.failWrites = 0 + f.mu.Unlock() + + if err := dev.SetImage(0, noise(int(dev.Pixels), 5)); err != nil { + t.Fatal(err) + } + pressed := make([]byte, dev.keyStateOffset+int(dev.Keys)) + pressed[dev.keyStateOffset+7] = 1 + f.handles[1].input <- pressed + + select { + case k, ok := <-keys: + if !ok || k.Index != 7 || !k.Pressed { + t.Fatalf("got %+v (open %v), want key 7 pressed", k, ok) + } + case <-time.After(time.Second): + t.Fatal("no key from the reopened device") + } +} + +func TestCloseEndsKeys(t *testing.T) { + f := &fakeDeck{} + dev := newFakeMK2(t, f) + keys, err := dev.ReadKeys() + if err != nil { + t.Fatal(err) + } + if err := dev.Close(); err != nil { + t.Fatal(err) + } + if _, ok := <-keys; ok { + t.Fatal("got a key after Close") + } + if err := dev.Reset(); !errors.Is(err, ErrDisconnected) { + t.Fatalf("Reset() after Close = %v, want ErrDisconnected", err) + } +} + +func TestClearDrawsEveryKeyOnce(t *testing.T) { + f := &fakeDeck{} + dev := newFakeMK2(t, f) + if err := dev.Clear(); err != nil { + t.Fatal(err) + } + seen := map[uint8]bool{} + for _, r := range f.log() { + p := decodePage(r.data) + if p.index == 0 { + if p.key >= dev.Keys { + t.Errorf("drew key %d on a %d-key deck", p.key, dev.Keys) + } + seen[p.key] = true + } + } + if len(seen) != int(dev.Keys) { + t.Errorf("drew %d keys, want %d", len(seen), dev.Keys) + } +} diff --git a/tools/deckstress/main.go b/tools/deckstress/main.go new file mode 100644 index 0000000..d7204de --- /dev/null +++ b/tools/deckstress/main.go @@ -0,0 +1,271 @@ +// Command deckstress drives a Stream Deck the way a busy deck does: several +// keys redrawing at once while the brightness changes and fades, and the +// firmware is queried in between. It uses only the public API, so it builds +// against any version of the streamdeck package, and stops at the first +// error or after -duration. +// +// go run ./tools/deckstress -duration 10m +// go run ./tools/deckstress -serial # the same work from one goroutine +package main + +import ( + "flag" + "fmt" + "image" + "image/color" + "image/draw" + "math/rand" + "os" + "os/signal" + "strings" + "sync" + "sync/atomic" + "syscall" + "time" + + "github.com/muesli/streamdeck" +) + +var ( + duration = flag.Duration("duration", 10*time.Minute, "how long to run") + serial = flag.Bool("serial", false, "run every operation from one goroutine") + writers = flag.Int("writers", 3, "goroutines writing key images") + device = flag.String("device", "", "serial number of the deck to use") + block = flag.Int("block", 6, "noise block size in pixels; larger blocks make smaller images") + onlyImgs = flag.Bool("images-only", false, "write key images only, no brightness, fades or firmware queries") + gap = flag.Duration("gap", 0, "pause after every image") +) + +// counters of successful operations, read by the progress report. +var images, brightness, fades, firmware uint64 + +func main() { + flag.Parse() + + dev, err := openDevice() + if err != nil { + fmt.Fprintln(os.Stderr, "open:", err) + os.Exit(2) + } + + failed := make(chan error, 1) + fail := func(op string, err error) { + select { + case failed <- fmt.Errorf("%s: %w", op, err): + default: + } + } + stop := make(chan struct{}) + + keys, err := dev.ReadKeys() + if err != nil { + fmt.Fprintln(os.Stderr, "read keys:", err) + os.Exit(2) + } + go func() { + for range keys { //nolint:revive // drain key events + } + }() + + var wg sync.WaitGroup + if *serial { + wg.Add(1) + go func() { + defer wg.Done() + runSerial(dev, stop, fail) + }() + } else { + runConcurrent(dev, stop, fail, &wg) + } + + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) + + start := time.Now() + progress := time.NewTicker(10 * time.Second) + defer progress.Stop() + + code := 0 +loop: + for { + select { + case err := <-failed: + fmt.Printf("FAIL after %s: %v\n", time.Since(start).Round(time.Millisecond), err) + code = 1 + break loop + case <-progress.C: + report(start) + case <-time.After(time.Until(start.Add(*duration))): + fmt.Printf("PASS: %s without an error\n", *duration) + break loop + case <-sigs: + fmt.Println("interrupted") + code = 130 + break loop + } + } + close(stop) + wg.Wait() + report(start) + + _ = dev.Reset() + _ = dev.Close() + os.Exit(code) +} + +func openDevice() (*streamdeck.Device, error) { + devs, err := streamdeck.Devices() + if err != nil { + return nil, err + } + for i := range devs { + if *device != "" && devs[i].Serial != *device { + continue + } + dev := &devs[i] + if err := dev.Open(); err != nil { + return nil, err + } + ver, err := dev.FirmwareVersion() + if err != nil { + return nil, fmt.Errorf("firmware version: %w", err) + } + fmt.Printf("deck %s, firmware %s, %d keys, serial=%v writers=%d block=%d images-only=%v gap=%s\n", + dev.Serial, strings.TrimRight(ver, " \x00"), dev.Keys, *serial, *writers, *block, *onlyImgs, *gap) + if err := dev.Reset(); err != nil { + return nil, fmt.Errorf("reset: %w", err) + } + return dev, nil + } + return nil, fmt.Errorf("no Stream Deck found") +} + +func report(start time.Time) { + fmt.Printf("%6s images=%d brightness=%d fades=%d firmware=%d\n", + time.Since(start).Round(time.Second), + atomic.LoadUint64(&images), atomic.LoadUint64(&brightness), + atomic.LoadUint64(&fades), atomic.LoadUint64(&firmware)) +} + +func runConcurrent(dev *streamdeck.Device, stop <-chan struct{}, fail func(string, error), wg *sync.WaitGroup) { + every := func(op string, pause time.Duration, f func(r *rand.Rand) error) { + wg.Add(1) + go func(seed int64) { + defer wg.Done() + r := rand.New(rand.NewSource(seed)) //nolint:gosec // test patterns, not secrets + for { + select { + case <-stop: + return + default: + } + if err := f(r); err != nil { + fail(op, err) + return + } + time.Sleep(pause) + } + }(time.Now().UnixNano() + int64(len(op))) + } + + for i := 0; i < *writers; i++ { + every("image", 0, func(r *rand.Rand) error { + return setImage(dev, r) + }) + } + if *onlyImgs { + return + } + every("brightness", 20*time.Millisecond, func(r *rand.Rand) error { + if err := dev.SetBrightness(30 + below(r, 70)); err != nil { + return err + } + atomic.AddUint64(&brightness, 1) + return nil + }) + every("fade", 100*time.Millisecond, func(*rand.Rand) error { + if err := dev.Fade(90, 30, 250*time.Millisecond); err != nil { + return err + } + if err := dev.Fade(30, 90, 250*time.Millisecond); err != nil { + return err + } + atomic.AddUint64(&fades, 2) + return nil + }) + every("firmware", 50*time.Millisecond, func(*rand.Rand) error { + if _, err := dev.FirmwareVersion(); err != nil { + return err + } + atomic.AddUint64(&firmware, 1) + return nil + }) +} + +// runSerial does the concurrent run's work in turn from one goroutine, at +// least as fast: the control for whether overlap is what fails. +func runSerial(dev *streamdeck.Device, stop <-chan struct{}, fail func(string, error)) { + r := rand.New(rand.NewSource(time.Now().UnixNano())) //nolint:gosec // test patterns, not secrets + for round := 0; ; round++ { + select { + case <-stop: + return + default: + } + for i := 0; i < *writers; i++ { + if err := setImage(dev, r); err != nil { + fail("image", err) + return + } + } + if *onlyImgs { + continue + } + if err := dev.SetBrightness(30 + below(r, 70)); err != nil { + fail("brightness", err) + return + } + atomic.AddUint64(&brightness, 1) + if round%8 == 0 { + if err := dev.Fade(90, 30, 250*time.Millisecond); err != nil { + fail("fade", err) + return + } + atomic.AddUint64(&fades, 1) + } + if _, err := dev.FirmwareVersion(); err != nil { + fail("firmware", err) + return + } + atomic.AddUint64(&firmware, 1) + } +} + +func setImage(dev *streamdeck.Device, r *rand.Rand) error { + key := below(r, int(dev.Keys)) + if err := dev.SetImage(key, noise(int(dev.Pixels), r)); err != nil { + return err + } + atomic.AddUint64(&images, 1) + time.Sleep(*gap) + return nil +} + +// noise draws coloured blocks, which come out of the JPEG encoder at a few +// KB: an image of several pages, like an icon with a label. +func noise(size int, r *rand.Rand) image.Image { + img := image.NewRGBA(image.Rect(0, 0, size, size)) + block := *block + for y := 0; y < size; y += block { + for x := 0; x < size; x += block { + c := color.RGBA{below(r, 256), below(r, 256), below(r, 256), 255} + draw.Draw(img, image.Rect(x, y, x+block, y+block), image.NewUniform(c), image.Point{}, draw.Src) + } + } + return img +} + +// below returns a random number from 0 up to n, which is at most 256. +func below(r *rand.Rand, n int) uint8 { + return uint8(r.Intn(n)) //nolint:gosec // n is at most 256 +} diff --git a/widget.go b/widget.go index 60764b1..53b48a5 100644 --- a/widget.go +++ b/widget.go @@ -5,6 +5,7 @@ import ( "image" "image/color" "image/draw" + _ "image/png" // decodes icons; the Linux build got it from the X11 libraries "os" "path/filepath" "time" @@ -73,6 +74,12 @@ func (w *BaseWidget) RequiresUpdate() bool { return true } +// Repaint makes the widget draw again on the next update, even before its +// interval has passed. +func (w *BaseWidget) Repaint() { + w.lastUpdate = time.Time{} +} + // Update renders the widget. func (w *BaseWidget) Update() error { return w.render(w.dev, nil) @@ -119,6 +126,12 @@ func NewWidget(dev *streamdeck.Device, base string, kc KeyConfig, bg image.Image case "top": return NewTopWidget(bw, kc.Widget), nil + case "toggle": + return NewToggleWidget(bw, kc.Widget) + + case "temp": + return NewTempWidget(bw, kc.Widget), nil + case "command": return NewCommandWidget(bw, kc.Widget), nil @@ -143,7 +156,26 @@ func (w *BaseWidget) render(dev *streamdeck.Device, fg image.Image) error { draw.Draw(img, img.Bounds(), fg, image.Point{}, draw.Over) } - return dev.SetImage(w.key, img) + if err := dev.SetImage(w.key, img); err != nil { + w.Repaint() + return drawError{key: w.key, err: err} + } + return nil +} + +// drawError is a key image the device did not take. deckmaster survives it: +// the widget draws again on the next update. +type drawError struct { + key uint8 + err error +} + +func (e drawError) Error() string { + return fmt.Sprintf("can't draw key %d: %v", e.key, e.err) +} + +func (e drawError) Unwrap() error { + return e.err } // change the interval a widget gets rendered in. diff --git a/widget_button.go b/widget_button.go index e57025d..436824d 100644 --- a/widget_button.go +++ b/widget_button.go @@ -1,8 +1,11 @@ package main import ( + "fmt" "image" "image/color" + "os" + "strings" "time" ) @@ -10,20 +13,29 @@ import ( type ButtonWidget struct { *BaseWidget - icon image.Image - label string - fontsize float64 - color color.Color - flatten bool + icon image.Image + iconPath string + iconCommand string + label string + fontsize float64 + color color.Color + flatten bool } // NewButtonWidget returns a new ButtonWidget. func NewButtonWidget(bw *BaseWidget, opts WidgetConfig) (*ButtonWidget, error) { - bw.setInterval(time.Duration(opts.Interval)*time.Millisecond, 0) - - var icon, label string + var icon, iconCommand, label string _ = ConfigValue(opts.Config["icon"], &icon) + _ = ConfigValue(opts.Config["iconCommand"], &iconCommand) _ = ConfigValue(opts.Config["label"], &label) + + // A button whose icon follows a command is repainted every second unless + // the widget sets its own interval. + var defaultInterval time.Duration + if iconCommand != "" { + defaultInterval = time.Second + } + bw.setInterval(time.Duration(opts.Interval)*time.Millisecond, defaultInterval) var fontsize float64 _ = ConfigValue(opts.Config["fontsize"], &fontsize) var color color.Color @@ -36,11 +48,13 @@ func NewButtonWidget(bw *BaseWidget, opts WidgetConfig) (*ButtonWidget, error) { } w := &ButtonWidget{ - BaseWidget: bw, - label: label, - fontsize: fontsize, - color: color, - flatten: flatten, + BaseWidget: bw, + iconPath: icon, + iconCommand: iconCommand, + label: label, + fontsize: fontsize, + color: color, + flatten: flatten, } if icon != "" { if err := w.LoadImage(icon); err != nil { @@ -51,6 +65,27 @@ func NewButtonWidget(bw *BaseWidget, opts WidgetConfig) (*ButtonWidget, error) { return w, nil } +// refreshIcon runs iconCommand and switches to the image file its output +// names. A failing command or an unreadable image keeps the current icon, so a +// missing media player cannot take the daemon down. +func (w *ButtonWidget) refreshIcon() { + out, err := runCommand(w.iconCommand) + if err != nil { + fmt.Fprintf(os.Stderr, "iconCommand failed: %s\n", err) + return + } + + path := strings.TrimSpace(out) + if path == "" || path == w.iconPath { + return + } + if err := w.LoadImage(path); err != nil { + fmt.Fprintf(os.Stderr, "Can't load icon %s: %s\n", path, err) + return + } + w.iconPath = path +} + // LoadImage loads an image from disk. func (w *ButtonWidget) LoadImage(path string) error { path, err := expandPath(w.base, path) @@ -76,6 +111,10 @@ func (w *ButtonWidget) SetImage(img image.Image) { // Update renders the widget. func (w *ButtonWidget) Update() error { + if w.iconCommand != "" { + w.refreshIcon() + } + size := int(w.dev.Pixels) margin := size / 18 height := size - (margin * 2) diff --git a/widget_recent_window.go b/widget_recent_window.go index ff7750d..d058e50 100644 --- a/widget_recent_window.go +++ b/widget_recent_window.go @@ -51,10 +51,10 @@ func (w *RecentWindowWidget) Update() error { img := image.NewRGBA(image.Rect(0, 0, int(w.dev.Pixels), int(w.dev.Pixels))) if int(w.window) < len(recentWindows) { - if w.lastID == recentWindows[w.window].ID { + id := recentWindows[w.window].ID + if w.lastID == id { return nil } - w.lastID = recentWindows[w.window].ID var name string if w.showTitle { @@ -67,7 +67,12 @@ func (w *RecentWindowWidget) Update() error { w.label = name w.SetImage(recentWindows[w.window].Icon) - return w.ButtonWidget.Update() + // A window that did not reach the deck is drawn again next time. + if err := w.ButtonWidget.Update(); err != nil { + return err + } + w.lastID = id + return nil } return w.render(w.dev, img) diff --git a/widget_temp.go b/widget_temp.go new file mode 100644 index 0000000..e66924d --- /dev/null +++ b/widget_temp.go @@ -0,0 +1,253 @@ +package main + +import ( + "fmt" + "image" + "image/color" + "math" + "os" + "path/filepath" + "strconv" + "strings" + "time" +) + +var ( + // warnFillColor and critFillColor fill the bar once a sensor passes its + // warning or critical temperature. + warnFillColor = color.RGBA{246, 116, 0, 255} + critFillColor = color.RGBA{218, 68, 83, 255} +) + +const ( + // defaultCritTemp is the full bar for a sensor that reports no critical + // temperature of its own. + defaultCritTemp = 100.0 + // maxPlausibleTemp bounds the thresholds a sensor reports; NVMe drives + // report 65261.85 °C for sensors without one. + maxPlausibleTemp = 150.0 +) + +// TempWidget shows one hwmon temperature sensor as a bar that fills towards +// the sensor's critical temperature. +type TempWidget struct { + *BaseWidget + + label string + // the hwmon chip (its `name`), the sensor on it (its `temp*_label`, or + // empty for an unlabelled one) and, for a chip with several instances, a + // part of the chip's resolved sysfs device path + chip, sensor, device string + // warning and critical temperatures in °C from the config, or zero to + // take the sensor's own + warn, crit float64 + + color color.Color + fillColor color.Color + + // the sensor's temp*_input and its thresholds, found on the first update + input string + inputWarn, inputCrit float64 + + lastValue float64 + lastError string +} + +// NewTempWidget returns a new TempWidget. +func NewTempWidget(bw *BaseWidget, opts WidgetConfig) *TempWidget { + bw.setInterval(time.Duration(opts.Interval)*time.Millisecond, time.Second) + + w := &TempWidget{BaseWidget: bw} + _ = ConfigValue(opts.Config["label"], &w.label) + _ = ConfigValue(opts.Config["chip"], &w.chip) + _ = ConfigValue(opts.Config["sensor"], &w.sensor) + _ = ConfigValue(opts.Config["device"], &w.device) + _ = ConfigValue(opts.Config["warn"], &w.warn) + _ = ConfigValue(opts.Config["crit"], &w.crit) + _ = ConfigValue(opts.Config["color"], &w.color) + _ = ConfigValue(opts.Config["fillColor"], &w.fillColor) + + if w.label == "" { + w.label = w.sensor + } + if w.color == nil { + w.color = DefaultColor + } + if w.fillColor == nil { + w.fillColor = defaultFillColor + } + + w.Repaint() + return w +} + +// Repaint makes the widget draw again on the next update, even if the +// temperature has not changed since it last drew. +func (w *TempWidget) Repaint() { + w.BaseWidget.Repaint() + w.lastValue = math.NaN() +} + +// Update renders the widget. +func (w *TempWidget) Update() error { + temp, err := w.read() + if err != nil { + // A sensor that is missing or fails to answer shows a dash rather + // than taking the daemon down, and is looked up again after the + // interval, since hwmon numbers change when a driver reloads. + w.input = "" + if msg := err.Error(); msg != w.lastError { + fmt.Fprintf(os.Stderr, "Can't retrieve temperature: %s\n", msg) + w.lastError = msg + } + temp = math.Inf(-1) + } else { + w.lastError = "" + } + + if temp == w.lastValue { + // Nothing to draw, so wait out the interval before asking again. + w.lastUpdate = time.Now() + return nil + } + + m := meter{ + value: "–", + label: w.label, + color: w.color, + fillColor: w.fillColor, + } + if !math.IsInf(temp, -1) { + warn, crit := w.thresholds() + m.fill = temp * 100 / crit + m.value = strconv.Itoa(int(math.Round(temp))) + "°" + switch { + case temp >= crit: + m.fillColor = critFillColor + case warn > 0 && temp >= warn: + m.fillColor = warnFillColor + } + } + + size := int(w.dev.Pixels) + img := image.NewRGBA(image.Rect(0, 0, size, size)) + m.draw(img, img.Bounds(), w.dev.DPI) + + // A value that did not reach the deck is drawn again next time. + if err := w.render(w.dev, img); err != nil { + return err + } + w.lastValue = temp + return nil +} + +// read returns the sensor's temperature in °C, finding the sensor first if +// it has not been found yet. +func (w *TempWidget) read() (float64, error) { + if w.input == "" { + input, err := findTempInput(w.chip, w.sensor, w.device) + if err != nil { + return 0, err + } + w.input = input + w.inputWarn = readTempThreshold(input, "_max") + w.inputCrit = readTempThreshold(input, "_crit") + } + + millidegrees, err := readSysfsInt(w.input) + if err != nil { + return 0, err + } + return float64(millidegrees) / 1000, nil +} + +// thresholds returns the warning and critical temperatures: the config's, +// else the sensor's, else no warning and a critical temperature of 100 °C. +func (w *TempWidget) thresholds() (float64, float64) { + warn, crit := w.warn, w.crit + if warn <= 0 { + warn = w.inputWarn + } + if crit <= 0 { + crit = w.inputCrit + } + if crit <= 0 { + crit = defaultCritTemp + } + if warn >= crit { + warn = 0 + } + return warn, crit +} + +// findTempInput returns the temp*_input file of the hwmon sensor labelled +// `sensor` on the chip named `chip`, or of its unlabelled sensor when `sensor` +// is empty. A non-empty `device` must be part of the chip's resolved device +// path, which tells apart two chips of the same kind, such as two NVMe drives. +func findTempInput(chip, sensor, device string) (string, error) { + dirs, err := filepath.Glob("/sys/class/hwmon/hwmon*") + if err != nil { + return "", err + } + + for _, dir := range dirs { + name, err := readSysfsString(filepath.Join(dir, "name")) + if err != nil || name != chip { + continue + } + if device != "" { + path, err := filepath.EvalSymlinks(filepath.Join(dir, "device")) + if err != nil || !strings.Contains(path, device) { + continue + } + } + + inputs, err := filepath.Glob(filepath.Join(dir, "temp*_input")) + if err != nil { + return "", err + } + for _, input := range inputs { + label, _ := readSysfsString(strings.TrimSuffix(input, "_input") + "_label") + if label == sensor { + return input, nil + } + } + } + + if device != "" { + return "", fmt.Errorf("no %s sensor %q on a device matching %q", chip, sensor, device) + } + return "", fmt.Errorf("no %s sensor %q", chip, sensor) +} + +// readTempThreshold reads the threshold with `suffix` (_max, _crit) beside a +// temp*_input file in °C, or returns zero if the sensor has no plausible one. +func readTempThreshold(input, suffix string) float64 { + millidegrees, err := readSysfsInt(strings.TrimSuffix(input, "_input") + suffix) + if err != nil { + return 0 + } + temp := float64(millidegrees) / 1000 + if temp <= 0 || temp > maxPlausibleTemp { + return 0 + } + return temp +} + +// readSysfsInt reads a sysfs attribute that holds one signed number. +func readSysfsInt(path string) (int64, error) { + data, err := readSysfsString(path) + if err != nil { + return 0, err + } + return strconv.ParseInt(data, 10, 64) +} + +// readSysfsString reads a sysfs attribute without its trailing newline. +func readSysfsString(path string) (string, error) { + data, err := os.ReadFile(path) + if err != nil { + return "", err + } + return strings.TrimSpace(string(data)), nil +} diff --git a/widget_toggle.go b/widget_toggle.go new file mode 100644 index 0000000..f3d066d --- /dev/null +++ b/widget_toggle.go @@ -0,0 +1,122 @@ +package main + +import ( + "fmt" + "reflect" +) + +// repainter is implemented by every widget through BaseWidget. +type repainter interface { + Repaint() +} + +// ToggleWidget shows one of several widgets on a single key. A tap switches to +// the next one, so a key can hold the time and the date, or two meters. +type ToggleWidget struct { + *BaseWidget + + views []Widget + current int +} + +// NewToggleWidget returns a new ToggleWidget. +func NewToggleWidget(bw *BaseWidget, opts WidgetConfig) (*ToggleWidget, error) { + configs, err := toggleViewConfigs(opts.Config["widgets"]) + if err != nil { + return nil, err + } + + // Every view is built once, so a switch keeps what it has fetched and + // starts nothing new in the background. + views := make([]Widget, 0, len(configs)) + for _, c := range configs { + v, err := NewWidget(bw.dev, bw.base, KeyConfig{Index: bw.key, Widget: c}, bw.background) + if err != nil { + return nil, fmt.Errorf("toggle widget: %w", err) + } + views = append(views, v) + } + + return &ToggleWidget{ + BaseWidget: bw, + views: views, + }, nil +} + +// toggleViewConfigs reads the `widgets` list of a toggle widget. Each entry is +// a table shaped like a key's own `widget` table. +func toggleViewConfigs(v interface{}) ([]WidgetConfig, error) { + var tables []map[string]interface{} + switch vt := v.(type) { + case []map[string]interface{}: + tables = vt + case []interface{}: + for _, t := range vt { + table, ok := t.(map[string]interface{}) + if !ok { + return nil, fmt.Errorf("toggle widget: each entry in widgets must be a table, not %v", reflect.TypeOf(t)) + } + tables = append(tables, table) + } + default: + return nil, fmt.Errorf("toggle widget: widgets must be a list of tables, not %v", reflect.TypeOf(v)) + } + if len(tables) < 2 { + return nil, fmt.Errorf("toggle widget: widgets needs at least two entries, has %d", len(tables)) + } + + configs := make([]WidgetConfig, 0, len(tables)) + for i, t := range tables { + var c WidgetConfig + if id, ok := t["id"].(string); ok && id != "" { + c.ID = id + } else { + return nil, fmt.Errorf("toggle widget: entry %d needs an id", i) + } + if interval, ok := t["interval"]; ok { + var ms int64 + if err := ConfigValue(interval, &ms); err != nil || ms < 0 { + return nil, fmt.Errorf("toggle widget: entry %d has an invalid interval %v", i, interval) + } + c.Interval = uint(ms) + } + if config, ok := t["config"]; ok { + table, ok := config.(map[string]interface{}) + if !ok { + return nil, fmt.Errorf("toggle widget: config of entry %d must be a table", i) + } + c.Config = table + } + configs = append(configs, c) + } + + return configs, nil +} + +// RequiresUpdate returns true when the shown widget wants to be repainted. +func (w *ToggleWidget) RequiresUpdate() bool { + return w.views[w.current].RequiresUpdate() +} + +// Update renders the shown widget. +func (w *ToggleWidget) Update() error { + return w.views[w.current].Update() +} + +// Repaint makes the shown widget draw again on the next update. +func (w *ToggleWidget) Repaint() { + if r, ok := w.views[w.current].(repainter); ok { + r.Repaint() + } +} + +// TriggerAction switches to the next widget on a tap. deckmaster calls it only +// for a key without an action of its own. A hold does nothing. +func (w *ToggleWidget) TriggerAction(hold bool) { + if hold { + return + } + + w.current = (w.current + 1) % len(w.views) + w.Repaint() +} diff --git a/widget_top.go b/widget_top.go index 0b377cf..d9707a8 100644 --- a/widget_top.go +++ b/widget_top.go @@ -1,129 +1,297 @@ package main import ( + "errors" "fmt" "image" "image/color" "image/draw" + "math" + "os" + "path/filepath" "strconv" + "strings" "time" "github.com/shirou/gopsutil/cpu" "github.com/shirou/gopsutil/mem" ) -// TopWidget is a widget displaying the current CPU/MEM usage as a bar. +// TopWidget is a widget displaying the current CPU/MEM/GPU usage as bars. +// `mode` holds one mode per bar, split on `;`, and so does `fillColor`: two +// modes share the key as two columns. type TopWidget struct { *BaseWidget - mode string - color color.Color - fillColor color.Color + modes []string + color color.Color + fillColors []color.Color + + // sysfs directory of the GPU the gpu and vram modes read, found on the + // first update + gpuDevice string + // whether the missing GPU has been reported + noGPUReported bool - lastValue float64 + lastValues []float64 } +// defaultFillColor fills a bar that has no fillColor of its own. +var defaultFillColor = color.RGBA{166, 155, 182, 255} + // NewTopWidget returns a new TopWidget. func NewTopWidget(bw *BaseWidget, opts WidgetConfig) *TopWidget { bw.setInterval(time.Duration(opts.Interval)*time.Millisecond, time.Second/2) - var mode string - _ = ConfigValue(opts.Config["mode"], &mode) - var color, fillColor color.Color - _ = ConfigValue(opts.Config["color"], &color) - _ = ConfigValue(opts.Config["fillColor"], &fillColor) + var modes []string + _ = ConfigValue(opts.Config["mode"], &modes) + var textColor color.Color + _ = ConfigValue(opts.Config["color"], &textColor) + var fillColors []color.Color + _ = ConfigValue(opts.Config["fillColor"], &fillColors) - return &TopWidget{ + if textColor == nil { + textColor = DefaultColor + } + for len(fillColors) < len(modes) { + fillColors = append(fillColors, defaultFillColor) + } + + w := &TopWidget{ BaseWidget: bw, - mode: mode, - color: color, - fillColor: fillColor, + modes: modes, + color: textColor, + fillColors: fillColors, + lastValues: make([]float64, len(modes)), } + w.Repaint() + return w } -// Update renders the widget. -func (w *TopWidget) Update() error { - var value float64 - var label string +// Repaint makes the widget draw again on the next update, even if no value +// has changed since it last drew. +func (w *TopWidget) Repaint() { + w.BaseWidget.Repaint() + for i := range w.lastValues { + w.lastValues[i] = math.NaN() + } +} - switch w.mode { +// usage returns the current value of a mode as a percentage, and the label +// its bar carries. +func (w *TopWidget) usage(mode string) (float64, string, error) { + switch mode { case "cpu": cpuUsage, err := cpu.Percent(0, false) if err != nil { - return fmt.Errorf("can't retrieve CPU usage: %s", err) + return 0, "", fmt.Errorf("can't retrieve CPU usage: %s", err) } - - value = cpuUsage[0] - label = "CPU" + return cpuUsage[0], "CPU", nil case "memory": memory, err := mem.VirtualMemory() if err != nil { - return fmt.Errorf("can't retrieve memory usage: %s", err) + return 0, "", fmt.Errorf("can't retrieve memory usage: %s", err) } - value = memory.UsedPercent - label = "MEM" + return memory.UsedPercent, "MEM", nil + + case "gpu", "vram": + usage, err := w.gpuUsage(mode) + return usage, strings.ToUpper(mode), err default: - return fmt.Errorf("unknown widget mode: %s", w.mode) + return 0, "", fmt.Errorf("unknown widget mode: %s", mode) } +} - if w.lastValue == value { - return nil +// gpuUsage returns how busy the GPU is in gpu mode, or how much of its VRAM is +// in use in vram mode, as a percentage. +func (w *TopWidget) gpuUsage(mode string) (float64, error) { + if w.gpuDevice == "" { + device, err := findAMDGPU() + if err != nil { + return 0, err + } + w.gpuDevice = device } - w.lastValue = value - if w.color == nil { - w.color = DefaultColor + if mode == "gpu" { + busy, err := readSysfsUint(filepath.Join(w.gpuDevice, "gpu_busy_percent")) + return float64(busy), err } - if w.fillColor == nil { - w.fillColor = color.RGBA{166, 155, 182, 255} + + used, err := readSysfsUint(filepath.Join(w.gpuDevice, "mem_info_vram_used")) + if err != nil { + return 0, err + } + total, err := readSysfsUint(filepath.Join(w.gpuDevice, "mem_info_vram_total")) + if err != nil { + return 0, err + } + if total == 0 { + return 0, fmt.Errorf("%s reports no VRAM", w.gpuDevice) + } + return float64(used) * 100 / float64(total), nil +} + +// errNoGPU is returned for the gpu and vram modes on a machine without an +// amdgpu card. +var errNoGPU = errors.New("no amdgpu card found in /sys/class/drm") + +// findAMDGPU returns the sysfs device directory of the amdgpu card with the +// most VRAM, which is the discrete one when an integrated GPU sits beside it. +func findAMDGPU() (string, error) { + totals, err := filepath.Glob("/sys/class/drm/card*/device/mem_info_vram_total") + if err != nil { + return "", err + } + + var device string + var most uint64 + for _, path := range totals { + total, err := readSysfsUint(path) + if err != nil || total <= most { + continue + } + device, most = filepath.Dir(path), total + } + if device == "" { + return "", errNoGPU + } + return device, nil +} + +// readSysfsUint reads a sysfs attribute that holds one unsigned number. +func readSysfsUint(path string) (uint64, error) { + data, err := os.ReadFile(path) + if err != nil { + return 0, err + } + return strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64) +} + +// Update renders the widget. +func (w *TopWidget) Update() error { + if len(w.modes) == 0 { + return fmt.Errorf("top widget needs a mode") + } + + values := make([]float64, len(w.modes)) + labels := make([]string, len(w.modes)) + for i, mode := range w.modes { + value, label, err := w.usage(mode) + switch { + case errors.Is(err, errNoGPU): + // A machine without an amdgpu card, a Mac among them, draws the + // bar empty. + if !w.noGPUReported { + fmt.Fprintf(os.Stderr, "Can't retrieve GPU usage: %s\n", err) + w.noGPUReported = true + } + value = math.Inf(-1) + + case err != nil: + if mode != "gpu" && mode != "vram" { + return err + } + // A GPU that fails to answer keeps its last frame rather than + // taking the daemon down, and is asked again after the interval. + fmt.Fprintf(os.Stderr, "Can't retrieve GPU usage: %s\n", err) + w.lastUpdate = time.Now() + return nil + } + values[i], labels[i] = value, label + } + + if equalValues(values, w.lastValues) { + // Nothing to draw, so wait out the interval before asking again. + w.lastUpdate = time.Now() + return nil } size := int(w.dev.Pixels) - margin := size / 18 img := image.NewRGBA(image.Rect(0, 0, size, size)) + for i, frame := range meterColumns(size, len(values)) { + m := meter{ + fill: values[i], + value: strconv.FormatInt(int64(values[i]), 10), + label: labels[i], + color: w.color, + fillColor: w.fillColors[i], + } + if math.IsInf(values[i], -1) { + m.value = "–" + } + if len(values) == 1 { + m.label = "% " + m.label + } + m.draw(img, frame, w.dev.DPI) + } + + // Values that did not reach the deck are drawn again next time. + if err := w.render(w.dev, img); err != nil { + return err + } + w.lastValues = values + return nil +} + +// equalValues reports whether two readings hold the same values. NaN, which +// Repaint leaves behind, equals nothing. +func equalValues(a, b []float64) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// meter is one bar on a key: a frame filled from the bottom up to `fill` +// percent, with `value` inside it and `label` underneath. +type meter struct { + fill float64 + value string + label string + color color.Color + fillColor color.Color +} + +// meterColumns splits a key of `size` pixels into `count` columns of equal +// width, one meter each. +func meterColumns(size, count int) []image.Rectangle { + frames := make([]image.Rectangle, count) + for i := range frames { + frames[i] = image.Rect(size*i/count, 0, size*(i+1)/count, size) + } + return frames +} + +// draw paints the meter into `frame`, a column of img. A full-width frame +// keeps upstream's single bar: 48 px wide with the value at 13 pt. A narrower +// frame gets a slimmer bar and a smaller value. +func (m meter) draw(img *image.RGBA, frame image.Rectangle, dpi uint) { + width, size := frame.Dx(), frame.Dy() + pad, valueSize := width/6, 13.0 + if width < size { + pad, valueSize = width/7, 10 + } + + bar := image.Rect(frame.Min.X+pad, frame.Min.Y+6, frame.Max.X-pad, frame.Max.Y-18) + inner := bar.Inset(1) + fill := inner.Inset(1) + level := math.Max(0, math.Min(100, m.fill)) + fill.Min.Y = fill.Max.Y - int(math.Round(float64(fill.Dy())*level/100)) + + draw.Draw(img, bar, &image.Uniform{m.color}, image.Point{}, draw.Src) + draw.Draw(img, inner, &image.Uniform{color.RGBA{0, 0, 0, 255}}, image.Point{}, draw.Src) + draw.Draw(img, fill, &image.Uniform{m.fillColor}, image.Point{}, draw.Src) + + drawString(img, bar, ttfFont, m.value, dpi, valueSize, m.color, image.Pt(-1, -1)) - draw.Draw(img, - image.Rect(12, 6, size-12, size-18), - &image.Uniform{w.color}, - image.Point{}, draw.Src) - draw.Draw(img, - image.Rect(13, 7, size-14, size-20), - &image.Uniform{color.RGBA{0, 0, 0, 255}}, - image.Point{}, draw.Src) - draw.Draw(img, - image.Rect(14, 7+int(float64(size-26)*(1-value/100)), size-15, size-21), - &image.Uniform{w.fillColor}, - image.Point{}, draw.Src) - - // draw percentage - bounds := img.Bounds() - bounds.Min.Y = 6 - bounds.Max.Y -= 18 - - drawString(img, - bounds, - ttfFont, - strconv.FormatInt(int64(value), 10), - w.dev.DPI, - 13, - w.color, - image.Pt(-1, -1)) - - // draw description - bounds = img.Bounds() - bounds.Min.Y = size - 16 - bounds.Max.Y -= margin - - drawString(img, - bounds, - ttfFont, - "% "+label, - w.dev.DPI, - -1, - w.color, - image.Pt(-1, -1)) - - return w.render(w.dev, img) + caption := image.Rect(frame.Min.X, frame.Max.Y-16, frame.Max.X, frame.Max.Y-size/18) + drawString(img, caption, ttfFont, m.label, dpi, -1, m.color, image.Pt(-1, -1)) } diff --git a/window.go b/window.go index 9efa6e9..a561b15 100644 --- a/window.go +++ b/window.go @@ -1,9 +1,29 @@ package main import ( + "image" + "github.com/muesli/streamdeck" ) +// ActiveWindowChangedEvent gets emitted when the active window changes. +type ActiveWindowChangedEvent struct { + Window Window +} + +// WindowClosedEvent gets emitted when a window gets closed. +type WindowClosedEvent struct { + Window Window +} + +// Window describes an X11 window. +type Window struct { + ID uint32 + Class string + Name string + Icon image.Image +} + func handleActiveWindowChanged(dev *streamdeck.Device, event ActiveWindowChangedEvent) { verbosef("Active window changed to %s (%d, %s)", event.Window.Class, event.Window.ID, event.Window.Name)