diff --git a/flake.lock b/flake.lock index eeb7d54..2d45d58 100644 --- a/flake.lock +++ b/flake.lock @@ -55,17 +55,14 @@ ] }, "locked": { - "lastModified": 1787539381, - "narHash": "sha256-e8vhxuSYAa+/QEnz0m5Dxdot7J0sb1VrjUInY2yUeg0=", - "owner": "illustris", - "repo": "flake", - "rev": "842f2aa7d9a5904222630bbfe2e97055526faa6d", - "type": "github" + "lastModified": 1791049652, + "narHash": "sha256-V/rSlfVW+FQopcqR1r1vyLe0KujnP0KjCpajxCzWiiA=", + "path": "/home/illustris/src/flake", + "type": "path" }, "original": { - "owner": "illustris", - "repo": "flake", - "type": "github" + "path": "/home/illustris/src/flake", + "type": "path" } }, "nixfs": { diff --git a/flake.nix b/flake.nix index cf84ab0..7717349 100644 --- a/flake.nix +++ b/flake.nix @@ -8,8 +8,7 @@ inputs.nixpkgs.follows = "nixpkgs"; }; illustris = { - # url = "path:///home/illustris/src/flake"; - url = "github:illustris/flake"; + url = "path:///home/illustris/src/flake"; inputs = { nixpkgs.follows = "nixpkgs"; firefox-addons.follows = "firefox-addons"; @@ -80,7 +79,9 @@ useGlobalPkgs = true; backupFileExtension = "hm-bak"; users.illustris = {...}: { + disabledModules = [ (illustris + "/homeConfigurations/modules/hyprland") ]; imports = [ + ./modules/hyprland/home.nix (import ( illustris + "/homeConfigurations/profiles/dailyDriver/home.nix" ) inputs) diff --git a/modules/default.nix b/modules/default.nix index 8b4a354..5630669 100644 --- a/modules/default.nix +++ b/modules/default.nix @@ -2,5 +2,6 @@ { imports = [ ./hdmi-relink + ./hyprland ]; } diff --git a/modules/hdmi-relink/default.nix b/modules/hdmi-relink/default.nix index 760cab0..55a879e 100644 --- a/modules/hdmi-relink/default.nix +++ b/modules/hdmi-relink/default.nix @@ -36,11 +36,11 @@ in systemd.user.services.hdmi-relink = { description = "Re-initialise HDMI-0 TMDS link on wake"; - partOf = [ "graphical-session.target" ]; - after = [ "graphical-session.target" ]; - wantedBy = [ "graphical-session.target" ]; - # XAUTHORITY is already exported to the user manager by the session - environment.DISPLAY = ":0"; + 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 diff --git a/modules/hyprland/COPYING.grid b/modules/hyprland/COPYING.grid new file mode 100644 index 0000000..501993b --- /dev/null +++ b/modules/hyprland/COPYING.grid @@ -0,0 +1,27 @@ +The GridVariants geometry in geometry.lua is derived from XMonad.Layout.GridVariants. +Copyright (c) Norbert Zeh +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/modules/hyprland/README.md b/modules/hyprland/README.md new file mode 100644 index 0000000..4ae7a23 --- /dev/null +++ b/modules/hyprland/README.md @@ -0,0 +1,174 @@ +# Desktop Hyprland + +This host uses Hyprland 0.56's native Lua configuration, managed by UWSM. +The shared `illustris` flake points at `/home/illustris/src/flake`; its old +laptop-oriented Hyprland module is disabled only on this host. + +## 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 local 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 +XDG_RUNTIME_DIR=$(mktemp -d) HYPRLAND_INSTANCE_SIGNATURE=test lua modules/hyprland/test.lua +PYTHONDONTWRITEBYTECODE=1 python modules/hyprland/test_panel.py +``` + +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. diff --git a/modules/hyprland/bindings.lua b/modules/hyprland/bindings.lua new file mode 100644 index 0000000..a015872 --- /dev/null +++ b/modules/hyprland/bindings.lua @@ -0,0 +1,91 @@ +local D = desktop +local function run(command) hl.exec_cmd("uwsm app -- " .. command) end +local function bind(keys, description, action, opts) + opts = opts or {} + opts.description = description + hl.bind(keys, action, opts) +end +local function command(keys, description, cmd) bind(keys, description, function() run(cmd) end) end + +hl.config({ + general = { layout = "lua:grid", gaps_in = 1, gaps_out = 2, border_size = 1, + ["col.active_border"] = "rgb(00ccff)", ["col.inactive_border"] = "rgb(808080)" }, + decoration = { rounding = 2, blur = { enabled = false }, shadow = { enabled = false } }, + animations = { enabled = false }, + input = { kb_layout = "us", follow_mouse = 1, repeat_delay = 300, repeat_rate = 40 }, + cursor = { no_hardware_cursors = true }, + misc = { disable_hyprland_logo = true, force_default_wallpaper = 0 }, + scrolling = { column_width = 0.5, follow_focus = true, wrap_focus = false, + explicit_column_widths = "0.333, 0.5, 0.667, 1.0" }, + group = { auto_group = false, groupbar = { height = 24, font_size = 12, font_family = "Noto Sans", + gradients = true, ["col.active"] = "rgb(00a6cc)", ["col.inactive"] = "rgb(31363b)", + text_color = "rgb(eff0f1)", rounding = 0, gaps_in = 1, gaps_out = 0 } }, +}) +for name, value in pairs({ GDK_SCALE = "1", GDK_DPI_SCALE = "1", QT_SCALE_FACTOR = "1", + QT_AUTO_SCREEN_SCALE_FACTOR = "0", QT_QPA_PLATFORM = "wayland;xcb", QT_QPA_PLATFORMTHEME = "kde", + NIXOS_OZONE_WL = "1", XCURSOR_SIZE = "24", HYPRCURSOR_SIZE = "24", GTK_THEME = "Breeze-Dark" }) do + hl.env(name, value) +end + +hl.window_rule({ name = "no-maximize", match = { class = ".*" }, suppress_event = "maximize" }) +hl.window_rule({ name = "dialogs", match = { title = "^(Open File|Save File|Save As|Authentication Required|Select what to share|Hyprland portal check).*$" }, float = true, center = true }) + +command("SUPER + Return", "Open st", tools.terminal) +command("SUPER + D", "Application launcher", tools.launcher) +command("SUPER + CTRL + E", "Open Dolphin", tools.files) +command("SUPER + V", "Clipboard history", tools.clipboard) +command("SUPER + SHIFT + L", "Lock desktop", tools.lock) +command("SUPER + SHIFT + slash", "Keyboard shortcuts", tools.help) +command("SUPER + slash", "Keyboard shortcuts", tools.help) +command("Print", "Screenshot focused monitor", tools.screenshot .. " monitor") +command("SHIFT + Print", "Screenshot all monitors", tools.screenshot .. " all") +command("SUPER + SHIFT + Print", "Screenshot selection", tools.screenshot .. " region") +command("SUPER + SHIFT + Q", "Session menu", tools.menu) +bind("SUPER + SHIFT + C", "Close window", hl.dsp.window.close()) +for key, mode in pairs({ G = "grid", M = "monocle", T = "tabbed", R = "scrolling" }) do + bind("SUPER + " .. key, "Layout: " .. mode, function() D.layout_set(mode) end) +end +bind("SUPER + space", "Cycle layouts", D.layout_cycle) +bind("SUPER + F", "Fullscreen window", hl.dsp.window.fullscreen()) +bind("SUPER + SHIFT + space", "Return window to tiling", function() D.float("disable") end) +bind("SUPER + CTRL + space", "Toggle floating", function() D.float("toggle") end) +bind("SUPER + J", "Focus next window/tab", function() D.focus_step(1) end, { repeating = true }) +bind("SUPER + K", "Focus previous window/tab", function() D.focus_step(-1) end, { repeating = true }) +bind("SUPER + SHIFT + J", "Swap next window", function() D.swap_step(1) end) +bind("SUPER + SHIFT + K", "Swap previous window", function() D.swap_step(-1) end) +bind("SUPER + SHIFT + Return", "Promote to first window", function() D.master(true) end) +bind("SUPER + CTRL + M", "Focus first window", function() D.master(false) end) +for key, direction in pairs({ Left = "left", Right = "right", Up = "up", Down = "down" }) do + bind("SUPER + " .. key, "Focus " .. direction, function() D.direction(direction) end, { repeating = true }) + bind("SUPER + CTRL + " .. key, "Move workspace " .. direction, hl.dsp.workspace.move({ monitor = direction })) +end +bind("SUPER + minus", "Narrow scrolling column", hl.dsp.layout("colresize -conf")) +bind("SUPER + equal", "Widen scrolling column", hl.dsp.layout("colresize +conf")) +bind("SUPER + CTRL + minus", "Grid: reduce width/height ratio, split into columns sooner", function() D.grid_ratio_adjust(-0.1) end, { repeating = true }) +bind("SUPER + CTRL + equal", "Grid: increase width/height ratio, split into columns later", function() D.grid_ratio_adjust(0.1) end, { repeating = true }) +bind("SUPER + CTRL + BackSpace", "Grid: reset width/height ratio to 1.20", function() D.grid_ratio_set(1.2) end) +bind("SUPER + S", "Show scratchpad", D.scratchpad) +bind("SUPER + SHIFT + S", "Send window to scratchpad", function() D.move("special:magic") end) +for i = 1, 9 do + local workspace = tostring(i) + bind("SUPER + " .. workspace, "Workspace " .. workspace, + hl.dsp.focus({ workspace = workspace, on_current_monitor = true })) + bind("SUPER + SHIFT + " .. workspace, "Send window to workspace " .. workspace, function() D.move(workspace) end) +end +for key, kind in pairs({ W = "oled", E = "lg" }) do + bind("SUPER + " .. key, "Focus " .. kind .. " monitor", function() D.monitor_focus(kind, false) end) + bind("SUPER + SHIFT + " .. key, "Send window to " .. kind .. " monitor", function() D.monitor_focus(kind, true) end) +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) +bind("SUPER + mouse:272", "Move window with mouse", hl.dsp.window.drag(), { drag = true }) +bind("SUPER + mouse:273", "Resize window with mouse", hl.dsp.window.resize(), { drag = true }) +command("XF86AudioRaiseVolume", "Volume up", tools.volume .. " set-volume -l 1.5 @DEFAULT_AUDIO_SINK@ 5%+") +command("XF86AudioLowerVolume", "Volume down", tools.volume .. " set-volume @DEFAULT_AUDIO_SINK@ 5%-") +command("XF86AudioMute", "Mute speakers", tools.volume .. " set-mute @DEFAULT_AUDIO_SINK@ toggle") +command("XF86AudioMicMute", "Mute microphone", tools.volume .. " set-mute @DEFAULT_AUDIO_SOURCE@ toggle") +command("XF86AudioPlay", "Play/pause", tools.player .. " play-pause") +command("XF86AudioNext", "Next track", tools.player .. " next") +command("XF86AudioPrev", "Previous track", tools.player .. " previous") diff --git a/modules/hyprland/default.nix b/modules/hyprland/default.nix new file mode 100644 index 0000000..8c9f729 --- /dev/null +++ b/modules/hyprland/default.nix @@ -0,0 +1,29 @@ +{ lib, pkgs, ... }: +{ + programs.hyprland.withUWSM = true; + programs.waybar.enable = lib.mkForce false; + programs.hyprlock.enable = true; + services.hypridle.enable = lib.mkForce false; + # 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.blueman.enable = true; + services.udisks2.enable = true; + services.displayManager.defaultSession = lib.mkForce "hyprland-uwsm"; + systemd.user.services.plasma-custom-wm.partOf = [ "plasma-workspace.target" ]; + xdg.portal = { + extraPortals = [ pkgs.kdePackages.xdg-desktop-portal-kde ]; + config.hyprland = { + default = [ + "hyprland" + "kde" + ]; + "org.freedesktop.impl.portal.FileChooser" = [ "kde" ]; + "org.freedesktop.impl.portal.ScreenCast" = [ "hyprland" ]; + "org.freedesktop.impl.portal.Screenshot" = [ "hyprland" ]; + }; + }; +} diff --git a/modules/hyprland/desktop.lua b/modules/hyprland/desktop.lua new file mode 100644 index 0000000..fb98f7f --- /dev/null +++ b/modules/hyprland/desktop.lua @@ -0,0 +1,546 @@ +local geometry = require("geometry") +local D = { modes = {}, orders = {}, ratios = {}, hdr = true, lg_enabled = true } +desktop = D +local layouts = { grid = "lua:grid", monocle = "monocle", tabbed = "lua:tabbed", scrolling = "scrolling" } +local cycle = { "grid", "monocle", "tabbed", "scrolling" } +local busy, queued, recovering = false, false, false +local recovery_epoch, lg_mode = 0, "1920x1080@60" +local timers = {} +local outputs = { oled = "desc:Dell Inc. AW3225QF JR11YZ3", lg = "desc:LG Electronics LG HDR 4K 0x000404F0" } +local signature = (os.getenv("HYPRLAND_INSTANCE_SIGNATURE") or "verify"):gsub("[^%w_-]", "_") +local state_path = (os.getenv("XDG_RUNTIME_DIR") or "/tmp") .. "/hypr-desktop-" .. signature .. ".state" + +local function later(ms, fn) + -- --verify-config has no event loop; upstream cannot clean up Lua timers there. + if not os.getenv("HYPRLAND_INSTANCE_SIGNATURE") then return end + local timer + timer = hl.timer(function() + timers[timer] = nil + fn() + end, { timeout = ms, type = "oneshot" }) + timers[timer] = true +end + +local function key(ws) return tostring(ws.id) end +local function wid(w) return tostring(w.stable_id) end +local function dispatch(action) return hl.dispatch(action) end +local function active_workspace() + return hl.get_active_special_workspace() or hl.get_active_workspace() +end +local function selector(ws) return ws.special and ("special:" .. ws.name:gsub("^special:", "")) or tostring(ws.id) end + +local function save() + local f = io.open(state_path .. ".tmp", "w") + if not f then return end + f:write("hdr ", D.hdr and "1" or "0", "\nlg ", D.lg_enabled and "1" or "0", "\n") + for id, mode in pairs(D.modes) do + f:write("mode ", id, " ", mode, "\n") + if D.orders[id] then f:write("order ", id, " ", table.concat(D.orders[id], ","), "\n") end + end + for id, ratio in pairs(D.ratios) do f:write("ratio ", id, " ", string.format("%.2f", ratio), "\n") end + local function panel(output, ws) + if ws then + f:write("panel ", output, " ", key(ws), " ", D.mode(ws), " ", string.format("%.2f", D.grid_ratio(ws)), "\n") + end + end + panel("*", active_workspace()) + for _, m in ipairs(hl.get_monitors()) do + panel(m.name, hl.get_active_special_workspace(m) or hl.get_active_workspace(m)) + end + f:close() + os.rename(state_path .. ".tmp", state_path) +end + +-- Session state is data, never executable Lua. A fresh compositor gets Grid. +local f = io.open(state_path, "r") +if f then + for line in f:lines() do + local id, mode = line:match("^mode (%-?%d+) (%a+)$") + if id and layouts[mode] then D.modes[id] = mode end + local rid, ratio = line:match("^ratio (%-?%d+) ([%d.]+)$") + ratio = tonumber(ratio) + if rid and ratio and ratio >= 0.25 and ratio <= 4 then D.ratios[rid] = ratio end + local oid, order = line:match("^order (%-?%d+) ([%d,]+)$") + if oid then + D.orders[oid] = {} + for item in order:gmatch("%d+") do table.insert(D.orders[oid], item) end + end + if line == "hdr 0" then D.hdr = false end + if line == "lg 0" then D.lg_enabled = false end + end + f:close() +end + +local function ordered(windows, id, retain_missing) + local present, result, order = {}, {}, {} + for _, w in ipairs(windows) do present[wid(w)] = w end + for _, w_id in ipairs(D.orders[id] or {}) do + if present[w_id] then + result[#result + 1] = present[w_id] + order[#order + 1] = w_id + present[w_id] = nil + elseif retain_missing then + order[#order + 1] = w_id + end + end + for _, w in ipairs(windows) do + if present[wid(w)] then + result[#result + 1] = w + order[#order + 1] = wid(w) + present[wid(w)] = nil + end + end + D.orders[id] = order + return result +end + +local function tiled(ws) + return ordered(hl.get_windows({ workspace = ws, floating = false, mapped = true }), key(ws)) +end + +function D.mode(ws) return D.modes[key(ws or active_workspace())] or "grid" end + +function D.grid_ratio(ws) + ws = ws or active_workspace() + return ws and D.ratios[key(ws)] or geometry.default_ratio +end + +function D.grid_ratio_set(ratio) + assert(type(ratio) == "number" and ratio >= 0.25 and ratio <= 4, "Grid ratio must be between 0.25 and 4") + local ws = active_workspace() + if not ws then return end + D.ratios[key(ws)] = math.floor(ratio * 100 + 0.5) / 100 + if D.mode(ws) == "grid" then dispatch(hl.dsp.layout("reorder")) end + save() +end + +function D.grid_ratio_adjust(delta) + D.grid_ratio_set(math.max(0.25, math.min(4, D.grid_ratio() + delta))) +end + +local function dissolve(ws) + for _, group in ipairs(ws:get_groups()) do + local w = group.current + if w then dispatch(hl.dsp.group.toggle({ window = w })) end + end +end + +local function tabs(ws) + local windows = tiled(ws) + if #windows == 0 then return end + local layout = windows[1].layout + -- Workspace rules apply on the next event-loop turn. Grouping while + -- Monocle still owns the targets strands its inactive input flags. + if layout and layout.name and layout.name ~= layouts.tabbed then + later(15, function() if D.mode(ws) == "tabbed" then tabs(ws) end end) + return + end + local active = hl.get_active_window() + local root = windows[1] + -- One native group supplies real tabs, hiding and input isolation. + if not root.group then dispatch(hl.dsp.group.toggle({ window = root })) end + local group = root.group + if not group then return end + for i = 2, #windows do + local w = windows[i] + if w.group ~= group then + if w.group then dispatch(hl.dsp.group.toggle({ window = w })) end + group:add(w) + end + end + if active and active.workspace == ws and not active.floating then + dispatch(hl.dsp.focus({ window = active })) + end +end + +local function reconcile() + if busy then return end + busy = true + for _, ws in ipairs(hl.get_workspaces()) do + local mode = D.mode(ws) + D.modes[key(ws)] = mode + if mode == "tabbed" then tabs(ws) else tiled(ws) end + end + save() + busy = false +end + +local function schedule() + if queued or busy then return end + queued = true + later(30, function() queued = false; reconcile() end) +end + +function D.layout_set(mode) + assert(layouts[mode], "expected grid, monocle, tabbed, or scrolling") + local ws = active_workspace() + if not ws then return end + local old, active = D.mode(ws), hl.get_active_window() + local order = D.orders[key(ws)] + D.modes[key(ws)] = mode + busy = true + if old == "tabbed" and mode ~= "tabbed" then dissolve(ws) end + D.orders[key(ws)] = order + hl.workspace_rule({ workspace = selector(ws), layout = layouts[mode] }) + if mode == "tabbed" then tabs(ws) end + busy = false + save() + local function finish() + if D.mode(ws) ~= mode then return end + local windows = tiled(ws) + local layout = windows[1] and windows[1].layout + if layout and layout.name and layout.name ~= layouts[mode] then later(15, finish); return end + busy = true + if mode == "tabbed" then tabs(ws) end + if active and active.mapped and active.workspace == ws and active_workspace() == ws then + dispatch(hl.dsp.focus({ window = active })) + end + busy = false + save() + end + later(15, finish) +end + +function D.layout_cycle() + local current = D.mode() + for i, mode in ipairs(cycle) do + if mode == current then D.layout_set(cycle[i % #cycle + 1]); return end + end +end + +local function detach(w) + if w and w.group then w.group:remove(w) end +end + +function D.move(workspace) + local w = hl.get_active_window() + if not w then return end + local source = w.workspace + local source_selector, source_special = selector(source), source.special + local remaining = {} + for _, other in ipairs(tiled(source)) do + if other ~= w then remaining[#remaining + 1] = other end + end + busy = true + detach(w) + dispatch(hl.dsp.window.move({ window = w, workspace = workspace, silent = true })) + -- Moving its last window can destroy a special workspace immediately. + if #remaining > 0 then dispatch(hl.dsp.focus({ window = remaining[1] })) + elseif not source_special then dispatch(hl.dsp.focus({ workspace = source_selector })) end + busy = false + schedule() +end + +function D.float(action) + local w = hl.get_active_window() + if not w then return end + busy = true + if action ~= "disable" then detach(w) end + dispatch(hl.dsp.window.float({ window = w, action = action or "toggle" })) + busy = false + schedule() +end + +function D.scratchpad() + dispatch(hl.dsp.workspace.toggle_special("magic")) + local ws = hl.get_active_special_workspace() + if ws and ws.name == "special:magic" then + local windows = hl.get_windows({ workspace = ws, mapped = true }) + if #windows > 0 then dispatch(hl.dsp.focus({ window = windows[1] })) end + end +end + +function D.focus_step(delta) + local ws = active_workspace() + if not ws then return end + local windows = tiled(ws) + local active, index = hl.get_active_window(), nil + for i, w in ipairs(windows) do if w == active then index = i; break end end + if #windows > 0 then + dispatch(hl.dsp.focus({ window = windows[index and (index - 1 + delta) % #windows + 1 or 1] })) + end +end + +local function spatial_direction(windows, active, direction) + local boxes, index = {}, nil + for i, w in ipairs(windows) do + local at, size = w.at, w.size + boxes[i] = { x = at.x, y = at.y, w = size.x, h = size.y } + if w == active then index = i end + end + if not index then + local at, size = active.at, active.size + index = #boxes + 1 + boxes[index] = { x = at.x, y = at.y, w = size.x, h = size.y } + end + local next_index = geometry.neighbor(boxes, index, direction, active.floating) + return next_index and windows[next_index] +end + +local function scroll_direction(windows, active, direction) + local layout = active.layout + if not layout or not layout.column then return active end + local column, row = layout.column.index, layout.index_in_column + local horizontal = direction == "left" or direction == "right" + local delta = (direction == "left" or direction == "up") and -1 or 1 + local candidates = {} + for _, w in ipairs(windows) do + local other = w.layout + if other and other.column then + if horizontal and other.column.index == column + delta then + candidates[#candidates + 1] = w + elseif not horizontal and other.column.index == column and other.index_in_column == row + delta then + return w + end + end + end + return spatial_direction(candidates, active, direction) or candidates[1] or active +end + +function D.direction(direction) + local ws, active = active_workspace(), hl.get_active_window() + if not ws then return end + local mode = D.mode(ws) + if mode == "tabbed" or mode == "monocle" then + D.focus_step((direction == "left" or direction == "up") and -1 or 1) + return + end + local windows = {} + for _, w in ipairs(hl.get_windows({ workspace = ws, mapped = true })) do + if not w.hidden and w.accepts_input ~= false then windows[#windows + 1] = w end + end + if #windows == 0 then return end + if not active or active.workspace ~= ws or not active.mapped or active.hidden then + -- A tape drag or native focus message can leave the viewport unfocused. + local first = windows[1] + for _, w in ipairs(windows) do + local col = w.layout and w.layout.column + local current = first.layout and first.layout.column + if col and (not current or col.index < current.index) then first = w end + end + dispatch(hl.dsp.focus({ window = first })) + return + end + local target + if mode == "scrolling" and not active.floating then + target = scroll_direction(windows, active, direction) + else + target = spatial_direction(windows, active, direction) + end + -- Explicit focus brings the tape into view before warping the cursor. + -- Native scrolling focus can warp into empty space and clear input focus. + if target then dispatch(hl.dsp.focus({ window = target })) end +end + +function D.master(promote) + local ws, active = active_workspace(), hl.get_active_window() + if not ws then return end + local windows = tiled(ws) + if #windows == 0 then return end + if not promote then dispatch(hl.dsp.focus({ window = windows[1] })); return end + for i, w in ipairs(windows) do + if w == active then + local order = D.orders[key(ws)] + order[1], order[i] = order[i], order[1] + save() + if D.mode(ws) == "grid" then dispatch(hl.dsp.layout("reorder")) + elseif D.mode(ws) == "tabbed" then busy = true; dissolve(ws); tabs(ws); busy = false + else dispatch(hl.dsp.window.swap({ target = windows[1], window = active })) end + return + end + end +end + +function D.swap_step(delta) + local ws, active = active_workspace(), hl.get_active_window() + if not ws or not active then return end + local windows = tiled(ws) + for i, w in ipairs(windows) do + if w == active then + local j = (i - 1 + delta) % #windows + 1 + local order = D.orders[key(ws)] + order[i], order[j] = order[j], order[i] + save() + if D.mode(ws) == "grid" then dispatch(hl.dsp.layout("reorder")) + elseif D.mode(ws) == "tabbed" then busy = true; dissolve(ws); tabs(ws); busy = false + else dispatch(hl.dsp.window.swap({ target = windows[j], window = active })) end + return + end + end +end + +hl.layout.register("grid", { + recalculate = function(ctx) + if #ctx.targets == 0 then return end + local windows, targets = {}, {} + for _, target in ipairs(ctx.targets) do + if target.window then + windows[#windows + 1] = target.window + targets[wid(target.window)] = target + end + end + if #windows == 0 then return end + -- During layout changes targets arrive one at a time. Sorting that + -- temporary subset must not discard the workspace's complete order. + windows = ordered(windows, key(windows[1].workspace), true) + local boxes = geometry.grid(ctx.area, #windows, D.grid_ratio(windows[1].workspace)) + for i, w in ipairs(windows) do targets[wid(w)]:place(boxes[i]) end + end, + layout_msg = function(_, msg) return msg == "reorder" end, +}) +hl.layout.register("tabbed", { + recalculate = function(ctx) + for _, target in ipairs(ctx.targets) do target:place(ctx.area) end + 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 + +function D.wake() + dispatch(hl.dsp.dpms({ action = "enable" })) + D.recover_lg() +end + +local function restore() + for id, mode in pairs(D.modes) do + hl.workspace_rule({ workspace = id, layout = layouts[mode] }) + end + D.monitors() + D.recover_lg() + schedule() +end +for _, event in ipairs({ "window.open", "window.close", "window.move_to_workspace", "window.update_rules", "workspace.created" }) do + hl.on(event, schedule) +end +hl.on("workspace.active", function() save(); schedule() end) +hl.on("workspace.special_active", save) +hl.on("monitor.focused", save) +hl.on("config.reloaded", function() later(40, restore) 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.on("hyprland.start", function() restore(); hl.exec_cmd("uwsm finalize") 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 }) + +return D diff --git a/modules/hyprland/desktopctl.sh b/modules/hyprland/desktopctl.sh new file mode 100644 index 0000000..8d1211a --- /dev/null +++ b/modules/hyprland/desktopctl.sh @@ -0,0 +1,29 @@ +case "${1:-menu}" in + grid|monocle|tabbed|scrolling) + hyprctl eval "desktop.layout_set(\"$1\")" ;; + cycle) hyprctl eval 'desktop.layout_cycle()' ;; + dual) hyprctl eval 'desktop.display_profile(true)' ;; + solo) hyprctl eval 'desktop.display_profile(false)' ;; + hdr) hyprctl eval 'desktop.hdr_toggle()' ;; + wake) hyprctl eval 'desktop.wake()' ;; + sleep) hyprctl eval 'hl.dispatch(hl.dsp.dpms({action="disable"}))' ;; + status) exec desktop-panel --once ;; + help) + hyprctl -j binds | jq -r 'map(select(.description != "")) | .[] | + ([if (.modmask % 128 >= 64) then "Super" else empty end, + if (.modmask % 8 >= 4) then "Ctrl" else empty end, + if (.modmask % 16 >= 8) then "Alt" else empty end, + if (.modmask % 2 == 1) then "Shift" else empty end, + .key] | join("+")) + " - " + .description' | + wofi --dmenu --prompt 'Shortcuts' --width 750 --height 650 >/dev/null ;; + menu) + choice=$(printf '%s\n' 'Grid' 'Monocle' 'Tabs' 'Scroll' 'Dual monitors' 'OLED only' 'Toggle HDR' 'Retrain LG HDMI' 'Lock' 'Suspend' 'Log out' | + wofi --dmenu --prompt 'Desktop') || exit 0 + case "$choice" in + Grid) desktopctl grid ;; Monocle) desktopctl monocle ;; Tabs) desktopctl tabbed ;; Scroll) desktopctl scrolling ;; + 'Dual monitors') desktopctl dual ;; 'OLED only') desktopctl solo ;; 'Toggle HDR') desktopctl hdr ;; + 'Retrain LG HDMI') desktopctl wake ;; Lock) hyprlock ;; Suspend) systemctl suspend ;; + 'Log out') uwsm stop ;; + esac ;; + *) echo 'Usage: desktopctl {grid|monocle|tabbed|scrolling|cycle|dual|solo|hdr|wake|sleep|status|help|menu}' >&2; exit 2 ;; +esac diff --git a/modules/hyprland/geometry.lua b/modules/hyprland/geometry.lua new file mode 100644 index 0000000..a3436f0 --- /dev/null +++ b/modules/hyprland/geometry.lua @@ -0,0 +1,75 @@ +local M = {} +M.default_ratio = 1.2 + +-- Port of XMonad.Layout.GridVariants (BSD-3-Clause, Norbert Zeh). +-- Distribute the rounding remainder like splitEvenly, including short columns. +local function boundaries(n, parts) + local size = math.ceil(n / parts) + local extra = size * parts - n + local result = {0} + for i = 1, parts do result[i + 1] = i * size - math.min(i, extra) end + return result +end + +function M.grid(area, n, aspect) + if n == 0 then return {} end + aspect = aspect or M.default_ratio + local screen = area.w / area.h + local ideal = math.sqrt(screen * n / aspect) + local lo, hi = math.floor(ideal), math.ceil(ideal) + local cols + if lo == 0 then cols = hi + elseif math.floor(n / hi) == 0 then cols = lo + elseif (screen * math.ceil(n / lo) / lo) / aspect + < aspect / (screen * math.floor(n / hi) / hi) then cols = lo + else cols = hi end + cols = math.min(n, math.max(1, cols)) + local xs, counts = boundaries(area.w, cols), boundaries(n, cols) + local boxes = {} + for col = 1, cols do + local rows = counts[col + 1] - counts[col] + local ys = boundaries(area.h, rows) + for row = 1, rows do + boxes[#boxes + 1] = { + x = area.x + xs[col], y = area.y + ys[row], + w = xs[col + 1] - xs[col], h = ys[row + 1] - ys[row], + } + end + end + return boxes +end + +-- Prefer an aligned neighbor, then the nearest edge and center. Gaps and +-- uneven column heights must not make another cell unreachable. +function M.neighbor(boxes, index, direction, allow_diagonal) + local origin = boxes[index] + if not origin then return end + local horizontal = direction == "left" or direction == "right" + local sign = (direction == "left" or direction == "up") and -1 or 1 + local function axes(box) + if horizontal then return box.x, box.w, box.y, box.h end + return box.y, box.h, box.x, box.w + end + local a, length, cross, extent = axes(origin) + local best, score + for i, box in ipairs(boxes) do + local b, size, other, span = axes(box) + local forward = sign * (b + size / 2 - a - length / 2) + local overlap = math.min(cross + extent, other + span) - math.max(cross, other) + if i ~= index and forward > 0 and (overlap > 0 or allow_diagonal) then + local gap = sign > 0 and b - a - length or a - b - size + local candidate = { overlap > 0 and 0 or 1, math.max(0, gap), + math.max(0, -overlap), math.abs(other + span / 2 - cross - extent / 2), forward } + local better = not score + if score then + for j, value in ipairs(candidate) do + if value ~= score[j] then better = value < score[j]; break end + end + end + if better then best, score = i, candidate end + end + end + return best +end + +return M diff --git a/modules/hyprland/home.nix b/modules/hyprland/home.nix new file mode 100644 index 0000000..ed864f1 --- /dev/null +++ b/modules/hyprland/home.nix @@ -0,0 +1,433 @@ +{ + config, + lib, + pkgs, + ... +}: +let + target = "wayland-session@hyprland.desktop.target"; + panel = pkgs.writeScriptBin "desktop-panel" '' + #!${lib.getExe pkgs.python3} + ${builtins.readFile ./panel.py} + ''; + # NVIDIA's EGL surface cleanup can spin after resume; keep the locker on Mesa. + lockPackage = pkgs.symlinkJoin { + name = "hyprlock-software"; + paths = [ pkgs.hyprlock ]; + nativeBuildInputs = [ pkgs.makeWrapper ]; + postBuild = '' + wrapProgram "$out/bin/hyprlock" \ + --set LIBGL_ALWAYS_SOFTWARE 1 \ + --set __EGL_VENDOR_LIBRARY_FILENAMES ${pkgs.mesa}/share/glvnd/egl_vendor.d/50_mesa.json + ''; + meta = pkgs.hyprlock.meta; + }; + ctl = pkgs.writeShellApplication { + name = "desktopctl"; + runtimeInputs = + with pkgs; + [ + hyprland + jq + wofi + uwsm + systemd + ] + ++ [ + lockPackage + panel + ]; + text = builtins.readFile ./desktopctl.sh; + }; + screenshot = pkgs.writeShellApplication { + name = "desktop-screenshot"; + runtimeInputs = with pkgs; [ + grim + slurp + wl-clipboard + hyprland + jq + libnotify + ]; + text = builtins.readFile ./screenshot.sh; + }; + clipboard = pkgs.writeShellApplication { + name = "desktop-clipboard"; + runtimeInputs = with pkgs; [ + cliphist + wofi + wl-clipboard + ]; + text = '' + choice=$(cliphist list | wofi --dmenu --prompt Clipboard) || exit 0 + [ -n "$choice" ] || exit 0 + printf '%s\n' "$choice" | cliphist decode | wl-copy + ''; + }; + tools = { + terminal = lib.getExe pkgs.st; + launcher = "${lib.getExe pkgs.wofi} --show drun"; + files = lib.getExe pkgs.kdePackages.dolphin; + clipboard = lib.getExe clipboard; + lock = lib.getExe lockPackage; + screenshot = lib.getExe screenshot; + menu = "${lib.getExe ctl} menu"; + help = "${lib.getExe ctl} help"; + volume = "${pkgs.wireplumber}/bin/wpctl"; + player = lib.getExe pkgs.playerctl; + }; + isolated = { + Unit = { + PartOf = lib.mkForce [ target ]; + After = lib.mkForce [ target ]; + }; + Install.WantedBy = lib.mkForce [ target ]; + }; + wallpaper = "/home/illustris/Downloads/adrien-olichon-RCAhiGJsUUE-unsplash.jpg"; +in +{ + home.packages = with pkgs; [ + ctl + screenshot + clipboard + wl-clipboard + cliphist + grim + slurp + wofi + hyprpaper + pavucontrol + playerctl + networkmanagerapplet + blueman + udiskie + kdePackages.kdeconnect-kde + kdePackages.breeze + kdePackages.breeze-icons + kdePackages.qtwayland + xdg-utils + ]; + wayland.systemd.target = target; + wayland.windowManager.hyprland = { + enable = true; + configType = "lua"; + systemd.enable = false; + extraLuaFiles = { + geometry = { + content = ./geometry.lua; + autoLoad = false; + }; + desktop = { + content = ./desktop.lua; + autoLoad = false; + }; + bindings = { + content = ./bindings.lua; + autoLoad = false; + }; + }; + extraConfig = '' + package.path = ${lib.generators.toLua { } (config.xdg.configHome + "/hypr/?.lua;")} .. package.path + tools = ${lib.generators.toLua { } tools} + require("desktop") + require("bindings") + ''; + }; + programs.wofi = { + enable = true; + settings = { + width = 600; + height = 480; + allow_images = true; + insensitive = true; + term = "st"; + }; + style = '' + window { background: #232629; color: #eff0f1; border: 1px solid #00ccff; } + #input { background: #31363b; color: #eff0f1; margin: 10px; border: 0; border-radius: 0; } + #entry { padding: 8px 12px; } + #entry:selected { background: #00576b; } + #text:selected { color: #eff0f1; } + ''; + }; + # The pinned Firefox/GTK build crashes in xdg_output_handle_name on native Wayland. + # At scale 1 XWayland stays sharp, and this wrapper only changes Hyprland sessions. + programs.firefox.package = pkgs.firefox.overrideAttrs (old: { + makeWrapperArgs = old.makeWrapperArgs ++ [ + "--run" + '' + if [ "''${XDG_CURRENT_DESKTOP:-}" = Hyprland ]; then + export GDK_BACKEND=x11 MOZ_ENABLE_WAYLAND=0 + fi + '' + ]; + }); + services = { + dunst = { + enable = true; + settings.global = { + font = "Noto Sans 11"; + frame_color = "#00ccff"; + background = "#232629"; + foreground = "#eff0f1"; + frame_width = 1; + corner_radius = 2; + origin = "top-right"; + offset = "16x16"; + width = 420; + }; + }; + cliphist = { + enable = true; + allowImages = true; + systemdTargets = [ target ]; + }; + hyprpaper = { + enable = true; + systemdTarget = target; + settings = { + ipc = true; + splash = false; + wallpaper = [ + { + monitor = ""; + path = wallpaper; + fit_mode = "cover"; + } + ]; + }; + }; + network-manager-applet.enable = true; + blueman-applet = { + enable = true; + systemdTargets = [ target ]; + }; + polkit-gnome.enable = true; + udiskie = { + enable = true; + tray = "auto"; + }; + hypridle = { + enable = true; + systemdTarget = target; + settings = { + general = { + lock_cmd = "pidof hyprlock || ${lib.getExe pkgs.uwsm} app -- ${lib.getExe lockPackage}"; + before_sleep_cmd = "loginctl lock-session"; + after_sleep_cmd = "${lib.getExe ctl} wake"; + ignore_dbus_inhibit = false; + }; + listener = [ + { + timeout = 420; + on-timeout = "loginctl lock-session"; + } + { + timeout = 480; + on-timeout = "${lib.getExe ctl} sleep"; + on-resume = "${lib.getExe ctl} wake"; + } + ]; + }; + }; + }; + programs.hyprlock = { + enable = true; + package = lockPackage; + settings = { + general = { + hide_cursor = true; + ignore_empty_input = true; + screencopy_mode = 1; + }; + auth.pam.enabled = true; + background = [ + { + monitor = ""; + path = wallpaper; + blur_passes = 2; + blur_size = 6; + } + ]; + input-field = [ + { + monitor = ""; + size = "360, 52"; + outline_thickness = 2; + outer_color = "rgb(00ccff)"; + inner_color = "rgb(232629)"; + font_color = "rgb(eff0f1)"; + placeholder_text = "Password"; + position = "0, -100"; + halign = "center"; + valign = "center"; + } + ]; + label = [ + { + monitor = ""; + text = "$TIME"; + font_family = "Noto Sans"; + font_size = 72; + color = "rgb(eff0f1)"; + position = "0, 80"; + halign = "center"; + valign = "center"; + } + ]; + }; + }; + programs.waybar = { + enable = true; + package = pkgs.waybar.overrideAttrs (old: { + patches = (old.patches or [ ]) ++ [ + ./waybar-lua.patch + ./waybar-ipc.patch + ]; + }); + systemd = { + enable = true; + targets = [ target ]; + }; + settings.main = { + layer = "top"; + position = "bottom"; + height = 32; + spacing = 6; + modules-left = [ + "custom/menu" + "hyprland/workspaces" + "custom/layout" + "wlr/taskbar" + ]; + modules-center = [ "clock" ]; + modules-right = [ + "mpris" + "idle_inhibitor" + "pulseaudio" + "network" + "bluetooth" + "tray" + ]; + "custom/menu" = { + format = "Apps"; + on-click = tools.launcher; + on-click-right = tools.menu; + tooltip = false; + }; + "hyprland/workspaces" = { + all-outputs = true; + sort-by-number = true; + move-to-monitor = true; + }; + "custom/layout" = { + exec = lib.getExe panel; + return-type = "json"; + restart-interval = 1; + on-click = "${lib.getExe ctl} cycle"; + on-click-right = tools.menu; + }; + "wlr/taskbar" = { + format = "{icon} {title}"; + icon-size = 18; + max-length = 28; + on-click = "activate"; + on-click-middle = "close"; + tooltip-format = "{app_id}: {title}"; + }; + clock = { + format = "{:%a %d %b %H:%M}"; + tooltip-format = "{calendar}"; + }; + mpris = { + format = "{artist} - {title}"; + max-length = 35; + }; + idle_inhibitor = { + format = "{icon}"; + format-icons = { + activated = "Keep Awake: On"; + deactivated = "Keep Awake: Off"; + }; + tooltip = true; + tooltip-format-activated = "Automatic locking and display sleep are paused. Click to resume."; + tooltip-format-deactivated = "Automatic locking and display sleep are enabled. Click to keep awake."; + }; + pulseaudio = { + format = "Vol {volume}%"; + format-muted = "Muted"; + on-click = "pavucontrol"; + on-click-right = "wpctl set-mute @DEFAULT_AUDIO_SINK@ toggle"; + }; + network = { + format-ethernet = "LAN"; + format-wifi = "{essid} {signalStrength}%"; + format-disconnected = "Offline"; + tooltip-format = "{ifname}: {ipaddr}"; + on-click = "nm-connection-editor"; + }; + bluetooth = { + format = "BT {status}"; + on-click = "blueman-manager"; + }; + tray = { + icon-size = 20; + spacing = 8; + }; + }; + style = '' + * { font-family: "Noto Sans"; font-size: 12px; border: none; border-radius: 0; min-height: 0; } + window#waybar { background: #232629; color: #eff0f1; border-top: 1px solid #4d5257; } + #workspaces button { padding: 0 10px; color: #bdc3c7; background: transparent; } + #workspaces button.active { color: #00ccff; background: #31363b; border-bottom: 2px solid #00ccff; } + #workspaces button.urgent { background: #da4453; } + #custom-menu, #custom-layout, #clock, #pulseaudio, #network, #bluetooth, #idle_inhibitor, #mpris, #tray { padding: 0 8px; } + #custom-layout { color: #00ccff; } + #idle_inhibitor.activated { color: #00ccff; } + #taskbar button { padding: 0 8px; color: #bdc3c7; } + #taskbar button.active { background: #31363b; color: #eff0f1; } + tooltip { background: #31363b; color: #eff0f1; } + ''; + }; + systemd.user.services = { + waybar = isolated; + network-manager-applet = isolated; + polkit-gnome = isolated; + udiskie = isolated; + dunst.Install.WantedBy = [ target ]; + dunst.Unit.ConditionEnvironment = "XDG_CURRENT_DESKTOP=Hyprland"; + kdeconnect-hyprland = { + Unit = { + Description = "KDE Connect for Hyprland"; + PartOf = [ target ]; + After = [ target ]; + }; + Service.ExecStart = "${pkgs.kdePackages.kdeconnect-kde}/bin/kdeconnect-indicator"; + Install.WantedBy = [ target ]; + }; + }; + # These packages also install XDG autostarts; the Hyprland units own their lifecycle. + xdg.configFile = { + "autostart/nm-applet.desktop".text = '' + [Desktop Entry] + Type=Application + Name=NetworkManager Applet + Exec=${pkgs.networkmanagerapplet}/bin/nm-applet + NotShowIn=KDE;GNOME;COSMIC;Hyprland; + ''; + "autostart/blueman.desktop".text = '' + [Desktop Entry] + Type=Application + Name=Blueman Applet + Exec=${pkgs.blueman}/bin/blueman-applet + NotShowIn=Hyprland; + ''; + "autostart/picom.desktop".text = '' + [Desktop Entry] + Type=Application + Name=picom + Exec=${pkgs.picom}/bin/picom + NotShowIn=Hyprland; + ''; + }; +} diff --git a/modules/hyprland/panel.py b/modules/hyprland/panel.py new file mode 100644 index 0000000..b1875cb --- /dev/null +++ b/modules/hyprland/panel.py @@ -0,0 +1,96 @@ +import argparse +import ctypes +import json +import os +from pathlib import Path +import re +import select +import struct + +IN_CLOSE_WRITE, IN_MOVED_TO, IN_DELETE, IN_Q_OVERFLOW = 0x8, 0x80, 0x200, 0x4000 + + +def status(path, output): + mode, ratio = "grid", 1.2 + try: + lines = path.read_text().splitlines() + except FileNotFoundError: + lines = [] + for line in lines: + fields = line.split() + if len(fields) != 5 or fields[:2] != ["panel", output]: + continue + if fields[3] not in ("grid", "monocle", "tabbed", "scrolling"): + continue + try: + candidate = float(fields[4]) + except ValueError: + continue + if 0.25 <= candidate <= 4: + mode, ratio = fields[3], candidate + labels = {"grid": "Grid", "monocle": "Monocle", "tabbed": "Tabs", "scrolling": "Scroll"} + text = f"Grid {ratio:.2f}:1" if mode == "grid" else labels[mode] + return { + "text": text, + "class": mode, + "tooltip": ( + f"Grid target width/height: {ratio:.2f}:1\n" + "Super+Ctrl+-: taller windows, split into columns sooner\n" + "Super+Ctrl+=: wider windows, split into columns later\n" + "Super+Ctrl+Backspace: reset to 1.20:1\n" + "Click: cycle layouts | Right click: desktop controls" + ), + } + + +def watch(path, output): + # Watch the directory: the controller replaces the state file atomically. + libc = ctypes.CDLL(None, use_errno=True) + libc.inotify_init1.argtypes = [ctypes.c_int] + libc.inotify_init1.restype = ctypes.c_int + libc.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32] + libc.inotify_add_watch.restype = ctypes.c_int + fd = libc.inotify_init1(os.O_NONBLOCK | os.O_CLOEXEC) + if fd < 0: + raise OSError(ctypes.get_errno(), "inotify_init1") + try: + if libc.inotify_add_watch(fd, os.fsencode(path.parent), IN_CLOSE_WRITE | IN_MOVED_TO | IN_DELETE) < 0: + raise OSError(ctypes.get_errno(), "inotify_add_watch") + last = None + changed = True + header = struct.Struct("iIII") + while True: + if changed: + current = json.dumps(status(path, output)) + if current != last: + print(current, flush=True) + last = current + select.select([fd], [], []) + events = os.read(fd, 65536) + changed = False + offset = 0 + while offset < len(events): + _, mask, _, length = header.unpack_from(events, offset) + offset += header.size + name = events[offset : offset + length].split(b"\0", 1)[0] + changed |= name == os.fsencode(path.name) or bool(mask & IN_Q_OVERFLOW) + offset += length + finally: + os.close(fd) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--once", action="store_true") + args = parser.parse_args() + signature = re.sub(r"[^a-zA-Z0-9_-]", "_", os.environ.get("HYPRLAND_INSTANCE_SIGNATURE", "verify")) + path = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / f"hypr-desktop-{signature}.state" + output = os.environ.get("WAYBAR_OUTPUT_NAME") or "*" + if args.once: + print(json.dumps(status(path, output))) + else: + watch(path, output) + + +if __name__ == "__main__": + main() diff --git a/modules/hyprland/screenshot.sh b/modules/hyprland/screenshot.sh new file mode 100644 index 0000000..19cd8e4 --- /dev/null +++ b/modules/hyprland/screenshot.sh @@ -0,0 +1,16 @@ +directory="${XDG_PICTURES_DIR:-$HOME/Pictures}/Screenshots" +mkdir -p "$directory" +file="$directory/$(date +%Y-%m-%d_%H-%M-%S_%N).png" +case "${1:-monitor}" in + region) + geometry=$(slurp) || exit 0 + [ -n "$geometry" ] || exit 0 + grim -g "$geometry" "$file" ;; + monitor) + output=$(hyprctl -j monitors | jq -r '.[] | select(.focused) | .name') + grim -o "$output" "$file" ;; + all) grim "$file" ;; + *) echo 'Usage: desktop-screenshot {monitor|all|region}' >&2; exit 2 ;; +esac +wl-copy --type image/png < "$file" +notify-send -i "$file" 'Screenshot saved and copied' "$file" diff --git a/modules/hyprland/test.lua b/modules/hyprland/test.lua new file mode 100644 index 0000000..f554902 --- /dev/null +++ b/modules/hyprland/test.lua @@ -0,0 +1,322 @@ +package.path = "modules/hyprland/?.lua;" .. package.path +local geometry = require("geometry") +for _, area in ipairs({ { x = 0, y = 1680, w = 3840, h = 2128 }, { x = 3840, y = 0, w = 2160, h = 3808 }, + { x = 7, y = 13, w = 1919, h = 1079 } }) do + for _, aspect in ipairs({ 0.25, 0.8, 1.2, 1.6, 2.4, 4 }) do + for n = 1, 40 do + local boxes, covered = geometry.grid(area, n, aspect), 0 + assert(#boxes == n) + for i, a in ipairs(boxes) do + assert(a.w > 0 and a.h > 0 and a.x >= area.x and a.y >= area.y) + assert(a.x + a.w <= area.x + area.w and a.y + a.h <= area.y + area.h) + covered = covered + a.w * a.h + for j = i + 1, #boxes do + local b = boxes[j] + assert(a.x + a.w <= b.x or b.x + b.w <= a.x or a.y + a.h <= b.y or b.y + b.h <= a.y, + "overlapping grid windows") + end + end + assert(covered == area.w * area.h, "unfilled grid space") + end + end +end +local reference = geometry.grid({ x = 0, y = 0, w = 3840, h = 2160 }, 5, 1.6) +assert(reference[1].w == 1920 and reference[1].h == 1080) +assert(reference[3].x == 1920 and reference[3].h == 720) +local portrait = { x = 3840, y = 0, w = 2160, h = 3808 } +assert(geometry.default_ratio == 1.2) +assert(geometry.grid(portrait, 4)[4].x == portrait.x, "1.20 keeps the four-window portrait stack") +assert(geometry.grid(portrait, 5)[5].x > portrait.x, "1.20 splits the portrait stack at five windows") +assert(geometry.grid(portrait, 4, 0.8)[4].x > portrait.x, "lower ratio must split into columns sooner") +assert(geometry.grid(portrait, 6, 2.4)[6].x == portrait.x, "higher ratio must defer the split") +local unequal = geometry.grid(portrait, 7) +assert(not geometry.neighbor(unequal, 1, "up"), "top of a short column must not jump diagonally") +assert(not geometry.neighbor(unequal, 4, "up"), "top of a tall column must not jump diagonally") + +local windows, workspaces, events, pending, active, rules = {}, {}, {}, {}, nil, {} +local providers = {} +local monitors, clock, current_workspace = {}, 0, nil +local dpms = false +local function workspace(id) + local ws = { id = id, name = tostring(id), special = false } + function ws:get_groups() + local result, seen = {}, {} + for _, w in ipairs(windows) do + if w.workspace == self and w.group and not seen[w.group] then + seen[w.group] = true; result[#result + 1] = w.group + end + end + return result + end + workspaces[#workspaces + 1] = ws + return ws +end +local one, two = workspace(1), workspace(2) +local function window(id, ws, floating) + local w = { stable_id = id, workspace = ws, floating = floating or false, mapped = true } + windows[#windows + 1] = w + return w +end +local a, b, c = window(1, one), window(2, one), window(3, one) +local dialog = window(4, one, true) +active = b +local function group(w) + local g = { windows = { w }, current = w } + function g:add(item) self.windows[#self.windows + 1] = item; item.group = self end + function g:remove(item) + for i, member in ipairs(self.windows) do + if member == item then table.remove(self.windows, i); break end + end + item.group = nil + self.current = self.windows[1] + end + w.group = g + return g +end +local function action(op) return function(args) return { op = op, args = args or {} } end end +hl = { + layout = { register = function(name, provider) providers[name] = provider end }, + timer = function(fn, opts) pending[#pending + 1] = { fn = fn, at = clock + opts.timeout }; return fn end, + on = function(event, fn) events[event] = fn end, + exec_cmd = function() end, + monitor = function() end, + workspace_rule = function(rule) rules[rule.workspace] = rule.layout end, + get_active_workspace = function(m) return m and m.active_workspace or active and active.workspace or current_workspace or one end, + get_active_special_workspace = function(m) return m and m.active_special_workspace end, + get_active_window = function() return active end, + get_workspaces = function() return workspaces end, + get_monitors = function() return monitors end, + get_windows = function(filter) + local result = {} + for _, w in ipairs(windows) do + if w.workspace == filter.workspace and (filter.floating == nil or w.floating == filter.floating) and w.mapped then + result[#result + 1] = w + end + end + return result + end, + dsp = { group = { toggle = action("group") }, focus = action("focus"), + window = { move = action("move"), float = action("float"), swap = action("swap") }, + dpms = action("dpms"), layout = action("layout") }, +} +function hl.dispatch(dsp) + local args, w = dsp.args, dsp.args.window + if dsp.op == "group" then + if w.group then + local members = w.group.windows + for _, member in ipairs(members) do member.group = nil end + else group(w) end + elseif dsp.op == "focus" then active = w + elseif dsp.op == "move" then + -- Model the native behavior: a move carries the group unless detached first. + local members = w.group and w.group.windows or { w } + for _, member in ipairs(members) do member.workspace = args.workspace == "2" and two or one end + elseif dsp.op == "float" then + if args.action == "enable" then w.floating = true + elseif args.action == "disable" then w.floating = false + else w.floating = not w.floating end + elseif dsp.op == "dpms" then + if args.action == "enable" then dpms = true + elseif args.action == "disable" then dpms = false + else dpms = not dpms end + end +end +local function flush() + local list = pending; pending = {} + for _, timer in ipairs(list) do clock = math.max(clock, timer.at); timer.fn() end +end +local function advance(ms) + local until_time = clock + ms + while #pending > 0 do + table.sort(pending, function(a, b) return a.at < b.at end) + if pending[1].at > until_time then break end + local timer = table.remove(pending, 1) + clock = timer.at + timer.fn() + end + clock = until_time +end +local D = require("desktop") +D.layout_set("tabbed") +assert(a.group and a.group == b.group and a.group == c.group and not dialog.group) +assert(active == b and #a.group.windows == 3) +local new = window(5, one) +events["window.open"](); flush() +assert(new.group == a.group and #a.group.windows == 4, "new window must join workspace tabs") +active = b; D.move("2"); flush() +assert(b.workspace == two and not b.group) +assert(a.workspace == one and c.workspace == one and new.workspace == one, "move must affect only selected tab") +active = c; D.float("enable"); flush() +assert(c.floating and not c.group and a.group == new.group) +D.float("disable"); flush() +assert(not c.floating and c.group == a.group, "sinking must rejoin tabs") +D.float("disable"); flush() +assert(not c.floating and c.group == a.group, "sinking a tiled tab must be a no-op") +D.wake(); assert(dpms, "wake must turn outputs on") +D.wake(); assert(dpms, "repeated wake must leave outputs on") +D.layout_set("monocle") +assert(not a.group and not c.group and not new.group, "leaving tabs must dissolve group") +D.grid_ratio_set(0.8) +assert(D.grid_ratio(one) == 0.8 and D.grid_ratio(two) == 1.2, "ratio changes must be per workspace") +assert(not pcall(D.grid_ratio_set, 0) and not pcall(D.grid_ratio_set, 0/0), "invalid ratios must be rejected") +active = b; D.layout_set("scrolling") +D.grid_ratio_set(2.4) +package.loaded.desktop = nil +D = require("desktop") +assert(D.mode(one) == "monocle" and D.mode(two) == "scrolling", "reload must preserve workspace modes") +assert(D.grid_ratio(one) == 0.8 and D.grid_ratio(two) == 2.4, "reload must preserve ratios") +active = a; D.layout_cycle() +assert(D.mode(one) == "tabbed") +D.grid_ratio_adjust(-100); assert(D.grid_ratio() == 0.25) +D.grid_ratio_adjust(100); assert(D.grid_ratio() == 4) +D.grid_ratio_set(geometry.default_ratio) +advance(100) + +-- Reproduce WS4: three columns, two rows, with actual border/gap insets. +local navigation = workspace(4) +local cells = {} +for col = 0, 2 do + for row = 0, 1 do + local w = window(10 + #cells, navigation) + w.at = { x = col * 1280 + 3, y = 1683 + row * 1064 } + w.size = { x = 1274, y = 1058 } + cells[#cells + 1] = w + end +end +active = cells[5] +D.direction("left"); assert(active == cells[3], "Left must reach the middle column") +D.direction("left"); assert(active == cells[1], "Left must reach the first column") +D.direction("left"); assert(active == cells[1], "Left boundary must keep focus on this workspace") +D.direction("down"); assert(active == cells[2]) +D.direction("right"); assert(active == cells[4]) +D.direction("right"); assert(active == cells[6]) +D.direction("right"); assert(active == cells[6], "Right must not move focus onto LG") +D.direction("up"); assert(active == cells[5]) +D.direction("up"); assert(active == cells[5], "Up must stop at the top row") +current_workspace, active = navigation, nil +D.direction("right"); assert(active == cells[1], "arrows must recover missing focus") +active = nil +D.focus_step(1); assert(active == cells[1], "cycle recovery must not skip the first window") + +-- Native column order can differ from the controller's saved window order. +D.layout_set("scrolling") +for i, w in ipairs(cells) do + local col = 2 - math.floor((i - 1) / 2) + w.at.x = col * 1920 + 3 + w.layout = { column = { index = col }, index_in_column = (i - 1) % 2 } +end +active = cells[5] +for _ = 1, 20 do D.direction("left"); assert(active == cells[5], "scrolling must clamp at first column") end +D.direction("right"); assert(active == cells[3], "scrolling must follow native columns") +D.direction("down"); assert(active == cells[4], "scrolling Down must stay in its column") +D.direction("right"); assert(active == cells[2], "scrolling must preserve vertical position") +for _ = 1, 20 do D.direction("right"); assert(active == cells[2], "scrolling must clamp at last column") end +D.direction("down"); assert(active == cells[2], "scrolling must stop at last row") +active = nil +D.direction("left"); assert(active == cells[5], "scrolling must recover focus at the first column") + +-- Rule application is deferred: tabs must wait until Monocle releases its +-- targets, otherwise grouping strands inactive input flags on the old windows. +for _, w in ipairs(cells) do w.layout = { name = "monocle" } end +D.layout_set("tabbed") +assert(not cells[1].group, "must not group targets while Monocle still owns them") +advance(20) +assert(not cells[1].group, "must wait for actual layout activation, not a fixed delay") +for _, w in ipairs(cells) do w.layout = { name = "lua:tabbed" } end +advance(20) +assert(cells[1].group and cells[6].group == cells[1].group, "tabs must group once the new layout owns the targets") +D.layout_set("grid") +assert(not cells[1].group and not cells[6].group) +local saved_order = table.concat(D.orders["4"], ",") +local area = { x = 0, y = 1680, w = 3840, h = 2128 } +providers.grid.recalculate({ area = area, targets = { { window = cells[5], place = function() end } } }) +assert(table.concat(D.orders["4"], ",") == saved_order, "partial target transfer must preserve complete window order") +local previous_focus = active +active = nil +for _, w in ipairs(cells) do w.layout = { name = "lua:grid" } end +advance(20) +assert(active == previous_focus, "layout completion must restore selected window after native focus loss") +for _, w in ipairs(cells) do w.mapped = false end +active = nil +D.direction("left"); assert(active == nil, "empty workspace must be safe") +current_workspace, active = nil, a + +-- 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 } +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 = clock } + hl.timer(function() + if not connected or stuck then return end + if disabled then + monitors = {} + events["monitor.removed"](lg) + else + local was_off = #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) + 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 #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 #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; 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 +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: Grid/Scrolling navigation and boundaries, focus recovery, deferred tabs, variable ratio; moves, sink/wake, panel/reload state; HDMI recovery") diff --git a/modules/hyprland/test_panel.py b/modules/hyprland/test_panel.py new file mode 100644 index 0000000..246bc43 --- /dev/null +++ b/modules/hyprland/test_panel.py @@ -0,0 +1,53 @@ +import json +import os +from pathlib import Path +import select +import subprocess +import sys +import tempfile +import time +import unittest + +import panel + + +class PanelTest(unittest.TestCase): + def test_each_output_and_invalid_state(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "state" + path.write_text("panel * 1 monocle 1.60\npanel DP-1 1 monocle 1.60\npanel HDMI-A-1 2 grid 0.80\n") + self.assertEqual(panel.status(path, "DP-1")["text"], "Monocle") + self.assertEqual(panel.status(path, "HDMI-A-1")["text"], "Grid 0.80:1") + self.assertEqual(panel.status(path, "*")["text"], "Monocle") + path.write_text("panel DP-1 1 grid nan\npanel DP-1 1 grid 999\npanel DP-1 1 garbage 1.60\n") + self.assertEqual(panel.status(path, "DP-1")["text"], "Grid 1.20:1") + + def test_atomic_replacement_updates_without_polling(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "hypr-desktop-panel-test.state" + path.write_text("panel DP-1 1 grid 1.60\npanel HDMI-A-1 2 monocle 1.60\n") + env = dict(os.environ, XDG_RUNTIME_DIR=directory, + HYPRLAND_INSTANCE_SIGNATURE="panel-test", WAYBAR_OUTPUT_NAME="DP-1") + process = subprocess.Popen([sys.executable, str(Path(panel.__file__))], env=env, + stdout=subprocess.PIPE, text=True) + try: + self.assertTrue(select.select([process.stdout], [], [], 2)[0]) + self.assertEqual(json.loads(process.stdout.readline())["text"], "Grid 1.60:1") + replacement = path.with_suffix(".tmp") + replacement.write_text("panel DP-1 1 grid 1.60\npanel HDMI-A-1 2 tabbed 1.60\n") + replacement.replace(path) + self.assertFalse(select.select([process.stdout], [], [], 0.1)[0], "unrelated output must not refresh this label") + replacement.write_text("panel DP-1 3 grid 1.20\npanel HDMI-A-1 2 tabbed 1.60\n") + start = time.monotonic() + replacement.replace(path) + self.assertTrue(select.select([process.stdout], [], [], 0.5)[0], "update waited for polling") + self.assertEqual(json.loads(process.stdout.readline())["text"], "Grid 1.20:1") + self.assertLess(time.monotonic() - start, 0.5) + finally: + process.terminate() + process.wait(timeout=2) + process.stdout.close() + + +if __name__ == "__main__": + unittest.main() diff --git a/modules/hyprland/waybar-ipc.patch b/modules/hyprland/waybar-ipc.patch new file mode 100644 index 0000000..41cfec0 --- /dev/null +++ b/modules/hyprland/waybar-ipc.patch @@ -0,0 +1,150 @@ +--- a/include/modules/hyprland/backend.hpp ++++ b/include/modules/hyprland/backend.hpp +@@ -1,5 +1,6 @@ + #pragma once + ++#include + #include + #include + #include +@@ -43,10 +44,11 @@ + + std::thread ipcThread_; + std::mutex callbackMutex_; ++ std::mutex socketMutex_; + util::JsonParser parser_; + std::list> callbacks_; +- int socketfd_; // the hyprland socket file descriptor ++ int socketfd_ = -1; // the hyprland socket file descriptor + pid_t socketOwnerPid_; +- bool running_ = true; // the ipcThread will stop running when this is false ++ std::atomic running_ = true; // the ipcThread will stop running when this is false + }; + }; // namespace waybar::modules::hyprland +--- a/src/modules/hyprland/backend.cpp ++++ b/src/modules/hyprland/backend.cpp +@@ -56,14 +56,11 @@ + + running_ = false; + spdlog::info("Hyprland IPC stopping..."); +- if (socketfd_ != -1) { +- spdlog::trace("Shutting down socket"); +- if (shutdown(socketfd_, SHUT_RDWR) == -1) { +- spdlog::error("Hyprland IPC: Couldn't shutdown socket"); +- } +- spdlog::trace("Closing socket"); +- if (close(socketfd_) == -1) { +- spdlog::error("Hyprland IPC: Couldn't close socket"); ++ { ++ std::lock_guard lock(socketMutex_); ++ if (socketfd_ != -1) { ++ // Wake the reader; the listener owns and closes the descriptor. ++ shutdown(socketfd_, SHUT_RDWR); + } + } + ipcThread_.join(); +@@ -85,14 +82,7 @@ + + spdlog::info("Hyprland IPC starting"); + +- struct sockaddr_un addr; +- socketfd_ = socket(AF_UNIX, SOCK_STREAM, 0); +- +- if (socketfd_ == -1) { +- spdlog::error("Hyprland IPC: socketfd failed"); +- return; +- } +- ++ struct sockaddr_un addr = {}; + addr.sun_family = AF_UNIX; + + auto socketPath = IPC::getSocketFolder(his) / ".socket2.sock"; +@@ -100,40 +90,58 @@ + + addr.sun_path[sizeof(addr.sun_path) - 1] = 0; + +- int l = sizeof(struct sockaddr_un); +- +- if (connect(socketfd_, (struct sockaddr*)&addr, l) == -1) { +- spdlog::error("Hyprland IPC: Unable to connect?"); +- return; +- } +- auto* file = fdopen(socketfd_, "r"); +- if (file == nullptr) { +- spdlog::error("Hyprland IPC: Couldn't open file descriptor"); +- return; +- } ++ bool resync = false; + while (running_) { +- std::array buffer; // Hyprland socket2 events are max 1024 bytes +- +- auto* receivedCharPtr = fgets(buffer.data(), buffer.size(), file); +- +- if (receivedCharPtr == nullptr) { +- std::this_thread::sleep_for(std::chrono::milliseconds(1)); ++ const int fd = socket(AF_UNIX, SOCK_STREAM, 0); ++ if (fd == -1) { ++ std::this_thread::sleep_for(std::chrono::milliseconds(250)); + continue; + } +- +- std::string messageReceived(buffer.data()); +- messageReceived = messageReceived.substr(0, messageReceived.find_first_of('\n')); +- spdlog::debug("hyprland IPC received {}", messageReceived); +- +- try { +- parseIPC(messageReceived); +- } catch (std::exception& e) { +- spdlog::warn("Failed to parse IPC message: {}, reason: {}", messageReceived, e.what()); +- } catch (...) { +- throw; ++ { ++ std::lock_guard lock(socketMutex_); ++ if (!running_) { ++ close(fd); ++ break; ++ } ++ socketfd_ = fd; ++ } ++ FILE* file = nullptr; ++ if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == 0) { ++ file = fdopen(fd, "r"); ++ } ++ if (file != nullptr) { ++ // Missed events cannot be replayed; rebuild module state from socket1. ++ if (resync) { ++ try { ++ parseIPC("configreloaded>>"); ++ } catch (const std::exception& e) { ++ spdlog::warn("Hyprland IPC resync failed: {}", e.what()); ++ } ++ } ++ resync = true; ++ while (running_) { ++ std::array buffer; ++ if (fgets(buffer.data(), buffer.size(), file) == nullptr) break; ++ std::string messageReceived(buffer.data()); ++ messageReceived = messageReceived.substr(0, messageReceived.find_first_of('\n')); ++ spdlog::debug("hyprland IPC received {}", messageReceived); ++ try { ++ parseIPC(messageReceived); ++ } catch (const std::exception& e) { ++ spdlog::warn("Failed to parse IPC message: {}, reason: {}", messageReceived, e.what()); ++ } ++ } ++ } ++ { ++ std::lock_guard lock(socketMutex_); ++ if (file != nullptr) fclose(file); ++ else close(fd); ++ socketfd_ = -1; ++ } ++ if (running_) { ++ spdlog::warn("Hyprland IPC disconnected, reconnecting"); ++ std::this_thread::sleep_for(std::chrono::milliseconds(250)); + } +- +- std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + spdlog::debug("Hyprland IPC stopped"); + } diff --git a/modules/hyprland/waybar-lua.patch b/modules/hyprland/waybar-lua.patch new file mode 100644 index 0000000..3f77c71 --- /dev/null +++ b/modules/hyprland/waybar-lua.patch @@ -0,0 +1,45 @@ +--- a/src/modules/hyprland/workspace.cpp ++++ b/src/modules/hyprland/workspace.cpp +@@ -1,4 +1,5 @@ + #include ++#include + #include + + #include +@@ -69,22 +70,20 @@ + bool Workspace::handleClicked(GdkEventButton* bt) const { + if (bt->type == GDK_BUTTON_PRESS) { + try { +- if (id() > 0) { // normal +- if (m_workspaceManager.moveToMonitor()) { +- m_ipc.getSocket1Reply("dispatch focusworkspaceoncurrentmonitor " + std::to_string(id())); +- } else { +- m_ipc.getSocket1Reply("dispatch workspace " + std::to_string(id())); +- } +- } else if (!isSpecial()) { // named (this includes persistent) +- if (m_workspaceManager.moveToMonitor()) { +- m_ipc.getSocket1Reply("dispatch focusworkspaceoncurrentmonitor name:" + name()); +- } else { +- m_ipc.getSocket1Reply("dispatch workspace name:" + name()); +- } +- } else if (id() != -99) { // named special +- m_ipc.getSocket1Reply("dispatch togglespecialworkspace " + name()); +- } else { // special +- m_ipc.getSocket1Reply("dispatch togglespecialworkspace"); ++ // This host uses Hyprland's native Lua parser and movable workspaces. ++ const auto quote = [](const std::string& value) { ++ Json::StreamWriterBuilder writer; ++ writer["indentation"] = ""; ++ return Json::writeString(writer, Json::Value(value)); ++ }; ++ if (isSpecial()) { ++ const auto specialName = id() == -99 ? "" : name(); ++ m_ipc.getSocket1Reply("eval hl.dispatch(hl.dsp.workspace.toggle_special(" + ++ quote(specialName) + "))"); ++ } else { ++ const auto selector = id() > 0 ? std::to_string(id()) : "name:" + name(); ++ m_ipc.getSocket1Reply("eval hl.dispatch(hl.dsp.focus({workspace=" + quote(selector) + ++ ",on_current_monitor=true}))"); + } + return true; + } catch (const std::exception& e) {