MERIDIANAN ENGINEERING CHRONICLE

ENTRY 02 / RUST · LINUX · GTK4 · PACKAGING · DESKTOP

A Linux brightness app that never asks for root

Every brightness tool I had tried handled one display type or demanded root.

03 NOV 202611 MIN READSOURCE: MARKDOWN + REGISTRY

SYS.08 - RUST DESKTOP SYSTEMS

Twinkle Linux is a system tray application that sets brightness on every connected display, external and internal, from one popup, without sudo, udev rules, or group membership.

Why a brightness slider is harder than it looks

My desk is a laptop panel plus two external monitors that want different brightness at different times of day. Linux exposes those displays through two unrelated subsystems: internal panels sit behind /sys/class/backlight, which a normal user cannot write, and external monitors speak DDC/CI over an I2C bus, a protocol built for factory test rigs that tolerates exactly one in-flight command. Every brightness tool I had tried handled one display type or demanded root.

So I wrote my own. Twinkle Linux is a GTK4 tray app: a master slider, per-monitor cards, config-driven presets, and a day/night schedule computed from solar math, fully offline. Commits span March 9 to November 3, 2026: 50 commits on 11 active days (MEASURED: git log; the clone may be shallow, so treat 50 as a floor), 6,070 lines of Rust across 20 source files (MEASURED: find + wc -l, examples excluded), 42 test functions (MEASURED: grep '#[test]'). The arc is honest about how side projects run: 9 in March to get a skeleton compiling, 29 in a six-day May burst to make it usable, a six-month gap, then 12 in November to finish the schedule and fight CI into a 1.0.0 release (MEASURED: commit date histogram). This article is about what the quiet parts cost: the tray protocol, the I2C bus, the timezone, and the packaging.

The shape of the system

One process, two event loops that must not touch each other: GTK4 is single-threaded, ksni (the tray) is async on tokio. The bridge is boring on purpose. Menu events reach the UI over an mpsc channel polled with glib::timeout_add_local; slider writes cross back through glib::spawn_future_local so the async ddcutil call never blocks the UI (FROM REPO: README “Channel bridge”, src/main.rs). The schedule engine ticks every 30 seconds, applies the phase brightness, and suspends itself for the current phase when a human drags a slider (FROM REPO: src/core/schedule.rs).

flowchart TD
    TRAY["Tray icon: ksni, StatusNotifierItem over D-Bus"]
    POPUP["Brightness popup: GTK4 cards and sliders"]
    DIALOG["Settings dialog: 4 tabs"]
    subgraph PROC["One process: GTK main loop + tokio runtime"]
        ENG["Schedule engine: 30 s tick, solar math"]
        MGR["DDCManager: monitor cache, dock dedup"]
        CFG["ConfigManager: JSON at ~/.config/twinkle-linux"]
    end
    DDC["ddcutil subprocess: --brief, timeout, retry"]
    LOGIND["systemd-logind: org.freedesktop.login1"]
    SYSFS["/sys/class/backlight"]
    I2C["/dev/i2c-N: DDC/CI, VCP code 0x10"]

    TRAY -->|"menu events over mpsc"| POPUP
    DIALOG -->|"load and save"| CFG
    POPUP -->|"slider drag, 300 ms debounce"| MGR
    POPUP -->|"ManualChange event"| ENG
    ENG -->|"target brightness"| MGR
    ENG -->|"status line, only when text changes"| TRAY
    MGR -->|"external monitors"| DDC
    DDC -->|"setvcp 10"| I2C
    MGR -->|"internal panel"| LOGIND
    LOGIND -->|"SetBrightness"| SYSFS

Every fallible operation returns a typed error instead of an unwrap, and the taxonomy is the design: “the tool is missing”, “the bus timed out”, and “this monitor does not support that code” have different user-facing remedies. From src/ddc/error.rs, the first variants of the eleven-variant enum:

#[derive(Error, Debug)]
pub enum DDCError {
    /// ddcutil is not available on the system.
    #[error("ddcutil is not available on this system")]
    DDCNotAvailable,

    /// Command execution failed.
    #[error("Command execution failed: {0}")]
    CommandExecution(#[from] CommandExecutionError),

    /// Monitor not found.
    #[error("Monitor not found: bus {bus}")]
    MonitorNotFound { bus: i32 },

    /// Permission denied when accessing I2C device.
    #[error("Permission denied: {0}")]
    PermissionDenied(String),

    /// Timeout occurred during operation.
    #[error("Operation timed out after {0}s")]
    Timeout(f64),

    /// VCP code not supported by the monitor.
    #[error("VCP code 0x{vcp_code:02X} not supported by monitor")]
    VCPNotSupported { vcp_code: u8 },

The boring parts got the same treatment. Configuration is JSON at ~/.config/twinkle-linux/config.json; #[serde(default)] means missing fields fall back to defaults and unknown fields are ignored, so a 0.1.0-era file keeps working after newer sections shipped (FROM REPO: src/core/config.rs, CHANGELOG 1.0.0).

Decisions I would defend in a review

ksni instead of libappindicator

The first tray icon used libappindicator (FROM REPO: commit 6270aa0, May 8). It links GTK3, and GTK3 plus GTK4 in one process is a crash, not a warning. The same day I replaced it with ksni, which implements StatusNotifierItem in pure Rust over D-Bus (FROM REPO: commit 3f594c5, README decision table). The cost is documented rather than hidden: SNI is not GNOME’s native protocol, so stock GNOME needs the AppIndicator extension. A hard dependency with one known quirk beats a crash-prone library with wide coverage.

Shell out to ddcutil, never talk raw I2C

Three options existed: drive /dev/i2c-* directly (the ddcci crates), own the protocol with a udev rule, or spawn the ddcutil CLI. I rejected raw I2C because its edge cases (stalled transactions, docks exposing one bus per port, suspend/resume) are precisely the bugs that eat weekends, and ddcutil has accumulated years of workarounds. The cost is a subprocess per read or write: 0.5 second timeout, 1 retry, exponential backoff at 2.0 (FROM REPO: src/ddc/command.rs constants). A slider drag fires dozens of value-changed events and would flood the I2C bus, so writes are debounced. From src/ui/widgets/brightness_slider.rs:

            // Cancel any previous pending timer.
            // g_source_remove() returns FALSE if source already fired — that's fine, ignore it.
            if let Some(old_id) = pending_source_id.lock().ok().and_then(|mut id| id.take()) {
                unsafe {
                    gtk4::glib::ffi::g_source_remove(old_id);
                }
            }

            // Set a new 300ms debounce timer
            let cb = callback_clone.clone();
            let new_id =
                glib::timeout_add_local(std::time::Duration::from_millis(300), move || {
                    cb(value);
                    glib::ControlFlow::Break
                });

            // Store the raw source ID (u32)
            // SourceId doesn't expose as_raw(), but we can get it via IntoGlib
            let raw_id: u32 = unsafe { std::mem::transmute(new_id) };
            if let Ok(mut id) = pending_source_id.lock() {
                *id = Some(raw_id);
            }

That transmute survived too long. Cancelling an already-fired GLib source used to panic the whole app (FROM REPO: commit 8d6ad93, “debounce timer source double-remove panic”); the raw-ID dance exists because a callback must cancel its own predecessor. The popup module later switched to as_raw() (FROM REPO: src/ui/brightness_popup.rs line 118); the slider still carries the transmute and a comment claiming as_raw() does not exist, which its sibling file disproves. Stale comments next to unsafe code are worse than no comments, and this one should be the next commit.

systemd-logind owns the internal panel

For laptop panels the options were: write sysfs as root, ship a udev rule and put users in the video group, or call SetBrightness on systemd-logind, which already runs as root on every modern distribution; GNOME and KDE use the same path. I rejected the udev rule because it turns every install into a security decision the user did not sign up for. The legacy rule is still shipped as an opt-in fallback for distributions that lock down /dev/i2c-* (packaging/99-twinkle-i2c.rules, scripts/install-udev-rules.sh), but the supported path keeps the README promise: no sudo, no udev rules, no group membership (FROM REPO: README “No root”).

Timezones belong in function signatures

The schedule worked on my CET laptop and failed on UTC CI runners: the API converted results to the host timezone, so tests pinned to CET passed at home and failed in the cloud (FROM REPO: CHANGELOG 1.0.0, “Test job”). The easy fix was TZ=... in the workflow. The right fix was making the schedule API offset-explicit: decide takes a DateTime<FixedOffset>, sun_times_local takes the offset in seconds as an argument, and the engine passes Local::now().fixed_offset(). Results are identical on any machine, and tests pin CET by construction rather than by environment. From src/core/schedule.rs, the sunrise equation, pure math with no network:

    let m = (357.529_1 + 0.985_600_28 * (j_star - J2000)).rem_euclid(360.0);

    // Equation of the center (degrees).
    let c = 1.914_8 * sin_deg(m) + 0.020_0 * sin_deg(2.0 * m) + 0.000_3 * sin_deg(3.0 * m);

    // Ecliptic longitude (degrees): true anomaly + 180° + perihelion longitude.
    let lambda = (m + c + 180.0 + PERIHELION_LONGITUDE_DEG).rem_euclid(360.0);

    // Solar transit (Julian date).
    let j_transit = j_star + 0.005_3 * sin_deg(m) - 0.006_9 * sin_deg(2.0 * lambda);

    // Sun declination (degrees).
    let sin_delta = sin_deg(lambda) * sin_deg(AXIAL_TILT_DEG);
    let delta = sin_delta.asin().to_degrees();

    // Hour angle for the sunrise altitude (degrees).
    let cos_omega = (sin_deg(SUNRISE_ALTITUDE_DEG) - sin_deg(latitude) * sin_deg(delta))
        / (cos_deg(latitude) * cos_deg(delta));
    if !(-1.0..=1.0).contains(&cos_omega) {
        // Polar day or polar night: no sunrise/sunset on this date.
        return None;
    }
    let omega = acos_deg(cos_omega);

    let jd_sunrise = j_transit - omega / 360.0;
    let jd_sunset = j_transit + omega / 360.0;

    let sunrise = DateTime::from_timestamp(unix_secs_from_julian(jd_sunrise), 0)?.naive_utc();
    let sunset = DateTime::from_timestamp(unix_secs_from_julian(jd_sunset), 0)?.naive_utc();
    Some((sunrise, sunset))
}

Nobody should trust a hand-rolled sunrise equation, so the tests do not: they pin sunrise and sunset against sunrise-sunset.org references for Wrocław in November (CET) and June (CEST), asserting within 5 minutes (FROM REPO: schedule.rs tests; CHANGELOG records ±2 minutes observed). There is even a polar-night test: Svalbard in December returns None.

The C++ sibling

twinkle-cpp is a port, not an abandoned experiment: the same module split (core, ddc, ui), 2,595 lines of C++23/26 against the Rust 6,070 (MEASURED: wc -l), and 33 GTest cases against the Rust 42 (MEASURED: grep -c 'TEST('). CONTRIBUTING.md makes the relationship a rule: implement in Rust first, mirror the structure in C++ (FROM REPO: CONTRIBUTING.md).

The port is strong evidence the architecture was language-independent. The Rust DDCResult<T> = Result<T, DDCError> became using DDCResult = std::expected<T, DDCError> in the C++ error header (FROM REPO: include/twinkle/ddc/error.hpp); the debounce and the detect-parse flow transferred unchanged. Writing DESIGN.md for the C++ tree produced the best documentation in the repository, because porting forces you to explain decisions you had been carrying in your head.

One honest caveat: DESIGN.md advertises C++26 static reflection auto-generating VCP names and config serialization; the sources contain no consteval and no meta:: (MEASURED: grep across twinkle-cpp/src and include). The doc describes a target, not the code, and the implied toolchain (GCC 15+ per the C++ README) is newer than the distro the app targets: Ubuntu 24.10 or Fedora 41 and up (FROM REPO: twinkle-cpp/README.md). The port needs a decision: finish it against the reflection-free reality, or move the reflection section into a roadmap.

Distribution is part of the design

Most desktop projects stop at cargo build --release. This repository carries a .desktop file with translated comments and keywords in four languages (packaging/twinkle-linux.desktop), an install script that builds to ~/.local without root (scripts/install-user.sh), and CI that builds a release binary from every v* tag on a runner pinned to ubuntu-24.04, the target distribution (FROM REPO: .github/workflows/build.yml, CHANGELOG 1.0.0).

Two of the four formats are drafts. The snap manifest still declares version ‘0.1.0’ while the app is at 1.0.0, and the flatpak manifest pins ddcutil with a 64-character sha256 that contains non-hex characters, a placeholder flatpak-builder would reject (FROM REPO: packaging/snap/snapcraft.yaml, packaging/flatpak/com.github.twinkle-twinkle.TwinkleLinux.yml). Manifests that cannot build are negative documentation: they advertise nonexistent support.

The aarch64 leg tells the same story. Cross-compiling GTK4 for ARM on GitHub runners never worked: pkg-config refused to resolve GTK without an arm64 sysroot; after registering the multiarch tree, apt still demanded exact M-A:same version equality between the amd64 image snapshot and ports.ubuntu.com; then the libpango1.0-dev:arm64 unpack failed anyway (FROM REPO: CHANGELOG 1.0.0). Five CI commits on November 3 proved the wall was structural, so I removed the leg: x86_64 Ubuntu 24.04 is the supported target and the recipe lives in git history (commits 83e392c through 184fc07). One green target beats two half-red ones.

Numbers

All from the repository:

What broke, and what I would do differently

The tray menu that rendered empty. Round 1 shipped a checkmark toggle, a disabled info row, and a dynamic row count; the GNOME AppIndicator extension renders exactly that combination as an empty box with dead clicks. The engine also pushed updates every 30-second tick, and layout churn destabilizes shell menus (FROM REPO: CHANGELOG round 2). The fix was surrender: plain items only, constant structure, schedule state in the label text, updates only when the text changes. A tray menu is not a UI toolkit; the shell owns rendering and you get text.

The quick slider that never appeared. Round 3 added a borderless all-monitors slider opening on tray click, because dbusmenu items are text-only. On real GNOME sessions the panel did not show; round 4 removed it and restored a config-driven menu list (FROM REPO: CHANGELOG rounds 3 and 4). Shipping UI twice against a shell I do not control taught me to test tray changes on stock GNOME first.

Widget tests that segfaulted CI: gtk4::init() on a display-less runner leaves partially initialized GLib state, and the test binary died with SIGSEGV 11 at exit. They now require DISPLAY or WAYLAND_DISPLAY before touching GTK and skip cleanly headless (FROM REPO: CHANGELOG round 5). Red for the wrong reason trains everyone to ignore red.

Release notes with a wrong year: the CHANGELOG dates 0.1.0 as 2025-05-09 while every commit around it is May 2026 (MEASURED: git log --date=short). A one-character typo in the document people trust most; a release-checklist date check is cheaper.

What I would reorder: make the flatpak and snap drafts real or delete them, and instrument the idle footprint, because “lightweight” is currently an adjective, not a number. v1.0.0 shipped November 3, 2026 with one supported target and a green pipeline; the flatpak manifest is next, and it does not ship until flatpak-builder builds it from a real sha256.