# DWN - Desktop Window Manager

retoor <retoor@molodetz.nl>

A production-ready X11 window manager written in ANSI C with EWMH/ICCCM protocol compliance, tiling-first workflow, integrated desktop components, and optional AI integration via OpenRouter API.

## Design Philosophy

DWN prioritizes a seamless, distraction-free desktop experience:

- **Zero borders and gaps**: Windows tile edge-to-edge without visual separation
- **Minimal chrome**: 28px title bars provide window controls without excess decoration
- **Tiling-first**: Master-stack layout as the default, with floating and monocle modes available
- **Keyboard-driven**: Comprehensive shortcuts for all operations
- **Modular architecture**: Single-responsibility modules with strict encapsulation
- **ANSI C**: Maximum portability and minimal dependencies

## Features

### Window Management

**Layout Modes**
- **Tiling**: Master-stack layout with configurable master ratio (0.1-0.9) and master window count
- **Floating**: Traditional overlapping windows with free positioning
- **Monocle**: Single maximized window per workspace

**Composable Window Snapping**
- Super+Arrow keys snap windows to half-screen positions
- Double-press extends to full width/height
- Combinations create quarter-screen positions (e.g., Super+Left then Super+Up = top-left quarter)

**Directional Resizing**
- Resize windows from any edge or corner
- Respects layout bounds and snap constraints

**Window States**
- Fullscreen (Alt+F11): Covers entire screen including panels
- Maximized (Alt+F10): Fills usable area with title bar
- Minimized (Alt+F9): Hidden from view
- Floating (Super+F9): Exempt from tiling layout
- Sticky: Visible on all workspaces
- Urgent: Demands attention with taskbar highlight

### Workspace System

- 9 independent virtual workspaces (F1-F9)
- Per-workspace layout persistence
- MRU (Most Recently Used) focus stack per workspace
- Alt-Tab cycles through MRU order
- Shift+F1-F9 moves focused window to target workspace
- Ctrl+Alt+Left/Right navigates adjacent workspaces

### Panels

**Top Panel**
- Workspace indicators with active/inactive/urgent states
- Taskbar with window buttons
- System tray with XEmbed protocol support
- Battery indicator (multi-battery support)
- Volume control with slider
- Top memory process display
- Top CPU process display
- Key press counter
- Mouse distance traveled
- Clock

**Bottom Panel**
- News ticker with scrolling headlines
- Configurable visibility

### System Tray

**XEmbed Protocol**
- Acquires `_NET_SYSTEM_TRAY_S0` selection
- Docks external application icons (nm-applet, blueman, Telegram, etc.)
- Forwards click events to icon windows
- Automatic cleanup on application close

**Built-in Widgets**
- Battery: Percentage display, charging indicator, multi-battery support
- Volume: Click for slider, scroll to adjust, right-click to mute
- Fade effects: Click "S:X.X" or "I:XX%" to adjust animation speed and glow intensity
- Process monitors: Rotating display of top CPU/memory consumers

### Ambient Glow Effects

Visual feedback system with phase-offset animations:
- Panel background subtle color cycling
- Workspace indicator glow
- Taskbar button highlighting
- Clock and statistics display
- Window title text glow on focus
- Configurable animation speed

### Activity Tracking

- **Key press counter**: Total keypresses displayed in panel
- **Mouse distance**: Cumulative mouse movement in pixels
- **XInput2 integration**: Raw event monitoring for accurate tracking

### Focus Transitions

- Animated color transitions on window focus changes
- Taskbar button color interpolation
- Title bar glow animations
- Bold font rendering for Alt-Tab selection

### Notification System

D-Bus implementation of `org.freedesktop.Notifications`:
- Receives notifications from all applications
- Stacked display with timeout management
- Urgency levels: low, normal, critical
- Click to dismiss

### News Ticker

- Fetches headlines from configured sources
- Smooth pixel-based scrolling animation
- Super+Return opens current article in browser
- Automatic refresh interval
- Sentiment indicators (positive/negative/neutral)

### AI Integration

**Command Palette (Super+Shift+A)**
- Natural language command execution
- OpenRouter API with configurable model selection
- Context-aware responses based on current workspace

**Context Analysis (Super+A)**
- Task type detection (coding, browsing, communication)
- Window and application analysis
- Intelligent suggestions

**Exa Semantic Search (Super+Shift+E)**
- Meaning-based web search
- Results displayed in dmenu/rofi
- Select to open in browser

### Screenshot and OCR

**Screenshot API**
- Fullscreen capture
- Active window capture
- Area selection capture
- Async capture with callbacks
- Base64 encoding for API transmission
- PNG output

**OCR API**
- Tesseract-based text extraction
- Multi-language support
- Confidence scoring
- Async processing

### WebSocket API

Programmatic control on port 8777:

| Command | Description |
|---------|-------------|
| `get_status` | Window manager state |
| `get_workspaces` | Workspace information |
| `get_clients` | All managed windows |
| `switch_workspace` | Change active workspace |
| `focus_client` | Focus specific window |
| `run_command` | Execute shell command |
| `screenshot` | Capture screen |
| `ocr` | Extract text from image |
| `get_fade_settings` | Get fade effect settings |
| `set_fade_speed` | Set animation speed (0.1-3.0) |
| `set_fade_intensity` | Set glow intensity (0.0-1.0) |

**Event Subscription**

Subscribe to real-time events including fade changes:

```bash
# Subscribe to fade events
python3 examples/dwn_api_client.py subscribe fade_speed_changed fade_intensity_changed

# Listen for all events
python3 examples/dwn_api_client.py listen
```

**Fade Control Example**

```bash
# Get current fade settings
python3 examples/dwn_api_client.py fade-settings

# Set fade speed (faster animation)
python3 examples/dwn_api_client.py fade-speed 1.5

# Set fade intensity (dimmer glow)
python3 examples/dwn_api_client.py fade-intensity 0.5

# Run interactive demo
python3 examples/fade_control_demo.py
```

### Automation

**XDG Autostart**
- Scans `/etc/xdg/autostart/` and `~/.config/autostart/`
- Parses `.desktop` files
- Custom autostart directory support

**Service Manager**
- Background process management
- Automatic restart on failure

### Interactive Features

**Tutorial (Super+T)**
- Step-by-step keyboard shortcut training
- Waits for correct input
- Progressive difficulty

**Demo Mode (Super+Shift+D)**
- Automated feature showcase
- Configurable timing
- Covers all major features

**Shortcuts Help (Super+S)**
- Quick reference overlay
- All keyboard bindings displayed

## Installation

### Dependencies

Required libraries (via pkg-config):
- X11, Xext, Xinerama, Xrandr, Xft, Xi
- fontconfig
- libdbus-1
- libcurl
- libpng
- tesseract (optional, for OCR)

### Build

```bash
make deps      # Auto-install dependencies (apt/dnf/pacman)
make           # Build with -O2 optimization
make install   # Install to /usr/local/bin (PREFIX configurable)
```

### Testing

```bash
make run       # Launch in nested Xephyr window
```

### Build Targets

| Target | Description |
|--------|-------------|
| `make` | Release build with optimization |
| `make debug` | Debug build with -g -DDEBUG |
| `make clean` | Remove build artifacts |
| `make format` | Run clang-format |
| `make check` | Run cppcheck static analysis |

## Configuration

Configuration file: `~/.config/dwn/config` (INI format)

### General

```ini
[general]
terminal = xfce4-terminal
launcher = dmenu_run
file_manager = thunar
focus_mode = click              # click or follow
focus_follow_delay = 100        # 0-1000ms
decorations = true
```

### Appearance

```ini
[appearance]
border_width = 0                # 0-50px
title_height = 28               # 0-100px
panel_height = 32               # 0-100px
gap = 0                         # 0-100px
font = fixed
```

### Layout

```ini
[layout]
default = tiling                # tiling, floating, monocle
master_ratio = 0.55             # 0.1-0.9
master_count = 1                # 1-10
```

### Panels

```ini
[panels]
top = true
bottom = true
```

### Colors

```ini
[colors]
panel_bg = #080808
panel_fg = #00ff00
workspace_active = #ff00ff
workspace_inactive = #222222
workspace_urgent = #ff0000
title_focused_bg = #00ffff
title_focused_fg = #000000
title_unfocused_bg = #111111
title_unfocused_fg = #444444
border_focused = #00ff00
border_unfocused = #000000
notification_bg = #111111
notification_fg = #00ffff
```

### AI

```ini
[ai]
model = google/gemini-2.0-flash-exp:free
openrouter_api_key = sk-or-v1-your-key
exa_api_key = your-exa-key
```

Environment variables:
```bash
export OPENROUTER_API_KEY=sk-or-v1-your-key
export EXA_API_KEY=your-exa-key
```

API keys:
- OpenRouter: https://openrouter.ai/keys
- Exa: https://dashboard.exa.ai/api-keys

### Autostart

```ini
[autostart]
enabled = true
xdg_autostart = true
path = ~/.config/dwn/autostart.d
```

### API

```ini
[api]
enabled = true
port = 8777
```

### Demo

```ini
[demo]
step_delay = 4000               # 1000-30000ms
ai_timeout = 15000              # 5000-60000ms
window_timeout = 5000           # 1000-30000ms
```

## Keyboard Shortcuts

### Application Launchers

| Shortcut | Action |
|----------|--------|
| `Ctrl+Alt+T` | Terminal |
| `Super` / `Alt+F2` | Application launcher |
| `Super+E` | File manager |
| `Super+B` | Web browser |
| `Print` | Screenshot |

### Window Management

| Shortcut | Action |
|----------|--------|
| `Alt+F4` | Close window |
| `Alt+Tab` | Next window (MRU order) |
| `Alt+Shift+Tab` | Previous window |
| `Alt+F9` | Toggle minimize |
| `Alt+F10` | Toggle maximize |
| `Alt+F11` | Toggle fullscreen |
| `Super+F9` | Toggle floating |

### Workspace Navigation

| Shortcut | Action |
|----------|--------|
| `F1` - `F9` | Switch to workspace 1-9 |
| `Shift+F1` - `Shift+F9` | Move window to workspace 1-9 |
| `Ctrl+Alt+Right` | Next workspace |
| `Ctrl+Alt+Left` | Previous workspace |

### Layout Control

| Shortcut | Action |
|----------|--------|
| `Super+Space` | Cycle layout mode |
| `Super+H` | Shrink master area |
| `Super+L` | Expand master area |
| `Super+I` | Increase master count |
| `Super+D` | Decrease master count / Show desktop |

### Window Snapping

| Shortcut | Action |
|----------|--------|
| `Super+Left` | Snap left (50% or 100%) |
| `Super+Right` | Snap right (50% or 100%) |
| `Super+Up` | Snap top (50% or 100%) |
| `Super+Down` | Snap bottom (50% or 100%) |

### AI Features

| Shortcut | Action |
|----------|--------|
| `Super+A` | Context analysis |
| `Super+Shift+A` | Command palette |
| `Super+Shift+E` | Exa semantic search |

### News and Help

| Shortcut | Action |
|----------|--------|
| `Super+Return` | Open current article |
| `Super+S` | Shortcuts help |
| `Super+T` | Interactive tutorial |
| `Super+Shift+D` | Toggle demo mode |
| `Super+Backspace` | Quit DWN |

## Architecture

### Module Structure

| Module | Responsibility |
|--------|----------------|
| main.c | X11 initialization, event loop, signal handling |
| client.c | Window management, focus, frame creation |
| workspace.c | Virtual desktop management, MRU stacks |
| layout.c | Tiling, floating, monocle algorithms |
| decorations.c | Title bars, borders, glow animations |
| panel.c | Top/bottom panel rendering, widgets |
| systray.c | XEmbed system tray, battery/volume widgets |
| notifications.c | D-Bus notification daemon |
| atoms.c | EWMH/ICCCM atom management |
| keys.c | Keyboard shortcut handling |
| config.c | INI configuration parser |
| ai.c | OpenRouter API, Exa search integration |
| news.c | News ticker with scrolling animation |
| screenshot.c | Screen capture API |
| ocr.c | Tesseract text extraction |
| autostart.c | XDG autostart implementation |
| services.c | Background service management |
| demo.c | Automated feature demonstration |
| api.c | WebSocket server |
| util.c | Logging, memory, string utilities, glow effects |

### New Abstraction Layer (v2.0)

DWN now includes a modern abstraction layer for future extensibility:

**Core Abstractions** (`include/core/`)
- `wm_types.h` - Abstract handles, geometry, colors, events
- `wm_string.h/c` - Safe dynamic strings with automatic memory management
- `wm_list.h/c` - Dynamic array container with sorting and iteration
- `wm_hashmap.h/c` - Hash table with automatic resizing
- `wm_client.h/c` - Abstract client type with bidirectional legacy sync

**Backend Interface** (`include/backends/`)
- `backend_interface.h` - Backend-agnostic vtable (80+ operations)
- `x11/x11_backend.h/c` - X11 implementation with event translation
- Designed for future Wayland and headless backends

**Plugin System** (`include/plugins/`)
- `layout_plugin.h` - Layout plugin API with state management
- `widget_plugin.h` - Widget plugin API for panel components
- Built-in layouts: tiling, floating, monocle, grid
- Support for dynamic plugin loading

The abstraction layer maintains **100% API compatibility** with existing code while enabling:
- Backend portability (X11 → Wayland migration path)
- Dynamic plugin loading for layouts and widgets
- Type-safe handles replacing void* casts
- Memory-safe string and container operations

### Design Patterns

**Encapsulation**
- Opaque pointer types hide internal structures
- Header exposes only public API
- Implementation details remain private

**Error Handling**
- Status code return values
- Output parameters for results
- Enum-based error codes

**Resource Management**
- Goto cleanup pattern for multi-resource functions
- Every allocation has corresponding free
- XGrabServer/XUngrabServer for atomic X11 operations

**Event Architecture**
- Select-based multiplexed I/O
- 60fps animation loop with 16ms timeout
- Async request queues for AI/screenshot/OCR

**Naming Conventions**
- Module prefix for functions: `client_focus()`, `workspace_switch()`
- Snake_case for functions and variables
- CamelCase for types and structs

### Design Patterns

**Encapsulation**
- Opaque pointer types hide internal structures
- Header exposes only public API
- Implementation details remain private

**Error Handling**
- Status code return values
- Output parameters for results
- Enum-based error codes

**Resource Management**
- Goto cleanup pattern for multi-resource functions
- Every allocation has corresponding free
- XGrabServer/XUngrabServer for atomic X11 operations

**Event Architecture**
- Select-based multiplexed I/O
- 60fps animation loop with 16ms timeout
- Async request queues for AI/screenshot/OCR

**Naming Conventions**
- Module prefix for functions: `client_focus()`, `workspace_switch()`
- Snake_case for functions and variables
- CamelCase for types and structs

### Key Constants

| Constant | Value |
|----------|-------|
| MAX_CLIENTS | 256 |
| MAX_WORKSPACES | 9 |
| MAX_MONITORS | 8 |
| MAX_NOTIFICATIONS | 32 |
| MAX_KEYBINDINGS | 64 |

## WebSocket API Examples

### Python

```python
import websocket
import json

ws = websocket.create_connection("ws://localhost:8777/ws")

ws.send(json.dumps({"command": "get_clients"}))
clients = json.loads(ws.recv())

ws.send(json.dumps({"command": "switch_workspace", "workspace": 3}))

ws.send(json.dumps({"command": "focus_client", "window": 12345678}))

ws.close()
```

### Response Format

```json
{
  "status": "ok",
  "data": {
    "clients": [
      {
        "window": 12345678,
        "title": "Firefox",
        "class": "firefox",
        "workspace": 1,
        "x": 0, "y": 32,
        "width": 960, "height": 540,
        "focused": true
      }
    ]
  }
}
```

## Project Structure

```
dwn/
├── src/                   # Implementation files
│   ├── core/              # Abstract core types (string, list, hashmap, client)
│   ├── backends/x11/      # X11 backend implementation
│   └── plugins/           # Plugin system (layout, widget managers)
│       └── layouts/       # Built-in layout plugins
├── include/               # Header files
│   ├── core/              # Core abstraction headers
│   ├── backends/          # Backend interface headers
│   └── plugins/           # Plugin API headers
├── manual/                # Documentation website (HTML)
├── config/                # Configuration templates
├── scripts/               # Utility scripts
├── examples/              # API usage examples
└── build/                 # Build artifacts
```

## License

MIT License - see LICENSE file.
