Bladeren bron

Port the radio UI to Python, serialize DRM panel access

Replace the C application with a Python one (linux/radio/, launched as
radio-ui sim|i2c|drm), compatible with Python 3.7.3 on the target through
3.14. The panel core stays in C, shared with the kernel driver, and is
loaded through ctypes. Add a test mode taking keys from an X window while
driving the real panel and MPD, plus Python UI tests.

In the DRM driver, let CRTC enable/disable claim the panel from the flush
worker so backlight writes cannot interleave with their transactions,
retry failed backlight writes, and apply a pending backlight change
before suspend. The core only records a new backlight level once the
expander accepted it.

Update the report and README.
k4be 2 weken geleden
bovenliggende
commit
8db27d2e54
28 gewijzigde bestanden met toevoegingen van 2240 en 1872 verwijderingen
  1. 1 0
      .gitignore
  2. 14 32
      Makefile
  3. 44 19
      README.md
  4. 0 94
      app/app.h
  5. 0 241
      app/app_core.c
  6. 0 74
      app/log_kmsg.c
  7. 0 160
      app/main_drm.c
  8. 0 329
      app/main_gtk.c
  9. 0 286
      app/main_i2c.c
  10. 0 269
      app/mpd_client.c
  11. 0 96
      app/platform_linux.c
  12. 0 25
      app/platform_linux.h
  13. 0 216
      app/ui_render.c
  14. 58 31
      docs/REPORT.md
  15. 10 0
      radio-ui
  16. 1 0
      radio/__init__.py
  17. 243 0
      radio/__main__.py
  18. 178 0
      radio/app.py
  19. 186 0
      radio/drm.py
  20. 98 0
      radio/gtkkeys.py
  21. 159 0
      radio/libpanel.c
  22. 289 0
      radio/mpd.py
  23. 136 0
      radio/panel.py
  24. 172 0
      radio/platform.py
  25. 168 0
      radio/render.py
  26. 162 0
      radio/sim.py
  27. 51 0
      radio/state.py
  28. 270 0
      tests/test_ui.py

+ 1 - 0
.gitignore

@@ -5,3 +5,4 @@ driver/.*.cmd
 driver/Module.symvers
 driver/modules.order
 driver/.tmp_versions/
+__pycache__/

+ 14 - 32
Makefile

@@ -1,7 +1,7 @@
 # Linux port: run from this directory.
 #   make test        panel core tests (no hardware, no libraries)
-#   make gtk         window with simulated panel and on-screen keys
-#   make target      i2c-dev and DRM frontends for the real panel
+#   make lib         panel core library for the Python UI (./radio-ui)
+#   make pytest      UI tests: MPD client, rendering, simulated panel
 #   make dtbo        device tree overlay
 #   make module      DRM driver, against KDIR (default: running kernel source)
 
@@ -9,21 +9,16 @@ BUILD   := build
 CC      ?= gcc
 CFLAGS  ?= -O2 -g
 CFLAGS  += -std=gnu11 -Wall -Wextra -MMD -MP
-CFLAGS  += -Idriver -Isim -Iapp
+CFLAGS  += -Idriver -Isim
 KDIR    ?= /usr/src/linux
 
 CORE     := driver/s1d13700_core.c
 SIM      := sim/s1d13700_sim.c
-APP      := app/app_core.c app/ui_render.c app/mpd_client.c app/log_kmsg.c
-PLATFORM := app/platform_linux.c
+PYTHON   ?= python3
+PANEL_LIB := $(BUILD)/libradiopanel.so
 
-APP_PKGS := glib-2.0 cairo pangocairo libmpdclient
-GTK_PKGS := gtk+-3.0 $(APP_PKGS)
-
-objs = $(addprefix $(BUILD)/,$(1:.c=.o))
-
-.PHONY: all test asan gtk target dtbo module clean
-all: test gtk
+.PHONY: all test asan lib pytest dtbo module clean
+all: test lib
 
 # ---- tests -----------------------------------------------------------------
 $(BUILD)/test_panel: tests/test_panel.c $(CORE) $(SIM)
@@ -40,28 +35,15 @@ test: $(BUILD)/test_panel
 asan: $(BUILD)/test_panel_asan
 	$<
 
-# ---- applications ----------------------------------------------------------
-gtk: $(BUILD)/radio-gtk
-target: $(BUILD)/radio-i2c $(BUILD)/radio-drm
-
-$(BUILD)/radio-gtk: CFLAGS += $(shell pkg-config --cflags $(GTK_PKGS))
-$(BUILD)/radio-gtk: LDLIBS += $(shell pkg-config --libs $(GTK_PKGS))
-$(BUILD)/radio-gtk: $(call objs,app/main_gtk.c $(APP) $(CORE) $(SIM))
-	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
+# ---- Python UI -------------------------------------------------------------
+lib: $(PANEL_LIB)
 
-$(BUILD)/radio-i2c: CFLAGS += $(shell pkg-config --cflags $(APP_PKGS))
-$(BUILD)/radio-i2c: LDLIBS += $(shell pkg-config --libs $(APP_PKGS))
-$(BUILD)/radio-i2c: $(call objs,app/main_i2c.c $(PLATFORM) $(APP) $(CORE))
-	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
-
-$(BUILD)/radio-drm: CFLAGS += $(shell pkg-config --cflags $(APP_PKGS) libdrm)
-$(BUILD)/radio-drm: LDLIBS += $(shell pkg-config --libs $(APP_PKGS) libdrm)
-$(BUILD)/radio-drm: $(call objs,app/main_drm.c $(PLATFORM) $(APP))
-	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
-
-$(BUILD)/%.o: %.c
+$(PANEL_LIB): radio/libpanel.c $(CORE) $(SIM)
 	@mkdir -p $(dir $@)
-	$(CC) $(CFLAGS) -c -o $@ $<
+	$(CC) $(CFLAGS) -fPIC -shared -o $@ $^
+
+pytest: $(PANEL_LIB)
+	$(PYTHON) -W 'ignore::DeprecationWarning:gi.events' -m unittest discover -s tests -p 'test_*.py' -v
 
 # ---- device tree and kernel module -----------------------------------------
 dtbo: $(BUILD)/radio-panel.dtbo

+ 44 - 19
README.md

@@ -1,44 +1,68 @@
 # Linux port
 
 Replaces the LPC1114 firmware: the panel and keys hang off I²C expanders on the
-Linux board. The panel runs on real hardware through `radio-i2c`; the DRM
-driver, keys and overlay have not run yet.
+Linux board. The panel runs on real hardware through `radio-ui i2c` and
+`radio-ui drm`; keys and the overlay have not run yet.
 
 | Path | What |
 |---|---|
 | `driver/s1d13700_core.*` | Panel core, used by everything: init, 2 bpp conversion, write planner, TCA9539 stream |
 | `driver/s1d13700_drm.c` | DRM driver (6.x kernels) |
 | `sim/` | Model of the TCA9539 and S1D13700: decodes the I²C bytes and flags bus faults |
-| `app/` | UI and MPD client, plus the frontends: `main_gtk.c`, `main_i2c.c`, `main_drm.c` |
+| `radio/` | The application, in Python: UI, MPD client and the `sim`, `i2c` and `drm` frontends |
+| `radio/libpanel.c` | The panel core and simulator as a library for the application |
+| `radio-ui` | Starts the application |
 | `dts/radio-panel.dts` | Overlay for the keys, backlight and panel |
-| `tests/` | Panel core tests and a fake MPD server |
+| `tests/` | Panel core tests, application tests and a fake MPD server |
 
 ## Building
 
     make test          # panel core tests, no hardware or libraries
-    make gtk           # needs gtk+-3.0, cairo, pangocairo, libmpdclient
-    make target        # i2c-dev and DRM frontends; DRM also needs libdrm
+    make lib           # build/libradiopanel.so, needed by the application
+    make pytest        # application tests, no hardware or display
     make dtbo
     make module KDIR=/path/to/kernel
 
+The application runs on Python 3.7.3 (Debian buster) to 3.14 and needs
+PyGObject with GLib, Pango and PangoCairo, pycairo and its PyGObject bridge;
+GTK 3 for `sim` and `--window-keys`; libdrm for `drm`. On Debian:
+
+    apt install python3-gi python3-gi-cairo gir1.2-pango-1.0 gir1.2-gtk-3.0
+
+`RADIO_PANEL_LIB` points it at the library if it is not in `build/`.
+
 ## Running
 
 Window with the simulated panel, using a real MPD:
 
-    build/radio-gtk --host radio.lo
+    ./radio-ui sim --host radio.lo
 
 The window shows the simulator's display memory, and the traffic each update
 costs. Keys: `Z X C V B` for prev/play/pause/stop/next, arrows, `Enter`, `Esc`,
-`M`, `L`, `Space` for pause.
+`M`, `L`, `Space` for pause, and a multimedia keyboard's media keys.
 
-Real panel through i2c-dev, for bring-up or on a kernel too old for the driver:
+Real panel through i2c-dev, for bring-up or on a kernel too old for the driver,
+or through the DRM driver:
 
-    build/radio-i2c --bus N --pattern geometry
-    build/radio-i2c --bus N --pattern gray
-    build/radio-i2c --bus N --host radio.lo
+    ./radio-ui i2c --bus N --pattern geometry
+    ./radio-ui i2c --bus N --pattern gray
+    ./radio-ui i2c --bus N --host radio.lo
+    ./radio-ui drm --host radio.lo
 
 `--bus` must name a known adapter; motherboard and display buses are always
 refused. Only use the bus number of the adapter the panel is wired to.
+`./radio-ui FRONTEND --help` lists all options.
+
+### Test mode: real panel, PC keyboard
+
+`--window-keys` opens a small window on the X display; keys typed into it (the
+same as in `sim`) go to the app, which drives the real panel and the real MPD:
+
+    ./radio-ui i2c --bus 11 --host radio.lo --window-keys
+    ./radio-ui drm --host radio.lo --window-keys
+
+It also has a button per key. Closing the window quits. Evdev is not read in
+this mode unless `--input` is given as well.
 
 Text uses Verdana and Andale Mono (Microsoft core fonts) if installed, otherwise
 Liberation Sans and Mono, drawn without antialiasing.
@@ -55,14 +79,14 @@ To try the keys without touching the real player, run the fake MPD and point
 the panel at it:
 
     tests/fake_mpd.py 6601 build/mpd-commands.log 5 &
-    build/radio-i2c --bus 11 --host localhost --port 6601
+    ./radio-ui i2c --bus 11 --host localhost --port 6601 --window-keys
 
 Never scan or use the other buses on this PC: some reach the CPU regulators.
 
 ### Simulating keys
 
-The panel frontends read keys from evdev only: the device named `radio-keys`,
-or whatever `--input` names. On the PC without the U2 keypad:
+The panel frontends read keys from evdev: the device named `radio-keys`, or
+whatever `--input` names. On the PC without the U2 keypad:
 
 - **PC keyboard:** `--input /dev/input/by-id/<keyboard>-event-kbd` (needs read
   access, group `input`). Arrows and Esc map directly; the media keys of a
@@ -71,10 +95,10 @@ or whatever `--input` names. On the PC without the U2 keypad:
   ordinary key. The keyboard keeps typing into the focused window too.
 - **Virtual device:** with `CONFIG_INPUT_UINPUT`, create a device named
   `radio-keys` (for example `evemu-device` or python-evdev's `UInput`) and send
-  the codes in `app/platform_linux.c`. `radio-i2c` finds it without `--input`.
+  the codes in `radio/platform.py`. `radio-ui` finds it without `--input`.
   The development kernel has uinput disabled.
-- **Window:** `build/radio-gtk` has every key as a button and shortcut, but
-  draws on the simulated panel only.
+- **Window:** `--window-keys` (above), or `radio-ui sim`, which draws on the
+  simulated panel only.
 
 ## Wiring
 
@@ -110,4 +134,5 @@ internal ones). `INT` goes to a host GPIO with a pull-up.
 ## To confirm on hardware
 
 - TC/R (`--tcr`) for frame rate; 162 comes from the AVR project's 2 bpp setup
-- The DRM driver, keys (`evtest`) and the overlay
+- Keys (`evtest`) and the overlay
+- The application on the target's Python 3.7.3

+ 0 - 94
app/app.h

@@ -1,94 +0,0 @@
-/*
- * Radio UI: everything that is the same in the window and on the real panel.
- * The frontends supply a way to show pixels and feed in key presses.
- */
-#ifndef RADIO_APP_H
-#define RADIO_APP_H
-
-#include <cairo.h>
-#include <glib.h>
-#include <stdbool.h>
-#include <stdint.h>
-
-enum radio_key {
-	RK_ESC, RK_NEXT, RK_STOP, RK_MENU, RK_LIST, RK_UP, RK_PREV,
-	RK_RIGHT, RK_DOWN, RK_PAUSE, RK_OK, RK_LEFT, RK_PLAY,
-	RK_COUNT
-};
-
-enum play_state { PLAY_UNKNOWN, PLAY_PLAYING, PLAY_PAUSED, PLAY_STOPPED };
-
-#define LOG_ROWS	7
-#define LOG_COLS	44
-#define TITLE_MAX	512
-
-struct radio_state {
-	bool connected;
-	char server[128];
-
-	enum play_state state;
-	char title[TITLE_MAX];
-	int song_pos;		/* -1: none */
-	unsigned int queue_len;
-	unsigned int elapsed_ms;
-	gint64 elapsed_stamp_us;	/* monotonic time elapsed_ms was read */
-	unsigned int total_ms;	/* 0: unknown, e.g. a stream */
-	int volume;		/* -1: unknown */
-	bool repeat, random;
-
-	char log[LOG_ROWS][LOG_COLS * 4 + 1];	/* UTF-8, wrapped */
-};
-
-/* Current position, advanced locally between MPD updates while playing */
-unsigned int radio_state_elapsed_ms(const struct radio_state *s);
-
-/* ---- rendering ---------------------------------------------------------- */
-void ui_render(cairo_t *cr, const struct radio_state *s, int width, int height);
-
-/* ---- app ---------------------------------------------------------------- */
-struct app_frontend {
-	void *ctx;
-	/* pixels is the whole frame; (x, y, w, h) bounds what changed */
-	void (*present)(void *ctx, const uint32_t *pixels, int stride,
-			int x, int y, int w, int h);
-	void (*backlight)(void *ctx, bool on);
-};
-
-struct app_options {
-	const char *host;
-	unsigned int port;
-	int width, height;
-	bool kmsg;		/* show this machine's kernel log */
-};
-
-struct app;
-
-struct app *app_new(const struct app_options *opt, const struct app_frontend *fe);
-void app_free(struct app *app);
-void app_key(struct app *app, enum radio_key key);
-void app_log(struct app *app, const char *text);
-
-/* ---- MPD client --------------------------------------------------------- */
-struct mpdc;
-
-enum mpdc_command {
-	MPDC_PLAY, MPDC_TOGGLE, MPDC_STOP, MPDC_NEXT, MPDC_PREV,
-	MPDC_VOLUME_UP, MPDC_VOLUME_DOWN, MPDC_REFRESH,
-};
-
-/* Called on the GLib main loop whenever *state may have changed */
-typedef void (*mpdc_changed_fn)(void *user);
-typedef void (*mpdc_log_fn)(void *user, const char *text);
-
-struct mpdc *mpdc_new(const char *host, unsigned int port, struct radio_state *state,
-		      mpdc_changed_fn changed, mpdc_log_fn log, void *user);
-void mpdc_free(struct mpdc *m);
-void mpdc_command(struct mpdc *m, enum mpdc_command cmd);
-
-/* ---- kernel log --------------------------------------------------------- */
-struct log_kmsg;
-
-struct log_kmsg *log_kmsg_new(mpdc_log_fn log, void *user);
-void log_kmsg_free(struct log_kmsg *k);
-
-#endif /* RADIO_APP_H */

+ 0 - 241
app/app_core.c

@@ -1,241 +0,0 @@
-#include <stdlib.h>
-#include <string.h>
-
-#include "app.h"
-
-#define BACKLIGHT_TIMEOUT_S	30
-#define KEY_LOCKOUT_US		300000	/* as the firmware: 300 ms after a press */
-#define LOG_REDRAW_MS		1000	/* scrolling is the costliest redraw */
-
-struct app {
-	struct app_options opt;
-	struct app_frontend fe;
-	struct radio_state state;
-	struct mpdc *mpd;
-	struct log_kmsg *kmsg;
-
-	cairo_surface_t *surface;
-	uint32_t *prev;
-	bool prev_valid;
-
-	guint render_id;
-	guint log_timer_id;
-	guint tick_id;
-	guint backlight_id;
-	gint64 key_time_us[RK_COUNT];
-};
-
-unsigned int radio_state_elapsed_ms(const struct radio_state *s)
-{
-	gint64 extra;
-	unsigned int ms = s->elapsed_ms;
-
-	/* with the link down the player's position is unknown, so hold it */
-	if (!s->connected || s->state != PLAY_PLAYING || !s->elapsed_stamp_us)
-		return ms;
-	extra = (g_get_monotonic_time() - s->elapsed_stamp_us) / 1000;
-	ms += (unsigned int)extra;
-	return (s->total_ms && ms > s->total_ms) ? s->total_ms : ms;
-}
-
-/* Render, and hand the frontend the bounding box of what actually changed */
-static gboolean render_now(gpointer data)
-{
-	struct app *app = data;
-	int w = app->opt.width, h = app->opt.height;
-	int stride, x, y, x0 = w, y0 = h, x1 = 0, y1 = 0;
-	const uint32_t *pixels;
-	cairo_t *cr;
-
-	app->render_id = 0;
-
-	cr = cairo_create(app->surface);
-	ui_render(cr, &app->state, w, h);
-	cairo_destroy(cr);
-	cairo_surface_flush(app->surface);
-
-	pixels = (const uint32_t *)cairo_image_surface_get_data(app->surface);
-	stride = cairo_image_surface_get_stride(app->surface);
-
-	for (y = 0; y < h; y++) {
-		const uint32_t *a = (const uint32_t *)((const char *)pixels + y * stride);
-		const uint32_t *b = app->prev + y * w;
-
-		if (app->prev_valid && !memcmp(a, b, (size_t)w * 4))
-			continue;
-		for (x = 0; x < w; x++) {
-			if (app->prev_valid && a[x] == b[x])
-				continue;
-			if (x < x0)
-				x0 = x;
-			if (x >= x1)
-				x1 = x + 1;
-		}
-		if (y < y0)
-			y0 = y;
-		y1 = y + 1;
-		memcpy(app->prev + y * w, a, (size_t)w * 4);
-	}
-	app->prev_valid = true;
-
-	if (x1 > x0)
-		app->fe.present(app->fe.ctx, pixels, stride, x0, y0, x1 - x0, y1 - y0);
-	return G_SOURCE_REMOVE;
-}
-
-static void schedule_render(struct app *app)
-{
-	if (!app->render_id)
-		app->render_id = g_idle_add(render_now, app);
-}
-
-static void on_mpd_changed(void *user)
-{
-	schedule_render(user);
-}
-
-static gboolean log_timer(gpointer data)
-{
-	struct app *app = data;
-
-	app->log_timer_id = 0;
-	schedule_render(app);
-	return G_SOURCE_REMOVE;
-}
-
-/* Append one wrapped row, scrolling the pane; batched into one redraw */
-static void log_push_row(struct app *app, const char *start, const char *end)
-{
-	struct radio_state *s = &app->state;
-	size_t len = (size_t)(end - start);
-
-	memmove(s->log[0], s->log[1], sizeof(s->log[0]) * (LOG_ROWS - 1));
-	if (len > sizeof(s->log[0]) - 1)
-		len = sizeof(s->log[0]) - 1;
-	memcpy(s->log[LOG_ROWS - 1], start, len);
-	s->log[LOG_ROWS - 1][len] = '\0';
-}
-
-void app_log(struct app *app, const char *text)
-{
-	char *clean = g_utf8_make_valid(text, -1);
-	const char *p = clean;
-
-	do {
-		const char *q = p;
-		int n = 0;
-
-		while (*q && n < LOG_COLS) {
-			q = g_utf8_next_char(q);
-			n++;
-		}
-		log_push_row(app, p, q);
-		p = q;
-	} while (*p);
-
-	g_free(clean);
-
-	if (!app->log_timer_id)
-		app->log_timer_id = g_timeout_add(LOG_REDRAW_MS, log_timer, app);
-}
-
-static void on_log(void *user, const char *text)
-{
-	app_log(user, text);
-}
-
-static gboolean tick(gpointer data)
-{
-	struct app *app = data;
-
-	if (app->state.state == PLAY_PLAYING)
-		schedule_render(app);
-	return G_SOURCE_CONTINUE;
-}
-
-static gboolean backlight_expired(gpointer data)
-{
-	struct app *app = data;
-
-	app->backlight_id = 0;
-	if (app->fe.backlight)
-		app->fe.backlight(app->fe.ctx, false);
-	return G_SOURCE_REMOVE;
-}
-
-static void backlight_wake(struct app *app)
-{
-	if (app->fe.backlight)
-		app->fe.backlight(app->fe.ctx, true);
-	if (app->backlight_id)
-		g_source_remove(app->backlight_id);
-	app->backlight_id = g_timeout_add_seconds(BACKLIGHT_TIMEOUT_S,
-						  backlight_expired, app);
-}
-
-void app_key(struct app *app, enum radio_key key)
-{
-	gint64 now = g_get_monotonic_time();
-
-	if ((unsigned int)key >= RK_COUNT)
-		return;
-	if (now - app->key_time_us[key] < KEY_LOCKOUT_US)
-		return;
-	app->key_time_us[key] = now;
-
-	backlight_wake(app);
-
-	switch (key) {
-	case RK_PREV:	mpdc_command(app->mpd, MPDC_PREV); break;
-	case RK_PLAY:	mpdc_command(app->mpd, MPDC_PLAY); break;
-	case RK_PAUSE:	mpdc_command(app->mpd, MPDC_TOGGLE); break;
-	case RK_STOP:	mpdc_command(app->mpd, MPDC_STOP); break;
-	case RK_NEXT:	mpdc_command(app->mpd, MPDC_NEXT); break;
-	case RK_ESC:	mpdc_command(app->mpd, MPDC_REFRESH); break;
-	case RK_UP:	mpdc_command(app->mpd, MPDC_VOLUME_UP); break;
-	case RK_DOWN:	mpdc_command(app->mpd, MPDC_VOLUME_DOWN); break;
-	default:	break;	/* MENU, LIST, OK, LEFT, RIGHT: not assigned yet */
-	}
-}
-
-struct app *app_new(const struct app_options *opt, const struct app_frontend *fe)
-{
-	struct app *app = g_new0(struct app, 1);
-
-	app->opt = *opt;
-	app->fe = *fe;
-	app->state.song_pos = -1;
-	app->state.volume = -1;
-	g_strlcpy(app->state.server, opt->host, sizeof(app->state.server));
-
-	app->surface = cairo_image_surface_create(CAIRO_FORMAT_RGB24,
-						  opt->width, opt->height);
-	app->prev = g_new0(uint32_t, (gsize)opt->width * opt->height);
-
-	app->mpd = mpdc_new(opt->host, opt->port, &app->state,
-			    on_mpd_changed, on_log, app);
-	if (opt->kmsg)
-		app->kmsg = log_kmsg_new(on_log, app);
-
-	app->tick_id = g_timeout_add_seconds(1, tick, app);
-	backlight_wake(app);
-	schedule_render(app);
-	return app;
-}
-
-void app_free(struct app *app)
-{
-	if (app->render_id)
-		g_source_remove(app->render_id);
-	if (app->log_timer_id)
-		g_source_remove(app->log_timer_id);
-	if (app->backlight_id)
-		g_source_remove(app->backlight_id);
-	g_source_remove(app->tick_id);
-	if (app->kmsg)
-		log_kmsg_free(app->kmsg);
-	mpdc_free(app->mpd);
-	cairo_surface_destroy(app->surface);
-	g_free(app->prev);
-	g_free(app);
-}

+ 0 - 74
app/log_kmsg.c

@@ -1,74 +0,0 @@
-/* Kernel log pane source: follows /dev/kmsg from the moment it is opened. */
-#include <errno.h>
-#include <fcntl.h>
-#include <glib-unix.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "app.h"
-
-struct log_kmsg {
-	int fd;
-	guint watch_id;
-	mpdc_log_fn log;
-	void *user;
-};
-
-static gboolean on_kmsg(gint fd, GIOCondition cond, gpointer data)
-{
-	struct log_kmsg *k = data;
-	char buf[4096];
-	ssize_t n;
-
-	(void)cond;
-	for (;;) {
-		char *text, *end;
-
-		n = read(fd, buf, sizeof(buf) - 1);
-		if (n < 0 && errno == EPIPE)
-			continue;	/* records were overwritten; carry on */
-		if (n <= 0)
-			break;
-		buf[n] = '\0';
-
-		/* "prio,seq,usec,flags;message\n" then optional " KEY=value" lines */
-		text = strchr(buf, ';');
-		if (!text)
-			continue;
-		text++;
-		end = strchr(text, '\n');
-		if (end)
-			*end = '\0';
-		k->log(k->user, text);
-	}
-	if (n == 0 || (n < 0 && errno != EAGAIN)) {
-		k->watch_id = 0;
-		return G_SOURCE_REMOVE;
-	}
-	return G_SOURCE_CONTINUE;
-}
-
-struct log_kmsg *log_kmsg_new(mpdc_log_fn log, void *user)
-{
-	struct log_kmsg *k = g_new0(struct log_kmsg, 1);
-
-	k->log = log;
-	k->user = user;
-	k->fd = open("/dev/kmsg", O_RDONLY | O_NONBLOCK | O_CLOEXEC);
-	if (k->fd < 0) {
-		log(user, "Nie można otworzyć /dev/kmsg");
-		return k;
-	}
-	lseek(k->fd, 0, SEEK_END);
-	k->watch_id = g_unix_fd_add(k->fd, G_IO_IN, on_kmsg, k);
-	return k;
-}
-
-void log_kmsg_free(struct log_kmsg *k)
-{
-	if (k->watch_id)
-		g_source_remove(k->watch_id);
-	if (k->fd >= 0)
-		close(k->fd);
-	g_free(k);
-}

+ 0 - 160
app/main_drm.c

@@ -1,160 +0,0 @@
-/*
- * UI on the panel through the s1d13700-tca DRM driver: one dumb buffer, with
- * each change reported as a dirty rectangle.
- */
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/mman.h>
-#include <unistd.h>
-#include <xf86drm.h>
-#include <xf86drmMode.h>
-
-#include "platform_linux.h"
-
-#define DRIVER_NAME	"s1d13700-tca"
-
-struct drm_dev {
-	int fd;
-	uint32_t fb_id, pitch;
-	uint8_t *map;
-	const char *backlight;
-};
-
-/* Only ever our own device: never take over the machine's real display */
-static int open_panel(void)
-{
-	char path[32];
-	int i, fd;
-
-	for (i = 0; i < 16; i++) {
-		drmVersionPtr v;
-		bool match;
-
-		snprintf(path, sizeof(path), "/dev/dri/card%d", i);
-		fd = open(path, O_RDWR | O_CLOEXEC);
-		if (fd < 0)
-			continue;
-		v = drmGetVersion(fd);
-		match = v && !strcmp(v->name, DRIVER_NAME);
-		drmFreeVersion(v);
-		if (match)
-			return fd;
-		close(fd);
-	}
-	return -1;
-}
-
-static int setup_output(struct drm_dev *d, drmModeModeInfo *mode)
-{
-	drmModeRes *res = drmModeGetResources(d->fd);
-	drmModeConnector *conn;
-	uint32_t handles[4] = { 0 }, pitches[4] = { 0 }, offsets[4] = { 0 };
-	uint32_t handle, pitch, crtc;
-	uint64_t size, offset;
-	int ret = -1;
-
-	if (!res || res->count_connectors < 1 || res->count_crtcs < 1)
-		goto out_res;
-	conn = drmModeGetConnector(d->fd, res->connectors[0]);
-	if (!conn || conn->count_modes < 1)
-		goto out_conn;
-
-	*mode = conn->modes[0];
-	crtc = res->crtcs[0];
-
-	if (drmModeCreateDumbBuffer(d->fd, mode->hdisplay, mode->vdisplay, 32, 0,
-				    &handle, &pitch, &size))
-		goto out_conn;
-	handles[0] = handle;
-	pitches[0] = pitch;
-	if (drmModeAddFB2(d->fd, mode->hdisplay, mode->vdisplay,
-			  0x34325258 /* XR24 */, handles, pitches, offsets, &d->fb_id, 0))
-		goto out_conn;
-	if (drmModeMapDumbBuffer(d->fd, handle, &offset))
-		goto out_conn;
-	d->map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, d->fd, (off_t)offset);
-	if (d->map == MAP_FAILED)
-		goto out_conn;
-	memset(d->map, 0xff, size);
-	d->pitch = pitch;
-
-	if (drmModeSetCrtc(d->fd, crtc, d->fb_id, 0, 0, &conn->connector_id, 1, mode))
-		goto out_conn;
-	ret = 0;
-out_conn:
-	drmModeFreeConnector(conn);
-out_res:
-	drmModeFreeResources(res);
-	return ret;
-}
-
-static void present(void *ctx, const uint32_t *pixels, int stride, int x, int y, int w, int h)
-{
-	struct drm_dev *d = ctx;
-	drmModeClip clip = { (uint16_t)x, (uint16_t)y, (uint16_t)(x + w), (uint16_t)(y + h) };
-	int row;
-
-	for (row = y; row < y + h; row++)
-		memcpy(d->map + (size_t)row * d->pitch + (size_t)x * 4,
-		       (const char *)pixels + row * stride + x * 4, (size_t)w * 4);
-	if (drmModeDirtyFB(d->fd, d->fb_id, &clip, 1))
-		g_printerr("DIRTYFB failed: %s\n", strerror(errno));
-}
-
-static void backlight(void *ctx, bool on)
-{
-	platform_backlight_set(((struct drm_dev *)ctx)->backlight, on);
-}
-
-int main(int argc, char **argv)
-{
-	static struct drm_dev d;
-	static int port = 6600;
-	static char *host, *input, *blpath;
-	static gboolean kmsg;
-	static GOptionEntry entries[] = {
-		{ "host", 0, 0, G_OPTION_ARG_STRING, &host, "MPD host (localhost)", "NAME" },
-		{ "port", 0, 0, G_OPTION_ARG_INT, &port, "MPD port (6600)", "N" },
-		{ "input", 0, 0, G_OPTION_ARG_FILENAME, &input, "Key input device (auto: " DEFAULT_KEYS_NAME ")", "PATH" },
-		{ "backlight", 0, 0, G_OPTION_ARG_FILENAME, &blpath, "Backlight sysfs brightness file", "PATH" },
-		{ "kmsg", 0, 0, G_OPTION_ARG_NONE, &kmsg, "Show the kernel log", NULL },
-		{ NULL, 0, 0, 0, NULL, NULL, NULL },
-	};
-	GOptionContext *ctx = g_option_context_new("- radio panel over DRM");
-	struct app_frontend fe = { &d, present, backlight };
-	struct app_options opt;
-	drmModeModeInfo mode;
-	GError *err = NULL;
-	struct app *app;
-
-	g_option_context_add_main_entries(ctx, entries, NULL);
-	if (!g_option_context_parse(ctx, &argc, &argv, &err)) {
-		g_printerr("%s\n", err->message);
-		return 1;
-	}
-	d.backlight = blpath ? blpath : DEFAULT_BACKLIGHT;
-
-	d.fd = open_panel();
-	if (d.fd < 0) {
-		g_printerr("no %s DRM device found\n", DRIVER_NAME);
-		return 1;
-	}
-	if (setup_output(&d, &mode)) {
-		g_printerr("cannot set up the display: %s\n", strerror(errno));
-		return 1;
-	}
-
-	opt = (struct app_options){ host ? host : "localhost", port,
-				    mode.hdisplay, mode.vdisplay, kmsg };
-	app = app_new(&opt, &fe);
-	if (!platform_keys_start(app, input))
-		g_printerr("no key input device, running display-only\n");
-
-	platform_run();
-
-	app_free(app);
-	return 0;
-}

+ 0 - 329
app/main_gtk.c

@@ -1,329 +0,0 @@
-/*
- * Development window. Frames take the real path: conversion, planner, TCA9539
- * byte stream, then the simulated expander and controller. The window shows
- * the simulator's display memory, so it is what the panel would receive.
- */
-#include <gdk/gdkkeysyms.h>
-#include <gtk/gtk.h>
-#include <stdio.h>
-#include <string.h>
-
-#include "app.h"
-#include "s1d13700_core.h"
-#include "s1d13700_sim.h"
-
-#define SCL_HZ		400000
-#define TX_CAP		1025	/* the driver's message limit */
-
-struct gui {
-	struct app *app;
-	struct s1d_config cfg;
-	struct s1d_panel panel;
-	struct s1d_sim sim;
-	uint8_t shadow[S1D_VRAM_SIZE];
-	uint8_t next[S1D_VRAM_SIZE];
-	uint8_t tx[TX_CAP];
-	uint8_t *levels;
-
-	cairo_surface_t *image;
-	GtkWidget *window, *lcd, *stats;
-	GtkWidget *buttons[RK_COUNT];
-	bool backlight;
-	unsigned long total_bytes;
-	guint frames;
-	int scale;
-
-	gchar **press;
-	int press_next;
-	const char *snapshot;
-};
-
-static const struct key_def {
-	enum radio_key key;
-	const char *label;
-	guint keyval, keyval2;
-	int col, row;		/* button grid */
-} key_defs[] = {
-	{ RK_PREV,  "⏮ Prev (Z)",   GDK_KEY_z, GDK_KEY_Z, 0, 0 },
-	{ RK_PLAY,  "▶ Play (X)",   GDK_KEY_x, GDK_KEY_X, 1, 0 },
-	{ RK_PAUSE, "⏯ Pause (C)",  GDK_KEY_c, GDK_KEY_space, 2, 0 },
-	{ RK_STOP,  "⏹ Stop (V)",   GDK_KEY_v, GDK_KEY_V, 3, 0 },
-	{ RK_NEXT,  "⏭ Next (B)",   GDK_KEY_b, GDK_KEY_B, 4, 0 },
-	{ RK_ESC,   "Esc",          GDK_KEY_Escape, 0, 0, 1 },
-	{ RK_UP,    "▲ Vol+ (↑)",   GDK_KEY_Up, 0, 2, 1 },
-	{ RK_MENU,  "Menu (M)",     GDK_KEY_m, GDK_KEY_M, 4, 1 },
-	{ RK_LEFT,  "◀ (←)",        GDK_KEY_Left, 0, 1, 2 },
-	{ RK_OK,    "OK (Enter)",   GDK_KEY_Return, GDK_KEY_KP_Enter, 2, 2 },
-	{ RK_RIGHT, "▶ (→)",        GDK_KEY_Right, 0, 3, 2 },
-	{ RK_DOWN,  "▼ Vol− (↓)",   GDK_KEY_Down, 0, 2, 3 },
-	{ RK_LIST,  "List (L)",     GDK_KEY_l, GDK_KEY_L, 4, 3 },
-};
-
-static int sim_xfer(void *ctx, const uint8_t *buf, size_t len)
-{
-	s1d_sim_i2c_write(ctx, buf, len);
-	return 0;
-}
-
-static void sim_delay(void *ctx, unsigned int ms)
-{
-	(void)ctx;
-	(void)ms;
-}
-
-static const struct s1d_ops sim_ops = { sim_xfer, sim_delay };
-
-static void update_image(struct gui *g)
-{
-	unsigned int w = g->cfg.width, h = g->cfg.height, x, y;
-	/* LCD look, from background to darkest level */
-	static const uint32_t lit[] = { 0xc4d890, 0x8ca060, 0x506438, 0x142010 };
-	static const uint32_t dark[] = { 0x4a5238, 0x363e2a, 0x242a1e, 0x101410 };
-	const uint32_t *pal = g->backlight ? lit : dark;
-	uint8_t *data;
-	int stride;
-	bool shown;
-
-	shown = s1d_sim_render(&g->sim, w, h, g->levels);
-	cairo_surface_flush(g->image);
-	data = cairo_image_surface_get_data(g->image);
-	stride = cairo_image_surface_get_stride(g->image);
-
-	for (y = 0; y < h; y++) {
-		uint32_t *row = (uint32_t *)(data + y * stride);
-
-		for (x = 0; x < w; x++)
-			row[x] = shown ? pal[g->levels[y * w + x] & 3] : pal[0];
-	}
-	cairo_surface_mark_dirty(g->image);
-	gtk_widget_queue_draw(g->lcd);
-}
-
-static void present(void *ctx, const uint32_t *pixels, int stride, int x, int y, int w, int h)
-{
-	struct gui *g = ctx;
-	char text[256];
-	int err, faults;
-
-	s1d_convert_xrgb8888(&g->cfg, pixels, stride, g->next, x, y, x + w, y + h);
-
-	memset(&g->panel.stats, 0, sizeof(g->panel.stats));
-	err = s1d_panel_update(&g->panel, g->next, y, y + h);
-	g->total_bytes += g->panel.stats.i2c_bytes;
-	g->frames++;
-	faults = s1d_sim_fault_count(&g->sim);
-
-	snprintf(text, sizeof(text),
-		 "last update: %lu LCD writes, %lu seeks, %lu I²C bytes, %.1f ms at 400 kHz  |  "
-		 "total %lu bytes in %u updates%s",
-		 g->panel.stats.writes, g->panel.stats.seeks, g->panel.stats.i2c_bytes,
-		 s1d_stats_bus_us(&g->panel.stats, SCL_HZ) / 1000.0,
-		 g->total_bytes, g->frames,
-		 err || faults ? "  |  BUS FAULTS, see stderr" : "");
-	gtk_label_set_text(GTK_LABEL(g->stats), text);
-	if (faults)
-		g_printerr("simulator faults: %d\n", faults);
-
-	update_image(g);
-}
-
-static void backlight(void *ctx, bool on)
-{
-	struct gui *g = ctx;
-
-	g->backlight = on;
-	update_image(g);
-}
-
-static gboolean lcd_draw(GtkWidget *w, cairo_t *cr, gpointer data)
-{
-	struct gui *g = data;
-
-	(void)w;
-	cairo_scale(cr, g->scale, g->scale);
-	cairo_set_source_surface(cr, g->image, 0, 0);
-	cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_NEAREST);
-	cairo_paint(cr);
-	return TRUE;
-}
-
-static void key_clicked(GtkButton *b, gpointer data)
-{
-	struct gui *g = data;
-
-	app_key(g->app, GPOINTER_TO_INT(g_object_get_data(G_OBJECT(b), "key")));
-}
-
-static gboolean key_press(GtkWidget *w, GdkEventKey *ev, gpointer data)
-{
-	struct gui *g = data;
-	unsigned int i;
-
-	(void)w;
-	for (i = 0; i < G_N_ELEMENTS(key_defs); i++) {
-		if (ev->keyval == key_defs[i].keyval ||
-		    (key_defs[i].keyval2 && ev->keyval == key_defs[i].keyval2)) {
-			app_key(g->app, key_defs[i].key);
-			return TRUE;
-		}
-	}
-	return FALSE;
-}
-
-static void build_window(struct gui *g)
-{
-	GtkWidget *box, *grid;
-	unsigned int i;
-
-	g->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
-	gtk_window_set_title(GTK_WINDOW(g->window), "Radio panel simulator");
-	gtk_window_set_resizable(GTK_WINDOW(g->window), FALSE);
-	g_signal_connect(g->window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
-	g_signal_connect(g->window, "key-press-event", G_CALLBACK(key_press), g);
-
-	box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
-	gtk_container_set_border_width(GTK_CONTAINER(box), 8);
-	gtk_container_add(GTK_CONTAINER(g->window), box);
-
-	g->lcd = gtk_drawing_area_new();
-	gtk_widget_set_size_request(g->lcd, (int)g->cfg.width * g->scale,
-				    (int)g->cfg.height * g->scale);
-	g_signal_connect(g->lcd, "draw", G_CALLBACK(lcd_draw), g);
-	gtk_box_pack_start(GTK_BOX(box), g->lcd, FALSE, FALSE, 0);
-
-	g->stats = gtk_label_new("");
-	gtk_label_set_xalign(GTK_LABEL(g->stats), 0);
-	gtk_label_set_line_wrap(GTK_LABEL(g->stats), TRUE);
-	gtk_label_set_max_width_chars(GTK_LABEL(g->stats), 60);
-	gtk_box_pack_start(GTK_BOX(box), g->stats, FALSE, FALSE, 0);
-
-	grid = gtk_grid_new();
-	gtk_grid_set_row_spacing(GTK_GRID(grid), 4);
-	gtk_grid_set_column_spacing(GTK_GRID(grid), 4);
-	gtk_grid_set_column_homogeneous(GTK_GRID(grid), TRUE);
-	gtk_box_pack_start(GTK_BOX(box), grid, FALSE, FALSE, 0);
-
-	for (i = 0; i < G_N_ELEMENTS(key_defs); i++) {
-		const struct key_def *d = &key_defs[i];
-		GtkWidget *b = gtk_button_new_with_label(d->label);
-
-		/* a focused button would take Space and Enter from the shortcuts */
-		gtk_widget_set_can_focus(b, FALSE);
-		g_object_set_data(G_OBJECT(b), "key", GINT_TO_POINTER(d->key));
-		g_signal_connect(b, "clicked", G_CALLBACK(key_clicked), g);
-		gtk_grid_attach(GTK_GRID(grid), b, d->col, d->row, 1, 1);
-		g->buttons[d->key] = b;
-	}
-}
-
-/* ---- scripted runs, for automated checks -------------------------------- */
-
-static const char *const key_names[RK_COUNT] = {
-	[RK_ESC] = "esc", [RK_NEXT] = "next", [RK_STOP] = "stop",
-	[RK_MENU] = "menu", [RK_LIST] = "list", [RK_UP] = "up",
-	[RK_PREV] = "prev", [RK_RIGHT] = "right", [RK_DOWN] = "down",
-	[RK_PAUSE] = "pause", [RK_OK] = "ok", [RK_LEFT] = "left",
-	[RK_PLAY] = "play",
-};
-
-static gboolean press_next(gpointer data)
-{
-	struct gui *g = data;
-	const char *name = g->press[g->press_next];
-	int i;
-
-	if (!name)
-		return G_SOURCE_REMOVE;
-	g->press_next++;
-	for (i = 0; i < RK_COUNT; i++)
-		if (!strcmp(name, key_names[i]))
-			gtk_button_clicked(GTK_BUTTON(g->buttons[i]));
-	return G_SOURCE_CONTINUE;
-}
-
-static gboolean finish(gpointer data)
-{
-	struct gui *g = data;
-
-	if (g->snapshot) {
-		GtkAllocation a;
-		cairo_surface_t *s;
-		cairo_t *cr;
-
-		gtk_widget_get_allocation(g->window, &a);
-		s = cairo_image_surface_create(CAIRO_FORMAT_RGB24, a.width, a.height);
-		cr = cairo_create(s);
-		gtk_widget_draw(g->window, cr);
-		cairo_destroy(cr);
-		cairo_surface_write_to_png(s, g->snapshot);
-		cairo_surface_destroy(s);
-	}
-	gtk_main_quit();
-	return G_SOURCE_REMOVE;
-}
-
-int main(int argc, char **argv)
-{
-	static struct gui g;
-	static char *host, *press, *snapshot;
-	static int port = 6600, width = 240, height = 160, bpp = 2, tcr = 162;
-	static int scale = 3, exit_after;
-	static gboolean kmsg;
-	static GOptionEntry entries[] = {
-		{ "host", 0, 0, G_OPTION_ARG_STRING, &host, "MPD host (radio.lo)", "NAME" },
-		{ "port", 0, 0, G_OPTION_ARG_INT, &port, "MPD port (6600)", "N" },
-		{ "width", 0, 0, G_OPTION_ARG_INT, &width, "Panel width (240)", "PX" },
-		{ "height", 0, 0, G_OPTION_ARG_INT, &height, "Panel height (160)", "PX" },
-		{ "bpp", 0, 0, G_OPTION_ARG_INT, &bpp, "Bits per pixel: 1, 2, 4 (2)", "N" },
-		{ "scale", 0, 0, G_OPTION_ARG_INT, &scale, "Window zoom (3)", "N" },
-		{ "kmsg", 0, 0, G_OPTION_ARG_NONE, &kmsg, "Show this machine's kernel log", NULL },
-		{ "press", 0, 0, G_OPTION_ARG_STRING, &press, "Click these keys, comma separated", "LIST" },
-		{ "snapshot", 0, 0, G_OPTION_ARG_FILENAME, &snapshot, "Write the window to a PNG before exiting", "FILE" },
-		{ "exit-after", 0, 0, G_OPTION_ARG_INT, &exit_after, "Quit after this many ms", "MS" },
-		{ NULL, 0, 0, 0, NULL, NULL, NULL },
-	};
-	struct app_frontend fe = { &g, present, backlight };
-	struct app_options opt;
-	GError *err = NULL;
-	guint64 size;
-
-	if (!gtk_init_with_args(&argc, &argv, NULL, entries, NULL, &err)) {
-		g_printerr("%s\n", err ? err->message : "cannot open display");
-		return 1;
-	}
-
-	g.cfg = (struct s1d_config){ width, height, bpp, tcr };
-	g.scale = scale;
-	g.backlight = true;
-	g.snapshot = snapshot;
-
-	s1d_sim_init(&g.sim);
-	if (s1d_panel_setup(&g.panel, &g.cfg, &sim_ops, &g.sim, g.shadow, g.tx, sizeof(g.tx)) ||
-	    s1d_panel_init(&g.panel)) {
-		g_printerr("invalid panel configuration\n");
-		return 1;
-	}
-
-	size = (guint64)width * height;
-	g.levels = g_malloc(size);
-	g.image = cairo_image_surface_create(CAIRO_FORMAT_RGB24, width, height);
-
-	build_window(&g);
-	update_image(&g);
-	gtk_widget_show_all(g.window);
-
-	opt = (struct app_options){ host ? host : "radio.lo", port, width, height, kmsg };
-	g.app = app_new(&opt, &fe);
-
-	if (press) {
-		g.press = g_strsplit(press, ",", -1);
-		g_timeout_add(400, press_next, &g);
-	}
-	if (exit_after)
-		g_timeout_add(exit_after, finish, &g);
-
-	gtk_main();
-
-	app_free(g.app);
-	return s1d_sim_fault_count(&g.sim) ? 2 : 0;
-}

+ 0 - 286
app/main_i2c.c

@@ -1,286 +0,0 @@
-/*
- * Drives the real panel directly through /dev/i2c-N, with no kernel driver.
- * This is the bring-up tool (--pattern), and the way to run on a kernel too
- * old for the DRM driver.
- *
- * Writing a raw byte stream to the wrong bus can reach anything attached to
- * it, so the adapter is checked by name before the first transfer.
- */
-#include <errno.h>
-#include <fcntl.h>
-#include <linux/i2c-dev.h>
-#include <linux/i2c.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/ioctl.h>
-#include <unistd.h>
-
-#include "platform_linux.h"
-#include "s1d13700_core.h"
-
-#define TX_CAP		1025
-
-/* Never, whatever the options: motherboard and display buses */
-static const char *const denied_adapters[] = { "PIIX4", "AMDGPU", "DPMST", "i801", "SMBus" };
-/* Known to be a dedicated bus for this panel */
-static const char *const known_adapters[] = { "MCP2221", "FT260", "i2c-tiny-usb", "mv64xxx" };
-
-struct panel_dev {
-	int fd;
-	unsigned int addr;
-	struct s1d_config cfg;
-	struct s1d_panel panel;
-	uint8_t shadow[S1D_VRAM_SIZE];
-	uint8_t next[S1D_VRAM_SIZE];
-	uint8_t tx[TX_CAP];
-	const char *backlight;
-};
-
-static int dev_xfer(void *ctx, const uint8_t *buf, size_t len)
-{
-	struct panel_dev *d = ctx;
-	struct i2c_msg msg = { d->addr, 0, (uint16_t)len, (uint8_t *)buf };
-	struct i2c_rdwr_ioctl_data data = { &msg, 1 };
-
-	return ioctl(d->fd, I2C_RDWR, &data) < 0 ? -errno : 0;
-}
-
-static void dev_delay(void *ctx, unsigned int ms)
-{
-	(void)ctx;
-	usleep(ms * 1000);
-}
-
-static const struct s1d_ops dev_ops = { dev_xfer, dev_delay };
-
-static void present(void *ctx, const uint32_t *pixels, int stride, int x, int y, int w, int h)
-{
-	struct panel_dev *d = ctx;
-	int err;
-
-	s1d_convert_xrgb8888(&d->cfg, pixels, stride, d->next, x, y, x + w, y + h);
-	err = s1d_panel_update(&d->panel, d->next, y, y + h);
-	if (err)
-		g_printerr("panel update failed: %s\n", strerror(-err));
-}
-
-/* sysfs if a path was given, otherwise the pin on the panel's own expander */
-static void backlight(void *ctx, bool on)
-{
-	struct panel_dev *d = ctx;
-	int err;
-
-	if (d->backlight) {
-		platform_backlight_set(d->backlight, on);
-		return;
-	}
-	err = s1d_panel_backlight(&d->panel, on);
-	if (err)
-		g_printerr("backlight: %s\n", strerror(-err));
-}
-
-static int open_bus(int bus, const char *allow)
-{
-	char path[64], name[128] = "";
-	unsigned long funcs = 0;
-	unsigned int i;
-	bool ok = false;
-	FILE *f;
-	int fd;
-
-	snprintf(path, sizeof(path), "/sys/class/i2c-dev/i2c-%d/name", bus);
-	f = fopen(path, "r");
-	if (!f || !fgets(name, sizeof(name), f)) {
-		g_printerr("i2c-%d: cannot read the adapter name\n", bus);
-		if (f)
-			fclose(f);
-		return -1;
-	}
-	fclose(f);
-	name[strcspn(name, "\n")] = '\0';
-
-	for (i = 0; i < G_N_ELEMENTS(denied_adapters); i++) {
-		if (strstr(name, denied_adapters[i])) {
-			g_printerr("i2c-%d (%s): refusing, this is not a panel bus\n", bus, name);
-			return -1;
-		}
-	}
-	for (i = 0; i < G_N_ELEMENTS(known_adapters); i++)
-		if (strstr(name, known_adapters[i]))
-			ok = true;
-	if (allow && !strcmp(allow, name))
-		ok = true;
-	if (!ok) {
-		g_printerr("i2c-%d (%s): unknown adapter; if it really is the panel's bus,\n"
-			   "pass --allow-adapter=\"%s\"\n", bus, name, name);
-		return -1;
-	}
-
-	snprintf(path, sizeof(path), "/dev/i2c-%d", bus);
-	fd = open(path, O_RDWR | O_CLOEXEC);
-	if (fd < 0) {
-		g_printerr("%s: %s\n", path, strerror(errno));
-		return -1;
-	}
-	if (ioctl(fd, I2C_FUNCS, &funcs) < 0 || !(funcs & I2C_FUNC_I2C)) {
-		g_printerr("i2c-%d (%s): no raw I2C support\n", bus, name);
-		close(fd);
-		return -1;
-	}
-	printf("using i2c-%d (%s)\n", bus, name);
-	return fd;
-}
-
-/* ---- bring-up patterns -------------------------------------------------- */
-
-static void put(uint32_t *fb, unsigned int w, unsigned int x, unsigned int y, uint32_t c)
-{
-	fb[y * w + x] = c;
-}
-
-/* Border, plus ticks every 10 px and long ticks every 50: shows the real size */
-static void pattern_geometry(uint32_t *fb, unsigned int w, unsigned int h)
-{
-	unsigned int x, y, i;
-
-	for (x = 0; x < w; x++) {
-		put(fb, w, x, 0, 0);
-		put(fb, w, x, h - 1, 0);
-		if (!(x % 10))
-			for (i = 0; i < (x % 50 ? 4u : 10u); i++)
-				put(fb, w, x, 1 + i, 0);
-	}
-	for (y = 0; y < h; y++) {
-		put(fb, w, 0, y, 0);
-		put(fb, w, w - 1, y, 0);
-		if (!(y % 10))
-			for (i = 0; i < (y % 50 ? 4u : 10u); i++)
-				put(fb, w, 1 + i, y, 0);
-	}
-	/* a diagonal shows skew from a wrong line length */
-	for (i = 0; i < h && i < w; i++)
-		put(fb, w, i, i, 0);
-}
-
-static void pattern_gray(uint32_t *fb, unsigned int w, unsigned int h)
-{
-	static const uint32_t levels[] = { 0xffffff, 0xaaaaaa, 0x555555, 0x000000 };
-	unsigned int x, y;
-
-	for (y = 0; y < h; y++)
-		for (x = 0; x < w; x++)
-			put(fb, w, x, y, levels[x * 4 / w]);
-}
-
-static int show_pattern(struct panel_dev *d, const char *name)
-{
-	unsigned int w = d->cfg.width, h = d->cfg.height;
-	uint32_t *fb = g_malloc((gsize)w * h * 4);
-	int err;
-
-	memset(fb, 0xff, (gsize)w * h * 4);
-	if (!strcmp(name, "geometry")) {
-		pattern_geometry(fb, w, h);
-	} else if (!strcmp(name, "gray")) {
-		pattern_gray(fb, w, h);
-	} else {
-		g_printerr("unknown pattern '%s' (geometry, gray)\n", name);
-		g_free(fb);
-		return 1;
-	}
-
-	s1d_convert_xrgb8888(&d->cfg, fb, w * 4, d->next, 0, 0, w, h);
-	err = s1d_panel_update(&d->panel, d->next, 0, h);
-	g_free(fb);
-	if (err) {
-		g_printerr("pattern failed: %s\n", strerror(-err));
-		return 1;
-	}
-	printf("pattern sent: %lu I2C bytes in %lu messages\n",
-	       d->panel.stats.i2c_bytes, d->panel.stats.i2c_msgs);
-	return 0;
-}
-
-int main(int argc, char **argv)
-{
-	static struct panel_dev d;
-	static int bus = -1, addr = 0x74, port = 6600;
-	static int width = 240, height = 160, bpp = 2, tcr = 162, tx_cap = TX_CAP;
-	static gboolean no_backlight;
-	static char *host, *pattern, *allow, *input, *blpath;
-	static gboolean kmsg;
-	static GOptionEntry entries[] = {
-		{ "bus", 0, 0, G_OPTION_ARG_INT, &bus, "I2C bus number (required)", "N" },
-		{ "addr", 0, 0, G_OPTION_ARG_INT, &addr, "Expander address (0x74 = 116)", "N" },
-		{ "allow-adapter", 0, 0, G_OPTION_ARG_STRING, &allow, "Accept the adapter with this exact name", "NAME" },
-		{ "width", 0, 0, G_OPTION_ARG_INT, &width, "Panel width (240)", "PX" },
-		{ "height", 0, 0, G_OPTION_ARG_INT, &height, "Panel height (160)", "PX" },
-		{ "bpp", 0, 0, G_OPTION_ARG_INT, &bpp, "Bits per pixel: 1, 2, 4 (2)", "N" },
-		{ "tcr", 0, 0, G_OPTION_ARG_INT, &tcr, "TC/R, sets the frame rate (162)", "N" },
-		{ "tx-cap", 0, 0, G_OPTION_ARG_INT, &tx_cap, "Largest I2C message, 7.." G_STRINGIFY(TX_CAP) " (" G_STRINGIFY(TX_CAP) ")", "BYTES" },
-		{ "no-backlight", 0, 0, G_OPTION_ARG_NONE, &no_backlight, "Leave the expander's backlight pin off", NULL },
-		{ "pattern", 0, 0, G_OPTION_ARG_STRING, &pattern, "Show a test pattern and exit: geometry, gray", "NAME" },
-		{ "host", 0, 0, G_OPTION_ARG_STRING, &host, "MPD host (localhost)", "NAME" },
-		{ "port", 0, 0, G_OPTION_ARG_INT, &port, "MPD port (6600)", "N" },
-		{ "input", 0, 0, G_OPTION_ARG_FILENAME, &input, "Key input device (auto: " DEFAULT_KEYS_NAME ")", "PATH" },
-		{ "backlight", 0, 0, G_OPTION_ARG_FILENAME, &blpath, "Backlight sysfs brightness file (default: expander pin P1.0)", "PATH" },
-		{ "kmsg", 0, 0, G_OPTION_ARG_NONE, &kmsg, "Show the kernel log", NULL },
-		{ NULL, 0, 0, 0, NULL, NULL, NULL },
-	};
-	GOptionContext *ctx = g_option_context_new("- radio panel over i2c-dev");
-	struct app_frontend fe = { &d, present, backlight };
-	struct app_options opt;
-	GError *err = NULL;
-	struct app *app;
-	int ret;
-
-	g_option_context_add_main_entries(ctx, entries, NULL);
-	if (!g_option_context_parse(ctx, &argc, &argv, &err)) {
-		g_printerr("%s\n", err->message);
-		return 1;
-	}
-	if (bus < 0) {
-		g_printerr("--bus is required\n");
-		return 1;
-	}
-
-	d.fd = open_bus(bus, allow);
-	if (d.fd < 0)
-		return 1;
-
-	d.addr = addr;
-	d.cfg = (struct s1d_config){ width, height, bpp, tcr };
-	d.backlight = blpath;
-	if (tx_cap < 0 || tx_cap > TX_CAP) {
-		g_printerr("--tx-cap: at most %d\n", TX_CAP);
-		return 1;
-	}
-
-	ret = s1d_panel_setup(&d.panel, &d.cfg, &dev_ops, &d, d.shadow, d.tx, tx_cap);
-	if (ret) {
-		g_printerr("invalid panel configuration\n");
-		return 1;
-	}
-	if (!blpath && !no_backlight)
-		s1d_panel_backlight(&d.panel, true);
-	ret = s1d_panel_init(&d.panel);
-	if (ret) {
-		g_printerr("panel init failed: %s\n", strerror(-ret));
-		return 1;
-	}
-
-	if (pattern)
-		return show_pattern(&d, pattern);
-
-	opt = (struct app_options){ host ? host : "localhost", port, width, height, kmsg };
-	app = app_new(&opt, &fe);
-	if (!platform_keys_start(app, input))
-		g_printerr("no key input device, running display-only\n");
-
-	platform_run();
-
-	app_free(app);
-	s1d_panel_display(&d.panel, false);
-	return 0;
-}

+ 0 - 269
app/mpd_client.c

@@ -1,269 +0,0 @@
-/*
- * MPD connection on the GLib main loop. The connection sits in "idle" so
- * changes arrive as events instead of being polled; anything else first leaves
- * idle, does its work and goes back.
- */
-#include <glib-unix.h>
-#include <mpd/client.h>
-#include <stdio.h>
-#include <string.h>
-
-#include "app.h"
-
-#define CONNECT_TIMEOUT_MS	2000
-#define RECONNECT_S		3
-
-struct mpdc {
-	char *host;
-	unsigned int port;
-	struct radio_state *state;
-	mpdc_changed_fn changed;
-	mpdc_log_fn log;
-	void *user;
-
-	struct mpd_connection *conn;
-	guint watch_id;
-	guint retry_id;
-	bool was_connected;
-};
-
-static gboolean on_readable(gint fd, GIOCondition cond, gpointer data);
-static gboolean try_connect(gpointer data);
-
-static void note(struct mpdc *m, const char *text)
-{
-	m->log(m->user, text);
-}
-
-static void drop_connection(struct mpdc *m, const char *why)
-{
-	char buf[200];
-
-	if (m->watch_id) {
-		g_source_remove(m->watch_id);
-		m->watch_id = 0;
-	}
-	if (m->conn) {
-		mpd_connection_free(m->conn);
-		m->conn = NULL;
-	}
-	m->state->connected = false;
-	if (m->was_connected && why) {
-		snprintf(buf, sizeof(buf), "MPD: %s", why);
-		note(m, buf);
-	}
-	m->was_connected = false;
-	if (!m->retry_id)
-		m->retry_id = g_timeout_add_seconds(RECONNECT_S, try_connect, m);
-	m->changed(m->user);
-}
-
-/*
- * Returns false if the connection was lost. A command MPD merely refused,
- * such as changing the volume with no mixer, does not end the session.
- */
-static bool check_connection(struct mpdc *m)
-{
-	char buf[256];
-
-	switch (mpd_connection_get_error(m->conn)) {
-	case MPD_ERROR_SUCCESS:
-		return true;
-	case MPD_ERROR_SERVER:
-		snprintf(buf, sizeof(buf), "MPD: %s",
-			 mpd_connection_get_error_message(m->conn));
-		note(m, buf);
-		if (mpd_connection_clear_error(m->conn))
-			return true;
-		break;
-	default:
-		break;
-	}
-	g_strlcpy(buf, mpd_connection_get_error_message(m->conn), sizeof(buf));
-	drop_connection(m, buf);
-	return false;
-}
-
-static void format_title(char *out, size_t size, const struct mpd_song *song)
-{
-	const char *artist = mpd_song_get_tag(song, MPD_TAG_ARTIST, 0);
-	const char *title = mpd_song_get_tag(song, MPD_TAG_TITLE, 0);
-	const char *name = mpd_song_get_tag(song, MPD_TAG_NAME, 0);
-	const char *uri = mpd_song_get_uri(song);
-	const char *slash;
-
-	if (artist && title) {
-		snprintf(out, size, "%s - %s", artist, title);
-	} else if (title && name) {	/* a stream announcing what it plays */
-		snprintf(out, size, "%s: %s", name, title);
-	} else if (title || name) {
-		g_strlcpy(out, title ? title : name, size);
-	} else {
-		slash = strrchr(uri, '/');
-		g_strlcpy(out, (slash && slash[1] && !strstr(uri, "://")) ? slash + 1 : uri, size);
-	}
-}
-
-static void refresh(struct mpdc *m)
-{
-	struct radio_state *s = m->state;
-	struct mpd_status *status;
-	struct mpd_song *song;
-
-	status = mpd_run_status(m->conn);
-	if (!status) {
-		check_connection(m);
-		return;
-	}
-
-	switch (mpd_status_get_state(status)) {
-	case MPD_STATE_PLAY:	s->state = PLAY_PLAYING; break;
-	case MPD_STATE_PAUSE:	s->state = PLAY_PAUSED; break;
-	case MPD_STATE_STOP:	s->state = PLAY_STOPPED; break;
-	default:		s->state = PLAY_UNKNOWN; break;
-	}
-	s->song_pos = mpd_status_get_song_pos(status);
-	s->queue_len = mpd_status_get_queue_length(status);
-	s->elapsed_ms = mpd_status_get_elapsed_ms(status);
-	s->elapsed_stamp_us = g_get_monotonic_time();
-	s->total_ms = mpd_status_get_total_time(status) * 1000;
-	s->volume = mpd_status_get_volume(status);
-	s->repeat = mpd_status_get_repeat(status);
-	s->random = mpd_status_get_random(status);
-	mpd_status_free(status);
-
-	s->title[0] = '\0';
-	/* as the firmware: a stopped player shows no title */
-	if (s->state != PLAY_STOPPED) {
-		song = mpd_run_current_song(m->conn);
-		if (song) {
-			format_title(s->title, sizeof(s->title), song);
-			mpd_song_free(song);
-		} else if (!check_connection(m)) {
-			return;
-		}
-	}
-	m->changed(m->user);
-}
-
-static void enter_idle(struct mpdc *m)
-{
-	if (!m->conn)
-		return;
-	if (!mpd_send_idle_mask(m->conn, MPD_IDLE_QUEUE | MPD_IDLE_PLAYER |
-				MPD_IDLE_MIXER | MPD_IDLE_OPTIONS))
-		check_connection(m);
-}
-
-static gboolean on_readable(gint fd, GIOCondition cond, gpointer data)
-{
-	struct mpdc *m = data;
-
-	(void)fd;
-	if (cond & (G_IO_HUP | G_IO_ERR)) {
-		m->watch_id = 0;
-		drop_connection(m, "connection closed");
-		return G_SOURCE_REMOVE;
-	}
-
-	mpd_recv_idle(m->conn, false);
-	if (!check_connection(m))
-		return G_SOURCE_REMOVE;	/* drop_connection removed this source */
-
-	refresh(m);
-	if (m->conn)
-		enter_idle(m);
-	return m->conn ? G_SOURCE_CONTINUE : G_SOURCE_REMOVE;
-}
-
-static gboolean try_connect(gpointer data)
-{
-	struct mpdc *m = data;
-	struct mpd_connection *c;
-	char buf[200];
-
-	m->retry_id = 0;
-
-	c = mpd_connection_new(m->host, m->port, CONNECT_TIMEOUT_MS);
-	if (!c || mpd_connection_get_error(c) != MPD_ERROR_SUCCESS) {
-		if (c)
-			mpd_connection_free(c);
-		m->retry_id = g_timeout_add_seconds(RECONNECT_S, try_connect, m);
-		return G_SOURCE_REMOVE;
-	}
-
-	m->conn = c;
-	m->state->connected = true;
-	m->was_connected = true;
-	snprintf(buf, sizeof(buf), "Połączono z MPD: %s", m->host);
-	note(m, buf);
-
-	refresh(m);
-	if (m->conn) {
-		m->watch_id = g_unix_fd_add(mpd_connection_get_fd(m->conn),
-					    G_IO_IN | G_IO_HUP | G_IO_ERR,
-					    on_readable, m);
-		enter_idle(m);
-	}
-	return G_SOURCE_REMOVE;
-}
-
-void mpdc_command(struct mpdc *m, enum mpdc_command cmd)
-{
-	bool ok = true;
-
-	if (!m->conn) {
-		note(m, "Brak połączenia z MPD");
-		return;
-	}
-
-	/* leave idle; any event it reports is covered by the refresh below */
-	mpd_run_noidle(m->conn);
-	if (!check_connection(m))
-		return;
-
-	switch (cmd) {
-	case MPDC_PLAY:		ok = mpd_run_play(m->conn); break;
-	case MPDC_TOGGLE:	ok = mpd_run_toggle_pause(m->conn); break;
-	case MPDC_STOP:		ok = mpd_run_stop(m->conn); break;
-	case MPDC_NEXT:		ok = mpd_run_next(m->conn); break;
-	case MPDC_PREV:		ok = mpd_run_previous(m->conn); break;
-	case MPDC_VOLUME_UP:	ok = mpd_run_change_volume(m->conn, 1); break;
-	case MPDC_VOLUME_DOWN:	ok = mpd_run_change_volume(m->conn, -1); break;
-	case MPDC_REFRESH:	break;
-	}
-	if (!ok && !check_connection(m))
-		return;
-
-	refresh(m);
-	if (m->conn)
-		enter_idle(m);
-}
-
-struct mpdc *mpdc_new(const char *host, unsigned int port, struct radio_state *state,
-		      mpdc_changed_fn changed, mpdc_log_fn log, void *user)
-{
-	struct mpdc *m = g_new0(struct mpdc, 1);
-
-	m->host = g_strdup(host);
-	m->port = port;
-	m->state = state;
-	m->changed = changed;
-	m->log = log;
-	m->user = user;
-	/* not directly: the owner must finish construction first */
-	m->retry_id = g_idle_add(try_connect, m);
-	return m;
-}
-
-void mpdc_free(struct mpdc *m)
-{
-	if (m->watch_id)
-		g_source_remove(m->watch_id);
-	if (m->retry_id)
-		g_source_remove(m->retry_id);
-	if (m->conn)
-		mpd_connection_free(m->conn);
-	g_free(m->host);
-	g_free(m);
-}

+ 0 - 96
app/platform_linux.c

@@ -1,96 +0,0 @@
-#include <errno.h>
-#include <fcntl.h>
-#include <glib-unix.h>
-#include <linux/input.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/ioctl.h>
-#include <unistd.h>
-
-#include "platform_linux.h"
-
-static const struct {
-	unsigned short code;
-	enum radio_key key;
-} keymap[] = {
-	{ KEY_ESC, RK_ESC }, { KEY_NEXTSONG, RK_NEXT }, { KEY_STOPCD, RK_STOP },
-	{ KEY_MENU, RK_MENU }, { KEY_LIST, RK_LIST }, { KEY_UP, RK_UP },
-	{ KEY_PREVIOUSSONG, RK_PREV }, { KEY_RIGHT, RK_RIGHT },
-	{ KEY_DOWN, RK_DOWN }, { KEY_PAUSECD, RK_PAUSE }, { KEY_OK, RK_OK },
-	{ KEY_LEFT, RK_LEFT }, { KEY_PLAYCD, RK_PLAY },
-};
-
-static gboolean on_input(gint fd, GIOCondition cond, gpointer data)
-{
-	struct app *app = data;
-	struct input_event ev;
-	unsigned int i;
-
-	(void)cond;
-	while (read(fd, &ev, sizeof(ev)) == (ssize_t)sizeof(ev)) {
-		/* 1 press, 2 autorepeat: app_key() applies the lockout */
-		if (ev.type != EV_KEY || ev.value == 0)
-			continue;
-		for (i = 0; i < G_N_ELEMENTS(keymap); i++)
-			if (keymap[i].code == ev.code)
-				app_key(app, keymap[i].key);
-	}
-	return G_SOURCE_CONTINUE;
-}
-
-static int find_keys_device(void)
-{
-	char path[32], name[64];
-	int i, fd;
-
-	for (i = 0; i < 32; i++) {
-		snprintf(path, sizeof(path), "/dev/input/event%d", i);
-		fd = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
-		if (fd < 0)
-			continue;
-		if (ioctl(fd, EVIOCGNAME(sizeof(name)), name) > 0 &&
-		    !strcmp(name, DEFAULT_KEYS_NAME))
-			return fd;
-		close(fd);
-	}
-	return -1;
-}
-
-bool platform_keys_start(struct app *app, const char *path)
-{
-	int fd = path ? open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC) : find_keys_device();
-
-	if (fd < 0)
-		return false;
-	g_unix_fd_add(fd, G_IO_IN, on_input, app);
-	return true;
-}
-
-void platform_backlight_set(const char *path, bool on)
-{
-	FILE *f;
-
-	if (!path)
-		return;
-	f = fopen(path, "w");
-	if (!f)
-		return;
-	fputs(on ? "1\n" : "0\n", f);
-	fclose(f);
-}
-
-static gboolean on_signal(gpointer data)
-{
-	g_main_loop_quit(data);
-	return G_SOURCE_REMOVE;
-}
-
-void platform_run(void)
-{
-	GMainLoop *loop = g_main_loop_new(NULL, FALSE);
-
-	g_unix_signal_add(SIGINT, on_signal, loop);
-	g_unix_signal_add(SIGTERM, on_signal, loop);
-	g_main_loop_run(loop);
-	g_main_loop_unref(loop);
-}

+ 0 - 25
app/platform_linux.h

@@ -1,25 +0,0 @@
-/* What the real-hardware frontends share: key events and the backlight. */
-#ifndef RADIO_PLATFORM_LINUX_H
-#define RADIO_PLATFORM_LINUX_H
-
-#include <stdbool.h>
-
-#include "app.h"
-
-#define DEFAULT_KEYS_NAME	"radio-keys"
-#define DEFAULT_BACKLIGHT	"/sys/class/backlight/radio-backlight/brightness"
-
-/*
- * Feed key presses from an evdev device into the app. path may be NULL to
- * look for the input device named DEFAULT_KEYS_NAME. Returns false, leaving
- * the UI display-only, if there is none.
- */
-bool platform_keys_start(struct app *app, const char *path);
-
-/* Write to a sysfs brightness file; a NULL path does nothing. */
-void platform_backlight_set(const char *path, bool on);
-
-/* Run the GLib main loop until SIGINT or SIGTERM. */
-void platform_run(void);
-
-#endif /* RADIO_PLATFORM_LINUX_H */

+ 0 - 216
app/ui_render.c

@@ -1,216 +0,0 @@
-#include <math.h>
-#include <pango/pangocairo.h>
-#include <stdio.h>
-
-#include "app.h"
-
-/*
- * Absolute sizes: these are panel pixels, not points. Text is drawn without
- * antialiasing, so these are fonts whose hinting holds up in plain black and
- * white at 9-11 px. Verdana and Andale Mono are Microsoft core fonts, with
- * Liberation as the fallback.
- */
-#define FONT_TITLE	"DejaVu Sans 11px"
-#define FONT_STATUS	"DejaVu Sans Mono 10px"
-#define FONT_SMALL	"Verdana, Liberation Sans 9px"
-#define FONT_LOG	"Andale Mono, Liberation Mono 9px"
-
-#define TITLE_Y		0
-#define TITLE_LINES	3
-#define STATUS_Y	40
-#define ICON_SIZE	12
-#define BAR_Y		54
-#define OPTIONS_Y	60
-#define LINK_Y		71
-#define LOG_Y		85
-#define LOG_LINE_H	10	/* 9 px text: room for Polish accents */
-
-/*
- * Gray edges look smeared on the panel at 2 bpp, so glyphs are rendered in
- * plain black and white; full hinting snaps the outlines to the pixel grid.
- */
-#ifndef UI_TEXT_ANTIALIAS
-#define UI_TEXT_ANTIALIAS	CAIRO_ANTIALIAS_NONE
-#endif
-
-static PangoLayout *new_layout(cairo_t *cr, const char *font)
-{
-	PangoLayout *l = pango_cairo_create_layout(cr);
-	PangoFontDescription *d = pango_font_description_from_string(font);
-	cairo_font_options_t *fo = cairo_font_options_create();
-
-	cairo_font_options_set_antialias(fo, UI_TEXT_ANTIALIAS);
-	cairo_font_options_set_hint_style(fo, CAIRO_HINT_STYLE_FULL);
-	cairo_font_options_set_hint_metrics(fo, CAIRO_HINT_METRICS_ON);
-	pango_cairo_context_set_font_options(pango_layout_get_context(l), fo);
-	cairo_font_options_destroy(fo);
-
-	pango_layout_set_font_description(l, d);
-	pango_font_description_free(d);
-	return l;
-}
-
-static void draw_text(cairo_t *cr, const char *font, int x, int y, int w,
-		      PangoAlignment align, const char *text)
-{
-	PangoLayout *l = new_layout(cr, font);
-
-	pango_layout_set_width(l, w * PANGO_SCALE);
-	pango_layout_set_alignment(l, align);
-	pango_layout_set_ellipsize(l, PANGO_ELLIPSIZE_END);
-	pango_layout_set_text(l, text, -1);
-	cairo_move_to(cr, x, y);
-	pango_cairo_show_layout(cr, l);
-	g_object_unref(l);
-}
-
-static void draw_title(cairo_t *cr, int w, const char *text)
-{
-	PangoLayout *l = new_layout(cr, FONT_TITLE);
-
-	pango_layout_set_width(l, w * PANGO_SCALE);
-	pango_layout_set_wrap(l, PANGO_WRAP_WORD_CHAR);
-	pango_layout_set_ellipsize(l, PANGO_ELLIPSIZE_END);
-	pango_layout_set_height(l, -TITLE_LINES);
-	pango_layout_set_text(l, text, -1);
-	cairo_move_to(cr, 1, TITLE_Y);
-	pango_cairo_show_layout(cr, l);
-	g_object_unref(l);
-}
-
-static void draw_icon(cairo_t *cr, enum play_state state, int x, int y)
-{
-	int s = ICON_SIZE;
-
-	switch (state) {
-	case PLAY_PLAYING:
-		cairo_move_to(cr, x + 2, y);
-		cairo_line_to(cr, x + s, y + s / 2.0);
-		cairo_line_to(cr, x + 2, y + s);
-		cairo_close_path(cr);
-		cairo_fill(cr);
-		break;
-	case PLAY_PAUSED:
-		cairo_rectangle(cr, x + 2, y, 3, s);
-		cairo_rectangle(cr, x + 7, y, 3, s);
-		cairo_fill(cr);
-		break;
-	case PLAY_STOPPED:
-		cairo_rectangle(cr, x + 1, y + 1, s - 2, s - 2);
-		cairo_fill(cr);
-		break;
-	default:
-		break;
-	}
-}
-
-static void format_time(char *buf, size_t size, unsigned int ms)
-{
-	unsigned int t = ms / 1000;
-
-	if (t >= 3600)
-		snprintf(buf, size, "%u:%02u:%02u", t / 3600, t / 60 % 60, t % 60);
-	else
-		snprintf(buf, size, "%u:%02u", t / 60, t % 60);
-}
-
-static void draw_status(cairo_t *cr, const struct radio_state *s, int w)
-{
-	char buf[64], a[16], b[16];
-	unsigned int elapsed;
-
-	draw_icon(cr, s->state, 2, STATUS_Y);
-	if (s->state == PLAY_STOPPED || s->song_pos < 0)
-		return;
-
-	snprintf(buf, sizeof(buf), "#%d/%u", s->song_pos + 1, s->queue_len);
-	draw_text(cr, FONT_STATUS, 20, STATUS_Y, 90, PANGO_ALIGN_LEFT, buf);
-
-	elapsed = radio_state_elapsed_ms(s);
-	format_time(a, sizeof(a), elapsed);
-	if (s->total_ms) {
-		format_time(b, sizeof(b), s->total_ms);
-		snprintf(buf, sizeof(buf), "%s/%s", a, b);
-	} else {
-		g_strlcpy(buf, a, sizeof(buf));
-	}
-	draw_text(cr, FONT_STATUS, 110, STATUS_Y, w - 112, PANGO_ALIGN_RIGHT, buf);
-
-	if (s->total_ms) {
-		int bar_w = w - 22;
-		int fill = (int)((guint64)elapsed * bar_w / s->total_ms);
-
-		cairo_set_line_width(cr, 1);
-		cairo_rectangle(cr, 20.5, BAR_Y + 0.5, bar_w - 1, 3);
-		cairo_stroke(cr);
-		cairo_rectangle(cr, 20, BAR_Y, fill, 4);
-		cairo_fill(cr);
-	}
-}
-
-static void draw_options(cairo_t *cr, const struct radio_state *s, int w)
-{
-	char buf[64];
-
-	if (!s->connected)
-		return;
-
-	snprintf(buf, sizeof(buf), "Włączone:%s%s",
-		 s->repeat ? " repeat" : "", s->random ? " random" : "");
-	draw_text(cr, FONT_SMALL, 1, OPTIONS_Y, 170, PANGO_ALIGN_LEFT, buf);
-
-	if (s->volume >= 0)
-		snprintf(buf, sizeof(buf), "Głośność %d%%", s->volume);
-	else
-		g_strlcpy(buf, "Głośność –", sizeof(buf));
-	draw_text(cr, FONT_SMALL, 150, OPTIONS_Y, w - 151, PANGO_ALIGN_RIGHT, buf);
-}
-
-static void draw_link(cairo_t *cr, const struct radio_state *s, int w)
-{
-	char buf[192];
-
-	if (s->connected)
-		return;
-
-	cairo_rectangle(cr, 0, LINK_Y, w, 12);
-	cairo_fill(cr);
-	cairo_set_source_rgb(cr, 1, 1, 1);
-	snprintf(buf, sizeof(buf), "Brak połączenia z %s", s->server);
-	draw_text(cr, FONT_SMALL, 2, LINK_Y, w - 4, PANGO_ALIGN_LEFT, buf);
-	cairo_set_source_rgb(cr, 0, 0, 0);
-}
-
-static void draw_log(cairo_t *cr, const struct radio_state *s, int w, int h)
-{
-	int i;
-
-	cairo_set_line_width(cr, 1);
-	cairo_move_to(cr, 0, LOG_Y - 1.5);
-	cairo_line_to(cr, w, LOG_Y - 1.5);
-	cairo_stroke(cr);
-
-	for (i = 0; i < LOG_ROWS; i++) {
-		int y = LOG_Y + i * LOG_LINE_H;
-
-		if (y + LOG_LINE_H > h)
-			break;
-		if (s->log[i][0])
-			draw_text(cr, FONT_LOG, 1, y - 1, w - 1, PANGO_ALIGN_LEFT, s->log[i]);
-	}
-}
-
-void ui_render(cairo_t *cr, const struct radio_state *s, int width, int height)
-{
-	cairo_set_antialias(cr, CAIRO_ANTIALIAS_NONE);
-	cairo_set_source_rgb(cr, 1, 1, 1);
-	cairo_paint(cr);
-	cairo_set_source_rgb(cr, 0, 0, 0);
-
-	if (s->title[0])
-		draw_title(cr, width - 2, s->title);
-	draw_status(cr, s, width);
-	draw_options(cr, s, width);
-	draw_link(cr, s, width);
-	draw_log(cr, s, width, height);
-}

+ 58 - 31
docs/REPORT.md

@@ -4,14 +4,14 @@ Status as of 2026-11-09. All code is in `linux/`. The LPC1114 firmware in the
 repository root is unchanged.
 
 **Update 2026-11-10:** the panel now runs on real hardware through i2c-dev
-(`radio-i2c --pattern geometry|gray` over a USB I²C bridge at 400 kHz): 240×160,
+(`radio-ui i2c --pattern geometry|gray` over a USB I²C bridge at 400 kHz): 240×160,
 2 bpp and pixel polarity confirmed. The control lines were remapped to the
 actual board (see `linux/README.md`), and the review in
 `linux/s1d13700-recommendations.md` was applied to the core and the DRM
 driver. The DRM driver, keys and device tree overlay are still untested on
 hardware.
 
-**Later on 2026-11-10:** the full UI ran on the real panel (`radio-i2c --host`),
+**Later on 2026-11-10:** the full UI ran on the real panel (`radio-ui i2c --host`),
 which led to three fixes:
 
 - **Cursor block.** A memory write turns the controller's cursor on even when
@@ -21,14 +21,26 @@ which led to three fixes:
   models the behaviour and the tests check that the cursor stays off and that
   an update while blanked does not switch the display back on.
 - **Text.** Gray glyph edges looked smeared at 2 bpp, so text is now drawn in
-  plain black and white with full hinting (`UI_TEXT_ANTIALIAS` overrides this
-  at build time). The small and log fonts became Verdana and Andale Mono
+  plain black and white with full hinting (`TEXT_ANTIALIAS` in
+  `radio/render.py` overrides this). The small and log fonts became Verdana and Andale Mono
   (Microsoft core fonts), with Liberation as the fallback. The log has 7 rows
   of 10 px, leaving room for Polish accents.
 - **DRM backlight.** The driver now registers a `radio-backlight` backlight
   device for the expander's P1.0 pin, driven from the flush worker, so the
   frontend's default sysfs path works. Still compiled only.
 
+**Update 2026-11-11:** the application is now Python (`linux/radio/`, run as
+`linux/radio-ui sim|i2c|drm`), written for Python 3.7.3 (Debian buster, on the
+target) through 3.14. The panel core stays in C, since the kernel driver shares
+it, and is loaded through ctypes from `build/libradiopanel.so` (`make lib`).
+The `sim` window's LCD area matched the C window pixel for pixel, apart from one
+pixel of progress bar caused by timing. New: a test mode (`--window-keys`) that
+drives the real panel and a real MPD but takes keys from a window on the PC's X
+display. The Python DRM frontend ran on the real panel with the driver loaded,
+against the fake MPD. The command names below were updated:
+`radio-gtk` → `radio-ui sim`, `radio-i2c` → `radio-ui i2c`, `radio-drm` →
+`radio-ui drm`.
+
 ## 1. Summary
 
 The LPC1114 is replaced by software on the Linux board, with the S1D13700 LCD
@@ -61,18 +73,18 @@ address binds to one driver, which is another reason for a separate expander.
 
 ## 3. Architecture
 
-    MPD (libmpdclient, idle events) ─┐
+    MPD (mpd.py, idle events) ───────┐
     /dev/kmsg (optional) ────────────┤
-    keys (evdev or window buttons) ──┤
+    keys (evdev, or a window) ───────┤
                                      ▼
-                       app_core.c  +  ui_render.c (Cairo/Pango)
-                                     │  XRGB8888 frame + changed rectangle
+                  app.py  +  render.py (Cairo/Pango)       Python
+                                     │  XRGB8888 frame + changed rows
              ┌───────────────────────┼─────────────────────────┐
              ▼                       ▼                         ▼
-        main_gtk.c              main_i2c.c                main_drm.c
+        radio-ui sim            radio-ui i2c              radio-ui drm
              │                       │                  dumb buffer + DIRTYFB
-             │                       │                         ▼
-             │                       │                  s1d13700_drm.c
+             ▼                       ▼                         ▼
+      libpanel.c (ctypes)     libpanel.c (ctypes)       s1d13700_drm.c
              ▼                       ▼                         ▼
        ┌───────────────── s1d13700_core.c ──────────────────────┐
        │ XRGB→2 bpp · byte diff against shadow · write planner  │
@@ -114,26 +126,32 @@ command or too many of them, unknown commands, bad registers, messages ending
 between P0 and P1, inconsistent SYSTEM SET, and writes during reset. The window
 frontend exits with an error code if any occurred.
 
-### Application (`linux/app/`)
+### Application (`linux/radio/`)
+
+Python 3.7.3 to 3.14, with PyGObject (GLib, Pango, PangoCairo), pycairo and
+python3-gi-cairo; GTK 3 only for the window and the test mode, libdrm only for
+`drm`. The MPD protocol is implemented directly, so no MPD library is needed.
 
 | File | Role |
 |---|---|
-| `app_core.c` | Render scheduling, changed-area detection, keys, backlight timeout, log batching |
-| `ui_render.c` | Screen layout: title, state icon, track, time, progress, options, volume, link warning, log |
-| `mpd_client.c` | Event-driven MPD connection; reconnects every 3 s |
-| `log_kmsg.c` | Follows the kernel log |
-| `main_gtk.c` | Window with simulated panel, buttons, shortcuts and a live traffic readout |
-| `main_i2c.c` | Real panel through i2c-dev, plus `--pattern geometry` / `gray` for bring-up |
-| `main_drm.c` | Real panel through the DRM driver |
-| `platform_linux.c` | evdev keys, sysfs backlight, signal handling |
+| `app.py` | Render scheduling, changed-rows detection, keys, backlight timeout, log batching, kernel log |
+| `render.py` | Screen layout: title, state icon, track, time, progress, options, volume, link warning, log |
+| `mpd.py` | Event-driven MPD connection; reconnects every 3 s |
+| `panel.py`, `libpanel.c` | The C panel core and simulator behind a handle, through ctypes |
+| `sim.py` | `sim`: window with simulated panel, buttons, shortcuts and a live traffic readout |
+| `gtkkeys.py` | Key table and buttons, and the test mode's key window |
+| `drm.py` | `drm`: the panel through the DRM driver (libdrm 2.4.97 calls, dumb buffer by ioctl) |
+| `platform.py` | evdev keys, sysfs backlight, i2c bus check, signal handling |
+| `__main__.py` | Command line, `i2c` frontend and its `--pattern geometry` / `gray` |
 
 Behaviour kept from the firmware: 300 ms key lockout, 30 s backlight, the same
 command for each key, no title while stopped. New: event-driven updates instead
 of 2 s polling, proper Polish characters, a progress bar, volume display. Log
 redraws are batched to at most one per second.
 
-Key mapping in the window: `Z X C V B` prev/play/pause/stop/next, arrows
-(Up/Down = volume), `Enter` OK, `Esc` refresh, `M` menu, `L` list, `Space` pause.
+Key mapping in the window and the test mode's key window: `Z X C V B` prev/play/pause/stop/next, arrows
+(Up/Down = volume), `Enter` OK, `Esc` refresh, `M` menu, `L` list, `Space` pause; also the media and volume keys of a
+multimedia keyboard.
 OK, Menu, List, Left and Right wake the backlight only, as in the firmware.
 
 ### DRM driver (`linux/driver/s1d13700_drm.c`)
@@ -172,15 +190,23 @@ re-sending DISP ON (the cursor fix); the last two rows predate it.
 | Panel tests: init values, invalid configs, no-change = no traffic, direction choice, gap merging, 2000 random update rounds at 1/2/4 bpp and message sizes 7/61/1025, error recovery, pixel conversion | Pass, also under ASan and UBSan |
 | The simulator's fault detector fires on bad streams | Pass |
 | All frontends, the overlay and the module compile; module with `W=1` | No warnings shown |
+| Python UI tests (`make pytest`, 17 tests): MPD parsing, commands, push and reconnect against the fake server; rendering through the simulator with no faults; key lockout; patterns; bus refusal; evdev codes against the overlay | Pass on 3.14.7 |
+| `radio-ui sim` against the C window, same fake server | LCD area identical except one progress bar pixel (timing) |
+| `radio-ui drm` on the real panel (driver loaded), fake MPD | Runs, no errors from the frontend or the kernel |
+| Test mode key window: every shortcut, media key and window close, injected as GDK events | All 13 keys mapped; closing the window quits |
+| DRM ctypes structures and ioctl numbers against the C headers | Identical |
 | Window buttons against a fake MPD: Next, Up, Down, Pause, Prev, Stop, Play, Esc, Menu | The seven MPD commands sent correctly; Menu sends none |
 | Real MPD on `radio.lo` (0.21.4), read-only | Connects and displays correctly; player state not changed |
 | MPD pushing a change | Triggers a refresh (fake server) |
 | Server lost, then back | Warning shown, reconnects automatically (fake server) |
-| `radio-i2c` on PIIX4, AMDGPU I²C and AUX buses | All refused, no traffic |
+| `radio-i2c` (C) on PIIX4, AMDGPU I²C and AUX buses; Python bus check with mocked names | All refused, no traffic |
 
-The kernel module was built but **never loaded**. The window's keyboard shortcuts
-were not exercised automatically (no input injection tool here), and neither was
-real MPD with key presses, to avoid changing playback.
+Python 3.7.3 was not run here (no interpreter or container available): the code
+was parsed with `ast.parse(feature_version=(3, 7))` and avoids newer library
+calls, but needs a run on the target. Real X keyboard delivery to the key window
+was not exercised (no input injection tool), nor real MPD with key presses, to
+avoid changing playback. `radio-ui i2c` was not run on hardware after the port:
+the DRM driver held the panel's address at the time.
 
 ## 7. Not verified
 
@@ -203,14 +229,14 @@ These can only be settled with hardware.
 
 | | Stay on 4.19 | Upgrade to current |
 |---|---|---|
-| Panel | `radio-i2c` | `radio-drm` + driver, or `radio-i2c` |
+| Panel | `radio-ui i2c` | `radio-ui drm` + driver, or `radio-ui i2c` |
 | Kernel changes | Overlay only | Overlay + module |
 | Standard graphics tools | No | Yes (DRM, fbdev emulation) |
 
 The driver cannot build on 4.19: it depends on damage tracking, shmem and client
 helpers from much later kernels. There is no 4.19 tree here to measure the gap.
 
-**Recommendation:** bring up on 4.19 with `radio-i2c`, which gets a working panel
+**Recommendation:** bring up on 4.19 with `radio-ui i2c`, which gets a working panel
 with no kernel risk. Upgrade only if standard graphics tools turn out to be
 wanted, since the application does not need DRM.
 
@@ -236,7 +262,8 @@ cost on the board.
 - [ ] Check the backlight through sysfs
 
 **Phase 2: application on the board**
-- [ ] Build on the SoC or cross-compile; install fonts (DejaVu)
+- [ ] Install python3-gi, python3-gi-cairo, gir1.2-pango-1.0 and fonts (DejaVu); `make lib` on the SoC
+- [ ] Run `make pytest` on the target's Python 3.7.3
 - [ ] Add a systemd unit with restart and `WatchdogSec` (the firmware had a watchdog; the app has no `sd_notify` yet)
 - [ ] Measure CPU load and real update times
 - [ ] Decide on volume control (section 11)
@@ -245,7 +272,7 @@ cost on the board.
 
 **Phase 3: DRM (only if upgrading)**
 - [ ] Upgrade the kernel; build the module for the target
-- [ ] Test with `modetest` and `radio-drm`
+- [ ] Test with `modetest` and `radio-ui drm` (the frontend has run on the dev PC)
 - [ ] Add R1/R2 formats and a blank/power-save path if useful
 - [ ] Keep fbcon off this panel: a blinking cursor means constant I²C traffic
 
@@ -283,7 +310,7 @@ cost on the board.
 The development PC is an AMD BC-250. Its `I2C_HEADER1` and possibly its PIIX4
 SMBus ports reach the voltage regulators (ISL69247, ISL95712). Do not attach the
 expanders there, and do not run `i2cdetect` scans on buses 6-10.
-`radio-i2c` refuses those buses by name. Use a dedicated USB adapter such as an
+`radio-ui i2c` refuses those buses by name. Use a dedicated USB adapter such as an
 MCP2221A; this needs `CONFIG_HID_MCP2221` and `CONFIG_GPIOLIB` enabled.
 
 ## 13. References

+ 10 - 0
radio-ui

@@ -0,0 +1,10 @@
+#!/usr/bin/env python3
+"""Radio panel UI; see radio/__main__.py or `radio-ui --help`."""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
+
+from radio.__main__ import main  # noqa: E402
+
+sys.exit(main())

+ 1 - 0
radio/__init__.py

@@ -0,0 +1 @@
+"""Radio front panel UI (see __main__.py)."""

+ 243 - 0
radio/__main__.py

@@ -0,0 +1,243 @@
+"""radio-ui: the radio panel UI.
+
+    radio-ui sim  [--host radio.lo]           window with the simulated panel
+    radio-ui i2c  --bus N [--host H]          real panel through i2c-dev
+    radio-ui drm  [--host H]                  real panel through the DRM driver
+
+i2c and drm read keys from evdev; with --window-keys (test mode) they read the
+PC keyboard through a window on $DISPLAY instead.
+"""
+import argparse
+import os
+import sys
+
+from . import platform
+
+
+def _int(text):
+    return int(text, 0)
+
+
+def _add_common(p, default_host):
+    p.add_argument("--host", default=default_host,
+                   help="MPD host, or a socket path (%(default)s)")
+    p.add_argument("--port", type=int, default=6600, help="MPD port (%(default)s)")
+    p.add_argument("--kmsg", action="store_true", help="show this machine's kernel log")
+
+
+def _add_geometry(p):
+    p.add_argument("--width", type=int, default=240, help="panel width (%(default)s)")
+    p.add_argument("--height", type=int, default=160, help="panel height (%(default)s)")
+    p.add_argument("--bpp", type=int, default=2, choices=(1, 2, 4),
+                   help="bits per pixel (%(default)s)")
+    p.add_argument("--tcr", type=int, default=162,
+                   help="TC/R, sets the frame rate (%(default)s)")
+
+
+def _add_keys(p, backlight_help):
+    p.add_argument("--input", metavar="PATH",
+                   help="key input device (default: the one named %s)"
+                   % platform.DEFAULT_KEYS_NAME)
+    p.add_argument("--window-keys", action="store_true",
+                   help="test mode: take keys from a window on the X display "
+                   "instead of evdev (also reads --input if given)")
+    p.add_argument("--backlight", metavar="PATH", help=backlight_help)
+
+
+def parse_args(argv):
+    ap = argparse.ArgumentParser(prog="radio-ui", description="Radio front panel UI")
+    sub = ap.add_subparsers(dest="frontend", metavar="FRONTEND")
+    sub.required = True
+
+    p = sub.add_parser("sim", help="window with the simulated panel and on-screen keys")
+    _add_common(p, "radio.lo")
+    _add_geometry(p)
+    p.add_argument("--scale", type=int, default=3, help="window zoom (%(default)s)")
+    p.add_argument("--window-keys", action="store_true",
+                   help="accepted for symmetry: this window always takes the keys")
+    p.add_argument("--press", metavar="LIST", help="click these keys, comma separated")
+    p.add_argument("--snapshot", metavar="FILE", help="write the window to a PNG before exiting")
+    p.add_argument("--exit-after", type=int, default=0, metavar="MS", help="quit after this many ms")
+
+    p = sub.add_parser("i2c", help="real panel through /dev/i2c-N")
+    _add_common(p, "localhost")
+    _add_geometry(p)
+    p.add_argument("--bus", type=int, required=True, help="I2C bus number")
+    p.add_argument("--addr", type=_int, default=0x74, help="expander address (0x74)")
+    p.add_argument("--allow-adapter", metavar="NAME",
+                   help="accept the adapter with this exact name")
+    p.add_argument("--tx-cap", type=int, default=1025, metavar="BYTES",
+                   help="largest I2C message, 7..1025 (%(default)s)")
+    p.add_argument("--no-backlight", action="store_true",
+                   help="leave the expander's backlight pin off")
+    p.add_argument("--pattern", choices=("geometry", "gray"),
+                   help="show a test pattern and exit")
+    _add_keys(p, "backlight sysfs brightness file (default: expander pin P1.0)")
+
+    p = sub.add_parser("drm", help="real panel through the s1d13700-tca DRM driver")
+    _add_common(p, "localhost")
+    _add_keys(p, "backlight sysfs brightness file (%s)" % platform.DEFAULT_BACKLIGHT)
+
+    args = ap.parse_args(argv)
+    if getattr(args, "tx_cap", 7) < 7 or getattr(args, "tx_cap", 0) > 1025:
+        ap.error("--tx-cap: 7..1025")
+    return args
+
+
+# ---- bring-up patterns ---------------------------------------------------------
+
+def make_pattern(name, w, h):
+    """XRGB8888, white background"""
+    fb = bytearray(b"\xff") * (w * h * 4)
+    black = b"\0\0\0\0"
+
+    def put(x, y):
+        o = (y * w + x) * 4
+        fb[o:o + 4] = black
+
+    if name == "geometry":
+        # border, plus ticks every 10 px and long ticks every 50: shows the real size
+        for x in range(w):
+            put(x, 0)
+            put(x, h - 1)
+            if not x % 10:
+                for i in range(4 if x % 50 else 10):
+                    put(x, 1 + i)
+        for y in range(h):
+            put(0, y)
+            put(w - 1, y)
+            if not y % 10:
+                for i in range(4 if y % 50 else 10):
+                    put(1 + i, y)
+        # a diagonal shows skew from a wrong line length
+        for i in range(min(w, h)):
+            put(i, i)
+    else:
+        levels = (0xff, 0xaa, 0x55, 0x00)
+        row = bytearray()
+        for x in range(w):
+            v = levels[x * 4 // w]
+            row += bytes((v, v, v, 0))
+        fb = row * h
+    return fb
+
+
+# ---- frontends -------------------------------------------------------------------
+
+def _start_keys(args, app, loop):
+    if args.window_keys:
+        from . import gtkkeys
+        gtkkeys.require_display()
+        gtkkeys.KeyWindow(app.key, loop.quit)
+        print("test mode: keys from the window on %s" % os.environ.get("DISPLAY", "?"))
+        if args.input and not platform.start_evdev_keys(app.key, args.input):
+            print("cannot read %s" % args.input, file=sys.stderr)
+    elif not platform.start_evdev_keys(app.key, args.input):
+        print("no key input device, running display-only", file=sys.stderr)
+
+
+def run_i2c(args):
+    from gi.repository import GLib
+
+    from .app import App
+    from .panel import Panel
+
+    try:
+        fd = platform.open_i2c_bus(args.bus, args.allow_adapter)
+    except platform.BusRefused as e:
+        print(e, file=sys.stderr)
+        return 1
+
+    panel = Panel(args.width, args.height, args.bpp, args.tcr, fd=fd, addr=args.addr,
+                  tx_cap=args.tx_cap)
+    if not args.backlight and not args.no_backlight:
+        panel.backlight(True)
+    try:
+        panel.init()
+    except OSError as e:
+        print(e, file=sys.stderr)
+        return 1
+
+    if args.pattern:
+        fb = make_pattern(args.pattern, args.width, args.height)
+        try:
+            panel.update(fb, args.width * 4, 0, 0, args.width, args.height)
+        except OSError as e:
+            print("pattern failed: %s" % e, file=sys.stderr)
+            return 1
+        st = panel.stats()
+        print("pattern sent: %d I2C bytes in %d messages" % (st.i2c_bytes, st.i2c_msgs))
+        return 0
+
+    def present(data, stride, x, y, w, h):
+        try:
+            panel.update(data, stride, x, y, w, h)
+        except OSError as e:
+            print("panel update failed: %s" % e, file=sys.stderr)
+
+    def backlight(on):
+        # sysfs if a path was given, otherwise the pin on the panel's own expander
+        if args.backlight:
+            platform.backlight_set(args.backlight, on)
+            return
+        try:
+            panel.backlight(on)
+        except OSError as e:
+            print("backlight: %s" % e, file=sys.stderr)
+
+    loop = GLib.MainLoop()
+    app = App(args.host, args.port, args.width, args.height, present, backlight, args.kmsg)
+    _start_keys(args, app, loop)
+    platform.run(loop)
+    app.close()
+    try:
+        panel.display(False)
+    except OSError:
+        pass
+    return 0
+
+
+def run_drm(args):
+    from gi.repository import GLib
+
+    from .app import App
+    from .drm import DrmError, DrmPanel
+
+    try:
+        dev = DrmPanel()
+    except (DrmError, OSError) as e:
+        print("cannot set up the display: %s" % e, file=sys.stderr)
+        return 1
+    blpath = args.backlight or platform.DEFAULT_BACKLIGHT
+
+    def present(*a):
+        try:
+            dev.present(*a)
+        except DrmError as e:
+            print(e, file=sys.stderr)
+
+    loop = GLib.MainLoop()
+    app = App(args.host, args.port, dev.width, dev.height, present,
+              lambda on: platform.backlight_set(blpath, on), args.kmsg)
+    _start_keys(args, app, loop)
+    platform.run(loop)
+    app.close()
+    return 0
+
+
+def run_sim(args):
+    from . import sim   # first: it picks the Gtk version
+    from gi.repository import GLib, Gtk
+
+    for sig in (2, 15):     # SIGINT, SIGTERM
+        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, sig, lambda *_: Gtk.main_quit() or False)
+    return sim.run(args)
+
+
+def main(argv=None):
+    args = parse_args(sys.argv[1:] if argv is None else argv)
+    return {"sim": run_sim, "i2c": run_i2c, "drm": run_drm}[args.frontend](args)
+
+
+if __name__ == "__main__":
+    sys.exit(main())

+ 178 - 0
radio/app.py

@@ -0,0 +1,178 @@
+"""Radio UI core: everything that is the same in the window and on the panel.
+
+A frontend supplies present(data, stride, x, y, w, h), which gets the whole
+XRGB8888 frame and the rectangle that changed, and optionally backlight(on).
+"""
+import errno
+import os
+
+import cairo
+from gi.repository import GLib
+
+from . import mpd, render
+from . import state as st
+
+BACKLIGHT_TIMEOUT_S = 30
+KEY_LOCKOUT_MS = 300        # as the firmware: 300 ms after a press
+LOG_REDRAW_MS = 1000        # scrolling is the costliest redraw
+
+_KEY_COMMANDS = {
+    "prev": mpd.PREV,
+    "play": mpd.PLAY,
+    "pause": mpd.TOGGLE,
+    "stop": mpd.STOP,
+    "next": mpd.NEXT,
+    "esc": mpd.REFRESH,
+    "up": mpd.VOLUME_UP,
+    "down": mpd.VOLUME_DOWN,
+    # menu, list, ok, left, right: not assigned yet
+}
+
+
+class App(object):
+    def __init__(self, host, port, width, height, present, backlight=None, kmsg=False):
+        self.width, self.height = width, height
+        self.present = present
+        self.backlight = backlight
+        self.state = st.RadioState(host)
+
+        self.surface = cairo.ImageSurface(cairo.FORMAT_RGB24, width, height)
+        self.stride = self.surface.get_stride()
+        self.prev = None
+
+        self.render_id = 0
+        self.log_timer_id = 0
+        self.backlight_id = 0
+        self.key_time_ms = {}
+
+        self.mpd = mpd.MpdClient(host, port, self.state, self._schedule_render, self.log)
+        self.kmsg = KmsgFollower(self.log) if kmsg else None
+        self.tick_id = GLib.timeout_add_seconds(1, self._tick)
+        self._backlight_wake()
+        self._schedule_render()
+
+    def close(self):
+        for attr in ("render_id", "log_timer_id", "backlight_id", "tick_id"):
+            if getattr(self, attr):
+                GLib.source_remove(getattr(self, attr))
+                setattr(self, attr, 0)
+        if self.kmsg:
+            self.kmsg.close()
+        self.mpd.close()
+
+    # ---- rendering ------------------------------------------------------------
+
+    def _render_now(self):
+        self.render_id = 0
+        cr = cairo.Context(self.surface)
+        render.render(cr, self.state, self.width, self.height)
+        del cr
+        self.surface.flush()
+
+        data = self.surface.get_data()
+        frame = bytes(data)
+        stride, y0, y1 = self.stride, None, 0
+        for y in range(self.height):
+            a = y * stride
+            if self.prev is not None and frame[a:a + stride] == self.prev[a:a + stride]:
+                continue
+            if y0 is None:
+                y0 = y
+            y1 = y + 1
+        self.prev = frame
+        # whole rows: the panel core finds the changed bytes itself
+        if y0 is not None:
+            self.present(data, stride, 0, y0, self.width, y1 - y0)
+        return False
+
+    def _schedule_render(self):
+        if not self.render_id:
+            self.render_id = GLib.idle_add(self._render_now)
+
+    def _tick(self):
+        if self.state.state == st.PLAY_PLAYING:
+            self._schedule_render()
+        return True
+
+    # ---- log ------------------------------------------------------------------
+
+    def log(self, text):
+        self.state.log_append(text)
+        if not self.log_timer_id:
+            self.log_timer_id = GLib.timeout_add(LOG_REDRAW_MS, self._log_timer)
+
+    def _log_timer(self):
+        self.log_timer_id = 0
+        self._schedule_render()
+        return False
+
+    # ---- keys and backlight -----------------------------------------------------
+
+    def _backlight_expired(self):
+        self.backlight_id = 0
+        if self.backlight:
+            self.backlight(False)
+        return False
+
+    def _backlight_wake(self):
+        if self.backlight:
+            self.backlight(True)
+        if self.backlight_id:
+            GLib.source_remove(self.backlight_id)
+        self.backlight_id = GLib.timeout_add_seconds(BACKLIGHT_TIMEOUT_S,
+                                                     self._backlight_expired)
+
+    def key(self, name):
+        if name not in st.KEYS:
+            return
+        now = st.monotonic_ms()
+        last = self.key_time_ms.get(name)
+        if last is not None and now - last < KEY_LOCKOUT_MS:
+            return
+        self.key_time_ms[name] = now
+        self._backlight_wake()
+        cmd = _KEY_COMMANDS.get(name)
+        if cmd is not None:
+            self.mpd.command(cmd)
+
+
+class KmsgFollower(object):
+    """Kernel log pane source: follows /dev/kmsg from the moment it is opened"""
+
+    def __init__(self, log):
+        self.log = log
+        self.watch_id = 0
+        try:
+            self.fd = os.open("/dev/kmsg", os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC)
+        except OSError:
+            self.fd = -1
+            log("Nie można otworzyć /dev/kmsg")
+            return
+        os.lseek(self.fd, 0, os.SEEK_END)
+        self.watch_id = GLib.io_add_watch(self.fd, GLib.PRIORITY_DEFAULT,
+                                          GLib.IO_IN, self._on_readable)
+
+    def _on_readable(self, fd, cond):
+        while True:
+            try:
+                rec = os.read(self.fd, 4096)
+            except OSError as e:
+                if e.errno == errno.EPIPE:
+                    continue    # records were overwritten; carry on
+                if e.errno == errno.EAGAIN:
+                    return True
+                break
+            if not rec:
+                break
+            # "prio,seq,usec,flags;message\n" then optional " KEY=value" lines
+            head, sep, text = rec.decode("utf-8", "replace").partition(";")
+            if sep:
+                self.log(text.split("\n", 1)[0])
+        self.watch_id = 0
+        return False
+
+    def close(self):
+        if self.watch_id:
+            GLib.source_remove(self.watch_id)
+        if self.fd >= 0:
+            os.close(self.fd)

+ 186 - 0
radio/drm.py

@@ -0,0 +1,186 @@
+"""The panel through the s1d13700-tca DRM driver: one dumb buffer, with each
+change reported as a dirty rectangle.
+
+libdrm through ctypes, limited to calls that libdrm 2.4.97 (Debian buster)
+already has; the dumb buffer is made with plain ioctls.
+"""
+import ctypes
+import ctypes.util
+import fcntl
+import mmap
+import os
+import struct
+
+DRIVER_NAME = "s1d13700-tca"
+FORMAT_XRGB8888 = 0x34325258    # "XR24"
+
+
+class DrmError(Exception):
+    pass
+
+
+class _Version(ctypes.Structure):
+    _fields_ = [("version_major", ctypes.c_int), ("version_minor", ctypes.c_int),
+                ("version_patchlevel", ctypes.c_int),
+                ("name_len", ctypes.c_int), ("name", ctypes.c_char_p),
+                ("date_len", ctypes.c_int), ("date", ctypes.c_char_p),
+                ("desc_len", ctypes.c_int), ("desc", ctypes.c_char_p)]
+
+
+class _Res(ctypes.Structure):
+    _fields_ = [("count_fbs", ctypes.c_int), ("fbs", ctypes.POINTER(ctypes.c_uint32)),
+                ("count_crtcs", ctypes.c_int), ("crtcs", ctypes.POINTER(ctypes.c_uint32)),
+                ("count_connectors", ctypes.c_int),
+                ("connectors", ctypes.POINTER(ctypes.c_uint32)),
+                ("count_encoders", ctypes.c_int),
+                ("encoders", ctypes.POINTER(ctypes.c_uint32)),
+                ("min_width", ctypes.c_uint32), ("max_width", ctypes.c_uint32),
+                ("min_height", ctypes.c_uint32), ("max_height", ctypes.c_uint32)]
+
+
+class ModeInfo(ctypes.Structure):
+    _fields_ = [("clock", ctypes.c_uint32)] + [
+        (n, ctypes.c_uint16) for n in (
+            "hdisplay", "hsync_start", "hsync_end", "htotal", "hskew",
+            "vdisplay", "vsync_start", "vsync_end", "vtotal", "vscan")] + [
+        ("vrefresh", ctypes.c_uint32), ("flags", ctypes.c_uint32),
+        ("type", ctypes.c_uint32), ("name", ctypes.c_char * 32)]
+
+
+class _Connector(ctypes.Structure):
+    _fields_ = [("connector_id", ctypes.c_uint32), ("encoder_id", ctypes.c_uint32),
+                ("connector_type", ctypes.c_uint32), ("connector_type_id", ctypes.c_uint32),
+                ("connection", ctypes.c_int),
+                ("mmWidth", ctypes.c_uint32), ("mmHeight", ctypes.c_uint32),
+                ("subpixel", ctypes.c_int),
+                ("count_modes", ctypes.c_int), ("modes", ctypes.POINTER(ModeInfo))]
+    # the rest (props, encoders) is not used
+
+
+class _Clip(ctypes.Structure):
+    _fields_ = [("x1", ctypes.c_uint16), ("y1", ctypes.c_uint16),
+                ("x2", ctypes.c_uint16), ("y2", ctypes.c_uint16)]
+
+
+def _iowr(nr, size):
+    return (3 << 30) | (size << 16) | (ord("d") << 8) | nr
+
+
+_CREATE_DUMB = struct.Struct("=IIIIIIQ")     # height width bpp flags handle pitch size
+_MAP_DUMB = struct.Struct("=IIQ")            # handle pad offset
+DRM_IOCTL_MODE_CREATE_DUMB = _iowr(0xB2, _CREATE_DUMB.size)
+DRM_IOCTL_MODE_MAP_DUMB = _iowr(0xB3, _MAP_DUMB.size)
+
+
+def _load_libdrm():
+    name = ctypes.util.find_library("drm") or "libdrm.so.2"
+    lib = ctypes.CDLL(name, use_errno=True)
+    vp, ci, u32 = ctypes.c_void_p, ctypes.c_int, ctypes.c_uint32
+    lib.drmGetVersion.restype = ctypes.POINTER(_Version)
+    lib.drmGetVersion.argtypes = [ci]
+    lib.drmFreeVersion.argtypes = [vp]
+    lib.drmModeGetResources.restype = ctypes.POINTER(_Res)
+    lib.drmModeGetResources.argtypes = [ci]
+    lib.drmModeFreeResources.argtypes = [vp]
+    lib.drmModeGetConnector.restype = ctypes.POINTER(_Connector)
+    lib.drmModeGetConnector.argtypes = [ci, u32]
+    lib.drmModeFreeConnector.argtypes = [vp]
+    lib.drmModeAddFB2.restype = ci
+    lib.drmModeAddFB2.argtypes = [ci, u32, u32, u32, ctypes.POINTER(u32 * 4),
+                                  ctypes.POINTER(u32 * 4), ctypes.POINTER(u32 * 4),
+                                  ctypes.POINTER(u32), u32]
+    lib.drmModeSetCrtc.restype = ci
+    lib.drmModeSetCrtc.argtypes = [ci, u32, u32, u32, u32, ctypes.POINTER(u32), ci,
+                                   ctypes.POINTER(ModeInfo)]
+    lib.drmModeDirtyFB.restype = ci
+    lib.drmModeDirtyFB.argtypes = [ci, u32, ctypes.POINTER(_Clip), u32]
+    return lib
+
+
+def _errno_error(what):
+    e = ctypes.get_errno()
+    return DrmError("%s: %s" % (what, os.strerror(e) if e else "failed"))
+
+
+class DrmPanel(object):
+    def __init__(self):
+        self.lib = _load_libdrm()
+        self.fd = self._open_panel()
+        try:
+            self._setup()
+        except Exception:
+            os.close(self.fd)
+            raise
+
+    def _open_panel(self):
+        """Only ever our own device: never take over the machine's real display"""
+        for i in range(16):
+            try:
+                fd = os.open("/dev/dri/card%d" % i, os.O_RDWR | os.O_CLOEXEC)
+            except OSError:
+                continue
+            v = self.lib.drmGetVersion(fd)
+            match = bool(v) and v.contents.name == DRIVER_NAME.encode()
+            if v:
+                self.lib.drmFreeVersion(v)
+            if match:
+                return fd
+            os.close(fd)
+        raise DrmError("no %s DRM device found" % DRIVER_NAME)
+
+    def _setup(self):
+        lib, fd = self.lib, self.fd
+        res = lib.drmModeGetResources(fd)
+        if not res:
+            raise _errno_error("no mode resources")
+        try:
+            r = res.contents
+            if r.count_connectors < 1 or r.count_crtcs < 1:
+                raise DrmError("no connector or CRTC")
+            crtc = r.crtcs[0]
+            conn = lib.drmModeGetConnector(fd, r.connectors[0])
+        finally:
+            lib.drmModeFreeResources(res)
+        if not conn:
+            raise _errno_error("no connector")
+        try:
+            c = conn.contents
+            if c.count_modes < 1:
+                raise DrmError("the connector has no mode")
+            self.mode = ModeInfo.from_buffer_copy(c.modes[0])
+            conn_id = ctypes.c_uint32(c.connector_id)
+        finally:
+            lib.drmModeFreeConnector(conn)
+
+        self.width, self.height = self.mode.hdisplay, self.mode.vdisplay
+        req = bytearray(_CREATE_DUMB.pack(self.height, self.width, 32, 0, 0, 0, 0))
+        fcntl.ioctl(fd, DRM_IOCTL_MODE_CREATE_DUMB, req, True)
+        _, _, _, _, handle, self.pitch, size = _CREATE_DUMB.unpack(bytes(req))
+
+        u32x4 = ctypes.c_uint32 * 4
+        fb_id = ctypes.c_uint32()
+        if lib.drmModeAddFB2(fd, self.width, self.height, FORMAT_XRGB8888,
+                             ctypes.byref(u32x4(handle)), ctypes.byref(u32x4(self.pitch)),
+                             ctypes.byref(u32x4(0)), ctypes.byref(fb_id), 0):
+            raise _errno_error("ADDFB2")
+        self.fb_id = fb_id.value
+
+        req = bytearray(_MAP_DUMB.pack(handle, 0, 0))
+        fcntl.ioctl(fd, DRM_IOCTL_MODE_MAP_DUMB, req, True)
+        offset = _MAP_DUMB.unpack(bytes(req))[2]
+        self.map = mmap.mmap(fd, size, mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE,
+                             offset=offset)
+        self.map[:] = b"\xff" * size
+
+        if lib.drmModeSetCrtc(fd, crtc, self.fb_id, 0, 0, ctypes.byref(conn_id), 1,
+                              ctypes.byref(self.mode)):
+            raise _errno_error("SETCRTC")
+
+    def present(self, data, stride, x, y, w, h):
+        for row in range(y, y + h):
+            src = row * stride + x * 4
+            dst = row * self.pitch + x * 4
+            self.map[dst:dst + w * 4] = data[src:src + w * 4]
+        clip = _Clip(x, y, x + w, y + h)
+        if self.lib.drmModeDirtyFB(self.fd, self.fb_id, ctypes.byref(clip), 1):
+            raise _errno_error("DIRTYFB")

+ 98 - 0
radio/gtkkeys.py

@@ -0,0 +1,98 @@
+"""Keys from the desktop: the shortcut table and button grid of the simulator
+window, and the test mode window that feeds the PC keyboard to a real panel."""
+import sys
+
+import gi
+
+gi.require_version("Gtk", "3.0")
+gi.require_version("Gdk", "3.0")
+from gi.repository import Gdk, Gtk  # noqa: E402
+
+# key, button label, GDK key names, grid column and row
+KEY_DEFS = (
+    ("prev", "⏮ Prev (Z)", ("z", "Z", "XF86AudioPrev"), 0, 0),
+    ("play", "▶ Play (X)", ("x", "X", "XF86AudioPlay"), 1, 0),
+    ("pause", "⏯ Pause (C)", ("c", "C", "space", "XF86AudioPause"), 2, 0),
+    ("stop", "⏹ Stop (V)", ("v", "V", "XF86AudioStop"), 3, 0),
+    ("next", "⏭ Next (B)", ("b", "B", "XF86AudioNext"), 4, 0),
+    ("esc", "Esc", ("Escape",), 0, 1),
+    ("up", "▲ Vol+ (↑)", ("Up", "XF86AudioRaiseVolume"), 2, 1),
+    ("menu", "Menu (M)", ("m", "M", "Menu"), 4, 1),
+    ("left", "◀ (←)", ("Left",), 1, 2),
+    ("ok", "OK (Enter)", ("Return", "KP_Enter"), 2, 2),
+    ("right", "▶ (→)", ("Right",), 3, 2),
+    ("down", "▼ Vol− (↓)", ("Down", "XF86AudioLowerVolume"), 2, 3),
+    ("list", "List (L)", ("l", "L"), 4, 3),
+)
+
+# by keyval: GDK versions differ in the names they give back (AudioPlay or
+# XF86AudioPlay), but all of them parse the X names
+_BY_KEYVAL = {}
+for _key, _label, _names, _col, _row in KEY_DEFS:
+    for _n in _names:
+        _v = Gdk.keyval_from_name(_n)
+        if _v and _v != Gdk.KEY_VoidSymbol:
+            _BY_KEYVAL[_v] = _key
+
+
+def require_display():
+    if Gdk.Display.get_default() is None:
+        print("cannot open the X display (is DISPLAY set?)", file=sys.stderr)
+        sys.exit(1)
+
+
+def key_for_event(event):
+    return _BY_KEYVAL.get(event.keyval)
+
+
+def key_grid(on_key):
+    """Grid with a button per key; returns (grid, {key: button})"""
+    grid = Gtk.Grid()
+    grid.set_row_spacing(4)
+    grid.set_column_spacing(4)
+    grid.set_column_homogeneous(True)
+    buttons = {}
+    for key, label, _names, col, row in KEY_DEFS:
+        b = Gtk.Button(label=label)
+        # a focused button would take Space and Enter from the shortcuts
+        b.set_can_focus(False)
+        b.connect("clicked", lambda _b, k=key: on_key(k))
+        grid.attach(b, col, row, 1, 1)
+        buttons[key] = b
+    return grid, buttons
+
+
+class KeyWindow(object):
+    """Test mode: a window on the desktop whose key presses go to the panel"""
+
+    def __init__(self, on_key, on_close):
+        self.on_key = on_key
+        self.window = Gtk.Window(title="Radio panel keys")
+        self.window.set_resizable(False)
+        self.window.connect("destroy", lambda _w: on_close())
+        self.window.connect("key-press-event", self._key_press)
+
+        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
+        box.set_border_width(8)
+        self.window.add(box)
+
+        hint = Gtk.Label(label="Keys typed here go to the panel.")
+        hint.set_xalign(0)
+        box.pack_start(hint, False, False, 0)
+        grid, _ = key_grid(self._pressed)
+        box.pack_start(grid, False, False, 0)
+        self.last = Gtk.Label(label="")
+        self.last.set_xalign(0)
+        box.pack_start(self.last, False, False, 0)
+        self.window.show_all()
+
+    def _pressed(self, key):
+        self.last.set_text("last key: " + key)
+        self.on_key(key)
+
+    def _key_press(self, _w, event):
+        key = key_for_event(event)
+        if key is None:
+            return False
+        self._pressed(key)
+        return True

+ 159 - 0
radio/libpanel.c

@@ -0,0 +1,159 @@
+/*
+ * Shared library for the Python UI: the panel core and the simulator behind
+ * an opaque handle, so Python never has to mirror the C structures.
+ *
+ * Transports: i2c-dev (the caller opens and checks the bus, then passes the
+ * file descriptor) or the simulator. All calls return 0 or -errno.
+ */
+#include <errno.h>
+#include <linux/i2c-dev.h>
+#include <linux/i2c.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+
+#include "s1d13700_core.h"
+#include "s1d13700_sim.h"
+
+#define PANEL_API_VERSION	1
+#define TX_CAP			1025	/* the driver's message limit */
+
+struct panel {
+	struct s1d_config cfg;
+	struct s1d_panel core;
+	struct s1d_sim sim;
+	bool use_sim;
+	int fd;
+	unsigned int addr;
+	uint8_t shadow[S1D_VRAM_SIZE];
+	uint8_t next[S1D_VRAM_SIZE];
+	uint8_t tx[TX_CAP];
+};
+
+static int i2c_xfer(void *ctx, const uint8_t *buf, size_t len)
+{
+	struct panel *p = ctx;
+	struct i2c_msg msg = { (uint16_t)p->addr, 0, (uint16_t)len, (uint8_t *)buf };
+	struct i2c_rdwr_ioctl_data data = { &msg, 1 };
+
+	return ioctl(p->fd, I2C_RDWR, &data) < 0 ? -errno : 0;
+}
+
+static void i2c_delay(void *ctx, unsigned int ms)
+{
+	(void)ctx;
+	usleep(ms * 1000);
+}
+
+static int sim_xfer(void *ctx, const uint8_t *buf, size_t len)
+{
+	s1d_sim_i2c_write(&((struct panel *)ctx)->sim, buf, len);
+	return 0;
+}
+
+static void sim_delay(void *ctx, unsigned int ms)
+{
+	(void)ctx;
+	(void)ms;
+}
+
+static const struct s1d_ops i2c_ops = { i2c_xfer, i2c_delay };
+static const struct s1d_ops sim_ops = { sim_xfer, sim_delay };
+
+int panel_api_version(void)
+{
+	return PANEL_API_VERSION;
+}
+
+/* fd < 0 selects the simulator. Returns NULL for a configuration the core rejects. */
+struct panel *panel_new(int fd, unsigned int addr, unsigned int width,
+			unsigned int height, unsigned int bpp, unsigned int tcr,
+			unsigned int tx_cap)
+{
+	struct panel *p = calloc(1, sizeof(*p));
+
+	if (!p)
+		return NULL;
+	p->cfg = (struct s1d_config){ width, height, bpp, tcr };
+	p->fd = fd;
+	p->addr = addr;
+	p->use_sim = fd < 0;
+	if (p->use_sim)
+		s1d_sim_init(&p->sim);
+	if (!tx_cap || tx_cap > TX_CAP)
+		tx_cap = TX_CAP;
+	if (s1d_panel_setup(&p->core, &p->cfg, p->use_sim ? &sim_ops : &i2c_ops, p,
+			    p->shadow, p->tx, tx_cap)) {
+		free(p);
+		return NULL;
+	}
+	return p;
+}
+
+void panel_free(struct panel *p)
+{
+	free(p);
+}
+
+int panel_init(struct panel *p)
+{
+	return s1d_panel_init(&p->core);
+}
+
+/*
+ * Convert the changed XRGB8888 rectangle into the pending native frame and
+ * bring the panel's rows [y0, y1) up to date with it.
+ */
+int panel_update(struct panel *p, const void *pixels, unsigned int pitch,
+		 unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1)
+{
+	s1d_convert_xrgb8888(&p->cfg, pixels, pitch, p->next, x0, y0, x1, y1);
+	return s1d_panel_update(&p->core, p->next, y0, y1);
+}
+
+int panel_display(struct panel *p, int on)
+{
+	return s1d_panel_display(&p->core, on);
+}
+
+int panel_backlight(struct panel *p, int on)
+{
+	return s1d_panel_backlight(&p->core, on);
+}
+
+/* writes, data_bytes, seeks, dir_changes, i2c_msgs, i2c_bytes */
+void panel_stats(const struct panel *p, unsigned long out[6])
+{
+	const struct s1d_stats *st = &p->core.stats;
+
+	out[0] = st->writes;
+	out[1] = st->data_bytes;
+	out[2] = st->seeks;
+	out[3] = st->dir_changes;
+	out[4] = st->i2c_msgs;
+	out[5] = st->i2c_bytes;
+}
+
+void panel_stats_reset(struct panel *p)
+{
+	memset(&p->core.stats, 0, sizeof(p->core.stats));
+}
+
+double panel_bus_us(const struct panel *p, unsigned int scl_hz)
+{
+	return (double)s1d_stats_bus_us(&p->core.stats, scl_hz);
+}
+
+/* Simulator only: levels gets width * height bytes. Returns 1 if shown. */
+int panel_sim_render(const struct panel *p, uint8_t *levels)
+{
+	if (!p->use_sim)
+		return -EINVAL;
+	return s1d_sim_render(&p->sim, p->cfg.width, p->cfg.height, levels);
+}
+
+int panel_sim_faults(const struct panel *p)
+{
+	return p->use_sim ? (int)s1d_sim_fault_count(&p->sim) : 0;
+}

+ 289 - 0
radio/mpd.py

@@ -0,0 +1,289 @@
+"""MPD connection on the GLib main loop.
+
+The connection sits in "idle", so changes arrive as events instead of being
+polled; a command first leaves idle, does its work and goes back. Commands are
+synchronous with a timeout, like libmpdclient's. Reconnects every 3 s.
+"""
+import socket
+
+from gi.repository import GLib
+
+from . import state as st
+
+CONNECT_TIMEOUT_S = 2.0
+RECONNECT_S = 3
+IDLE_SUBSYSTEMS = "playlist player mixer options"
+
+PLAY, TOGGLE, STOP, NEXT, PREV, VOLUME_UP, VOLUME_DOWN, REFRESH = range(8)
+
+_COMMANDS = {
+    PLAY: "play",
+    TOGGLE: "pause",
+    STOP: "stop",
+    NEXT: "next",
+    PREV: "previous",
+    VOLUME_UP: "volume +1",
+    VOLUME_DOWN: "volume -1",
+}
+
+
+class ConnectionLost(Exception):
+    pass
+
+
+class ServerError(Exception):
+    """ACK from the server: the command was refused, the session goes on"""
+
+
+def _ack_message(line):
+    # ACK [error@command_listNum] {current_command} message_text
+    brace = line.find("} ")
+    return line[brace + 2:] if brace >= 0 else line
+
+
+def format_title(song):
+    artist, title, name = song.get("artist"), song.get("title"), song.get("name")
+    uri = song.get("file", "")
+    if artist and title:
+        return "%s - %s" % (artist, title)
+    if title and name:      # a stream announcing what it plays
+        return "%s: %s" % (name, title)
+    if title or name:
+        return title or name
+    slash = uri.rfind("/")
+    if slash >= 0 and slash + 1 < len(uri) and "://" not in uri:
+        return uri[slash + 1:]
+    return uri
+
+
+class Connection(object):
+    """Blocking line protocol; any socket trouble raises ConnectionLost"""
+
+    def __init__(self, host, port):
+        if host.startswith("/"):
+            self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+            self.sock.settimeout(CONNECT_TIMEOUT_S)
+            try:
+                self.sock.connect(host)
+            except (OSError, socket.timeout):
+                self.sock.close()
+                raise
+        else:
+            self.sock = socket.create_connection((host, port), CONNECT_TIMEOUT_S)
+        self.sock.settimeout(CONNECT_TIMEOUT_S)
+        self.buf = b""
+        try:
+            hello = self.read_line()
+        except ConnectionLost:
+            self.close()
+            raise
+        if not hello.startswith("OK MPD "):
+            self.close()
+            raise ConnectionLost("not an MPD server")
+
+    def fileno(self):
+        return self.sock.fileno()
+
+    def close(self):
+        try:
+            self.sock.close()
+        except OSError:
+            pass
+
+    def send(self, line):
+        try:
+            self.sock.sendall(line.encode("utf-8") + b"\n")
+        except (OSError, socket.timeout) as e:
+            raise ConnectionLost(str(e) or "write failed")
+
+    def read_line(self):
+        while b"\n" not in self.buf:
+            try:
+                chunk = self.sock.recv(4096)
+            except socket.timeout:
+                raise ConnectionLost("timeout")
+            except OSError as e:
+                raise ConnectionLost(str(e))
+            if not chunk:
+                raise ConnectionLost("connection closed")
+            self.buf += chunk
+        line, self.buf = self.buf.split(b"\n", 1)
+        return line.decode("utf-8", "replace")
+
+    def read_response(self):
+        """Lines up to OK, as (key, value) pairs; ACK raises ServerError"""
+        pairs = []
+        while True:
+            line = self.read_line()
+            if line == "OK":
+                return pairs
+            if line.startswith("ACK "):
+                raise ServerError(_ack_message(line))
+            key, sep, value = line.partition(": ")
+            if sep:
+                pairs.append((key, value))
+
+    def command(self, line):
+        self.send(line)
+        return self.read_response()
+
+
+class MpdClient(object):
+    """changed() is called whenever state may have changed; log(text) notes events"""
+
+    def __init__(self, host, port, state, changed, log):
+        self.host, self.port = host, port
+        self.state = state
+        self.changed = changed
+        self.log = log
+        self.conn = None
+        self.watch_id = 0
+        self.was_connected = False
+        # not directly: the owner must finish construction first
+        self.retry_id = GLib.idle_add(self._try_connect)
+
+    def close(self):
+        if self.watch_id:
+            GLib.source_remove(self.watch_id)
+            self.watch_id = 0
+        if self.retry_id:
+            GLib.source_remove(self.retry_id)
+            self.retry_id = 0
+        if self.conn:
+            self.conn.close()
+            self.conn = None
+
+    # ---- connection ---------------------------------------------------------
+
+    def _drop(self, why):
+        if self.watch_id:
+            GLib.source_remove(self.watch_id)
+            self.watch_id = 0
+        if self.conn:
+            self.conn.close()
+            self.conn = None
+        self.state.connected = False
+        if self.was_connected and why:
+            self.log("MPD: %s" % why)
+        self.was_connected = False
+        if not self.retry_id:
+            self.retry_id = GLib.timeout_add_seconds(RECONNECT_S, self._try_connect)
+        self.changed()
+
+    def _try_connect(self):
+        self.retry_id = 0
+        try:
+            self.conn = Connection(self.host, self.port)
+        except (OSError, socket.timeout, ConnectionLost):
+            self.retry_id = GLib.timeout_add_seconds(RECONNECT_S, self._try_connect)
+            return False
+
+        self.state.connected = True
+        self.was_connected = True
+        self.log("Połączono z MPD: %s" % self.host)
+        if self._run(self._refresh):
+            self.watch_id = GLib.io_add_watch(
+                self.conn.fileno(), GLib.PRIORITY_DEFAULT,
+                GLib.IO_IN | GLib.IO_HUP | GLib.IO_ERR, self._on_readable)
+            self._enter_idle()
+        return False
+
+    def _run(self, fn, *args):
+        """Call fn; True if the connection survived it"""
+        try:
+            fn(*args)
+        except ServerError as e:
+            self.log("MPD: %s" % e)
+        except ConnectionLost as e:
+            self._drop(str(e))
+            return False
+        return True
+
+    def _enter_idle(self):
+        if self.conn:
+            try:
+                self.conn.send("idle " + IDLE_SUBSYSTEMS)
+            except ConnectionLost as e:
+                self._drop(str(e))
+
+    def _on_readable(self, fd, cond):
+        if cond & (GLib.IO_HUP | GLib.IO_ERR):
+            self.watch_id = 0
+            self._drop("connection closed")
+            return False
+        # the idle response: "changed: ..." lines, then OK
+        if not self._run(self.conn.read_response):
+            return False    # _drop() removed this watch
+        if not self._run(self._refresh):
+            return False
+        self._enter_idle()
+        return self.conn is not None
+
+    # ---- state ----------------------------------------------------------------
+
+    def _refresh(self):
+        s = self.state
+        status = dict(self.conn.command("status"))
+
+        s.state = {"play": st.PLAY_PLAYING, "pause": st.PLAY_PAUSED,
+                   "stop": st.PLAY_STOPPED}.get(status.get("state"), st.PLAY_UNKNOWN)
+        s.song_pos = _int(status.get("song"), -1)
+        s.queue_len = _int(status.get("playlistlength"), 0)
+        elapsed_s, total_s = 0.0, 0
+        time_field = status.get("time", "")
+        if ":" in time_field:
+            a, b = time_field.split(":", 1)
+            elapsed_s, total_s = _float(a, 0.0), _int(b, 0)
+        if "elapsed" in status:
+            elapsed_s = _float(status["elapsed"], elapsed_s)
+        if not total_s and "duration" in status:
+            total_s = int(_float(status["duration"], 0.0))
+        s.elapsed_ms = int(elapsed_s * 1000)
+        s.elapsed_stamp_ms = st.monotonic_ms()
+        s.total_ms = total_s * 1000
+        s.volume = _int(status.get("volume"), -1)
+        s.repeat = status.get("repeat") == "1"
+        s.random = status.get("random") == "1"
+
+        s.title = ""
+        # as the firmware: a stopped player shows no title
+        if s.state != st.PLAY_STOPPED:
+            song = {}
+            for key, value in self.conn.command("currentsong"):
+                song.setdefault(key.lower(), value)     # first value of each tag
+            if song:
+                s.title = format_title(song)
+        self.changed()
+
+    def command(self, cmd):
+        if not self.conn:
+            self.log("Brak połączenia z MPD")
+            return
+        # leave idle; any event it reports is covered by the refresh below
+        try:
+            self.conn.send("noidle")
+            self.conn.read_response()
+        except ServerError:
+            pass
+        except ConnectionLost as e:
+            self._drop(str(e))
+            return
+        line = _COMMANDS.get(cmd)
+        if line and not self._run(self.conn.command, line):
+            return
+        if self._run(self._refresh):
+            self._enter_idle()
+
+
+def _int(text, default):
+    try:
+        return int(text)
+    except (TypeError, ValueError):
+        return default
+
+
+def _float(text, default):
+    try:
+        return float(text)
+    except (TypeError, ValueError):
+        return default

+ 136 - 0
radio/panel.py

@@ -0,0 +1,136 @@
+"""The C panel core (driver/s1d13700_core.c) and simulator, through ctypes.
+
+The core is shared with the kernel driver, so it stays in C; build it with
+`make lib`. RADIO_PANEL_LIB overrides where the library is looked for.
+"""
+import ctypes
+import errno
+import os
+
+API_VERSION = 1
+LIB_NAME = "libradiopanel.so"
+TX_CAP = 1025
+
+_here = os.path.dirname(os.path.abspath(__file__))
+_lib = None
+
+
+class PanelError(Exception):
+    pass
+
+
+def _candidates():
+    env = os.environ.get("RADIO_PANEL_LIB")
+    if env:
+        yield env
+    yield os.path.join(_here, "..", "build", LIB_NAME)
+    yield os.path.join(_here, LIB_NAME)
+
+
+def load_library():
+    global _lib
+    if _lib is not None:
+        return _lib
+    tried = []
+    for path in _candidates():
+        path = os.path.normpath(path)
+        tried.append(path)
+        if os.path.exists(path):
+            lib = ctypes.CDLL(path)
+            break
+    else:
+        raise PanelError("panel library not found (run `make lib`); tried: "
+                         + ", ".join(tried))
+
+    vp = ctypes.c_void_p
+    ci, cu, cul = ctypes.c_int, ctypes.c_uint, ctypes.c_ulong
+    sigs = {
+        "panel_api_version": (ci, []),
+        "panel_new": (vp, [ci, cu, cu, cu, cu, cu, cu]),
+        "panel_free": (None, [vp]),
+        "panel_init": (ci, [vp]),
+        "panel_update": (ci, [vp, vp, cu, cu, cu, cu, cu]),
+        "panel_display": (ci, [vp, ci]),
+        "panel_backlight": (ci, [vp, ci]),
+        "panel_stats": (None, [vp, ctypes.POINTER(cul)]),
+        "panel_stats_reset": (None, [vp]),
+        "panel_bus_us": (ctypes.c_double, [vp, cu]),
+        "panel_sim_render": (ci, [vp, ctypes.c_char_p]),
+        "panel_sim_faults": (ci, [vp]),
+    }
+    for name, (res, args) in sigs.items():
+        fn = getattr(lib, name)
+        fn.restype = res
+        fn.argtypes = args
+    if lib.panel_api_version() != API_VERSION:
+        raise PanelError("%s is out of date, rebuild it with `make lib`" % path)
+    _lib = lib
+    return lib
+
+
+def _check(ret, what):
+    if ret < 0:
+        raise OSError(-ret, "%s: %s" % (what, os.strerror(-ret)))
+    return ret
+
+
+class Stats(object):
+    FIELDS = ("writes", "data_bytes", "seeks", "dir_changes", "i2c_msgs", "i2c_bytes")
+
+    def __init__(self, values, bus_us):
+        for name, v in zip(self.FIELDS, values):
+            setattr(self, name, v)
+        self.bus_us = bus_us
+
+
+class Panel(object):
+    """fd is an open, already checked /dev/i2c-N, or None for the simulator."""
+
+    def __init__(self, width=240, height=160, bpp=2, tcr=162, fd=None,
+                 addr=0x74, tx_cap=TX_CAP):
+        self._lib = load_library()
+        self.width, self.height = width, height
+        self.simulated = fd is None
+        self._h = self._lib.panel_new(-1 if fd is None else fd, addr, width,
+                                      height, bpp, tcr, tx_cap)
+        if not self._h:
+            raise PanelError("invalid panel configuration")
+
+    def close(self):
+        if self._h:
+            self._lib.panel_free(self._h)
+            self._h = None
+
+    def init(self):
+        _check(self._lib.panel_init(self._h), "panel init")
+
+    def update(self, data, stride, x, y, w, h):
+        """data: a writable buffer of XRGB8888 rows, such as a cairo surface's"""
+        buf = (ctypes.c_char * len(data)).from_buffer(data)
+        _check(self._lib.panel_update(self._h, ctypes.addressof(buf), stride,
+                                      x, y, x + w, y + h), "panel update")
+
+    def display(self, on):
+        _check(self._lib.panel_display(self._h, int(bool(on))), "display")
+
+    def backlight(self, on):
+        _check(self._lib.panel_backlight(self._h, int(bool(on))), "backlight")
+
+    def stats(self, scl_hz=400000):
+        out = (ctypes.c_ulong * 6)()
+        self._lib.panel_stats(self._h, out)
+        return Stats(list(out), self._lib.panel_bus_us(self._h, scl_hz))
+
+    def reset_stats(self):
+        self._lib.panel_stats_reset(self._h)
+
+    def sim_render(self):
+        """Simulator: (shown, levels), levels being one byte per pixel"""
+        levels = ctypes.create_string_buffer(self.width * self.height)
+        ret = self._lib.panel_sim_render(self._h, levels)
+        if ret == -errno.EINVAL:
+            raise PanelError("not a simulated panel")
+        return bool(ret), levels.raw
+
+    def sim_faults(self):
+        return self._lib.panel_sim_faults(self._h)

+ 172 - 0
radio/platform.py

@@ -0,0 +1,172 @@
+"""What the real-hardware frontends share: evdev keys, the backlight, the I2C
+bus check and running the main loop."""
+import fcntl
+import os
+import signal
+import struct
+import sys
+
+from gi.repository import GLib
+
+DEFAULT_KEYS_NAME = "radio-keys"
+DEFAULT_BACKLIGHT = "/sys/class/backlight/radio-backlight/brightness"
+
+# linux/input-event-codes.h; the overlay's radio-keys sends these
+EVDEV_KEYS = {
+    1: "esc",       # KEY_ESC
+    163: "next",    # KEY_NEXTSONG
+    166: "stop",    # KEY_STOPCD
+    139: "menu",    # KEY_MENU
+    395: "list",    # KEY_LIST
+    103: "up",      # KEY_UP
+    165: "prev",    # KEY_PREVIOUSSONG
+    106: "right",   # KEY_RIGHT
+    108: "down",    # KEY_DOWN
+    201: "pause",   # KEY_PAUSECD
+    352: "ok",      # KEY_OK
+    105: "left",    # KEY_LEFT
+    200: "play",    # KEY_PLAYCD
+}
+EV_KEY = 1
+
+# struct input_event: a struct timeval of two longs, then type, code, value.
+# The kernel keeps the two longs even for 32-bit time64 userspace.
+_EVENT = struct.Struct("llHHi")
+
+
+def _eviocgname(size):
+    # _IOC(_IOC_READ, 'E', 0x06, size)
+    return (2 << 30) | (size << 16) | (ord("E") << 8) | 0x06
+
+
+def _device_name(fd):
+    buf = bytearray(256)
+    try:
+        n = fcntl.ioctl(fd, _eviocgname(len(buf)), buf, True)
+    except OSError:
+        return None
+    return bytes(buf[:max(n, 0)]).split(b"\0", 1)[0].decode("utf-8", "replace")
+
+
+def _find_keys_device():
+    for i in range(32):
+        path = "/dev/input/event%d" % i
+        try:
+            fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC)
+        except OSError:
+            continue
+        if _device_name(fd) == DEFAULT_KEYS_NAME:
+            return fd
+        os.close(fd)
+    return -1
+
+
+def start_evdev_keys(on_key, path=None):
+    """Feed presses from an evdev device to on_key(name). path None looks for
+    the device named DEFAULT_KEYS_NAME. False if there is none."""
+    if path:
+        try:
+            fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC)
+        except OSError as e:
+            print("%s: %s" % (path, e.strerror), file=sys.stderr)
+            return False
+    else:
+        fd = _find_keys_device()
+        if fd < 0:
+            return False
+
+    def on_input(fd_, cond):
+        while True:
+            try:
+                data = os.read(fd, _EVENT.size * 32)
+            except BlockingIOError:
+                return True
+            except OSError:
+                return False    # device gone
+            if not data:
+                return False
+            for off in range(0, len(data) - _EVENT.size + 1, _EVENT.size):
+                _, _, etype, code, value = _EVENT.unpack_from(data, off)
+                # 1 press, 2 autorepeat: the app applies the lockout
+                if etype == EV_KEY and value and code in EVDEV_KEYS:
+                    on_key(EVDEV_KEYS[code])
+
+    GLib.io_add_watch(fd, GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_HUP | GLib.IO_ERR,
+                      on_input)
+    return True
+
+
+def backlight_set(path, on):
+    """Write to a sysfs brightness file; a None path does nothing"""
+    if not path:
+        return
+    try:
+        with open(path, "w") as f:
+            f.write("1\n" if on else "0\n")
+    except OSError:
+        pass
+
+
+# ---- i2c-dev ---------------------------------------------------------------
+
+# Never, whatever the options: motherboard and display buses
+DENIED_ADAPTERS = ("PIIX4", "AMDGPU", "DPMST", "i801", "SMBus")
+# Known to be a dedicated bus for this panel
+KNOWN_ADAPTERS = ("MCP2221", "FT260", "i2c-tiny-usb", "mv64xxx")
+
+I2C_FUNCS = 0x0705
+I2C_FUNC_I2C = 0x00000001
+
+
+class BusRefused(Exception):
+    pass
+
+
+def open_i2c_bus(bus, allow=None):
+    """Open /dev/i2c-N only if its adapter is known to be safe for the panel.
+    Writing a raw byte stream to the wrong bus can reach anything on it."""
+    try:
+        with open("/sys/class/i2c-dev/i2c-%d/name" % bus) as f:
+            name = f.readline().strip()
+    except OSError:
+        raise BusRefused("i2c-%d: cannot read the adapter name" % bus)
+
+    for bad in DENIED_ADAPTERS:
+        if bad in name:
+            raise BusRefused("i2c-%d (%s): refusing, this is not a panel bus" % (bus, name))
+    ok = any(k in name for k in KNOWN_ADAPTERS) or (allow is not None and allow == name)
+    if not ok:
+        raise BusRefused('i2c-%d (%s): unknown adapter; if it really is the panel\'s bus,\n'
+                         'pass --allow-adapter="%s"' % (bus, name, name))
+
+    path = "/dev/i2c-%d" % bus
+    try:
+        fd = os.open(path, os.O_RDWR | os.O_CLOEXEC)
+    except OSError as e:
+        raise BusRefused("%s: %s" % (path, e.strerror))
+    funcs = bytearray(struct.calcsize("L"))
+    try:
+        fcntl.ioctl(fd, I2C_FUNCS, funcs, True)
+        has_i2c = struct.unpack("L", bytes(funcs))[0] & I2C_FUNC_I2C
+    except OSError:
+        has_i2c = False
+    if not has_i2c:
+        os.close(fd)
+        raise BusRefused("i2c-%d (%s): no raw I2C support" % (bus, name))
+    print("using i2c-%d (%s)" % (bus, name))
+    return fd
+
+
+# ---- main loop ---------------------------------------------------------------
+
+def run(loop=None):
+    """Run the GLib main loop until SIGINT or SIGTERM, or loop.quit()"""
+    loop = loop or GLib.MainLoop()
+
+    def on_signal(*_):
+        loop.quit()
+        return False
+
+    for sig in (signal.SIGINT, signal.SIGTERM):
+        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, sig, on_signal)
+    loop.run()

+ 168 - 0
radio/render.py

@@ -0,0 +1,168 @@
+"""Screen layout, drawn with cairo and Pango in panel pixels.
+
+Sizes are absolute pixels, not points. Gray edges smear on the panel at 2 bpp,
+so text is drawn without antialiasing and with full hinting, in fonts whose
+hinting holds up in plain black and white at 9-11 px: Verdana and Andale Mono
+(Microsoft core fonts), with Liberation as the fallback.
+"""
+import cairo
+import gi
+
+gi.require_version("Pango", "1.0")
+gi.require_version("PangoCairo", "1.0")
+from gi.repository import Pango, PangoCairo  # noqa: E402
+
+from . import state as st  # noqa: E402
+
+FONT_TITLE = "DejaVu Sans 11px"
+FONT_STATUS = "DejaVu Sans Mono 10px"
+FONT_SMALL = "Verdana, Liberation Sans 9px"
+FONT_LOG = "Andale Mono, Liberation Mono 9px"
+
+TITLE_Y = 0
+TITLE_LINES = 3
+STATUS_Y = 40
+ICON_SIZE = 12
+BAR_Y = 54
+OPTIONS_Y = 60
+LINK_Y = 71
+LOG_Y = 85
+LOG_LINE_H = 10     # 9 px text: room for Polish accents
+
+TEXT_ANTIALIAS = cairo.ANTIALIAS_NONE
+
+_fonts = {}
+
+
+def _font(desc):
+    d = _fonts.get(desc)
+    if d is None:
+        d = _fonts[desc] = Pango.FontDescription.from_string(desc)
+    return d
+
+
+def _layout(cr, font):
+    layout = PangoCairo.create_layout(cr)
+    fo = cairo.FontOptions()
+    fo.set_antialias(TEXT_ANTIALIAS)
+    fo.set_hint_style(cairo.HINT_STYLE_FULL)
+    fo.set_hint_metrics(cairo.HINT_METRICS_ON)
+    PangoCairo.context_set_font_options(layout.get_context(), fo)
+    layout.context_changed()
+    layout.set_font_description(_font(font))
+    return layout
+
+
+def _text(cr, font, x, y, w, align, text):
+    layout = _layout(cr, font)
+    layout.set_width(w * Pango.SCALE)
+    layout.set_alignment(align)
+    layout.set_ellipsize(Pango.EllipsizeMode.END)
+    layout.set_text(text, -1)
+    cr.move_to(x, y)
+    PangoCairo.show_layout(cr, layout)
+
+
+def _title(cr, w, text):
+    layout = _layout(cr, FONT_TITLE)
+    layout.set_width(w * Pango.SCALE)
+    layout.set_wrap(Pango.WrapMode.WORD_CHAR)
+    layout.set_ellipsize(Pango.EllipsizeMode.END)
+    layout.set_height(-TITLE_LINES)
+    layout.set_text(text, -1)
+    cr.move_to(1, TITLE_Y)
+    PangoCairo.show_layout(cr, layout)
+
+
+def _icon(cr, state, x, y):
+    s = ICON_SIZE
+    if state == st.PLAY_PLAYING:
+        cr.move_to(x + 2, y)
+        cr.line_to(x + s, y + s / 2.0)
+        cr.line_to(x + 2, y + s)
+        cr.close_path()
+        cr.fill()
+    elif state == st.PLAY_PAUSED:
+        cr.rectangle(x + 2, y, 3, s)
+        cr.rectangle(x + 7, y, 3, s)
+        cr.fill()
+    elif state == st.PLAY_STOPPED:
+        cr.rectangle(x + 1, y + 1, s - 2, s - 2)
+        cr.fill()
+
+
+def format_time(ms):
+    t = ms // 1000
+    if t >= 3600:
+        return "%d:%02d:%02d" % (t // 3600, t // 60 % 60, t % 60)
+    return "%d:%02d" % (t // 60, t % 60)
+
+
+def _status(cr, s, w):
+    _icon(cr, s.state, 2, STATUS_Y)
+    if s.state == st.PLAY_STOPPED or s.song_pos < 0:
+        return
+
+    _text(cr, FONT_STATUS, 20, STATUS_Y, 90, Pango.Alignment.LEFT,
+          "#%d/%d" % (s.song_pos + 1, s.queue_len))
+
+    elapsed = s.current_elapsed_ms()
+    text = format_time(elapsed)
+    if s.total_ms:
+        text += "/" + format_time(s.total_ms)
+    _text(cr, FONT_STATUS, 110, STATUS_Y, w - 112, Pango.Alignment.RIGHT, text)
+
+    if s.total_ms:
+        bar_w = w - 22
+        fill = elapsed * bar_w // s.total_ms
+        cr.set_line_width(1)
+        cr.rectangle(20.5, BAR_Y + 0.5, bar_w - 1, 3)
+        cr.stroke()
+        cr.rectangle(20, BAR_Y, fill, 4)
+        cr.fill()
+
+
+def _options(cr, s, w):
+    if not s.connected:
+        return
+    text = "Włączone:" + (" repeat" if s.repeat else "") + (" random" if s.random else "")
+    _text(cr, FONT_SMALL, 1, OPTIONS_Y, 170, Pango.Alignment.LEFT, text)
+    text = "Głośność %d%%" % s.volume if s.volume >= 0 else "Głośność –"
+    _text(cr, FONT_SMALL, 150, OPTIONS_Y, w - 151, Pango.Alignment.RIGHT, text)
+
+
+def _link(cr, s, w):
+    if s.connected:
+        return
+    cr.rectangle(0, LINK_Y, w, 12)
+    cr.fill()
+    cr.set_source_rgb(1, 1, 1)
+    _text(cr, FONT_SMALL, 2, LINK_Y, w - 4, Pango.Alignment.LEFT,
+          "Brak połączenia z %s" % s.server)
+    cr.set_source_rgb(0, 0, 0)
+
+
+def _log(cr, s, w, h):
+    cr.set_line_width(1)
+    cr.move_to(0, LOG_Y - 1.5)
+    cr.line_to(w, LOG_Y - 1.5)
+    cr.stroke()
+    for i, row in enumerate(s.log):
+        y = LOG_Y + i * LOG_LINE_H
+        if y + LOG_LINE_H > h:
+            break
+        if row:
+            _text(cr, FONT_LOG, 1, y - 1, w - 1, Pango.Alignment.LEFT, row)
+
+
+def render(cr, s, width, height):
+    cr.set_antialias(cairo.ANTIALIAS_NONE)
+    cr.set_source_rgb(1, 1, 1)
+    cr.paint()
+    cr.set_source_rgb(0, 0, 0)
+    if s.title:
+        _title(cr, width - 2, s.title)
+    _status(cr, s, width)
+    _options(cr, s, width)
+    _link(cr, s, width)
+    _log(cr, s, width, height)

+ 162 - 0
radio/sim.py

@@ -0,0 +1,162 @@
+"""Development window. Frames take the real path: conversion, planner, TCA9539
+byte stream, then the simulated expander and controller. The window shows the
+simulator's display memory, so it is what the panel would receive."""
+import sys
+
+import cairo
+
+from . import gtkkeys   # first: it picks the Gtk version
+from gi.repository import GLib, Gtk  # noqa: E402,I100
+from .app import App
+from .panel import Panel
+
+SCL_HZ = 400000
+
+# LCD look, from background to darkest level, as (R, G, B)
+LIT = ((0xc4, 0xd8, 0x90), (0x8c, 0xa0, 0x60), (0x50, 0x64, 0x38), (0x14, 0x20, 0x10))
+DARK = ((0x4a, 0x52, 0x38), (0x36, 0x3e, 0x2a), (0x24, 0x2a, 0x1e), (0x10, 0x14, 0x10))
+
+
+def _channel_tables(palette):
+    """bytes.translate tables giving B, G, R of a level (only 2 bits are used)"""
+    return [bytes(palette[i & 3][c] for i in range(256)) for c in (2, 1, 0)]
+
+
+class SimWindow(object):
+    def __init__(self, args):
+        self.panel = Panel(args.width, args.height, args.bpp, args.tcr)
+        self.panel.init()
+        self.w, self.h = args.width, args.height
+        self.scale = args.scale
+        self.lit = True
+        self.total_bytes = 0
+        self.frames = 0
+        self.tables = {True: _channel_tables(LIT), False: _channel_tables(DARK)}
+        self.image = cairo.ImageSurface(cairo.FORMAT_RGB24, self.w, self.h)
+        self.snapshot = args.snapshot
+
+        self._build()
+        self._update_image()
+        self.window.show_all()
+        self.app = App(args.host, args.port, self.w, self.h, self._present,
+                       self._backlight, args.kmsg)
+
+        if args.press:
+            self.press = [k for k in args.press.split(",") if k]
+            GLib.timeout_add(400, self._press_next)
+        if args.exit_after:
+            GLib.timeout_add(args.exit_after, self._finish)
+
+    def _build(self):
+        self.window = Gtk.Window(title="Radio panel simulator")
+        self.window.set_resizable(False)
+        self.window.connect("destroy", lambda _w: Gtk.main_quit())
+        self.window.connect("key-press-event", self._key_press)
+
+        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
+        box.set_border_width(8)
+        self.window.add(box)
+
+        self.lcd = Gtk.DrawingArea()
+        self.lcd.set_size_request(self.w * self.scale, self.h * self.scale)
+        self.lcd.connect("draw", self._lcd_draw)
+        box.pack_start(self.lcd, False, False, 0)
+
+        self.stats = Gtk.Label(label="")
+        self.stats.set_xalign(0)
+        self.stats.set_line_wrap(True)
+        self.stats.set_max_width_chars(60)
+        box.pack_start(self.stats, False, False, 0)
+
+        grid, self.buttons = gtkkeys.key_grid(lambda k: self.app.key(k))
+        box.pack_start(grid, False, False, 0)
+
+    def _update_image(self):
+        shown, levels = self.panel.sim_render()
+        if not shown:
+            levels = bytes(self.w * self.h)
+        self.image.flush()
+        data = self.image.get_data()
+        stride = self.image.get_stride()
+        b, g, r = self.tables[self.lit]
+        row = bytearray(self.w * 4)
+        for y in range(self.h):
+            line = levels[y * self.w:(y + 1) * self.w]
+            row[0::4] = line.translate(b)
+            row[1::4] = line.translate(g)
+            row[2::4] = line.translate(r)
+            data[y * stride:y * stride + self.w * 4] = row
+        self.image.mark_dirty()
+        self.lcd.queue_draw()
+
+    def _present(self, data, stride, x, y, w, h):
+        self.panel.reset_stats()
+        failed = None
+        try:
+            self.panel.update(data, stride, x, y, w, h)
+        except OSError as e:
+            failed = e
+        st = self.panel.stats(SCL_HZ)
+        self.total_bytes += st.i2c_bytes
+        self.frames += 1
+        faults = self.panel.sim_faults()
+        self.stats.set_text(
+            "last update: %d LCD writes, %d seeks, %d I²C bytes, %.1f ms at 400 kHz  |  "
+            "total %d bytes in %d updates%s"
+            % (st.writes, st.seeks, st.i2c_bytes, st.bus_us / 1000.0,
+               self.total_bytes, self.frames,
+               "  |  BUS FAULTS, see stderr" if failed or faults else ""))
+        if failed:
+            print("panel update failed: %s" % failed, file=sys.stderr)
+        if faults:
+            print("simulator faults: %d" % faults, file=sys.stderr)
+        self._update_image()
+
+    def _backlight(self, on):
+        self.lit = on
+        self._update_image()
+
+    def _lcd_draw(self, _w, cr):
+        cr.scale(self.scale, self.scale)
+        cr.set_source_surface(self.image, 0, 0)
+        cr.get_source().set_filter(cairo.FILTER_NEAREST)
+        cr.paint()
+        return True
+
+    def _key_press(self, _w, event):
+        key = gtkkeys.key_for_event(event)
+        if key is None:
+            return False
+        self.app.key(key)
+        return True
+
+    # ---- scripted runs, for automated checks ----------------------------------
+
+    def _press_next(self):
+        if not self.press:
+            return False
+        name = self.press.pop(0)
+        if name in self.buttons:
+            self.buttons[name].clicked()
+        else:
+            print("--press: unknown key '%s'" % name, file=sys.stderr)
+        return True
+
+    def _finish(self):
+        if self.snapshot:
+            a = self.window.get_allocation()
+            s = cairo.ImageSurface(cairo.FORMAT_RGB24, a.width, a.height)
+            cr = cairo.Context(s)
+            self.window.draw(cr)
+            del cr
+            s.write_to_png(self.snapshot)
+        Gtk.main_quit()
+        return False
+
+
+def run(args):
+    gtkkeys.require_display()
+    win = SimWindow(args)
+    Gtk.main()
+    win.app.close()
+    return 2 if win.panel.sim_faults() else 0

+ 51 - 0
radio/state.py

@@ -0,0 +1,51 @@
+"""What the screen shows, shared by the MPD client, the log and the renderer."""
+import time
+
+LOG_ROWS = 7
+LOG_COLS = 44
+
+PLAY_UNKNOWN, PLAY_PLAYING, PLAY_PAUSED, PLAY_STOPPED = range(4)
+
+# Key identifiers, as the C version's enum radio_key; the names are what
+# --press and the help text use.
+KEYS = ("esc", "next", "stop", "menu", "list", "up", "prev",
+        "right", "down", "pause", "ok", "left", "play")
+
+
+def monotonic_ms():
+    return int(time.monotonic() * 1000)
+
+
+class RadioState(object):
+    def __init__(self, server=""):
+        self.connected = False
+        self.server = server
+        self.state = PLAY_UNKNOWN
+        self.title = ""
+        self.song_pos = -1          # -1: none
+        self.queue_len = 0
+        self.elapsed_ms = 0
+        self.elapsed_stamp_ms = 0   # monotonic time elapsed_ms was read
+        self.total_ms = 0           # 0: unknown, e.g. a stream
+        self.volume = -1            # -1: unknown
+        self.repeat = False
+        self.random = False
+        self.log = [""] * LOG_ROWS  # wrapped rows, oldest first
+
+    def current_elapsed_ms(self):
+        """Position, advanced locally between MPD updates while playing"""
+        ms = self.elapsed_ms
+        # with the link down the player's position is unknown, so hold it
+        if not self.connected or self.state != PLAY_PLAYING or not self.elapsed_stamp_ms:
+            return ms
+        ms += monotonic_ms() - self.elapsed_stamp_ms
+        return min(ms, self.total_ms) if self.total_ms else ms
+
+    def log_append(self, text):
+        """Wrap text into rows of LOG_COLS characters and scroll them in"""
+        text = text.replace("\n", " ").replace("\t", " ")
+        while True:
+            row, text = text[:LOG_COLS], text[LOG_COLS:]
+            self.log = self.log[1:] + [row]
+            if not text:
+                break

+ 270 - 0
tests/test_ui.py

@@ -0,0 +1,270 @@
+"""Python UI tests: no hardware, no X display. Run with `make pytest`.
+
+The MPD tests talk to tests/fake_mpd.py, never to a real player.
+"""
+import os
+import socket
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+from unittest import mock
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, os.path.join(HERE, ".."))
+
+from gi.repository import GLib  # noqa: E402
+
+from radio import mpd, platform  # noqa: E402
+from radio import state as st  # noqa: E402
+from radio.__main__ import make_pattern, parse_args  # noqa: E402
+from radio.app import App  # noqa: E402
+from radio.panel import Panel, PanelError, load_library  # noqa: E402
+
+
+def have_panel_lib():
+    try:
+        load_library()
+        return True
+    except PanelError:
+        return False
+
+
+def free_port():
+    s = socket.socket()
+    s.bind(("127.0.0.1", 0))
+    port = s.getsockname()[1]
+    s.close()
+    return port
+
+
+def run_loop_until(cond, timeout_s=5.0):
+    ctx = GLib.MainContext.default()
+    end = time.monotonic() + timeout_s
+    while not cond() and time.monotonic() < end:
+        ctx.iteration(False)
+        time.sleep(0.005)
+    return cond()
+
+
+class FakeMpd(object):
+    def __init__(self, idle_event_s=None):
+        self.port = free_port()
+        fd, self.log_path = tempfile.mkstemp(prefix="fake_mpd_")
+        os.close(fd)
+        cmd = [sys.executable, os.path.join(HERE, "fake_mpd.py"), str(self.port), self.log_path]
+        if idle_event_s is not None:
+            cmd.append(str(idle_event_s))
+        self.proc = subprocess.Popen(cmd)
+        end = time.monotonic() + 5
+        while time.monotonic() < end:
+            try:
+                socket.create_connection(("127.0.0.1", self.port), 0.2).close()
+                break
+            except OSError:
+                time.sleep(0.05)
+        # that probe connection is logged as nothing, but start from empty
+        open(self.log_path, "w").close()
+
+    def commands(self):
+        with open(self.log_path) as f:
+            return [line.strip() for line in f if line.strip()]
+
+    def stop(self):
+        self.proc.terminate()
+        self.proc.wait()
+        os.unlink(self.log_path)
+
+
+class TestState(unittest.TestCase):
+    def test_log_wraps_and_scrolls(self):
+        s = st.RadioState()
+        s.log_append("a" * (st.LOG_COLS + 3))
+        self.assertEqual(s.log[-2], "a" * st.LOG_COLS)
+        self.assertEqual(s.log[-1], "aaa")
+        for i in range(st.LOG_ROWS + 2):
+            s.log_append("line %d" % i)
+        self.assertEqual(len(s.log), st.LOG_ROWS)
+        self.assertEqual(s.log[-1], "line %d" % (st.LOG_ROWS + 1))
+
+    def test_log_counts_characters_not_bytes(self):
+        s = st.RadioState()
+        s.log_append("ż" * st.LOG_COLS)
+        self.assertEqual(s.log[-1], "ż" * st.LOG_COLS)
+        self.assertEqual(s.log[-2], "")
+
+    def test_elapsed_held_when_not_playing(self):
+        s = st.RadioState()
+        s.connected, s.state = True, st.PLAY_PAUSED
+        s.elapsed_ms, s.elapsed_stamp_ms = 5000, st.monotonic_ms() - 3000
+        self.assertEqual(s.current_elapsed_ms(), 5000)
+        s.state = st.PLAY_PLAYING
+        self.assertGreaterEqual(s.current_elapsed_ms(), 8000)
+        s.total_ms = 6000
+        self.assertEqual(s.current_elapsed_ms(), 6000)
+
+
+class TestTitle(unittest.TestCase):
+    def test_variants(self):
+        self.assertEqual(mpd.format_title({"artist": "A", "title": "T", "file": "x"}), "A - T")
+        self.assertEqual(mpd.format_title({"name": "Radio", "title": "T"}), "Radio: T")
+        self.assertEqual(mpd.format_title({"name": "Radio"}), "Radio")
+        self.assertEqual(mpd.format_title({"file": "dir/song.flac"}), "song.flac")
+        self.assertEqual(mpd.format_title({"file": "http://host/stream"}), "http://host/stream")
+        self.assertEqual(mpd.format_title({"file": "dir/"}), "dir/")
+
+
+class TestMpdClient(unittest.TestCase):
+    def setUp(self):
+        self.server = FakeMpd()
+        self.state = st.RadioState("localhost")
+        self.log = []
+        self.client = mpd.MpdClient("127.0.0.1", self.server.port, self.state,
+                                    lambda: None, self.log.append)
+        self.assertTrue(run_loop_until(lambda: self.state.connected))
+
+    def tearDown(self):
+        self.client.close()
+        self.server.stop()
+
+    def test_status_parsed(self):
+        s = self.state
+        self.assertEqual(s.state, st.PLAY_PLAYING)
+        self.assertEqual((s.song_pos, s.queue_len), (2, 10))
+        self.assertEqual((s.elapsed_ms, s.total_ms), (83100, 296000))
+        self.assertEqual(s.volume, 50)
+        self.assertTrue(s.repeat and s.random)
+        self.assertTrue(s.title.startswith("Zażółć Gęślą - Jaźń"))
+        self.assertIn("Połączono z MPD: 127.0.0.1", self.log)
+
+    def test_commands(self):
+        for cmd in (mpd.NEXT, mpd.VOLUME_UP, mpd.VOLUME_DOWN, mpd.TOGGLE, mpd.PREV,
+                    mpd.STOP, mpd.PLAY, mpd.REFRESH):
+            self.client.command(cmd)
+        sent = [c for c in self.server.commands()
+                if c not in ("status", "currentsong", "noidle")]
+        self.assertEqual(sent, ["next", "volume +1", "volume -1", "pause", "previous",
+                                "stop", "play"])
+        self.assertTrue(self.state.connected)
+
+    def test_stopped_has_no_title(self):
+        self.client.command(mpd.STOP)
+        self.assertEqual(self.state.state, st.PLAY_STOPPED)
+        self.assertEqual(self.state.title, "")
+
+    def test_reconnects_after_loss(self):
+        self.server.stop()
+        self.server = FakeMpd.__new__(FakeMpd)      # tearDown stops it again
+        self.assertTrue(run_loop_until(lambda: not self.state.connected))
+        self.assertTrue(any(line.startswith("MPD: ") for line in self.log))
+        port = self.client.port
+        restarted = FakeMpd()
+        try:
+            self.client.port = restarted.port
+            self.assertTrue(run_loop_until(lambda: self.state.connected,
+                                           mpd.RECONNECT_S + 3))
+        finally:
+            self.client.port = port
+            self.server = restarted
+
+    def test_idle_event_refreshes(self):
+        self.tearDown()
+        self.server = FakeMpd(idle_event_s=0.2)
+        self.state = st.RadioState()
+        self.client = mpd.MpdClient("127.0.0.1", self.server.port, self.state,
+                                    lambda: None, self.log.append)
+        self.assertTrue(run_loop_until(lambda: self.server.commands().count("status") >= 2))
+
+
+@unittest.skipUnless(have_panel_lib(), "panel library not built (make lib)")
+class TestPanel(unittest.TestCase):
+    def test_app_renders_to_simulator_without_faults(self):
+        panel = Panel()
+        panel.init()
+        frames = []
+
+        def present(data, stride, x, y, w, h):
+            frames.append((y, h))
+            panel.update(data, stride, x, y, w, h)
+
+        app = App("127.0.0.1", free_port(), 240, 160, present, None)
+        try:
+            self.assertTrue(run_loop_until(lambda: frames))
+            app.log("Zażółć gęślą jaźń")
+            self.assertTrue(run_loop_until(lambda: len(frames) >= 2, 3))
+        finally:
+            app.close()
+        self.assertEqual(frames[0], (0, 160))
+        self.assertLess(frames[1][1], 160)      # only the changed rows
+        self.assertEqual(panel.sim_faults(), 0)
+        shown, levels = panel.sim_render()
+        self.assertTrue(shown)
+        self.assertIn(3, set(levels))           # some black: the link warning
+
+    def test_key_lockout(self):
+        sent = []
+        app = App("127.0.0.1", free_port(), 240, 160, lambda *a: None)
+        app.mpd.command = sent.append
+        try:
+            app.key("next")
+            app.key("next")
+            app.key("menu")
+            app.key("bogus")
+        finally:
+            app.close()
+        self.assertEqual(sent, [mpd.NEXT])
+
+    def test_patterns(self):
+        for name in ("geometry", "gray"):
+            fb = make_pattern(name, 240, 160)
+            self.assertEqual(len(fb), 240 * 160 * 4)
+            panel = Panel()
+            panel.init()
+            panel.update(fb, 240 * 4, 0, 0, 240, 160)
+            self.assertEqual(panel.sim_faults(), 0)
+            levels = panel.sim_render()[1]
+            if name == "gray":
+                self.assertEqual([levels[x] for x in (0, 60, 120, 180)], [0, 1, 2, 3])
+            else:
+                self.assertEqual(levels[0], 3)
+                self.assertEqual(levels[241], 3)    # diagonal
+
+    def test_bad_config(self):
+        with self.assertRaises(PanelError):
+            Panel(width=241)
+
+
+class TestPlatform(unittest.TestCase):
+    def test_denied_bus_never_opened(self):
+        with mock.patch("builtins.open", mock.mock_open(read_data="SMBus PIIX4 adapter port 0\n")), \
+                mock.patch("os.open") as os_open:
+            with self.assertRaises(platform.BusRefused):
+                platform.open_i2c_bus(6)
+            os_open.assert_not_called()
+
+    def test_unknown_bus_needs_allow(self):
+        with mock.patch("builtins.open", mock.mock_open(read_data="Some adapter\n")), \
+                mock.patch("os.open") as os_open:
+            with self.assertRaises(platform.BusRefused) as cm:
+                platform.open_i2c_bus(3)
+            self.assertIn('--allow-adapter="Some adapter"', str(cm.exception))
+            os_open.assert_not_called()
+
+    def test_evdev_keys_match_overlay(self):
+        with open(os.path.join(HERE, "..", "dts", "radio-panel.dts")) as f:
+            dts = f.read()
+        import re
+        found = dict((label, int(code)) for label, code in re.findall(
+            r'label = "(\w+)";.*?linux,code = <(\d+)>', dts))
+        self.assertEqual(found, dict((v, k) for k, v in platform.EVDEV_KEYS.items()))
+        self.assertEqual(sorted(found), sorted(st.KEYS))
+
+    def test_args(self):
+        a = parse_args(["i2c", "--bus", "11", "--addr", "0x75", "--window-keys"])
+        self.assertEqual((a.bus, a.addr, a.window_keys, a.host), (11, 0x75, True, "localhost"))
+        self.assertEqual(parse_args(["sim"]).host, "radio.lo")
+
+
+if __name__ == "__main__":
+    unittest.main()