- C 70%
- JavaScript 23%
- CSS 3%
- Nix 2%
- Shell 1%
- 1 more language <1%
Viewport #
A Wayland compositor whose entire shell — wallpaper, dock, window frames, titlebars — is a web page, composited zero-copy alongside native Wayland clients.
wlroots handles DRM/KMS, input and the xdg-shell protocol. WPE WebKit renders
the UI to a DMA-BUF. Neither ever hands a pixel to the CPU.
┌──────────────────────────────────────────┐
│ shell (HTML/CSS/JS, loaded from a URL) │
└───────────────┬──────────────────────────┘
│ WPEBufferDMABuf ▲ JSON over
▼ (render_buffer) │ script handler
┌──────────────────────────────────────┴───┐
│ viewport (C) │
│ wlr_scene layer_web ← shell │
│ layer_apps ← xdg clients │
└───────────────┬──────────────────────────┘
▼ wlr_scene_output_commit
DRM/KMS
How it fits together #
The shell is the bottom layer. A single wlr_scene_buffer covering the
whole output layout, fed by WebKit's DMA-BUF. Client windows are stacked above
it in layer_apps.
Window placement is JavaScript's job. The shell draws a frame with a hole in
it — a <div class="viewport"> — measures where that hole landed on screen, and
sends the rect over IPC. The compositor moves the client's scene node there.
There is no layout policy in the C code at all.
Tiling is a tree of flexboxes. Split containers hold leaves, i3-style, and the tree renders to nested CSS flex containers — so the browser computes every rectangle and the shell only measures the result. Splitting, moving, resizing and fullscreen restructure the tree or adjust weights; no code calculates a window position. The gap between windows is a real element, which is why dragging a window edge needs no compositor support at all.
Hit-testing falls out of the layering. wlr_scene_node_at() returns a client
surface when the pointer is over a window and the shell's buffer everywhere
else, so "click went to the titlebar" versus "click went to the app" needs no
geometry bookkeeping and cannot go stale mid-animation.
Frame pacing is real vblank. WebKit will not paint frame N+1 until we acknowledge frame N; we acknowledge from the output's frame handler.
Explicit sync throughout. WebKit attaches a rendering fence to each frame;
we import it into a drm_syncobj timeline and let wlr_scene wait on that
point rather than blocking the compositor. Wayland clients get
zwp_linux_drm_syncobj_v1.
Why WPEPlatform and not libwpe #
nixpkgs ships libwpe and libwpe-fdo, and neither is a browser engine —
libWPEBackend-fdo-1.0.so contains zero WebKit symbols. They are the backend
ABI and one implementation of it. The engine, libWPEWebKit, is not packaged in
nixpkgs at all, and the webkitgtk tarball cannot be rebuilt with -DPORT=WPE
because it ships the GTK port only. So the flake builds WPE WebKit from the
separate upstream wpewebkit-2.52.5.tar.xz.
Since we compile the engine either way, we build it with
-DENABLE_WPE_PLATFORM=ON. That drops libwpe and libwpe-fdo entirely and
replaces the old wpe_view_backend indirection with GObject subclassing:
WPEDisplay advertises our DRM device and formats, WPEView::render_buffer
delivers each frame as a WPEBufferDMABuf whose fds, offsets, strides and
modifier map field-for-field onto wlr_dmabuf_attributes.
The legacy path would have meant standing up our own EGL display on a gbm
device and pulling fds out with EGL_MESA_image_dma_buf_export — several
hundred lines of glue to arrive at the same dma-buf.
Build #
nix develop # meson, ninja, wlroots 0.20, WPE WebKit, test clients
meson setup build
ninja -C build
The first nix develop compiles WPE WebKit from source. It is a full WebKit
build: expect hours and tens of gigabytes. There is no binary cache for it.
nix build .#wpewebkit # do this once, deliberately, before anything else
Run nested inside an existing compositor:
./build/viewport --url http://localhost:3000 --startup foot
On a TTY it takes the DRM session directly (needs seatd or logind).
Configuration #
Two tiers, because a settings UI cannot run on a display that is not working yet.
Bootstrap — ~/.config/viewport/config.json (or --config PATH), read
before any web content loads. This tier must stay in C. The shell is fetched
over the network; if it 404s, throws, or hangs, anything it owned dies with it.
A keybinding defined here still works in that state, which is the difference
between a broken desktop UI and a machine you cannot quit without switching to
a TTY.
{
"url": "http://localhost:3000",
"timeout_ms": 5000,
"layout": "tiling", // or "scrolling"
"adaptive_sync": false, // variable refresh rate, if the monitor will
"idle": { "lock_after": 600, "lock_command": "swaylock -f",
"blank_after": 900 },
"terminal": "rio",
"menu": "wmenu-run -i",
"binds": {
"Mod4+Return": "exec rio",
"Mod4+d": "exec wmenu-run -i",
"Mod4+Shift+q": "close",
"Mod4+Shift+e": "exit",
"Mod4+Shift+c": "reload"
}
}
reload re-reads the config file and reloads the shell, so a changed
keybinding takes effect without a restart. Only keys the file actually contains
are applied, which means a key present in the file wins over the equivalent
command-line flag on reload — the file is what you just edited. Startup-only
settings (shell URL, backend, socket path) are re-read but do nothing until
restart.
Actions are exec COMMAND, close, exit, reload, focus DIRECTION,
mode NAME, appearance toggle, lock, blank and shell COMMAND ARGS….
lock runs the same idle.lock_command the idle timer would, so there is one
place to configure what locking means; blank turns the outputs off until the
next input, exactly as the idle timer does. Chords use sway's
spelling — Mod4/Super/Logo, Shift, Ctrl, Alt — and any key
xkb_keysym_from_name accepts, including XF86AudioRaiseVolume. Caps and num
lock are masked out of matching. Bindings outrank both the focused client and
the shell, and fire on press only.
Asking for the workspace you are already on takes you back to the one before
it, so Mod4+2 pressed twice from workspace 1 goes to 2 and then back to 1 —
sway's workspace_auto_back_and_forth, and the same toggle it gives you.
Mod4+grave goes back without naming a workspace. The previous workspace is
remembered per output and survives a restart along with the rest of the layout.
focus takes next, prev, left, right, up or down. Directional
moves compare window centres, so they follow what is on screen — including
across monitors — rather than stacking order.
shell forwards the rest of the line to the web shell as
{"type":"shell.command","command":…,"args":[…]} and does nothing else. This
is the seam for everything that is layout policy: the defaults bind
Mod4+1..9 to shell workspace.switch N and Mod4+Shift+1..9 to
shell workspace.move N, and what a workspace is is defined entirely in
data/shell/shell.js. Add your own commands by binding them and handling the
name in handleShellCommand(); no compositor change is needed.
A chord may be scoped to a mode by writing mode/chord, mirroring sway's
mode "resize" blocks — resize/h only fires while resize mode is active, so
h keeps meaning "focus left" everywhere else. mode NAME switches; the bar
shows the active mode.
Only a few things live in C on purpose: focus and pointer grabs, because they
need the seat; spawning and exit, because they must work when the shell is
broken; /proc sampling and the settings portal, because a web page cannot do
either. Everything else — tiling, workspaces, fullscreen, resizing, the bar —
is the shell's.
Default bindings #
| Chord | Action |
|---|---|
Mod4+Return / Mod4+d |
terminal / launcher |
Mod4+h j k l, arrows |
focus, crossing monitors at the edge |
Mod4+Shift+h j k l |
move window, carrying it to the next monitor at the edge |
Mod4+1‑9 / +Shift |
switch / move to workspace |
Mod4+b / Mod4+v |
next window splits horizontally / vertically |
Mod4+e |
flip the focused container's layout |
Mod4+f |
fullscreen |
Mod4+r |
resize mode; then hjkl, Escape to leave |
Mod4 + right-drag |
resize; dragging the gap between windows also works |
Mod4+n |
toggle the bar |
Mod4+Shift+d |
toggle dark mode |
Mod4+Shift+q / +e / +c |
close / exit / reload the shell |
Dark mode #
Styling the shell cannot make client applications dark. Firefox, GTK and Qt
each ask the same question — color-scheme in the org.freedesktop.appearance
namespace, over D-Bus through xdg-desktop-portal — and with nothing answering
they all default to light.
That answer normally comes from a desktop environment. There isn't one here, so
the compositor implements org.freedesktop.impl.portal.Settings itself. The
GSettings route is deliberately avoided: it needs dconf and GNOME's schemas
installed, and silently does nothing when they are absent.
Three things must line up, and start.sh handles all of them — running from a
build tree gets none of them for free:
XDG_CURRENT_DESKTOP=viewport |
the portal picks a backend by matching this against each .portal file's UseIn= |
XDG_DATA_DIRS |
it only finds viewport.portal if that directory is on the search path |
dbus-update-activation-environment |
the portal is D-Bus activated and inherits its environment from the session, not from the compositor |
Setting XDG_CURRENT_DESKTOP with setenv() in the compositor is not enough:
the portal is a separate, already-running process. Verify with:
gdbus call --session --dest org.freedesktop.portal.Desktop \
--object-path /org/freedesktop/portal/desktop \
--method org.freedesktop.portal.Settings.ReadOne \
org.freedesktop.appearance color-scheme # (<uint32 1>,) means dark
Defining any binds object replaces the built-in defaults, so an empty one
means "no keybindings". Include an exit binding if you override them.
data/config.example.json is a fuller starting point.
Precedence is flags > config file > defaults.
-u, --url URL shell endpoint (default http://localhost:3000)
-f, --fallback URL used when the shell fails (default: bundled fallback.html)
-t, --timeout MS first-paint deadline before falling back (default 5000)
-s, --socket PATH control socket
-c, --config PATH config file (default ~/.config/viewport/config.json)
-T, --terminal CMD command bound to Mod4+Return
-M, --menu CMD command bound to Mod4+d
-b, --bind CHORD=ACT add a keybinding; repeatable
-e, --startup CMD command to run once up
-H, --headless headless backend instead of DRM
-d, --debug verbose logging, and mirror the shell's console
--debug also disables WebKit's cache and, for a file:// shell, watches its
directory and reloads on change — so editing shell.js updates the running
desktop without restarting the compositor. Saves are debounced, since editors
write-then-rename and emit several events per save. A shell served over HTTP is
left alone: that is a dev server's job, and watching it would mean polling.
Reloading resets shell state, so windows return via the view.added replay but
workspace assignments do not survive.
Runtime — the shell renders display settings in HTML and drives the
compositor over the same JSON channel it uses for window layout, and may
register further bindings with bind.add. That layer is additive and
expendable by design: keep exit and a terminal in the config file so they
survive the shell being unreachable. Everything else — wallpaper, dock
contents, theming — is pure shell state and never reaches the C side.
On NixOS the flake's module renders all of this for you:
programs.viewport = {
enable = true;
url = "http://localhost:3000";
terminal = "${pkgs.ghostty}/bin/ghostty";
menu = "${pkgs.wmenu}/bin/wmenu-run -i";
binds."Mod4+Shift+e" = "exit";
};
IPC #
Two transports, one dispatch table.
The page uses the script message handler, which works regardless of the shell's origin and is unaffected by CORS or mixed-content rules:
window.webkit.messageHandlers.viewport.postMessage(JSON.stringify(msg));
window.addEventListener('viewport', e => handle(e.detail));
External tooling uses a UNIX socket of newline-delimited JSON:
socat - UNIX:$VIEWPORT_SOCKET
Compositor → shell #
| Message | Payload |
|---|---|
config |
layout ("tiling" or "scrolling") |
view.added |
id, title, app_id, output (name of the output it opened on), floating, width, height, min_width, min_height |
view.props |
id, title, app_id |
view.removed |
id |
output.layout |
outputs[] with name, make, model, serial, enabled, x, y, width, height, usable_x, usable_y, usable_width, usable_height, hdr, hdr_capable, scale, transform, modes[] |
error |
context, message |
Shell → compositor #
| Message | Payload |
|---|---|
view.layout |
id, x, y, width, height, optional clip{x,y,width,height}, optional scale |
view.visible |
id, visible |
view.focus |
id |
view.close |
id |
view.opacity |
id, opacity (0–1) |
shell.overview |
active |
session.restore |
state (whatever was last saved, or empty) |
view.query |
— |
shell.focus |
— |
bind.add |
chord, action |
output.configure |
name, enabled, mode{width,height,refresh}, x, y, scale, transform, adaptive_sync |
output.query |
— |
output.confirm |
— |
output.hdr |
optional name (default: active output), optional enabled (absent toggles) |
session.save |
state (opaque string) |
session.query |
— |
quit |
— |
output.configure runs wlr_output_test_state before committing, so a mode the
hardware cannot drive is reported back as an error instead of blanking the
screen you are configuring from. A configuration that does commit is still
provisional: it reverts after twelve seconds unless an output.confirm arrives,
because a wrong mode blanks the very screen you would need in order to undo it.
A window is a real Wayland surface, so nothing the shell draws can crop it —
CSS overflow bounds the shell's own painting and no more. clip on
view.layout is how a window is cropped to the part of it that is on its
output, which is what keeps a column scrolled off the left of one monitor from
being drawn on the monitor beside it. Only the surface is clipped, never the
container: a popup is entitled to extend past the window it belongs to.
HDR #
Mod4+Shift+p switches the monitor you are looking at into HDR, and back.
Per output, because a display that can do it usually sits next to one that
cannot, and global would mean choosing which of the two to get wrong.
Two halves make it work. The output is switched to BT.2020 primaries and the PQ
transfer function, at ten bits per channel — eight cannot carry a PQ curve
without visible banding in exactly the dark gradients this is for. On its own
that would make everything look worse, because every SDR window would be
interpreted as if it were HDR. The other half is wp-color-management-v1,
attached to the scene: clients say what their content actually is, and the
renderer converts rather than reinterprets. SDR windows keep looking like SDR
windows, and a client with real HDR content can say so.
Switching is a full reconfiguration, not a lone image description: changing the
colour space a connector drives is a modeset, and a state carrying only the new
colorimetry is refused outright — which is how a monitor that plainly does HDR
came back reporting that it would not take it. The mode is restated and
allow_reconfiguration is set, so the driver is allowed the brief disruption
the switch actually costs.
Three things must be true, and the failure says which is missing: the display has to accept BT.2020 primaries, it has to accept the PQ transfer function, and the renderer has to support output colour transforms. That last one is the likeliest limit — wlroots' Vulkan renderer supports it and its GLES2 renderer does not, which is another reason this compositor defaults to Vulkan. It is reported at startup rather than left to be discovered by a keypress that does nothing.
Ten bits is a preference rather than a requirement. Which deep formats a plane
accepts depends on the driver, the connector and what else is on screen, so
several are tried in order and the first the hardware accepts is committed —
falling back to the output's current depth if none are taken, because banded
HDR beats no HDR. Capability is read from the connector and every candidate is
tested before it is committed, so a display that will not take it is left showing what it was
showing rather than going dark. The bar shows HDR while an output is in it —
otherwise the picture changes and nothing says why, and a monitor left in HDR
by a mis-hit key looks like a broken colour profile rather than a setting.
Only the features wlroots 0.20 actually implements are advertised: parametric image descriptions, PQ and BT.2020. sRGB is deliberately not advertised — the protocol treats it as always supported.
Media keys #
Bound by default, because a desktop where the play key does nothing is broken
in a way no application can fix from its own side: the key never reaches it.
XF86AudioPlay does not belong to the focused window — it belongs to whichever
player is playing, which is what playerctl resolves over MPRIS. Volume and
mute go to the sink through wpctl, since turning the volume down means the
machine and not whatever happens to be playing, and the brightness keys go to
brightnessctl.
Missing tools fail quietly per keypress rather than at startup, which is the
right trade for a binding nobody may ever press. As with every default, naming
any binds in the config replaces the whole set.
Notifications #
The compositor claims org.freedesktop.Notifications itself and forwards each
one to the shell, which draws it as part of the desktop. So notification styling
is the stylesheet already open in the editor rather than a second configuration
language in a second program, and it live-reloads with everything else.
If mako or dunst is already running it keeps the bus name and this stands aside — the log says so rather than failing.
Bodies are rendered as text, never as markup. A notification body is a string from an arbitrary program and the shell is a web page; rendering it as HTML would let anything that can send a notification run script in the desktop. Capabilities are reported as only what the shell honours, since claiming more has applications send content that is silently dropped.
Critical notifications never expire on their own, which the specification requires and which applications rely on. Closing reports why — expired, dismissed or withdrawn — because a daemon that never reports closure leaves programs believing their notification is still on screen, and some wait for it before sending the next.
Window rules #
"rules": [
{ "app_id": "cs2", "workspace": 3 },
{ "app_id": "pavucontrol", "floating": true, "width": 600, "height": 400 },
{ "title": "Picture-in-Picture", "floating": true }
]
Matched on app_id, or on title for applications that give every window the
same app_id and differ only in what they show. Both are substring matches: an
exact one would need the application's internal name known exactly. A rule is
applied before the window is inserted anywhere, so it goes straight where it
belongs rather than appearing in one place and jumping.
The compositor passes these to the shell without reading them. Which workspace a window opens on and whether it floats are layout decisions, and the compositor has no opinion about either.
Tablets #
A stylus reports pressure, tilt, distance, its own buttons and whether it is
hovering or touching. tablet-v2 carries all of it, and a drawing program that
gets only x and y has a pressure-sensitive brush reduced to one width of line.
The stylus also drives the cursor, which is what makes it work in the many programs that only understand a pointer. Tablets are absolute devices, so the cursor jumps to where the pen lands rather than moving relative to where it was, and touching the tablet focuses what is under the pen — otherwise drawing in a window would mean clicking it with a mouse first.
Idle #
Advertising idle-notify is not a policy: with nothing listening, the screens
stay lit for ever and the session never locks. "idle" in the config is the
policy, so a machine left alone behaves without a daemon having to be installed
and configured alongside it. Set neither threshold and there is none, leaving
the field to swayidle or anything else.
The compositor runs the locker named in lock_command rather than locking the
screen itself. That is the whole point of ext-session-lock: the program
drawing the lock screen is separate, and can crash without unlocking anything.
Blanking turns the outputs off, which is what actually saves the panel.
Idle inhibitors are honoured, and only while their surface is mapped — a paused video on a hidden workspace is not keeping anyone awake. An inhibitor counts as activity rather than merely pausing the countdown, so releasing one starts the clock again instead of firing immediately.
Key presses count as activity; releases do not. That is what makes blanking from a keybinding possible at all — the chord fires on press, and letting go of it would otherwise say someone is there and turn the screens straight back on. A grace period would have to outlast however long the keys were held; not counting the release avoids the question.
Mod4+Shift+x locks now and Mod4+Shift+b turns the screens off now — the
same two things the timer does, for when you are leaving rather than waiting to
be noticed leaving. The screens come back on the next keypress or mouse
movement, through the same path the timer's blanking uses.
wlr-output-power-management-v1 is advertised too, so wlopm and settings
panels can turn a monitor off on request rather than only on a timer.
What clients may ask for #
maximize and minimize are declined, but answered: the protocol requires a
configure in response to the request, and a client that gets none waits for one
— GTK's own maximize button hangs the window rather than doing nothing.
wm_capabilities is set to fullscreen alone, so a client can stop drawing
buttons for things this compositor will not do. It is sent on the initial
commit rather than at creation, because the surface is not initialised before
then and wlroots asserts rather than ignoring a configure scheduled too early.
A client dragging itself by its own titlebar (move, resize) is honoured
only for floating windows. A tiled window's place belongs to the layout, and
letting a client pull itself out of it by holding its titlebar would be a
surprise. The drag runs through the same machinery as Mod4+drag, so there is
one implementation of "the pointer is moving a window".
Keyboard shortcuts #
A virtual machine, a nested compositor or a remote desktop client needs the
chords this compositor would otherwise swallow — Mod4+Return has to reach the
guest rather than opening a terminal here.
keyboard-shortcuts-inhibit-v1 is how a client asks for that, and it applies
only while that client holds focus, so the bindings come back the moment focus
moves away.
Remembering the layout #
Restarting the compositor kills every client with it — they are its clients, and nothing survives that. So what is preserved is not the session but the places in it: the tree is written down with each window replaced by the application that was in it, and as those applications come back they are put where they were rather than piling up in the order they happen to start. Which matters most when the compositor is the thing being worked on.
A remembered place is an ordinary leaf whose id is negative. No real window has one, so every walk of the tree skips it and the renderers already drop leaves with no window — the structure, the column widths and the weights survive without a second representation to keep in step. A place nothing comes back for is dropped after 45 seconds, long enough for a browser restoring its own session and short enough that a workspace is not permanently shaped around something that is gone.
The state is stored in $XDG_STATE_HOME/viewport/session.json, written through
a temporary file and renamed so a compositor that dies mid-write leaves the
previous layout intact rather than half of a new one. Its contents are the
shell's own format: the compositor stores and returns the blob without
interpreting it, because the layout model belongs to the shell and the
compositor should not gain an opinion about workspaces just to store them.
Restoring only happens into an empty session — restoring over windows that are already open would move them somewhere they were never asked to be — and the shell asks for it before replaying its windows, so the places exist before the windows that fill them arrive.
Logging #
--debug mirrors the shell's console into the compositor log and serves the
shell uncached. Without it a JavaScript error in the shell is completely
silent and an edited shell appears to have no effect, so it is worth leaving
on — it costs a page fetch.
--trace is the expensive tier: every placement, clip and scale, which during
an animation is one line per window per frame. That is formatted I/O inside the
layout path and a log that grows by megabytes a minute, so it is separate. Pass
it when chasing a geometry bug and not otherwise.
Overview #
Mod4+o shows every workspace at once. Each thumbnail contains the workspace's
real tree — the same renderer, at output size, scaled down — so a miniature is
the layout rather than a picture of it.
The windows inside are real surfaces, and they are drawn shrunk rather than
resized: a thumbnail is smaller than many windows' minimum size, so asking
clients to resize would be refused about as often as it was honoured, and
slow when it wasn't. view.layout carries the window's real size plus a
scale, and the compositor scales the buffers the client already produced.
The scale has to be re-applied once per frame, before compositing.
wlr_scene_surface recomputes each buffer's destination size from its surface
on every commit, so a window with live content snaps back to full size the
moment it paints. Doing it per commit is not enough either: a client that
paints through subsurfaces — Firefox — commits on surfaces the toplevel has no
listener for, so its content stayed full size while simpler windows shrank.
Once a frame catches every case, and the write is skipped when the value already
matches, so it does not damage the scene by itself.
Crop and scale are applied together, in that order, every time. They are not independent — the scale is computed from what the crop left — so applying them at different moments lets a client commit land in between, leaving a destination that describes the whole window and a source that describes the strip which survived the crop. The strip is then stretched to fill it. The scale is also cleared on every window when the overview closes rather than waiting for the shell to send each one a new rect: a window whose rect has not changed gets no message, and an idle window never repaints, so it kept the overview's size until something made it draw again.
What gets scaled is the buffer's destination size, because whatever wlroots last put there already accounts for the surface's buffer scale, its transform, any viewport it set, and the crop. Computing from the buffer's own dimensions gets all of that wrong — most visibly for a client that renders at 2x and says so, which then draws at double size.
It cannot simply be read back each frame either: wlroots recomputes the destination only when the surface commits, so in between, reading it returns what this code last wrote and multiplying again shrinks the window a little further every frame. Each buffer's unscaled size is remembered alongside the value written from it — if the destination still matches what was written the remembered size still stands, and if it has changed then wlroots recomputed it and the new value is the unscaled one.
Two consequences worth knowing. Only the offsets between buffers are left
unscaled, so a client painting through subsurfaces — a browser compositing
video, mostly — shows those parts misplaced while shrunk; it is exact again the
moment the scale returns to 1. And input is routed to the shell for the duration
(shell.overview), because a click on a miniature means "take me there" rather
than reaching the client underneath. That routing is also what makes dragging
possible: press a window and release it over another thumbnail to move it to
that workspace, or release it where it started to go there. The overview stays
open after a move, so several windows can be arranged in one visit.
Visibility works differently while it is up. A window is normally on screen only if some monitor is displaying its workspace; the overview draws every workspace at once, including the ones no monitor is showing, so there the thumbnail's own render is the whole answer. Without that exception a window on an off-screen workspace stayed hidden and its thumbnail came out labelled empty.
Every workspace is shown, not only the occupied ones — an overview is how you get somewhere, and an empty workspace has to be visible to be a target. They are dealt out across the monitors rather than crowded onto one: a window element exists once in the DOM, so a workspace can only be drawn on one screen, and rendering all of them everywhere would have each grid steal the windows from the last. Each output keeps the workspace it was already showing.
Animation #
Window frames are DOM, so moving and resizing them animates in CSS and costs the compositor nothing. What does not come free is the window's contents: a real surface drawn at whatever rect the compositor was last told. Sampling geometry once after a relayout would slide the frame smoothly and snap the contents straight to the destination — worse than not animating at all.
So the shell resamples every window's rect each frame until the layout stops
moving, self-terminating a few idle frames later rather than listening for
transitionend, which is unreliable while dragging. Two things keep the cost
down: the compositor skips the client reconfigure when only the position
changed, so a window sliding across the screen never asks its client to resize;
and drags set a class that disables the transition, because interpolating
toward a pointer lags it by the whole duration.
Fading a window in cannot be done in CSS for the same reason, so it is tweened
in the shell and sent as view.opacity, which the compositor applies to the
surface itself. prefers-reduced-motion disables all of it.
Testing the shell #
The layout engine lives in shell.js, and running it under a headless
compositor proves nothing: the web view renders, but nothing drives the layout,
so a broken tree looks exactly like a working one. tests/shell.test.js stubs
the DOM far enough to run the real file unmodified and checks structure — four
windows make four columns, consume and expel are inverses, a tabbed container
shows exactly one window and it is the focused one.
timeout 20 node tests/shell.test.js data/shell/shell.js tiling
timeout 20 node tests/shell.test.js data/shell/shell.js scrolling
timeout because the shell sets a live-reload interval and so never exits.
Layout models #
"layout" in the config file picks which one the shell runs.
tiling — i3 and sway. Windows split the space they are given; containers
can be split, tabbed or stacked. Mod4+w and Mod4+s set the last two,
Mod4+e returns to a split. Tabs are the one place this shell draws a window
title, because a collapsed tab cannot be identified without one.
scrolling — niri. A workspace is an endless horizontal strip of columns;
each column holds one or more windows stacked vertically, and columns keep the
width they were given, so opening a window never reflows what is already there.
The view scrolls the minimum needed to keep the focused column on screen.
| Key | Scrolling layout |
|---|---|
Mod4+h / Mod4+l |
focus the column left / right |
Mod4+j / Mod4+k |
focus within the column |
Mod4+Shift+h/l |
move the column along the strip, or to the next monitor at its end |
Mod4+comma / Mod4+period |
consume the next window into this column / expel it back out |
Mod4+r |
cycle the column width (⅓, ½, ⅔, full) |
Mod4+right-drag, or dragging a column edge |
set the column width freely |
Mod4+Shift+r |
cycle the window's share of the column height |
Mod4+Home / Mod4+End |
jump to either end of the strip |
| three-finger swipe ←→ | scroll the strip under your fingers |
| three-finger swipe ↑↓ | previous / next workspace |
Column widths are fractions of the space a window may occupy — the tiling area minus its padding — and the dividers between columns come out of those fractions rather than being added on top. Both details matter: measured against the padded box a full-width column is two gaps too wide and runs off the right edge, and with dividers added on top two half-width columns plus the divider between them are wider than the screen, so moving focus from one to the other scrolls the strip and everything visibly shifts. Taking the (N-1) dividers out of N columns makes fractions summing to 1 fill the width exactly.
Resizing means changing a column's own width. Columns do not share space, so widening one takes nothing from its neighbours — it makes the strip longer and shifts everything after it along. Nothing you are not touching changes size, which is the point of the model and the one place it will surprise a sway user. Vertical resizing inside a column works the ordinary way, since windows stacked in a column do share it.
Directional focus moves to the shell in this mode: the compositor decides
direction from where windows are on screen, and the column you are reaching for
is usually scrolled off it. Both models share one tree — the strip's columns are
the workspace root's children — so switching layout and reloading rearranges
what is open rather than discarding it.
Writing a shell #
Style the frame however you like; leave the hole alone.
.viewport { background: transparent; } /* the compositor paints here */
const rect = viewportEl.getBoundingClientRect();
send({ type: 'view.layout', id,
x: Math.round(rect.left), y: Math.round(rect.top),
width: Math.round(rect.width), height: Math.round(rect.height) });
Measure with a ResizeObserver rather than pushing rects when you think
something moved — CSS transitions, font loading and ancestor reflows all change
that rect without firing anything you can subscribe to. data/shell/ is a
working reference.
Fallback #
The load deadline is on the first painted frame, not on the load event. A
server that accepts the connection and then stalls, and a shell whose JS throws
before rendering, both leave the user at a black screen and both are invisible
to load-failed. On timeout the compositor loads fallback.html, which speaks
the same IPC — windows opened while offline are still tiled, listed and
closable.
Status #
The architecture is grounded in the real 2.52.5 headers: the WPEDisplay and
WPEView vfunc tables, wpe_buffer_dma_buf_get_*, WebKitWebView's display
construct property, and wlroots 0.20's wlr_buffer_impl and
wlr_scene_buffer_set_buffer_with_options.
Built and running on real hardware — DRM/KMS on an RX 7900 XTX (radv, Mesa
26.1.5), dual 2560x1440, launched from a TTY via ./start.sh. Confirmed
working:
- the web shell renders as the desktop;
xdg-shellclients composite inside the frames it draws, one desktop per output - keybindings: terminal, launcher, close, exit, shell reload
wmenuand other layer-shell launchers, including keyboard focus- server-side decorations, so clients drop their own titlebars
- VT switching away and back, with the outputs repainting on resume
grimscreenshots from inside the session- clean shutdown: ~1s, no assertions
Earlier, nested inside sway:
- Vulkan renderer initialises; GBM allocator binds
/dev/dri/renderD128 WPEDisplayhands WebKit that same render node, and WebKit's frames arrive asWPEBufferDMABufand composite throughwlr_scene— the shell's HTML is visibly rendered as the desktop- an
xdg-shellclient (foot) maps, is reported over IPC as{"type":"view.added","id":1,"title":"foot","app_id":"foot"}, and is composited inside the frame the shell drew for it - the UNIX control socket serves
output.layoutwith real mode data
Also verified: wlr_scene reports Direct scan-out enabled for the shell
buffer when no client overlays it, and keybindings parse and reject bad input
with precise errors.
Protocols #
Beyond xdg-shell and linux-dmabuf, several protocols turned out to be
load-bearing rather than optional, each for a non-obvious reason:
| Protocol | Why |
|---|---|
wlr-layer-shell |
every Wayland launcher is a layer-shell client |
xdg-activation |
wmenu-run asserts on its absence and aborts before drawing |
xdg-decoration + KDE server-decoration |
both are needed: GTK4 ignores the former and honours the latter, so a GTK client keeps its own titlebar unless you offer both |
ext-image-copy-capture + wlr-screencopy |
screenshots from inside the session — the only way to see the desktop once it owns the display |
virtual-keyboard |
wtype, accessibility tools, and injecting keystrokes in tests |
primary-selection |
middle-click paste |
Debugging from inside #
Both capture protocols are implemented — ext-image-copy-capture-v1 and
zwlr-screencopy-v1 — so grim works as an ordinary client:
grim ~/shot.png # from a terminal inside the session
This is load-bearing rather than a nicety. Once the compositor is driving a TTY there is no outer compositor to screenshot it from, so without this there is no way to see what the desktop looks like, and debugging a visual shell becomes guesswork.
Pair it with --debug, which mirrors the page console into the compositor log
and disables WebKit's cache:
CONSOLE INFO outputs [object Object]
CONSOLE ERROR TypeError: ... # a shell exception, otherwise silent
Pointer capture #
Games need two things a desktop pointer does not provide, and they only work together:
| Protocol | Why |
|---|---|
zwp_relative_pointer_v1 |
mouselook is driven by how far the mouse moved, not where the cursor landed — an absolute position saturates at the screen edge, so a game without it can only turn so far |
zwp_pointer_constraints_v1 |
the cursor must stop moving, so it neither escapes onto the other monitor mid-fight nor feeds the client absolute motion it is no longer expecting |
While a lock is active the compositor stops moving its cursor entirely and the client is driven purely by deltas. Unaccelerated values are forwarded separately so a game can apply its own sensitivity. A constraint belongs to a surface, so it lapses when that surface loses the pointer — otherwise a game would keep the mouse captured after you focused something else.
This covers X11 games too. XGrabPointer has no direct equivalent on Wayland;
Xwayland implements it by taking out these same two protocols on the client's
behalf, so a native game and CS2 under Proton reach identical code.
XWayland #
X11 clients are tiled like any other window. The difference is confined to
src/view.c: an X11 window is not an xdg_toplevel, so title, class, sizing,
activation and closing go through accessors, and everything above — tiling,
workspaces, focus, the IPC view model — is unaware of which kind it has.
Three things about X11 shape that file:
- a surface exists before it has a
wl_surface, so mapping is two-stage and the scene tree is built onassociaterather than at creation; - position and size are a single operation in absolute screen coordinates, so placement is repeated on every resize;
- override-redirect windows — X11 menus and tooltips — bypass the window manager entirely. They are never tiled and appear exactly where the client asks, on the overlay layer. Tiling them would break every X11 menu.
Xwayland starts lazily: a session that never runs an X11 client pays nothing.
Touchpad gestures are split by finger count: three fingers belong to the
compositor (swipe to scroll the strip or change workspace), everything else is
forwarded to the focused client through pointer-gestures-v1, so pinch-to-zoom
in a browser keeps working. A gesture that starts as the compositor's stays
that way until it ends.
Client scale is reported over both fractional-scale-v1 and the wl_surface
preferred buffer scale, taken from the largest scale among the outputs in the
layout — a client renders at whatever it is told and the compositor stretches
whatever it gets, so saying nothing means everything paints at 1x and is scaled
up. Whole-number scales are rounded up, so a client that only understands those
overshoots rather than blurs.
When the shell breaks #
The entire layout lives in a web page, which is the point of this compositor and also its one structural risk: a JavaScript error or an unreachable shell means no window is ever placed, and the session becomes a black screen with a working keyboard.
So placement is watched. A window that maps and is not given a rect within two and a half seconds is laid out by a deliberately stupid built-in tiler — equal columns across the output, ignoring workspaces and the tiling tree, since the thing that maintains them is what stopped responding. It is not a layout anyone would choose; it exists so a broken shell leaves a desktop usable enough to open a terminal and fix it. The moment the shell does answer, the watchdog is disarmed for that window, so a merely slow shell costs nothing.
Not yet implemented: tablet and stylus input.
Installing #
On Arch or CachyOS, packaging/arch/ has a PKGBUILD. Every dependency is
already packaged there — including wpewebkit built with the WPE platform API,
which is the one that would otherwise mean compiling a browser engine — so it
builds in about a minute:
git archive --format=tar.gz --prefix=viewport-0.1.0/ -o viewport-0.1.0.tar.gz HEAD
cp packaging/arch/PKGBUILD . && makepkg -si
An installed copy needs no arguments: it ships its own shell and defaults to
it, and a wayland-sessions entry means a display manager will offer it as
something to log into. See packaging/arch/README.md for building it in a
container, which has two non-obvious wrinkles.
On NixOS, flake.nix provides both a package and a dev shell.
Licence #
MIT, matching wlroots. WPE WebKit and GLib are LGPL-2.1+ and dynamically linked, which imposes no licence condition on this code.