[Design] mkfreeOS — window server structured around contracts: same compositor on any OS
Posted: Tue Dec 01, 2026 4:08 pm
This is a companion to my earlier post on the kernel design. The same principle that keeps the kernel core decoupled from the CPU applies one layer up: the window server and client library have no OS-specific code at all. They never call accept(), pthread_create(), shmget(), or ioctl() directly. They only see eight pure virtual interfaces. mkfreeOS implements those interfaces in its GUI layer; swapping the platform means writing new implementations and changing the composition root — no protocol or compositor code changes.
Source at github.com/ramonmayedo/mkfreeOS (GPL v3). Internal documentation for the windowing subsystem is at github.com/ramonmayedo/mkfreeOS/tree/main/help/windowing — the full protocol tables, interface listings, and class maps are there for anyone who wants more detail than this post covers.
Architecture at a glance

Everything above the platform boundary is the portable core. The two boxes (client and server) are the same object files whether the host OS is mkfreeOS, Linux, or bare metal with a custom threading library.
The 8 platform interfaces
The parallel with the kernel's Arch struct is intentional. There, eight IArch* pointers isolate the CPU. Here, eight interfaces isolate the OS. All are injected at the composition root (main() of the server and the GClient constructor on the client); nothing else knows the concrete types.
EventServer is the one exception: it opens its file descriptors directly because there is no stable OS-independent abstraction for raw input device streams. When porting, replace the class and push the same MouseEvent* and KeyEvent* objects into the same EventQueue.
The wire protocol: just integers
Every message on the socket is a fixed 12-byte header:
No pointers, no OS types, no alignment surprises between 32-bit and 64-bit builds. Variable-length payloads follow the header as raw int arrays. The protocol is a pure byte-stream contract — it runs equally over an AF_LOCAL socket, a TCP connection, or a named pipe.
Handshake — the first exchange after connecting:
The eventHandle is the client's single channel for all server-to-client events (mouse, keyboard, resize, timer, clipboard). The full command and event tables are in the docs.
Zero-copy canvas: SHM double-buffer
Pixel data never crosses the socket. The client allocates a System V shared-memory segment, the server attaches to it, and both sides communicate only through a 16-byte header at the base of the segment:
Normal frame (no resize):
The compositor reads hdr->front dynamically inside buildFrame (under the state lock), so the slot selection is always consistent with the latest swap. On resize, the client allocates a new segment for the new dimensions and a sequence-numbered handshake (EVENT_RESIZE_REQUEST → WINDOW_ACK_RESIZE) ensures the server never reads from a segment whose size has changed.
The compositor: three phases, one lock
The compositor runs at a fixed 60 Hz in its own thread. Each tick calls Composer::present(), which splits the work into three phases:
The lock is held only during buildFrame. Pixel blitting and hardware submission run without it, so event dispatch and client reader threads proceed concurrently during the 14 ms that the compositor spends copying pixels.
buildFrame does three things under the lock:
Decoration surfaces (RenderSurface) are refcounted. buildFrame acquires a reference before releasing the lock, so the render phase can read the decoration bitmap safely even if the client destroys its window concurrently. The surface deletes itself when the refcount drops to zero.
Decoration system: theme ≠ metrics
The decoration renderer separates visual assets from geometry through two interfaces:
DecorationRenderer (the paint engine) takes both interfaces — it never owns bitmaps or fonts. ClassicDecorationTheme implements both, keeping them in one class for the common case while letting the interfaces be satisfied by any combination. Swapping the visual style means instantiating a different theme and updating one pointer at the composition root.
The current theme is a Windows Classic gray gradient. Button glyphs come from Marlett.fnt — the same font Windows Classic uses. Each button is a 20×20 bitmap (centered in a 22×22 hit area) with a Marlett glyph in its characteristic color: red for close, blue for maximize/restore, green for minimize. The three-button cluster is 80 px wide, right-aligned in the title bar.
The window implements IServerWindowDecoration to give the renderer its current state without creating a dependency on the Window class:
Resize: edge detection and seq-numbered ACK
Edge detection classifies the mouse position into a 3×3 zone grid (5 px borders on each side). Each cell maps to a resize direction enum and a cursor type. The compositor's cursor manager receives the cursor update on every MouseMove event that falls inside a window.
Drag accumulation runs without touching the actual window geometry. Each MouseMove applies the delta to _candidateRect, a snapshot of the starting rect. The compositor coalesces these: multiple drag events between two frame ticks produce a single requestResize call with only the final rect; intermediate positions are discarded.
Rate-limiting across the round-trip is the interesting part. When a resize is in flight (the server has sent EVENT_RESIZE_REQUEST and is waiting for the client's WINDOW_ACK_RESIZE), the server must not send another request until the ACK arrives — the client's SHM is mid-reallocation. _latestPendingRect absorbs all drag positions during this wait:
The sequence number prevents a stale ACK (from a cancelled resize) from being applied to a later one.
Clipboard: server as key broker, not data forwarder
No clipboard data ever passes through the server socket. The owner writes into a SHM segment, then sends the server only the shmkey and length. The server attaches to that segment as a keep-alive reference — if the owner later calls shmdt or disconnects, the kernel cannot destroy the segment because the server still holds an attachment. When a requester asks for the clipboard, the server posts EVENT_CLIPBOARD_DATA(key, len) and the requester does shmat/read/shmdt directly:
When the owner disconnects, ClipboardService::onClientDisconnect calls shmdt on the server's attachment. The segment is destroyed by the kernel only at that point.
Client task queue and wake callback
Background threads (timers, file I/O) need to post work onto the main thread safely. IClientRuntime provides a simple task queue:
The main event loop calls drainTasks() after every recvServerMsg() return. The wake callback solves the latency problem: without it, a background timer would have to wait up to the full recv timeout before its task executes. With it, post() fires the callback immediately, which causes CClient to send a csWake message to itself; the server echoes it back as EVENT_WAKE, unblocking the recv in under a millisecond.
ClientDispatcher uses a swap-and-run pattern: the entire pending list is atomically moved out under a mutex, then executed without holding it. This allows tasks to call post() re-entrantly without deadlocking.
What never changes / what you replace
What never changes regardless of OS:
In practice:
Source at github.com/ramonmayedo/mkfreeOS (GPL v3). Internal documentation for the windowing subsystem is at github.com/ramonmayedo/mkfreeOS/tree/main/help/windowing — the full protocol tables, interface listings, and class maps are there for anyone who wants more detail than this post covers.
Architecture at a glance
Code: Select all
┌───────────────────────────────────────────────────────────────────────────┐
│ Applications: notepad · fileExplorer · terminal_w │
├─────────────────────────────────┬─────────────────────────────────────────┤
│ CLIENT CORE (CClient / GClient) │ SERVER CORE (WindowServer) │
│ Only knows interfaces │ Only knows interfaces │
│ ◄──────── mkfree wire protocol (mkfree_msg) ──────────────────────────► │
├─────────────────────────────────┴─────────────────────────────────────────┤
│ INTERFACE CONTRACTS (8 pure-virtual headers) │
│ IClientTransport · IClientShmService · IClientRuntime │
│ IWindowTransport · IVideoOutput · ISynchronization │
│ ISharedMemoryService · IApplicationLauncher │
├──── platform boundary ────────────────────────────────────────────────────┤
│ mkfreeOS IMPLEMENTATIONS (src/userland/gui/) │
│ LocalClientTransport · LocalSocketTransport · PrimaryVideoOutput │
│ PosixSynchronization · SystemVSharedMemory · PosixApplicationLauncher │
│ EventServer (class-level contract — replace per platform) │
├───────────────────────────────────────────────────────────────────────────┤
│ Hardware / OS primitives │
│ AF_LOCAL socket · System V IPC · pthreads + sem · dev/video · dev/input │
└───────────────────────────────────────────────────────────────────────────┘
The 8 platform interfaces
The parallel with the kernel's Arch struct is intentional. There, eight IArch* pointers isolate the CPU. Here, eight interfaces isolate the OS. All are injected at the composition root (main() of the server and the GClient constructor on the client); nothing else knows the concrete types.
Code: Select all
Interface mkfreeOS implementation What it hides
───────────────────── ────────────────────────── ──────────────────────────────────
IWindowTransport LocalSocketTransport bind + listen + accept on AF_LOCAL
IClientTransport LocalClientTransport connect + send + recv
ISharedMemoryService SystemVSharedMemoryService shmget + shmat + shmctl IPC_RMID
IClientShmService SystemVClientShmService client-side shmget + shmat
ISynchronization PosixSynchronization pthread_mutex_t + sem_t + pthread_create
IApplicationLauncher PosixApplicationLauncher execv() in a detached pthread
IVideoOutput PrimaryVideoOutput ioctl(VIDEO_SET_MODE / VIDEO_PAINT_AREA)
EventServer (class contract) — mkfreeOS: open dev/input/* fds; another OS: replace class
Code: Select all
// src/userland/gui/windowserver/main.cpp — composition root
LocalSocketTransport transport;
SystemVSharedMemoryService shm;
PosixSynchronization sync;
PosixApplicationLauncher launcher;
PrimaryVideoOutput video;
WindowServer server(&transport, &shm, &sync, &launcher, &video);
// WindowServer only knows the five interface pointers above
The wire protocol: just integers
Every message on the socket is a fixed 12-byte header:
Code: Select all
struct mkfree_msg {
long mtype; // command or event kind
int parameter1; // p1 — meaning depends on mtype
int parameter2; // p2 — payload size or second parameter
};
Handshake — the first exchange after connecting:
Code: Select all
Client: csCreateConnection + HandshakeFlags{flags}
Server: esObjectCreated + HandshakeReply{eventHandle, clipboardHandle,
screenWidth, screenHeight}
Zero-copy canvas: SHM double-buffer
Pixel data never crosses the socket. The client allocates a System V shared-memory segment, the server attaches to it, and both sides communicate only through a 16-byte header at the base of the segment:
Code: Select all
SHM base
┌────────────────────────────────┐ offset 0
│ ShmWindowHeader (16 bytes) │
│ volatile int front; │ active slot index — 0 or 1
│ int slotBytes; │ width × height × 4
│ int _pad[2]; │
├────────────────────────────────┤ offset 16
│ Slot 0 — ARGB8888 pixels │ slotBytes bytes
├────────────────────────────────┤ offset 16 + slotBytes
│ Slot 1 — ARGB8888 pixels │ slotBytes bytes
└────────────────────────────────┘
Code: Select all
1. Client writes pixels into slot[1 − front] (the inactive slot)
2. Client sends WINDOW_SWAP_BUFFER command
3. Server: front ^= 1
4. Compositor reads slot[front] on the next 16ms tick
The compositor: three phases, one lock
The compositor runs at a fixed 60 Hz in its own thread. Each tick calls Composer::present(), which splits the work into three phases:
Code: Select all
present():
lock(g_stateMutex) → buildFrame() ← ~1–2 ms; snapshots state
unlock()
render() ← lock-free; pixel blit to backbuffer
for each damage rect:
ioctl(VIDEO_PAINT_AREA) ← lock-free; push to hardware
msleep(16)
buildFrame does three things under the lock:
- Flushes any pending drag or resize operations accumulated between ticks.
- Walks the z-order list and reads the active SHM front slot for each window.
- Repaints any decoration surfaces whose decoDirty flag is set — this is the only place decoration is ever repainted. setCaption(), maximize(), and minimize() just set the flag; the compositor paints once per tick, then clears it.
Code: Select all
Desktop (wallpaper) → Windows → Menus → ToolBar → Overlays → cursor (always last)
Decoration system: theme ≠ metrics
The decoration renderer separates visual assets from geometry through two interfaces:
Code: Select all
class IDecorationTheme { // visual assets — colors, bitmaps, fonts, icon cache
virtual int titleGradientStart() const = 0;
virtual int titleGradientEnd() const = 0;
virtual GgraphicsBitmap* closeButton() = 0;
virtual Gfont* titleFont() = 0;
virtual GgraphicsBitmap* getIcon(const char* path) = 0; // PNG cache
};
class IDecorationMetrics { // geometry — sizes, padding, insets
virtual DecorationButtonMetrics buttons() const = 0;
virtual DecorationTitleMetrics title() const = 0;
virtual Gpadding contentInsets() const = 0;
};
The current theme is a Windows Classic gray gradient. Button glyphs come from Marlett.fnt — the same font Windows Classic uses. Each button is a 20×20 bitmap (centered in a 22×22 hit area) with a Marlett glyph in its characteristic color: red for close, blue for maximize/restore, green for minimize. The three-button cluster is 80 px wide, right-aligned in the title bar.
The window implements IServerWindowDecoration to give the renderer its current state without creating a dependency on the Window class:
Code: Select all
class IServerWindowDecoration {
virtual int frameWidth() const = 0;
virtual const char* title() const = 0;
virtual const char* icon() const = 0;
virtual bool isMaximized() const = 0;
virtual bool hasTitleBar() const = 0;
};
Edge detection classifies the mouse position into a 3×3 zone grid (5 px borders on each side). Each cell maps to a resize direction enum and a cursor type. The compositor's cursor manager receives the cursor update on every MouseMove event that falls inside a window.
Drag accumulation runs without touching the actual window geometry. Each MouseMove applies the delta to _candidateRect, a snapshot of the starting rect. The compositor coalesces these: multiple drag events between two frame ticks produce a single requestResize call with only the final rect; intermediate positions are discarded.
Rate-limiting across the round-trip is the interesting part. When a resize is in flight (the server has sent EVENT_RESIZE_REQUEST and is waiting for the client's WINDOW_ACK_RESIZE), the server must not send another request until the ACK arrives — the client's SHM is mid-reallocation. _latestPendingRect absorbs all drag positions during this wait:
Code: Select all
resize in flight:
_hasPending = true → new drag positions update _latestPendingRect only
client ACKs (seq):
commit geometry
if _latestPendingRect differs from committed size:
_pendingSeq++, _hasPending = true → send next EVENT_RESIZE_REQUEST
Clipboard: server as key broker, not data forwarder
No clipboard data ever passes through the server socket. The owner writes into a SHM segment, then sends the server only the shmkey and length. The server attaches to that segment as a keep-alive reference — if the owner later calls shmdt or disconnects, the kernel cannot destroy the segment because the server still holds an attachment. When a requester asks for the clipboard, the server posts EVENT_CLIPBOARD_DATA(key, len) and the requester does shmat/read/shmdt directly:
Code: Select all
Owner: shmget + shmat → write → CLIPBOARD_CLAIM(key, len)
Server: attach(key) ← segment stays alive regardless of owner state
Requester: CLIPBOARD_REQUEST
Server: EVENT_CLIPBOARD_DATA(key, len)
Requester: shmat(key) → read len bytes → shmdt
Client task queue and wake callback
Background threads (timers, file I/O) need to post work onto the main thread safely. IClientRuntime provides a simple task queue:
Code: Select all
class IClientRuntime {
virtual void spawnDetached(void* (*fn)(void*), void* arg) = 0;
virtual void post(void (*fn)(void*), void* arg) = 0; // thread-safe enqueue
virtual int drainTasks() = 0; // execute on caller's thread
typedef void (*WakeFn)(void* ctx);
virtual void setWakeCallback(WakeFn fn, void* ctx) = 0;
};
Code: Select all
// Worker thread (e.g. a timer):
runtime->post(onTimerFired, arg); // enqueue + wake main thread
// Main event loop:
while (true) {
recvServerMsg(&cmd, &p1, &p2); // woken by csWake echo
runtime->drainTasks(); // runs onTimerFired on the main thread
if (cmd == EVENT_WINDOW_CLOSED) break;
}
What never changes / what you replace
What never changes regardless of OS:
- mkfreewire.h — all protocol structs, enums, payload layouts
- WindowServer, WindowService, Composer, WindowManager, OverlayManager
- CClient, GClient, CWindow, WindowSurface
- HandleTable, EventQueue, OutputQueue, ClientConnection
- DecorationRenderer, WindowComposer, OverlayComposer
- TimerServer, ClipboardService
- The event loop, double-buffer swap, resize ACK protocol, damage region logic
Code: Select all
Component Interface mkfreeOS impl Replace with
────────────────── ────────────────────── ───────────────────────── ──────────────────────────────
Server socket IWindowTransport LocalSocketTransport TCP, named pipe, any byte stream
Client socket IClientTransport LocalClientTransport Matching client side
Server SHM ISharedMemoryService SystemVSharedMemoryService mmap, CreateFileMapping, etc.
Client SHM IClientShmService SystemVClientShmService Same OS SHM API
Sync primitives ISynchronization PosixSynchronization Win32 CRITICAL_SECTION, SDL_mutex
App launcher IApplicationLauncher PosixApplicationLauncher CreateProcess, posix_spawn, etc.
Framebuffer output IVideoOutput PrimaryVideoOutput DRM/KMS, GDI, SDL surface, etc.
Input events EventServer (class contract) mkfreeOS opens dev/input/* Replace class; push same IEvent*
- Adding a new window type is a new Frame subclass and a compositor layer; nothing else changes.
- Adding a new input device is pushing IEvent* objects into the existing EventQueue.
- Porting to a new OS is writing 8 concrete implementation classes and changing the composition root; the protocol, compositor, and decoration system are untouched.
- Changing the visual theme is writing a new IDecorationTheme and updating one pointer.