Compare commits

..
7 Commits
Author SHA1 Message Date
illustris 96d459a1a1 hyprland: use shared desktop modules from GitHub
Pin illustris/flake to e09318c and consume its common Home Manager and NixOS Hyprland modules. Keep NVIDIA and monitor-specific settings, HDR controls and LG recovery in the desktop overrides.

Remove the duplicated controller, panel, scripts and Waybar patches, update the regression test and documentation, and normalize Nix indentation to tabs with lib.indent for embedded scripts.
2026-10-04 11:10:28 +05:30
illustris 3fcf3c9c57 add Hyprland desktop with XMonad-style layouts
Manage the desktop through native Lua and UWSM with Grid, Monocle, Tabs and Scrolling layouts. Add workspace-local navigation, bounded scrolling focus and a runtime Grid ratio defaulting to 1.20.

Configure the HDR OLED and portrait LG, HDMI recovery, NVIDIA suspend handling, independent locking and Plasma fallback. Fix Waybar workspace IPC and provide immediate per-output layout status.

Include desktop controls, screenshots, usage documentation and controller/panel regression tests. Use the authorized local illustris flake input.
2026-10-04 09:43:45 +05:30
illustris 6b0298e662 bump inputs
nixpkgs 2c423e0 (2026-08-22) with all inputs at their tips. Overlay
supplies wacomtablet's missing ECM/KF6/X11 deps until nixpkgs ships its
dependency metadata.
2026-08-24 08:22:45 +05:30
illustris ec74fa794f update for current nixpkgs
programs.adb removed upstream: systemd 258 handles uaccess; android-tools
provides the command. claude-code is unfree now. neofetch was removed;
fastfetch replaces it.
2026-08-24 08:16:25 +05:30
illustris df78533bcd port hdmi-relink to Zig 0.16
DebugAllocator, Init.Minimal args, manual opaque xcb extension externs
(libxcb 1.17), nanosleep-based sleepMs, raw-fd flock lock.
2026-08-24 08:16:25 +05:30
illustris e2ee0b72ac fix display wakeup 2026-08-21 11:26:12 +05:30
illustris c4fcbd67e2 reduce cuda rebuild 2026-05-20 23:29:39 +05:30
13 changed files with 1180 additions and 24 deletions

No files matched your search

+6 -4
View File
@@ -35,6 +35,7 @@
hosts.mode = "0644";
};
systemPackages = with pkgs; [
android-tools
asciinema
bcc
bind binutils-unwrapped bmon
@@ -50,8 +51,7 @@
killall
linuxPackages.perf lsof
mosh
ncdu neofetch nethogs networkmanager nfs-utils
nix-du
ncdu fastfetch nethogs networkmanager nfs-utils
nix-prefetch-git nix-tree
nnn
openvpn
@@ -88,6 +88,7 @@
# TODO: make a mergable option
nixpkgs.config = {
allowUnfreePredicate = pkg: builtins.elem (lib.getName pkg) [
"claude-code"
"cuda-merged"
"libnpp"
"libcusparse"
@@ -119,10 +120,10 @@
"zerotierone"
];
cudaSupport = true;
cudaCapabilities = [ "7.5" ]; # RTX 2080 Ti (Turing); add more if a different GPU is installed
};
programs = {
adb.enable = true;
appimage = {
enable = true;
binfmt = true;
@@ -198,6 +199,7 @@
enabledCollectors = [ "systemd" ];
};
};
retentionTime = "1y";
scrapeConfigs = [
{
job_name = "node_exporter";
@@ -264,7 +266,7 @@
storageDriver = "overlay2";
daemon.settings.bip = "192.168.9.0/22";
};
libvirtd.enable = false;
libvirtd.enable = true;
podman.enable = false;
};
Generated
+15 -15
View File
@@ -8,11 +8,11 @@
},
"locked": {
"dir": "pkgs/firefox-addons",
"lastModified": 1755835412,
"narHash": "sha256-RzTBJ5ERXrJk7JPIDp1vjUNMKka6tyg4RctIR3cxqsM=",
"lastModified": 1787457768,
"narHash": "sha256-cbgeu5NTb6DtB+tNs4E6z6K/1XKKM90gVmlkWMJe+gY=",
"owner": "rycee",
"repo": "nur-expressions",
"rev": "56254103ed36317cf471da3c93ac13805c72a7fa",
"rev": "25cfc8fdc413d73b3a47e3e86dafcad51cf5c9f9",
"type": "gitlab"
},
"original": {
@@ -29,11 +29,11 @@
]
},
"locked": {
"lastModified": 1755810213,
"narHash": "sha256-QdenO8f0PTg+tC6HuSvngKcbRZA5oZKmjUT+MXKOLQg=",
"lastModified": 1787487906,
"narHash": "sha256-zIdM+8teujHm5hc5MIPDnV7k2UeOOT/pFyFtWjOCwsY=",
"owner": "nix-community",
"repo": "home-manager",
"rev": "6911d3e7f475f7b3558b4f5a6aba90fa86099baa",
"rev": "cfba7ad5886b342b8dd63ba74354b3853ea4cfc9",
"type": "github"
},
"original": {
@@ -55,11 +55,11 @@
]
},
"locked": {
"lastModified": 1755607423,
"narHash": "sha256-XWzjp77whLmki/pe1NRHKXsj/NwDcyZe6QPMMfv2g1c=",
"lastModified": 1791091692,
"narHash": "sha256-0zXIyYNKooQiqacvigfv04N/F2k/qS1mP6/GcWOpCoU=",
"owner": "illustris",
"repo": "flake",
"rev": "270fbbc33443da18ee4ccd09801f9ce4bc99cfb1",
"rev": "e09318c7742dbc02f816a6384f0105c915c7a969",
"type": "github"
},
"original": {
@@ -75,11 +75,11 @@
]
},
"locked": {
"lastModified": 1753853405,
"narHash": "sha256-FDWuoxn5Ke4cZgX3IH6nze3da1FKy+f7fw3trxkuN84=",
"lastModified": 1775797235,
"narHash": "sha256-jcYMhsbmFOMMP2Vhv0jb/u/iCBW6XT1L2LLUVUPx94o=",
"owner": "illustris",
"repo": "nixfs",
"rev": "02fca4ccce6dda293fd0542b82747531185852af",
"rev": "086e395c9e0e6b51e70a7c406a06e84e8a0805dd",
"type": "github"
},
"original": {
@@ -90,11 +90,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1755615617,
"narHash": "sha256-HMwfAJBdrr8wXAkbGhtcby1zGFvs+StOp19xNsbqdOg=",
"lastModified": 1787360063,
"narHash": "sha256-dt4WdcvsA8/RCe+VZZwqU0X+XMM3wBbGCWA0/sFWzGo=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "20075955deac2583bb12f07151c2df830ef346b4",
"rev": "2c423e03bbafcff28bfadc6781a4a8257f205cb5",
"type": "github"
},
"original": {
+31 -1
View File
@@ -9,7 +9,6 @@
};
illustris = {
url = "github:illustris/flake";
# url = "path:///home/illustris/src/flake";
inputs = {
nixpkgs.follows = "nixpkgs";
firefox-addons.follows = "firefox-addons";
@@ -43,6 +42,35 @@
lib
pkgs
suckless
] ++ [
# TODO: drop when nixpkgs ships wacomtablet's dependency metadata
# (missing from pkgs/kde/generated/dependencies.json as of 2c423e0)
(final: prev: {
kdePackages = prev.kdePackages.overrideScope (kf: kp: {
wacomtablet = kp.wacomtablet.overrideAttrs (old: {
nativeBuildInputs = (old.nativeBuildInputs or [ ]) ++ [ kf.extra-cmake-modules ];
buildInputs = (old.buildInputs or [ ]) ++ (with kf; [
kcmutils
kconfig
kcoreaddons
kdbusaddons
kdoctools
kglobalaccel
ki18n
kio
knotifications
kwidgetsaddons
kwindowsystem
kxmlgui
libplasma
plasma5support
]) ++ [
final.libX11
final.libxcb
];
});
});
})
];
}
home-manager.nixosModules.default
@@ -52,6 +80,7 @@
backupFileExtension = "hm-bak";
users.illustris = {...}: {
imports = [
./modules/hyprland/home.nix
(import (
illustris + "/homeConfigurations/profiles/dailyDriver/home.nix"
) inputs)
@@ -62,6 +91,7 @@
nixfs.nixosModules.nixfs
{services.nixfs.enable = true;}
illustris.nixosModules.plasmonad
illustris.nixosModules.hyprland
{environment.systemPackages = [ nixtop.packages.x86_64-linux.nixtop ];}
];
};
+2
View File
@@ -1,5 +1,7 @@
{ config, pkgs, ... }:
{
imports = [
./hdmi-relink
./hyprland
];
}
+52
View File
@@ -0,0 +1,52 @@
# Re-initialise the HDMI-0 TMDS link after every wake.
#
# A DPMS off/on cycle on its own leaves the LG's link untrained: the CRTC stays
# programmed and the panel keeps HPD asserted, so the driver never retries and
# the panel sits at "no signal" until the cable is replugged. Nothing queryable
# distinguishes that from a healthy link -- xrandr, the driver's display masks
# and /sys/class/drm all report fine either way, and X reports the target mode
# whether or not the panel actually locked -- so the link is re-initialised
# unconditionally on wake, and the only real check is looking at the panel.
#
# Recovery is an ascending pixel-clock ladder, not a single hop. The transmitter
# will not train straight to 4K60 (594MHz, against this port's 600MHz maximum);
# the panel lights up and drops again. It will climb: disable the CRTC, then
# 1080p @148.5MHz, then 4K30 @297MHz, then 4K60 @594MHz. The middle rung must be
# the slowest mode at the target resolution -- picking the fastest one below the
# target selects 593.41MHz, the 59.94Hz near-twin, and the climb does nothing.
#
# Wake is detected from the X screensaver idle counter, NOT a DPMS Off->On edge:
# user input resets the idle counter but not the power level, and whoever blanked
# the screen may restore the level before the next poll, so testing it on the
# edge races and never matches. The level is latched instead, as evidence that
# the panels slept at some point during the idle.
#
# Implemented as a binary speaking X11 directly rather than a shell loop around
# xset(1)/xrandr(1): the poll loop then spawns no processes at all, which keeps
# it out of execsnoop, and it never issues an xrandr --query, which on this
# driver forces a full DFP re-probe.
{ config, lib, pkgs, ... }:
let
hdmi-relink = pkgs.callPackage ./package.nix {};
in
{
# also exposed for running by hand after a manual layout change
environment.systemPackages = [ hdmi-relink ];
systemd.user.services.hdmi-relink = {
description = "Re-initialise HDMI-0 TMDS link on wake";
partOf = [ "plasma-workspace.target" ];
after = [ "plasma-workspace.target" ];
wantedBy = [ "plasma-workspace.target" ];
# Plasma exports DISPLAY and XAUTHORITY to the user manager.
unitConfig.ConditionEnvironment = "XDG_SESSION_TYPE=x11";
serviceConfig = {
# ExecStart, not `script`, so systemd execs the binary directly
# instead of wrapping it in a generated shell script
ExecStart = "${lib.getExe hdmi-relink} --watch";
Restart = "on-failure";
RestartSec = 5;
};
};
}
+37
View File
@@ -0,0 +1,37 @@
{ lib, stdenv, zig, xorg }:
stdenv.mkDerivation {
pname = "hdmi-relink";
version = "0.4.0";
src = ./src;
nativeBuildInputs = [ zig ];
buildInputs = [ xorg.libxcb ];
# build-exe rather than `zig build`: this is one dependency-free file, and it
# avoids build.zig.zon, whose schema has churned across zig releases
buildPhase = ''
runHook preBuild
export ZIG_GLOBAL_CACHE_DIR="$TMPDIR/zig-cache"
zig build-exe main.zig \
-OReleaseSafe -lc \
-I${lib.getDev xorg.libxcb}/include \
-L${lib.getLib xorg.libxcb}/lib \
-lxcb -lxcb-randr -lxcb-dpms -lxcb-screensaver \
--name hdmi-relink
runHook postBuild
'';
installPhase = ''
runHook preInstall
install -Dm755 hdmi-relink $out/bin/hdmi-relink
runHook postInstall
'';
meta = {
description = "Re-initialise a wedged HDMI TMDS link on wake";
mainProgram = "hdmi-relink";
platforms = lib.platforms.linux;
};
}
+578
View File
@@ -0,0 +1,578 @@
//! Re-initialise a wedged TMDS link without replugging the cable.
//!
//! A DPMS off/on cycle can leave the panel's link untrained: the CRTC stays
//! programmed and the panel keeps HPD asserted, so the driver never retries and
//! the panel sits at "no signal". Nothing queryable distinguishes that from a
//! healthy link, so the link is re-initialised unconditionally on wake.
//!
//! Re-enabling at the target clock does not recover it -- 4K60 is 594MHz TMDS
//! against a 600MHz port maximum and will not re-train from the wedged state.
//! Bringing the link up at 1920x1080 (148.5MHz) first re-inits the transmitter,
//! after which the target mode trains normally.
//!
//! Wake is detected from the X screensaver idle counter, NOT the DPMS power
//! level: user input resets the idle counter but leaves the DPMS level at Off
//! until something forces it on, so an Off->On edge never occurs on a real
//! wake. The level is still read, as confirmation that the panels had slept.
//!
//! Speaks X11 directly over the existing socket so the poll loop spawns no
//! processes at all -- the whole daemon is a single execve at startup.
const std = @import("std");
const c = @cImport({
@cInclude("xcb/xcb.h");
@cInclude("xcb/randr.h");
@cInclude("xcb/dpms.h");
@cInclude("xcb/screensaver.h");
});
// libxcb 1.17 made xcb_extension_t opaque and Zig 0.16's translate-c refuses
// opaque-typed globals, so declare the extension key symbols by hand.
extern var xcb_randr_id: c.xcb_extension_t;
extern var xcb_dpms_id: c.xcb_extension_t;
extern var xcb_screensaver_id: c.xcb_extension_t;
const Config = struct {
output: []const u8 = "HDMI-0",
low_w: u16 = 1920,
low_h: u16 = 1080,
settle_ms: u64 = 3000,
interval_ms: u64 = 2000,
hold_ms: u64 = 1000,
/// Fallback for deciding the panels slept, when the DPMS level was never
/// caught off. Matches powerdevil's [AC][DPMSControl] idleTime.
idle_threshold_ms: u32 = 600_000,
watch: bool = false,
trace: bool = false,
};
const Conn = struct {
xc: *c.xcb_connection_t,
root: c.xcb_window_t,
};
/// std.Thread.sleep moved behind the Io interface in Zig 0.16; this daemon
/// only ever needs a plain blocking sleep.
fn sleepMs(ms: u64) void {
const ns = ms * std.time.ns_per_ms;
var req: std.os.linux.timespec = .{
.sec = @intCast(ns / std.time.ns_per_s),
.nsec = @intCast(ns % std.time.ns_per_s),
};
var rem: std.os.linux.timespec = undefined;
while (std.os.linux.errno(std.os.linux.nanosleep(&req, &rem)) == .INTR) req = rem;
}
fn logMsg(comptime fmt: []const u8, args: anytype) void {
// stderr goes straight to the journal under systemd; no logger(1) exec
std.debug.print("hdmi-relink: " ++ fmt ++ "\n", args);
}
fn connect() !Conn {
var screen_num: c_int = 0;
const xc = c.xcb_connect(null, &screen_num) orelse return error.ConnectFailed;
if (c.xcb_connection_has_error(xc) != 0) return error.ConnectFailed;
var iter = c.xcb_setup_roots_iterator(c.xcb_get_setup(xc));
var i: c_int = 0;
while (i < screen_num) : (i += 1) c.xcb_screen_next(&iter);
return .{ .xc = xc, .root = iter.data.*.root };
}
fn requireExt(xc: *c.xcb_connection_t, ext: *c.xcb_extension_t, name: []const u8) !void {
const reply = c.xcb_get_extension_data(xc, ext);
if (reply == null or reply.*.present == 0) {
logMsg("required X extension {s} is not available", .{name});
return error.MissingExtension;
}
}
/// Negotiate versions. Some servers reject extension requests until you have.
fn negotiate(xc: *c.xcb_connection_t) void {
if (c.xcb_randr_query_version_reply(xc, c.xcb_randr_query_version(xc, 1, 6), null)) |r|
std.c.free(r);
if (c.xcb_dpms_get_version_reply(xc, c.xcb_dpms_get_version(xc, 1, 2), null)) |r|
std.c.free(r);
if (c.xcb_screensaver_query_version_reply(xc, c.xcb_screensaver_query_version(xc, 1, 1), null)) |r|
std.c.free(r);
}
fn dpmsLevel(xc: *c.xcb_connection_t) !u16 {
const rep = c.xcb_dpms_info_reply(xc, c.xcb_dpms_info(xc), null) orelse
return error.DpmsQueryFailed;
defer std.c.free(rep);
return rep.*.power_level;
}
fn dpmsForceOn(xc: *c.xcb_connection_t) void {
// realign the server's bookkeeping with reality; a wake leaves it at Off
_ = c.xcb_dpms_force_level(xc, c.XCB_DPMS_DPMS_MODE_ON);
_ = c.xcb_flush(xc);
}
fn idleMs(xc: *c.xcb_connection_t, root: c.xcb_window_t) !u32 {
const rep = c.xcb_screensaver_query_info_reply(
xc,
c.xcb_screensaver_query_info(xc, root),
null,
) orelse return error.IdleQueryFailed;
defer std.c.free(rep);
return rep.*.ms_since_user_input;
}
fn configTimestamp(xc: *c.xcb_connection_t, root: c.xcb_window_t) !c.xcb_timestamp_t {
const res = c.xcb_randr_get_screen_resources_current_reply(
xc,
c.xcb_randr_get_screen_resources_current(xc, root),
null,
) orelse return error.NoScreenResources;
defer std.c.free(res);
return res.*.config_timestamp;
}
fn setCrtc(
xc: *c.xcb_connection_t,
crtc: c.xcb_randr_crtc_t,
cfg_ts: c.xcb_timestamp_t,
x: i16,
y: i16,
mode: c.xcb_randr_mode_t,
rotation: u16,
outs: []const c.xcb_randr_output_t,
) !void {
const rep = c.xcb_randr_set_crtc_config_reply(
xc,
c.xcb_randr_set_crtc_config(
xc,
crtc,
c.XCB_CURRENT_TIME,
cfg_ts,
x,
y,
mode,
rotation,
@intCast(outs.len),
if (outs.len == 0) null else outs.ptr,
),
null,
) orelse return error.SetCrtcFailed;
defer std.c.free(rep);
if (rep.*.status != c.XCB_RANDR_SET_CONFIG_SUCCESS) {
logMsg("SetCrtcConfig rejected: status={d}", .{rep.*.status});
return error.SetCrtcRejected;
}
}
fn findMode(list: [*c]c.xcb_randr_mode_info_t, n: c_int, id: c.xcb_randr_mode_t) ?c.xcb_randr_mode_info_t {
for (0..@intCast(n)) |k| if (list[k].id == id) return list[k];
return null;
}
/// On-screen footprint of a mode, which swaps axes under a quarter turn.
fn footprint(mi: c.xcb_randr_mode_info_t, rotation: u16) struct { w: u32, h: u32 } {
const quarter = c.XCB_RANDR_ROTATION_ROTATE_90 | c.XCB_RANDR_ROTATION_ROTATE_270;
return if (rotation & quarter != 0)
.{ .w = mi.height, .h = mi.width }
else
.{ .w = mi.width, .h = mi.height };
}
/// Grow the framebuffer if a placement would fall outside it.
///
/// SetCrtcConfig is rejected outright when the CRTC would extend past the
/// screen. We never shrink it ourselves, but xrandr(1) and kscreen both resize
/// the framebuffer to fit whatever they just set, so the screen can already be
/// too small for the mode we are restoring. Only ever grows.
fn growScreen(conn: Conn, need_w: u32, need_h: u32) void {
const geo = c.xcb_get_geometry_reply(conn.xc, c.xcb_get_geometry(conn.xc, conn.root), null) orelse return;
defer std.c.free(geo);
const cur_w: u32 = geo.*.width;
const cur_h: u32 = geo.*.height;
if (need_w <= cur_w and need_h <= cur_h) return;
const new_w: u32 = @max(cur_w, need_w);
const new_h: u32 = @max(cur_h, need_h);
// hold the original pixel density so DPI-derived sizing does not jump
const it = c.xcb_setup_roots_iterator(c.xcb_get_setup(conn.xc));
const px_w: u32 = it.data.*.width_in_pixels;
const px_h: u32 = it.data.*.height_in_pixels;
const mm_w: u32 = it.data.*.width_in_millimeters;
const mm_h: u32 = it.data.*.height_in_millimeters;
const nmm_w: u32 = if (px_w > 0) mm_w * new_w / px_w else mm_w;
const nmm_h: u32 = if (px_h > 0) mm_h * new_h / px_h else mm_h;
logMsg("growing framebuffer {d}x{d} -> {d}x{d}", .{ cur_w, cur_h, new_w, new_h });
_ = c.xcb_randr_set_screen_size(
conn.xc,
conn.root,
@intCast(new_w),
@intCast(new_h),
@intCast(nmm_w),
@intCast(nmm_h),
);
_ = c.xcb_flush(conn.xc);
}
/// Serialise re-inits across processes.
///
/// Running `hdmi-relink` by hand while the watcher is resident would otherwise
/// interleave the two SetCrtcConfig sequences, and whichever finishes last
/// restores the mode the other left behind -- permanently, since the restore
/// target is read from the CRTC.
///
/// Returns the locked file on success, null if no lock could be established at
/// all (in which case carry on unprotected), or error.Busy if another instance
/// holds it. The lock is released when the file is closed, including on crash.
fn acquireLock() !?std.posix.fd_t {
const dir: []const u8 = if (std.c.getenv("XDG_RUNTIME_DIR")) |v| std.mem.span(v) else "/tmp";
var buf: [256]u8 = undefined;
const path = std.fmt.bufPrint(&buf, "{s}/hdmi-relink.lock", .{dir}) catch return null;
// std.fs.File moved behind the Io interface in Zig 0.16; a bare fd is all
// this advisory lock needs.
const fd = std.posix.openat(
std.posix.AT.FDCWD,
path,
.{ .ACCMODE = .RDWR, .CREAT = true },
0o600,
) catch return null;
const rc = std.os.linux.flock(fd, std.posix.LOCK.EX | std.posix.LOCK.NB);
const err = std.os.linux.errno(rc);
if (err != .SUCCESS) {
_ = std.os.linux.close(fd);
if (err == .AGAIN) return error.Busy;
return null;
}
return fd;
}
/// Re-initialise the named output's link.
///
/// Only this output's CRTC is touched, and the screen size is never changed:
/// the intermediate low mode is strictly smaller than the target, so it always
/// fits the existing framebuffer. That makes it impossible to disturb the other
/// outputs' positions or refresh rates -- which is exactly what a shell
/// implementation driving xrandr(1) cannot avoid, because xrandr resizes the
/// framebuffer and renormalises every output when one is switched off.
fn reinit(conn: Conn, cfg: Config) !void {
const xc = conn.xc;
const lock = acquireLock() catch {
logMsg("another instance is re-initialising {s}; skipping", .{cfg.output});
return;
};
defer if (lock) |fd| {
_ = std.os.linux.close(fd);
};
const res = c.xcb_randr_get_screen_resources_current_reply(
xc,
c.xcb_randr_get_screen_resources_current(xc, conn.root),
null,
) orelse return error.NoScreenResources;
defer std.c.free(res);
var cfg_ts = res.*.config_timestamp;
const out_list = c.xcb_randr_get_screen_resources_current_outputs(res);
const n_out = c.xcb_randr_get_screen_resources_current_outputs_length(res);
const mode_list = c.xcb_randr_get_screen_resources_current_modes(res);
const n_modes = c.xcb_randr_get_screen_resources_current_modes_length(res);
// locate the output by name
var oi: ?*c.xcb_randr_get_output_info_reply_t = null;
var i: c_int = 0;
while (i < n_out) : (i += 1) {
const info = c.xcb_randr_get_output_info_reply(
xc,
c.xcb_randr_get_output_info(xc, out_list[@intCast(i)], cfg_ts),
null,
) orelse continue;
const name_ptr = c.xcb_randr_get_output_info_name(info);
const name_len: usize = @intCast(c.xcb_randr_get_output_info_name_length(info));
if (name_len == cfg.output.len and
std.mem.eql(u8, name_ptr[0..name_len], cfg.output))
{
oi = info;
break;
}
std.c.free(info);
}
const info = oi orelse {
logMsg("output {s} not found", .{cfg.output});
return error.OutputNotFound;
};
defer std.c.free(info);
if (info.*.connection != c.XCB_RANDR_CONNECTION_CONNECTED) {
logMsg("output {s} is not connected; nothing to do", .{cfg.output});
return;
}
if (info.*.crtc == 0) {
logMsg("output {s} is connected but disabled; nothing to do", .{cfg.output});
return;
}
// current geometry, kept verbatim so the restore is exact
const ci = c.xcb_randr_get_crtc_info_reply(
xc,
c.xcb_randr_get_crtc_info(xc, info.*.crtc, cfg_ts),
null,
) orelse return error.NoCrtcInfo;
defer std.c.free(ci);
const crtc = info.*.crtc;
const x = ci.*.x;
const y = ci.*.y;
const rotation = ci.*.rotation;
var target_mode = ci.*.mode;
if (target_mode == 0) {
logMsg("output {s} has no mode set; nothing to do", .{cfg.output});
return;
}
// Sitting at exactly the fallback resolution means a previous re-init was
// interrupted between steps 2 and 3 and never restored the real mode.
// Restoring "whatever is current" would then make the fallback permanent,
// so recover the EDID-preferred mode instead.
var target_w: u16 = 0;
var target_h: u16 = 0;
for (0..@intCast(n_modes)) |k| {
if (mode_list[k].id == target_mode) {
target_w = mode_list[k].width;
target_h = mode_list[k].height;
}
}
if (target_w == cfg.low_w and target_h == cfg.low_h) {
const n_pref: usize = @intCast(info.*.num_preferred);
const om_all = c.xcb_randr_get_output_info_modes(info);
if (n_pref > 0) {
const pref = om_all[0];
if (pref != target_mode) {
logMsg(
"{s} is stranded at the {d}x{d} fallback (a previous re-init did not finish); restoring preferred mode instead",
.{ cfg.output, cfg.low_w, cfg.low_h },
);
target_mode = pref;
}
}
}
// the CRTC's output list must be reproduced on restore (mirroring etc)
var outs_buf: [16]c.xcb_randr_output_t = undefined;
const co = c.xcb_randr_get_crtc_info_outputs(ci);
const n_co: usize = @intCast(c.xcb_randr_get_crtc_info_outputs_length(ci));
if (n_co > outs_buf.len) return error.TooManyOutputs;
for (0..n_co) |k| outs_buf[k] = co[k];
const outs = outs_buf[0..n_co];
// resolution and clock of the mode we have to end up on
target_w = 0;
target_h = 0;
var target_clock: u32 = 0;
if (findMode(mode_list, n_modes, target_mode)) |mi| {
target_w = mi.width;
target_h = mi.height;
target_clock = mi.dot_clock;
}
// Build an ascending pixel-clock ladder ending on the target.
//
// After a sleep the transmitter will not train straight to 594MHz -- the
// panel lights up and drops again -- but it will climb: 148.5MHz, then
// 297MHz, then 594MHz, each rung re-training one step closer. A single
// low-clock hop is not enough; the intermediate at the target resolution
// is what makes the last step succeed.
const om = c.xcb_randr_get_output_info_modes(info);
const n_om = c.xcb_randr_get_output_info_modes_length(info);
// fastest mode at the fallback resolution
var rung_low: c.xcb_randr_mode_t = 0;
var low_clock: u32 = 0;
// slowest mode at the target resolution -- the rung has to be a real step
// down (297MHz for a 594MHz target), not the 593.41MHz near-twin, or the
// climb is a no-op and the last hop fails exactly as a direct jump does
var rung_mid: c.xcb_randr_mode_t = 0;
var mid_clock: u32 = std.math.maxInt(u32);
for (0..@intCast(n_om)) |j| {
const mi = findMode(mode_list, n_modes, om[j]) orelse continue;
if (mi.id == target_mode) continue;
if (mi.width == cfg.low_w and mi.height == cfg.low_h and mi.dot_clock > low_clock) {
low_clock = mi.dot_clock;
rung_low = mi.id;
}
if (mi.width == target_w and mi.height == target_h and
mi.dot_clock < target_clock and mi.dot_clock < mid_clock)
{
mid_clock = mi.dot_clock;
rung_mid = mi.id;
}
}
var ladder: [3]c.xcb_randr_mode_t = undefined;
var n_rungs: usize = 0;
if (rung_low != 0) {
ladder[n_rungs] = rung_low;
n_rungs += 1;
}
if (rung_mid != 0) {
ladder[n_rungs] = rung_mid;
n_rungs += 1;
}
ladder[n_rungs] = target_mode;
n_rungs += 1;
logMsg("re-initialising {s}: climbing {d}kHz -> {d}kHz -> {d}kHz ({d} rungs)", .{
cfg.output,
low_clock / 1000,
if (rung_mid == 0) 0 else mid_clock / 1000,
target_clock / 1000,
n_rungs,
});
// tear the CRTC down so the transmitter is re-initialised
try setCrtc(xc, crtc, cfg_ts, 0, 0, c.XCB_NONE, c.XCB_RANDR_ROTATION_ROTATE_0, &.{});
for (ladder[0..n_rungs]) |mode| {
if (findMode(mode_list, n_modes, mode)) |mi| {
const fp = footprint(mi, rotation);
growScreen(conn, @as(u32, @intCast(x)) + fp.w, @as(u32, @intCast(y)) + fp.h);
}
// each SetCrtcConfig advances the config timestamp; a stale one is rejected
cfg_ts = try configTimestamp(xc, conn.root);
try setCrtc(xc, crtc, cfg_ts, x, y, mode, rotation, outs);
sleepMs(cfg.hold_ms);
}
_ = c.xcb_flush(xc);
// Leaving the panel on the fallback mode is the one failure that persists,
// so confirm the restore actually took rather than assuming success.
const check = c.xcb_randr_get_crtc_info_reply(
xc,
c.xcb_randr_get_crtc_info(xc, crtc, try configTimestamp(xc, conn.root)),
null,
) orelse return;
defer std.c.free(check);
if (check.*.mode != target_mode) {
logMsg("restore did not take: crtc is on mode {d}, expected {d}", .{ check.*.mode, target_mode });
return error.RestoreFailed;
}
}
fn watch(conn: Conn, cfg: Config) !void {
logMsg("watching for wake (output={s} interval={d}ms settle={d}ms idle-threshold={d}ms)", .{
cfg.output, cfg.interval_ms, cfg.settle_ms, cfg.idle_threshold_ms,
});
const on = c.XCB_DPMS_DPMS_MODE_ON;
var prev_idle = idleMs(conn.xc, conn.root) catch 0;
var prev_level = dpmsLevel(conn.xc) catch on;
// Latched, not sampled at the moment of the wake: whoever blanked the
// screen may restore the level before the next poll, and testing the level
// only on the idle edge then races with them and never matches.
var slept = prev_level != on;
while (true) {
sleepMs(cfg.interval_ms);
if (c.xcb_connection_has_error(conn.xc) != 0) {
logMsg("X connection lost; exiting for restart", .{});
return error.ConnectionLost;
}
const idle = idleMs(conn.xc, conn.root) catch |e| {
logMsg("idle query failed: {s}", .{@errorName(e)});
continue;
};
const level = dpmsLevel(conn.xc) catch |e| {
logMsg("dpms query failed: {s}", .{@errorName(e)});
continue;
};
defer prev_idle = idle;
if (level != on) slept = true;
if (cfg.trace) logMsg("trace idle={d} level={d} slept={}", .{ idle, level, slept });
if (level != prev_level) {
logMsg("dpms level {d} -> {d} (idle {d}ms, slept={})", .{ prev_level, level, idle, slept });
prev_level = level;
}
// A drop in the idle counter means input arrived.
if (idle >= prev_idle) continue;
// ...but only re-initialise if the panels actually powered down, either
// observed directly or inferred from an idle long enough to have
// tripped the DPMS timeout.
const long_idle = prev_idle >= cfg.idle_threshold_ms;
if (!slept and !long_idle) continue;
logMsg("wake detected (idle {d}ms -> {d}ms, level {d}, slept={}, long_idle={})", .{
prev_idle, idle, level, slept, long_idle,
});
slept = false;
dpmsForceOn(conn.xc);
sleepMs(cfg.settle_ms);
reinit(conn, cfg) catch |e| logMsg("re-init failed: {s}", .{@errorName(e)});
}
}
fn parseArgs(cfg: *Config, args: []const [:0]const u8) !void {
var i: usize = 1;
while (i < args.len) : (i += 1) {
const a = args[i];
if (std.mem.eql(u8, a, "--watch")) {
cfg.watch = true;
} else if (std.mem.eql(u8, a, "--output") and i + 1 < args.len) {
i += 1;
cfg.output = args[i];
} else if (std.mem.eql(u8, a, "--settle") and i + 1 < args.len) {
i += 1;
cfg.settle_ms = try std.fmt.parseInt(u64, args[i], 10) * 1000;
} else if (std.mem.eql(u8, a, "--interval") and i + 1 < args.len) {
i += 1;
cfg.interval_ms = try std.fmt.parseInt(u64, args[i], 10) * 1000;
} else if (std.mem.eql(u8, a, "--idle-threshold") and i + 1 < args.len) {
i += 1;
cfg.idle_threshold_ms = try std.fmt.parseInt(u32, args[i], 10) * 1000;
} else if (std.mem.eql(u8, a, "--trace")) {
cfg.trace = true;
} else if (std.mem.eql(u8, a, "--help") or std.mem.eql(u8, a, "-h")) {
std.debug.print(
\\usage: hdmi-relink [--watch] [--output NAME] [--settle SECS] [--interval SECS]
\\
\\ no args re-initialise the output once and exit
\\ --watch stay resident and re-initialise on every wake
\\
, .{});
std.process.exit(0);
} else {
logMsg("unknown argument: {s}", .{a});
return error.BadArgs;
}
}
}
pub fn main(init: std.process.Init.Minimal) !void {
var gpa = std.heap.DebugAllocator(.{}){};
defer _ = gpa.deinit();
const alloc = gpa.allocator();
var args = std.ArrayList([:0]const u8).empty;
defer args.deinit(alloc);
var it = std.process.Args.Iterator.init(init.args);
while (it.next()) |a| try args.append(alloc, a);
var cfg = Config{};
try parseArgs(&cfg, args.items);
const conn = try connect();
defer c.xcb_disconnect(conn.xc);
try requireExt(conn.xc, &xcb_randr_id, "RANDR");
try requireExt(conn.xc, &xcb_dpms_id, "DPMS");
try requireExt(conn.xc, &xcb_screensaver_id, "MIT-SCREEN-SAVER");
if (cfg.watch) try watch(conn, cfg) else try reinit(conn, cfg);
}
+180
View File
@@ -0,0 +1,180 @@
# Desktop Hyprland
This host uses Hyprland 0.56's native Lua configuration, managed by UWSM.
The shared `illustris` input is pinned to `github:illustris/flake` and provides
the common NixOS and Home Manager Hyprland modules. The dailyDriver profile
imports the home module. This directory keeps only the host's NVIDIA options,
display/HDR/HDMI recovery extension, and their tests. The shared controller,
bindings, panel, scripts and package patches live in
`homeConfigurations/modules/hyprland` in that flake and are also used by Yoga.
## Daily Use
Choose **Hyprland (uwsm-managed)** in LightDM. From a logged-in TTY, run
`uwsm start -e -D Hyprland hyprland.desktop`.
Plasma (X11), with the existing XMonad window manager, remains available.
| Shortcut | Action |
| --- | --- |
| Super+Enter | Customized st, through XWayland |
| Super+D | Application launcher |
| Super+Ctrl+E | Dolphin |
| Super+G / M / T / R | Grid / Monocle / Tabs / Scrolling |
| Super+Space | Cycle those four layouts |
| Super+J / K | Next / previous window or tab |
| Super+arrows | Directional focus within workspace; left/right scroll columns |
| Super+Shift+J / K | Swap window order |
| Super+Shift+Enter / Ctrl+M | Promote / focus first window |
| Super+F | Toggle fullscreen for the selected window |
| Super+Shift+Space / Ctrl+Space | Sink / toggle floating |
| Super+1 through 9 | Bring that workspace to the focused monitor |
| Super+Shift+1 through 9 | Move only the selected window, keeping source focus |
| Super+W / E | Focus OLED / LG |
| Super+Shift+W / E | Move selected window to OLED / LG |
| Super+Ctrl+arrows | Move the workspace to another monitor |
| Super+S / Shift+S | Show scratchpad / send selected window there |
| Super+minus / equal | Narrow / widen scrolling column |
| Super+Ctrl+minus / equal | Lower / raise Grid target width/height ratio |
| Super+Ctrl+Backspace | Reset this workspace's Grid ratio to 1.20:1 |
| Super+V | Clipboard history |
| Print / Shift+Print | Screenshot focused monitor / all monitors |
| Super+Shift+Print | Screenshot a region |
| Super+Shift+L | Lock |
| Super+Shift+Q | Session and display controls, including logout |
| Super+/ | Search shortcut descriptions |
| Super+mouse left / right | Drag / resize a window |
Screenshots go to `~/Pictures/Screenshots` and are copied to the clipboard.
The bottom panel exposes workspaces, the layout selector, tasks, media,
volume, network, Bluetooth, idle inhibition, and the tray.
Grid uses the same aspect calculation and remainder distribution as
XMonad's GridVariants. Its default target window width/height is 1.20:1.
Super+Ctrl+minus lowers the ratio, favoring taller windows and splitting into
columns sooner; Super+Ctrl+equal raises it, favoring wider windows and delaying
the split. The range is 0.25 to 4.00 in 0.10 steps, with Backspace resetting it.
Each workspace keeps its own ratio across config reloads. The panel shows
`Grid 1.20:1` (or the current ratio) while Grid is selected. Arrow navigation
selects neighbors by position, stops at workspace edges, and keeps every column
reachable. Use Super+W/E to change monitors. Scrolling arrows stop at the first
and last columns and recover window focus if the viewport loses it. Monocle hides
inactive tiled windows. Tabs combine
the workspace's tiled windows into one native group with a visible tab bar;
floating dialogs stay separate. Leaving Tabs dissolves that group. Moving or
floating a tab detaches the selected window before the operation. Tab creation
waits for the layout change to finish so Monocle releases its input restrictions.
Layouts and window order survive config reloads within the compositor session;
new sessions start in Grid. Runtime state is plain data under `$XDG_RUNTIME_DIR`.
Each monitor's layout label follows its own active workspace, updating directly
from state changes without polling. The **Keep Awake: On/Off** control pauses or
resumes automatic locking and display sleep; click it to toggle. Its tooltip
explains the current behavior. Manual locking and suspend remain available.
## Displays And Sleep
Outputs are matched by their full EDID descriptions, including serials.
The AW3225QF runs at its highest advertised 4K refresh rate (240 Hz), scale 1,
10-bit HDR, with SDR reference luminance 265 nits. The LG runs at 4K/60 Hz,
scale 1, transform 3, SDR/8-bit. In the dual profile, positions are `(0,1680)`
and `(3840,0)` so the landscape and portrait displays are bottom aligned.
Unplugging the LG migrates its workspaces; reconnecting leaves them where they
migrated. The OLED-only profile moves its origin to `(0,0)`.
| Shortcut / command | Action |
| --- | --- |
| Super+Shift+Alt+1 / `desktopctl dual` | Enable dual monitors |
| Super+Shift+Alt+2 / `desktopctl solo` | Disable LG, move workspaces onto OLED |
| Super+Shift+Alt+H / `desktopctl hdr` | Toggle OLED HDR |
| Super+Shift+Alt+R / `desktopctl wake` | Retrain LG HDMI link |
Hypridle locks at seven minutes and turns outputs off at eight minutes.
It locks before suspend and restores outputs after resume. LG recovery runs
at login, config reload, reconnect, dual-profile selection, and wake. New links
start at 1080p60. After a three-second settling period, recovery disables the
output for one second, then steps through 1080p60, 4K30, and 4K60. Each low-clock
mode is held for three seconds after the compositor confirms it is active.
The complete sequence takes about twelve seconds. Its own output events do not
restart it. Selecting OLED-only cancels pending recovery timers immediately;
unplugging resets the next connection to 1080p. A modeset timeout stops the ladder
and leaves a 1080p recovery rule. It never reenables an intentionally disabled LG.
A compositor capture cannot prove the physical LG has acquired its HDMI signal;
check the panel after wake. The initial direct 4K60 setup failed on the physical
LG despite healthy compositor state; the user confirmed signal acquisition
after disabling the output and bringing it up at 1080p60, then confirmed both
physical displays showed the lock screen after automatic recovery to 4K60.
NVIDIA full VRAM preservation and its suspend/resume services are enabled.
The module uses `NVreg_PreserveVideoMemoryAllocations=1` and `/var/tmp` storage.
Changing these settings requires a reboot. The previous loaded setting of 2
produced GPU errors and an EGL crash after suspend. With setting 1 loaded,
the compositor survived the live RTC suspend/resume tests with the same PID.
## Package Compatibility
Waybar 0.15's workspace button sends legacy dispatcher syntax. A shared patch
uses native Lua dispatch and selects workspaces on the clicked monitor.
Its event reader also fails to reconnect after a disconnected Hyprland socket,
leaving the active workspace highlight stuck. A second patch reconnects and
resynchronizes module state, with a 250 ms retry delay.
Hyprland 0.56's workspace JSON incorrectly reports every Lua layout with the
first registered name, so the layout label watches the controller's runtime state
through inotify. Atomic file replacements produce immediate updates, and changes
on another output do not change this output's label.
The pinned Firefox 154 / GTK build crashes in `xdg_output_handle_name` during
native Wayland initialization. Its package wrapper selects XWayland only when
`XDG_CURRENT_DESKTOP=Hyprland`; Plasma retains its existing behavior. Remove
this workaround after testing a fixed package revision. Native Dolphin and
the Hyprland screen-sharing / KDE file-chooser portals are available.
Hyprlock uses Mesa software rendering and shared-memory screen capture. NVIDIA
595's EGL Wayland surface destruction hung after unlocking a resumed session;
the locker spun in `eplWlDestroyWindow`. The software wrapper avoids that path
for the shortcut, desktop menu, and idle/suspend hooks. The final live test
confirmed automatic locking, compositor survival, restored outputs, and clean
locker exit after resume, with no NVIDIA errors during that cycle.
Idle locking launches Hyprlock through UWSM as a separate session app. Reloading
or restarting hypridle therefore does not kill an active locker; previously its
child process died during system activation, leaving an orphaned lock screen.
## Build And Verify
```sh
nix build .#nixosConfigurations.desktop.config.system.build.toplevel
sudo nixos-rebuild test --flake .#desktop
env -u HYPRLAND_INSTANCE_SIGNATURE Hyprland --verify-config -c ~/.config/hypr/hyprland.lua
nix build --inputs-from . illustris#checks.x86_64-linux.hyprland
shared_hyprland=$(nix flake metadata --inputs-from . --json illustris | jq -r '.path + "/homeConfigurations/modules/hyprland"')
XDG_RUNTIME_DIR=$(mktemp -d) HYPRLAND_INSTANCE_SIGNATURE=test \
lua modules/hyprland/test.lua "$shared_hyprland"
```
Use `hyprctl eval 'desktop.layout_set("tabbed")'` for IPC commands. Legacy
`hyprctl keyword` and `hyprctl dispatch workspace 1` do not work in Lua mode.
Check `hyprctl configerrors`, `hyprctl monitors -j`, and
`systemctl --user status wayland-wm@hyprland.desktop.service` when debugging.
Use `uwsm stop` to end the session. Hyprland auxiliary services are bound to
`wayland-session@hyprland.desktop.target`; they stop at logout and stay out of Plasma.
The XMonad and X11 HDMI recovery services stop with the Plasma session.
Live test captures and logs from this setup are preserved in
`~/.local/state/hyprland-parity`. Temporary build files are in `/tmp/hyprland-parity`.
Screen captures use `WAYLAND_DISPLAY=wayland-1 grim -o DP-1 ...` with the actual
socket name from `hyprctl instances -j`. They validate composition and geometry;
HDR is additionally checked through the compositor format and DRM colorspace.
Live tests passed for all four layouts, selected-tab moves, floating dialogs,
clipboard, screenshots, locking, screen sharing, the KDE file chooser, and the
Plasma fallback. Post-reboot tests additionally verified a real Waybar click
bringing an LG workspace onto the OLED, physical keyboard shortcuts and a
scratchpad round trip, dual/solo workspace migration, repeated wake/sink calls,
and suspend/resume with the software locker. HDMI controller tests additionally
cover delayed mode application, settling and hold times, duplicate wake events,
OLED-only cancellation, unplug/replug, and modeset timeouts. Test unlocks used Hyprlock's
documented SIGUSR1 mechanism; the PAM prompt and lock input isolation were checked.
The user confirmed physical LG signal acquisition after idle wake with the
updated recovery sequence; the live trace reached 4K60 in about twelve seconds.
Home Manager preserved the previous Waybar configuration as `.hm-bak` files.
The preexisting Firefox containers backup was retained as
`containers.json.hm-bak.before-hyprland-20261003` to resolve a backup collision.
+10
View File
@@ -0,0 +1,10 @@
{ lib, ... }:
{
# Preserve GPU allocations across suspend; EGL contexts otherwise fail on resume.
hardware.nvidia = {
powerManagement.enable = true;
powerManagement.kernelSuspendNotifier = false;
moduleParams.nvidia.NVreg_TemporaryFilePath = "/var/tmp";
};
services.displayManager.defaultSession = lib.mkForce "hyprland-uwsm";
}
+30
View File
@@ -0,0 +1,30 @@
{ ... }:
{
illustris.hyprland = {
wallpaper = "/home/illustris/Downloads/adrien-olichon-RCAhiGJsUUE-unsplash.jpg";
softwareRendering = true;
xwaylandFirefox = true;
compositorSettings.cursor.no_hardware_cursors = true;
monitorRules = [ ];
monitorKeys = {
W = "oled";
E = "lg";
};
extraLuaConfig = ''require("outputs")'';
extraCommands = {
dual = "desktop.display_profile(true)";
solo = "desktop.display_profile(false)";
hdr = "desktop.hdr_toggle()";
};
extraMenuEntries = {
"Dual monitors" = "dual";
"OLED only" = "solo";
"Toggle HDR" = "hdr";
"Retrain LG HDMI" = "wake";
};
};
wayland.windowManager.hyprland.extraLuaFiles.outputs = {
content = ./outputs.lua;
autoLoad = false;
};
}
+149
View File
@@ -0,0 +1,149 @@
local D = desktop
local later, selector, dispatch = D.later, D.workspace_selector, hl.dispatch
local recovering = false
local recovery_epoch, lg_mode = 0, "1920x1080@60"
local outputs = { oled = "desc:Dell Inc. AW3225QF JR11YZ3", lg = "desc:LG Electronics LG HDR 4K 0x000404F0" }
D.hdr, D.lg_enabled = D.flags.hdr ~= false, D.flags.lg ~= false
D.flags.hdr, D.flags.lg = D.hdr, D.lg_enabled
local function save()
D.flags.hdr, D.flags.lg = D.hdr, D.lg_enabled
D.save()
end
local function display(kind)
for _, m in ipairs(hl.get_monitors()) do
if kind == "oled" and m.description:find("AW3225QF", 1, true) and m.serial == "JR11YZ3" then return m end
if kind == "lg" and m.description:find("LG HDR 4K", 1, true) then return m end
end
end
function D.monitors()
if recovering then return end
local oled, lg = display("oled"), display("lg")
local refresh = 239.991
if oled then
refresh = 0
for _, mode in ipairs(oled.available_modes) do
if mode.width == 3840 and mode.height == 2160 then refresh = math.max(refresh, mode.refresh_rate) end
end
if refresh == 0 then refresh = 239.991 end
end
local dual = D.lg_enabled and lg ~= nil
hl.monitor({ output = outputs.oled, mode = string.format("3840x2160@%.3f", refresh),
position = dual and "0x1680" or "0x0", scale = 1, bitdepth = 10,
cm = D.hdr and "hdredid" or "srgb", sdr_max_luminance = 265, sdrbrightness = 1, sdrsaturation = 1 })
hl.monitor({ output = outputs.lg, mode = lg_mode, position = "3840x0", scale = 1,
transform = 3, bitdepth = 8, cm = "srgb", disabled = not D.lg_enabled })
end
local function cancel_recovery()
recovery_epoch = recovery_epoch + 1
recovering = false
lg_mode = "1920x1080@60"
D.lg_recovery = "pending"
end
function D.display_profile(dual)
D.lg_enabled = dual
-- Explicitly move workspaces before disabling; reconnecting does not move them back.
if not dual then
cancel_recovery()
local lg, oled = display("lg"), display("oled")
if lg and oled then
for _, ws in ipairs(hl.get_workspaces()) do
if ws.monitor == lg then dispatch(hl.dsp.workspace.move({ workspace = selector(ws), monitor = oled.name })) end
end
end
end
D.monitors()
if dual then later(300, D.recover_lg) end
save()
end
function D.hdr_toggle() D.hdr = not D.hdr; D.monitors(); save() end
function D.monitor_focus(kind, move)
local m = display(kind)
if not m then return end
if move then
if m.active_workspace then D.move(tostring(m.active_workspace.id)) end
else dispatch(hl.dsp.focus({ monitor = m.name })) end
end
-- Monitor rules apply asynchronously. Hold each rung only after its mode is active.
function D.recover_lg()
if not os.getenv("HYPRLAND_INSTANCE_SIGNATURE") or not D.lg_enabled or not display("lg") or recovering then return end
recovering = true
recovery_epoch = recovery_epoch + 1
local epoch = recovery_epoch
D.lg_recovery = "settling"
local steps = {
{ mode = false, hold = 1000 },
{ mode = "1920x1080@60", width = 1920, height = 1080, refresh = 60, hold = 3000 },
{ mode = "3840x2160@30", width = 3840, height = 2160, refresh = 30, hold = 3000 },
{ mode = "3840x2160@60", width = 3840, height = 2160, refresh = 60, hold = 1000 },
}
local function valid() return epoch == recovery_epoch and D.lg_enabled end
local rung
rung = function(index)
if not valid() then return end
local step = steps[index]
if not step then
recovering = false
D.lg_recovery = "ready"
D.monitors()
return
end
D.lg_recovery = step.mode or "off"
if step.mode then lg_mode = step.mode end
hl.monitor({ output = outputs.lg, disabled = not step.mode, mode = lg_mode })
local function await_mode(attempt)
if not valid() then return end
local lg = display("lg")
local applied = not step.mode and not lg or step.mode and lg
and lg.width == step.width and lg.height == step.height
and math.abs(lg.refresh_rate - step.refresh) < 0.1 and lg.dpms_status
if applied then
later(step.hold, function() rung(index + 1) end)
elseif attempt < 50 then
later(100, function() await_mode(attempt + 1) end)
else
cancel_recovery()
D.lg_recovery = "failed"
D.monitors()
end
end
later(100, function() await_mode(1) end)
end
-- Match the X11 helper's wake settling time before tearing down the HDMI link.
later(3000, function() rung(1) end)
end
D.on_wake = D.recover_lg
D.on_restore = function() D.monitors(); D.recover_lg() end
hl.on("monitor.added", function(m)
if recovering then return end
local lg_added = m.description:find("LG HDR 4K", 1, true) ~= nil
later(300, function()
if recovering then return end
D.monitors()
if lg_added then D.recover_lg() end
end)
end)
hl.on("monitor.removed", function(m)
if m.description:find("LG HDR 4K", 1, true) and not (recovering and D.lg_recovery == "off") then cancel_recovery() end
later(300, D.monitors)
end)
hl.monitor({ output = outputs.oled, mode = "3840x2160@239.991", position = "0x1680", scale = 1,
bitdepth = 10, cm = D.hdr and "hdredid" or "srgb", sdr_max_luminance = 265,
sdrbrightness = 1, sdrsaturation = 1 })
hl.monitor({ output = outputs.lg, mode = lg_mode, position = "3840x0", scale = 1,
transform = 3, bitdepth = 8, cm = "srgb", disabled = not D.lg_enabled })
local function bind(keys, description, action)
hl.bind(keys, action, { description = description })
end
bind("SUPER + SHIFT + ALT + 1", "Dual monitor profile", function() D.display_profile(true) end)
bind("SUPER + SHIFT + ALT + 2", "OLED only profile", function() D.display_profile(false) end)
bind("SUPER + SHIFT + ALT + H", "Toggle OLED HDR", D.hdr_toggle)
bind("SUPER + SHIFT + ALT + R", "Retrain LG HDMI after wake", D.wake)
+85
View File
@@ -0,0 +1,85 @@
local shared = assert(arg[1], "Pass the shared flake's homeConfigurations/modules/hyprland directory")
package.path = (arg[0]:match("^(.*/)") or "") .. "?.lua;" .. package.path
local context = dofile(shared .. "/test.lua")
local D, events, one, two, advance = context.desktop, context.events, context.one, context.two, context.advance
require("outputs")
-- Model delayed modesets and their added/removed events, rather than immediate rule updates.
local lg = { name = "HDMI-A-1", description = "LG Electronics LG HDR 4K 0x000404F0",
width = 3840, height = 2160, refresh_rate = 60, dpms_status = true, active_workspace = two }
local connected, stuck, apply_delay, commands = true, false, 1400, {}
local lg_rule = { mode = "3840x2160@60", disabled = false }
context.monitors = { lg }
hl.monitor = function(rule)
if not rule.output:find("LG HDR 4K", 1, true) then return end
for k, v in pairs(rule) do lg_rule[k] = v end
local mode, disabled = lg_rule.mode, lg_rule.disabled
commands[#commands + 1] = { mode = disabled and "off" or mode, at = context.clock() }
hl.timer(function()
if not connected or stuck then return end
if disabled then
context.monitors = {}
events["monitor.removed"](lg)
else
local was_off = #context.monitors == 0
lg.width, lg.height, lg.refresh_rate = mode:match("(%d+)x(%d+)@([%d.]+)")
lg.width, lg.height, lg.refresh_rate = tonumber(lg.width), tonumber(lg.height), tonumber(lg.refresh_rate)
context.monitors = { lg }
if was_off then events["monitor.added"](lg) end
end
end, { timeout = apply_delay })
end
local function count_off()
local count = 0
for _, command in ipairs(commands) do if command.mode == "off" then count = count + 1 end end
return count
end
events["hyprland.start"]()
advance(100)
assert(D.lg_recovery == "settling", "session startup must recover the LG")
D.wake(); D.wake()
advance(18000)
assert(D.lg_recovery == "ready" and lg.refresh_rate == 60 and lg.width == 3840)
local state = assert(io.open(os.getenv("XDG_RUNTIME_DIR") .. "/hypr-desktop-test.state")):read("*a")
assert(state:find("panel HDMI-A-1 2 scrolling 2.40", 1, true), "panel state must report each output's own layout and ratio")
assert(count_off() == 1, "wake and self-generated hotplug events must not restart recovery")
local off_index
for i, command in ipairs(commands) do if command.mode == "off" then off_index = i; break end end
local off, low, mid, high = table.unpack(commands, off_index, off_index + 3)
assert(low.mode == "1920x1080@60" and mid.mode == "3840x2160@30" and high.mode == "3840x2160@60")
assert(low.at - off.at >= apply_delay + 1000, "off hold starts after disable takes effect")
assert(mid.at - low.at >= apply_delay + 3000 and high.at - mid.at >= apply_delay + 3000,
"each mode must be applied before starting its hold")
events["config.reloaded"](); advance(100)
assert(D.lg_recovery == "settling", "config restore must recover the LG")
advance(18000)
assert(D.lg_recovery == "ready" and count_off() == 2)
D.wake(); advance(7500)
assert(D.lg_recovery == "1920x1080@60")
D.display_profile(false)
local solo_commands = #commands
advance(20000)
assert(lg_rule.disabled and #context.monitors == 0, "solo must cancel an in-progress recovery immediately")
for i = solo_commands + 1, #commands do assert(commands[i].mode == "off", "stale timer reenabled LG") end
D.wake(); advance(20000)
assert(lg_rule.disabled and #context.monitors == 0, "wake must respect intentional LG disable")
D.display_profile(true); advance(20000)
assert(D.lg_recovery == "ready" and lg.refresh_rate == 60, "dual must start low and retrain")
D.wake(); advance(6500)
connected = false; context.monitors = {}; events["monitor.removed"](lg)
advance(20000)
assert(D.lg_recovery == "pending" and lg_rule.mode == "1920x1080@60", "unplug must reset recovery to a safe mode")
connected = true
lg.width, lg.height, lg.refresh_rate = 1920, 1080, 60
context.monitors = { lg }; events["monitor.added"](lg)
advance(20000)
assert(D.lg_recovery == "ready" and lg.width == 3840 and lg.refresh_rate == 60, "replug must recover")
stuck = true
D.wake(); advance(10000)
assert(D.lg_recovery == "failed" and lg_rule.mode == "1920x1080@60",
"failed modeset must stop the ladder and leave a safe recovery rule")
print("PASS: desktop HDMI recovery, startup, solo cancellation, replug, modeset timeout and per-output panel state")
+5 -4
View File
@@ -1,6 +1,7 @@
{ stdenv, lib, fetchurl, dpkg, patchelf, qt5, libXtst, libXext, libX11, mkDerivation, makeWrapper, libXScrnSaver, writeScript, common-updater-scripts, curl, pup }:
let
inherit (lib) indent;
version = "2.16.5.1";
src =
if stdenv.hostPlatform.system == "i686-linux" then fetchurl {
@@ -20,12 +21,12 @@ in mkDerivation rec {
nativeBuildInputs = [ dpkg ];
# avoid https://github.com/NixOS/patchelf/issues/99
dontStrip = true;
unpackPhase = ''
unpackPhase = indent ''
mkdir pkg
dpkg-deb -x $src pkg
sourceRoot=pkg
'';
installPhase = ''
installPhase = indent ''
mkdir -p $out/bin
cp usr/bin/rescuetime $out/bin
@@ -35,7 +36,7 @@ in mkDerivation rec {
$out/bin/rescuetime
'';
passthru.updateScript = writeScript "${pname}-updater" ''
passthru.updateScript = writeScript "${pname}-updater" (indent ''
#!${stdenv.shell}
set -eu -o pipefail
PATH=${lib.makeBinPath [curl pup common-updater-scripts]}:$PATH
@@ -47,7 +48,7 @@ in mkDerivation rec {
update-source-version ${pname} 0 $(yes 0 | head -64 | tr -d "\n") --system=$platform
update-source-version ${pname} "$latestVersion" --system=$platform
done
'';
'');
meta = with lib; {
description = "Helps you understand your daily habits so you can focus and be more productive";