User Tools

Site Tools


computing:notes:pascal_x11_window_manager

This is an old revision of the document!


User

How to write an X11 window manager in Free Pascal?

Assistant

Writing an X11 window manager (WM) from scratch in Free Pascal is an incredibly rewarding “under the hood” project. Since you are using Debian 12 with Openbox and tint2, you are already familiar with how a lightweight, non-compositing window manager feels and operates.

To build one in Free Pascal, you will need to interface directly with libX11. Free Pascal includes standard X11 bindings out of the box, which makes this entirely possible without external dependencies.


1. The Core Architecture

An X11 window manager is essentially a client that tells the X Server how to position, resize, and frame other windows.

To achieve this, your program must follow a specific lifecycle:

  1. Connect to the X Server.
  2. Select Substructure Redirect on the root window (this tells X11 that you want to intercept window management events).
  3. Enter an Event Loop to listen for map requests, configure requests, and button presses.

2. A Minimal Working Example

Here is a bare-bones, working X11 window manager written in Free Pascal. It initializes the connection, intercepts window creation requests (MapRequest), and maps (displays) them on the screen.

Save this file as paswm.pas:

program paswm;
 
{$mode objfpc}{$H+}
 
uses
  X, XLib, XUtil;
 
var
  DisplayPtr: PDisplay;
  RootWin: Window;
  XEvent: TXEvent;
 
begin
  // 1. Connect to the X Server
  DisplayPtr := XOpenDisplay(nil);
  if DisplayPtr = nil then
  begin
    WriteLn(StdErr, 'Error: Cannot open X display.');
    Halt(1);
  end;
 
  WriteLn('PasWM started successfully.');
 
  RootWin := XDefaultRootWindow(DisplayPtr);
 
  // 2. Request Substructure Redirect and Substructure Notify
  // This is what makes this application a Window Manager.
  // Only ONE window manager can select this on the root window at a time.
  XSelectInput(DisplayPtr, RootWin, SubstructureRedirectMask or SubstructureNotifyMask);
  XSync(DisplayPtr, False);
 
  // 3. The Main Event Loop
  while True do
  begin
    XNextEvent(DisplayPtr, @XEvent);
 
    case XEvent._type of
      MapRequest:
        begin
          // A client window wants to be shown on screen.
          // A real WM would frame it here. We will just allow it to map.
          WriteLn('MapRequest received for Window ID: ', XEvent.xmaprequest.window);
          XMapWindow(DisplayPtr, XEvent.xmaprequest.window);
        end;
 
      ConfigureRequest:
        begin
          // A client window wants to resize or move itself.
          // For a minimal WM, we just grant its exact request.
          XConfigureWindow(DisplayPtr, XEvent.xconfigurerequest.window, 
                           XEvent.xconfigurerequest.value_mask, 
                           @XEvent.xconfigurerequest);
        end;
    end;
  end;
 
  // Clean up (unreachable in this infinite loop, but good practice)
  XCloseDisplay(DisplayPtr);
end.

3. Compiling the Code

Free Pascal handles the X11 linking automatically via the XLib unit. You can compile this directly from your terminal:

fpc -O2 paswm.pas

4. How to Test Your Window Manager Safely

Do not try to run this inside your active Openbox session; X11 only allows one window manager to run at a time. The XSelectInput call will crash if Openbox is already managing the root window.

Instead, use Xephyr, which opens a nested X server inside a window on your current desktop.

  1. Install Xephyr (if you don't have it):
sudo apt install xserver-xephyr
  1. Launch Xephyr on a new display number (e.g., :1):
Xephyr -br -ac -noext GLX -screen 800x600 :1 &
  1. Run your window manager targeting that display:
DISPLAY=:1 ./paswm &
  1. Launch a client application (like xterm) inside the nested server to see your WM respond to MapRequest events:
DISPLAY=:1 xterm &

You will see xterm appear in the top-left corner of the Xephyr window, and your Pascal binary will output log messages to your terminal. Because this example lacks decoration logic, you won't be able to drag or resize xterm yet.


Next Steps for Expansion

To evolve this into a usable window manager like Openbox, you will need to look into:

  • Reparenting: Creating a border/title bar window, and moving the client window inside it using XReparentWindow.
  • Mouse Actions: Binding ButtonPressMask and handling MotionNotify events so you can drag and resize windows.
  • Inter-Client Communication (ICCCM & EWMH): Implementing X properties so panels like tint2 can detect open windows, handle workspaces, and show taskbars correctly.

User

I was thinking:

  • wholly keyboard-based input;
  • tiling logic;
  • zero decoration;
  • zero additional modules. Additional functionality - toolbars and launchers - would instead be handled via additional programs.

Assistant

That approach is excellent. By stripping out title bars, borders, and complex mouse logic, you are looking at a classic, ultra-lightweight keyboard-driven tiling window manager (similar to dwm, i3, or ratpoison).

Since you want zero decorations and plan to delegate taskbars to external tools like tint2, your Free Pascal code can remain incredibly clean. You won't need to deal with XReparentWindow (which is usually the most headache-inducing part of writing a WM).

Here is how to structure the keyboard grabs, tiling architecture, and external program execution in Free Pascal.


1. Capturing Keyboard Shortcuts

To make it wholly keyboard-based, your WM needs to intercept specific key combinations globally (e.g., Mod4 / Super Key + Return to launch a terminal).

You achieve this using XGrabKey. You must loop through your shortcuts and grab them on the Root Window.

uses
  X, XLib, XUtil, Keysym;
 
procedure GrabKeys(DisplayPtr: PDisplay; RootWin: Window);
var
  Modifiers: Cardinal;
  TerminalKey: KeyCode;
begin
  // Use the Super/Windows key as the modifier
  Modifiers := Mod4Mask; 
 
  // Get the hardware keycode for the 'Return' key
  TerminalKey := XKeysymToKeycode(DisplayPtr, XK_Return);
 
  // Grab Super + Return
  XGrabKey(DisplayPtr, TerminalKey, Modifiers, RootWin, 
           True, GrabModeAsync, GrabModeAsync);
end;

When a user presses this combination, X11 will send a KeyPress event to your main loop.


2. Managing the Tiling State (The Layout)

Because it's a tiling WM, you need a data structure to track managed windows and calculate their positions. A dynamic array or a linked list of window records works perfectly.

Since you mentioned in the past that for…in loops aren't supported or ideal in your Lazarus/FPC setup, we will stick to clean, standard index-based arrays (for i := 0 to Count - 1).

type
  TClient = record
    Win: Window;
    // You can store specific per-window states here if needed
  end;
 
var
  Clients: array of TClient;
  ClientCount: Integer = 0;
 
procedure AddClient(Win: Window);
begin
  Inc(ClientCount);
  SetLength(Clients, ClientCount);
  Clients[ClientCount - 1].Win := Win;
end;

The Tiling Algorithm (Vertical Split Example)

Every time a window is mapped or destroyed, you run a Tile function. For a simple layout where the master window takes up the left half and all other windows stack on the right:

procedure Tile(DisplayPtr: PDisplay; RootWin: Window);
var
  i: Integer;
  ScreenWidth, ScreenHeight: Word;
  MasterWidth, StackWidth: Word;
  WinX, WinY, WinW, WinH: Integer;
begin
  if ClientCount = 0 then Exit;
 
  // 1. Get current screen dimensions
  ScreenWidth := XDisplayWidth(DisplayPtr, XDefaultScreen(DisplayPtr));
  ScreenHeight := XDisplayHeight(DisplayPtr, XDefaultScreen(DisplayPtr));
 
  // 2. Calculate layout
  if ClientCount = 1 then
  begin
    // Only one window? Full screen.
    XMoveResizeWindow(DisplayPtr, Clients[0].Win, 0, 0, ScreenWidth, ScreenHeight);
  end
  else
  begin
    // Split 50/50 between Master and Stack
    MasterWidth := ScreenWidth div 2;
    StackWidth := ScreenWidth - MasterWidth;
 
    // Master Window (Left side)
    XMoveResizeWindow(DisplayPtr, Clients[0].Win, 0, 0, MasterWidth, ScreenHeight);
 
    // Stack Windows (Right side, split vertically among remaining clients)
    WinH := ScreenHeight div (ClientCount - 1);
    WinX := MasterWidth;
 
    for i := 1 to ClientCount - 1 do
    begin
      WinY := (i - 1) * WinH;
      XMoveResizeWindow(DisplayPtr, Clients[i].Win, WinX, WinY, StackWidth, WinH);
    end;
  end;
  XSync(DisplayPtr, False);
end;

3. Handling Window Destruction (UnmapNotify / DestroyNotify)

If a user closes a terminal, you must catch the UnmapNotify or DestroyNotify event, remove that window ID from your Clients array, and re-tile the remaining windows. If you forget this step, your layout will leave blank gaps or try to manage “ghost” windows.


4. Spawning Launchers and Terminals

To launch an external program (like xterm or your favorite launcher via keyboard shortcut), you will use FPC's standard Unix or SysUtils units to fork a process.

Because a WM shouldn't freeze while waiting for the client application to close, you must use a non-blocking process execution.

uses
  Unix, BaseUnix;
 
procedure LaunchProgram(const Cmd: string);
var
  PID: TPid;
begin
  PID := fpFork;
  if PID = 0 then
  begin
    // Inside the child process: execute the command
    // Using execl to run it via sh so shell paths/arguments work
    fpexcl('/bin/sh', ['-c', Cmd]);
    // If fpexcl returns, it failed
    fpExit(1);
  end;
  // Inside the parent process (your WM): immediately return to the event loop
end;

5. Integrating with tint2

Because you aren't writing decoration frames, standard taskbars like tint2 won't automatically know about your windows unless you tell them. tint2 looks for specific X11 properties on the root window (Extended Window Manager Hints / EWMH).

For a bare-minimum integration, when you map or unmap a window, you should update the _NET_CLIENT_LIST property on the root window so tint2 can dynamically draw the window buttons.

procedure UpdateClientListProperty(DisplayPtr: PDisplay; RootWin: Window);
var
  WinList: array of Window;
  i: Integer;
  NetClientListAtom: Atom;
begin
  if ClientCount = 0 then Exit;
 
  SetLength(WinList, ClientCount);
  for i := 0 to ClientCount - 1 do
    WinList[i] := Clients[i].Win;
 
  NetClientListAtom := XInternAtom(DisplayPtr, '_NET_CLIENT_LIST', False);
 
  XChangeProperty(DisplayPtr, RootWin, NetClientListAtom, XA_WINDOW, 32,
                  PropModeReplace, @WinList[0], ClientCount);
end;

Put It Together in the Event Loop

Your main case statement will now look beautifully minimal:

case XEvent._type of
  MapRequest:
    begin
      AddClient(XEvent.xmaprequest.window);
      XMapWindow(DisplayPtr, XEvent.xmaprequest.window);
      Tile(DisplayPtr, RootWin);
      UpdateClientListProperty(DisplayPtr, RootWin);
    end;
 
  UnmapNotify:
    begin
      // 1. Remove XEvent.xunmap.window from Clients array
      // 2. Tile(DisplayPtr, RootWin);
      // 3. UpdateClientListProperty(DisplayPtr, RootWin);
    end;
 
  KeyPress:
    begin
      // Check if it's our grabbed keycode
      if XEvent.xkey.keycode = XKeysymToKeycode(DisplayPtr, XK_Return) then
      begin
        LaunchProgram('xterm');
      end;
    end;
end;

This structural architecture scales perfectly. If you decide to swap your tiling logic later from a master/stack layout to a binary space partition (like bspwm), you only have to rewrite the internal math of the Tile procedure without touching any of your X11 event-handling plumbing.

computing/notes/pascal_x11_window_manager.1794863487.txt.gz · Last modified: by tailkinker