Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Fern Shell is a modern, QML-based desktop shell for Hyprland. It provides a sleek status bar with live-reloadable components, designed for rapid iteration and easy customization.

Why Fern Shell?

Traditional BarsFern Shell
Recompile to change stylingLive reload on file save
Limited theming optionsFull design token system
Separate config languagesQML + TOML configuration
Complex build systemsNix flakes for reproducibility

Key Features

  • Live Reload: Change QML files and see updates instantly
  • Hyprland Native: Built specifically for Hyprland's layer-shell protocol
  • Design Tokens: Consistent theming with a three-tier token system
  • Minimal Dependencies: Qt6/QML frontend, optional Rust backend
  • Nix-First: Easy installation via Home-Manager or NixOS modules

Architecture at a Glance

┌─────────────────────────────────────┐
│         Fern Shell Package          │
├─────────────────────────────────────┤
│  QML/QuickShell Frontend            │
│  - Panel with modules               │
│  - Live-reloadable                  │
│  - System integration via D-Bus     │
├─────────────────────────────────────┤
│  Rust Service (fernctl)             │
│  - Configuration management         │
│  - Theme token generation           │
│  - File watching                    │
└─────────────────────────────────────┘

What's Next?

Installation

Fern Shell is distributed as a Nix flake with Home-Manager and NixOS modules.

Prerequisites

Home-Manager Installation

Add the flake to your flake.nix inputs:

{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    home-manager.url = "github:nix-community/home-manager";
    fern-shell.url = "github:adanoelle/fern-shell";
  };
}

Enable the module in your Home-Manager configuration:

{ inputs, ... }:
{
  imports = [ inputs.fern-shell.homeManagerModules.default ];

  programs.fern-shell = {
    enable = true;
    # Optional: customize settings
    settings = {
      appearance = {
        theme = "dark";
        accent = "#89b4fa";
      };
      bar = {
        position = "left";
        width = 48;
      };
    };
  };
}

NixOS Installation

For system-wide installation, use the NixOS module:

{ inputs, ... }:
{
  imports = [ inputs.fern-shell.nixosModules.default ];

  programs.fern-shell.enable = true;
}

Manual / Development

Clone and run directly:

git clone https://github.com/adanoelle/fern-shell
cd fern-shell
nix develop

# Run with live reload
qs -p fern/shell.qml

Verifying Installation

After installation, start Hyprland. Fern Shell should appear as a bar on the left edge of your screen.

If you don't see the bar:

  1. Check that Hyprland is running
  2. Look for errors: journalctl --user -u fern-shell
  3. See Troubleshooting

Quick Tour

This 5-minute walkthrough introduces the core concepts of Fern Shell.

The Bar

Fern Shell provides a vertical bar on the left edge of your screen:

  • Collapsed: A thin 4px accent line
  • Expanded: Full 48px bar with modules (hover to expand)

The bar automatically hides when not in use and expands when you move your mouse to the left edge.

Modules

The bar contains modules that display information:

ModuleDescription
WorkspacesShows Hyprland workspace indicators
ClockDisplays current time vertically
SpacerFlexible space between modules

Modules are arranged top-to-bottom in the order specified in your config.

Configuration

Fern Shell uses TOML for configuration. The config file is typically at ~/.config/fern/config.toml:

[appearance]
theme = "dark"
accent = "#89b4fa"

[bar]
position = "left"
width = 48
modules = ["workspaces", "spacer", "clock"]

Live Reload

One of Fern Shell's key features is live reload:

  1. Edit any QML file in fern/
  2. Save the file
  3. Changes appear immediately (no restart needed)

This makes styling and development much faster than traditional approaches.

The Border

Fern Shell also draws a subtle curved border around your screen, creating a polished visual effect that integrates with the bar.

Next Steps

Configuration

Fern Shell is configured through a combination of TOML files and Home-Manager/NixOS options.

Configuration Sources

  1. Home-Manager/NixOS options - Primary configuration method
  2. ~/.config/fern/config.toml - Runtime configuration file
  3. Environment variables - Override specific settings

Quick Example

[appearance]
theme = "dark"
accent = "#89b4fa"
font_family = "Inter"

[bar]
position = "left"
width = 48
persistent = false
modules = ["workspaces", "spacer", "clock"]

[modules.workspaces]
count = 10
show_empty = true

[modules.clock]
format_time = "%H\n%M"
format_date = "%a\n%d"

Sections

Config File Format

Complete reference for config.toml.

File Location

The configuration file is located at ~/.config/fern/config.toml.

Schema

[appearance]

KeyTypeDefaultDescription
theme"dark" | "light" | "auto""dark"Color scheme
accenthex color"#89b4fa"Accent color for highlights
font_familystring"Inter"Primary font
font_monostring"JetBrainsMono Nerd Font"Monospace font
font_iconstring"Material Symbols Rounded"Icon font

[bar]

KeyTypeDefaultDescription
position"left""left"Bar position (only left supported)
widthinteger48Expanded bar width in pixels
collapsed_widthinteger4Collapsed indicator width
persistentbooleanfalseKeep bar always visible
modulesarray["workspaces", "spacer", "clock"]Module order

[border]

KeyTypeDefaultDescription
thicknessinteger4Border thickness in pixels
roundinginteger24Corner radius in pixels

[modules.*]

Module-specific configuration. See Modules for details.

Example

[appearance]
theme = "dark"
accent = "#cba6f7"  # Catppuccin Mauve

[bar]
width = 52
persistent = false
modules = ["workspaces", "spacer", "clock"]

[border]
thickness = 4
rounding = 20

[modules.workspaces]
count = 8
show_empty = false

[modules.clock]
format_time = "%H\n%M"

Theming

Fern Shell uses a three-tier design token system for consistent theming.

Token Architecture

Tier 1: Primitives (built-in palettes)
  ↓
Tier 2: Semantic Tokens (configurable)
  ↓
Tier 3: Component Tokens (internal)

Tier 1: Primitives

Built-in color palettes that you don't configure directly:

Dark Palette (Catppuccin Mocha)

  • Base: #1e1e2e
  • Surface: #313244
  • Text: #cdd6f4

Light Palette (Catppuccin Latte)

  • Base: #eff1f5
  • Surface: #e6e9ef
  • Text: #4c4f69

Tier 2: Semantic Tokens

These are what you configure in config.toml:

[appearance]
theme = "dark"      # Selects the palette
accent = "#89b4fa"  # Override the accent color

Tier 3: Component Tokens

Internal mappings that components use. You don't configure these directly:

  • barBackground → background
  • moduleBackground → surface
  • textPrimary → foreground

Color Reference

TokenDarkLightUsage
background#1e1e2e#eff1f5Bar background
surface#313244#e6e9efModule backgrounds
foreground#cdd6f4#4c4f69Primary text
accent#89b4fa#1e66f5Active states

Fonts

[appearance]
font_family = "Inter"                    # UI text
font_mono = "JetBrainsMono Nerd Font"    # Monospace
font_icon = "Material Symbols Rounded"   # Icons

Custom Accents

Popular accent colors from Catppuccin:

NameHexPreview
Blue#89b4faDefault
Mauve#cba6f7Purple
Pink#f5c2e7Light pink
Teal#94e2d5Cyan-ish
Green#a6e3a1Soft green

Modules

Configure individual bar modules.

Available Modules

ModuleDescription
workspacesHyprland workspace indicators
clockTime and date display
spacerFlexible space (no config)

Workspaces

Shows workspace indicators as vertical pills.

[modules.workspaces]
count = 10          # Number of workspaces to show
show_empty = true   # Show empty workspace indicators

Visual States:

  • Active: Tall pill with accent color
  • Occupied: Small dot with dim color
  • Empty: Small dot with overlay color (if show_empty = true)

Clock

Displays time vertically.

[modules.clock]
format_time = "%H\n%M"    # Time format (newline for vertical)
format_date = "%a\n%d"    # Date format (optional)

Format Codes:

  • %H - Hour (24h)
  • %M - Minute
  • %a - Weekday abbreviation
  • %d - Day of month

Module Order

Modules appear in the order listed:

[bar]
modules = ["workspaces", "spacer", "clock"]
  • First module: Top of bar
  • Last module: Bottom of bar
  • spacer: Pushes modules apart

QML Components Overview

Fern Shell's UI is built with QML (Qt Modeling Language) using the QuickShell framework.

Component Architecture

shell.qml                    # Entry point
├── bar/
│   ├── BarWrapper.qml      # Expand/collapse state machine
│   ├── BarInteractions.qml # Mouse hover detection
│   ├── Bar.qml             # Module layout
│   ├── Border.qml          # Curved screen frame
│   └── Backgrounds.qml     # Bar background
├── components/
│   ├── StyledRect.qml      # Base animated rectangle
│   └── ModuleContainer.qml # Pill-shaped container
├── modules/
│   ├── Clock.qml           # Time display
│   └── Workspaces.qml      # Workspace indicators
├── services/
│   └── Hyprland.qml        # Hyprland IPC integration
└── config/
    ├── Theme.qml           # Design token singleton
    └── ConfigLoader.qml    # TOML configuration loader

Key Patterns

Singleton Services

Theme and Hyprland are singletons accessed via imports:

import "../config" as Config
import "../services" as Services

// Usage
color: Config.Theme.accent
activeWorkspace: Services.Hyprland.activeWsId

Required Properties

Components declare explicit dependencies:

Item {
    required property ShellScreen screen
    required property Item bar
}

Reactive Bindings

State flows through property bindings, not imperative updates:

// This automatically updates when bar.implicitWidth changes
width: bar.implicitWidth

Sections

Bar System

The bar system handles expansion, collapse, and hover detection.

Component Hierarchy

shell.qml
└── Scope (per screen)
    ├── panelWindow (visual layer)
    │   ├── inputRegion (fixed 48px hover zone)
    │   ├── Border
    │   ├── Backgrounds
    │   └── BarInteractions (MouseArea)
    │       └── BarWrapper (state machine)
    │           └── Bar (module layout)
    └── exclusionWindow (space reservation)

Dual-Window Architecture

Fern Shell uses two windows per screen:

WindowPurpose
panelWindowFull-screen visual layer (border, bar, hover)
exclusionWindow1px invisible window for exclusive zone

Why separate?

  • Visual effects need full-screen coverage
  • Exclusive zone is rectangular (just the bar area)
  • Prevents compositor bugs with complex geometry

BarWrapper State Machine

BarWrapper.qml uses QML's declarative state system:

states: State {
    name: "visible"
    when: root.shouldBeVisible
    PropertyChanges {
        root.implicitWidth: root.expandedWidth
    }
}

transitions: [
    Transition {
        from: ""
        to: "visible"
        NumberAnimation {
            property: "implicitWidth"
            duration: 300
        }
    }
]

States:

  • "" (default): Collapsed, implicitWidth = 4px
  • "visible": Expanded, implicitWidth = 48px

Hover Detection

BarInteractions.qml is a full-screen MouseArea with fixed thresholds:

MouseArea {
    // Fixed 48px + 15px tolerance (never animated)
    if (containsMouse && mouseX < Config.Theme.barWidth + 15) {
        bar.isHovered = true;
    }
}

Anti-Bounce Mechanism

Problem: If the hover zone shrank during collapse animation, the mouse could exit mid-animation, causing flicker.

Solution: Fixed input region that never changes:

// shell.qml
Item {
    id: inputRegion
    width: Config.Theme.barWidth  // Always 48px
}
mask: Region { item: inputRegion }

Edge Detection

When the mouse is at the screen edge (x < 5px), don't collapse:

onContainsMouseChanged: {
    if (!containsMouse) {
        if (lastMouseX > 5) {
            collapseTimer.start();
        }
        // If at edge, don't collapse
    }
}

Exclusive Zone Flow

bar.implicitWidth changes (4 → 48)
  → screenScope.currentBarWidth updates
    → exclusionWindow.exclusiveZone updates
      → Compositor pushes windows right

This happens automatically through QML property bindings.

Files

  • /fern/shell.qml - Entry point, dual-window setup
  • /fern/bar/BarWrapper.qml - State machine
  • /fern/bar/BarInteractions.qml - Hover detection
  • /fern/bar/Bar.qml - Module layout

Border & Backgrounds

The border system creates a curved frame around the screen using an inverted mask technique.

The Challenge

Wayland layer-shell windows are rectangular. To create curved corners, we need a creative approach.

Inverted Mask Technique

Border.qml draws a full-screen rectangle and cuts out the interior:

Step 1: Full-screen colored rectangle
┌───────────────────────────────────┐
│█████████████████████████████████  │
│█████████████████████████████████  │
│█████████████████████████████████  │
└───────────────────────────────────┘

Step 2: Create mask shape (invisible)
┌───────────────────────────────────┐
│    ╔═════════════════════════╗    │
│    ║                         ║    │
│    ║      (mask interior)    ║    │
│    ╚═════════════════════════╝    │
└───────────────────────────────────┘

Step 3: Apply inverted mask
┌───────────────────────────────────┐
│████╔═════════════════════════╗    │
│████║                         ║    │
│████║   (transparent cutout)  ║    │
│████╚═════════════════════════╝    │
└───────────────────────────────────┘

Implementation

// Border.qml
StyledRect {
    anchors.fill: parent
    color: Config.Theme.barBackground

    layer.enabled: true
    layer.effect: MultiEffect {
        maskSource: mask
        maskEnabled: true
        maskInverted: true    // Cut OUT the mask shape
    }
}

Item {
    id: mask
    layer.enabled: true
    visible: false

    Rectangle {
        anchors.fill: parent
        anchors.margins: Config.Theme.borderThickness  // 4px
        anchors.leftMargin: root.bar.implicitWidth     // Dynamic!
        radius: Config.Theme.borderRounding            // 24px
    }
}

Dynamic Left Margin

The mask's leftMargin binds to bar.implicitWidth:

  • Collapsed: leftMargin = 4px (thin border visible)
  • Expanded: leftMargin = 48px (border "hugs" the bar)

This creates seamless integration between bar and border.

Backgrounds

Backgrounds.qml is simpler - it fills the bar area:

StyledRect {
    width: root.bar.implicitWidth
    color: Config.Theme.barBackground
}

Why GPU Layers?

layer.enabled: true

This renders the item to a GPU texture, enabling:

  • Mask effects via shaders
  • Smooth animations
  • Hardware-accelerated compositing

Files

  • /fern/bar/Border.qml - Mask technique implementation
  • /fern/bar/Backgrounds.qml - Bar background fill
  • /fern/components/StyledRect.qml - Base rectangle with behaviors

Module Components

Clock and Workspaces module implementations.

Module Container

All modules use ModuleContainer.qml as a base - a pill-shaped container with consistent styling:

// ModuleContainer.qml
Rectangle {
    color: Config.Theme.moduleBackground
    radius: Config.Theme.moduleRadius
    // ...
}

Clock Module

Clock.qml displays time vertically with accent-colored text.

ModuleContainer {
    property color textColor: Config.Theme.accent

    ColumnLayout {
        Text {
            text: Qt.formatTime(new Date(), "HH")
            color: textColor
            font.family: Config.Theme.fontMono
        }
        Text {
            text: Qt.formatTime(new Date(), "mm")
            color: textColor
        }
    }

    Timer {
        interval: 1000
        running: true
        repeat: true
        onTriggered: // update time
    }
}

Key Points:

  • Uses Timer to update every second
  • Vertical layout with ColumnLayout
  • Monospace font for alignment

Workspaces Module

Workspaces.qml shows Hyprland workspace indicators.

ModuleContainer {
    required property ShellScreen screen

    readonly property int activeWsId:
        Services.Hyprland.activeWsIdForMonitor(screen)

    ColumnLayout {
        Repeater {
            model: wsCount

            Rectangle {
                readonly property bool isActive: wsId === activeWsId
                readonly property bool isOccupied:
                    Services.Hyprland.workspaceHasWindows(wsId)

                width: 8
                height: isActive ? 24 : 8
                radius: Config.Theme.radius.full

                color: isActive ? Config.Theme.accent
                     : isOccupied ? Config.Theme.foregroundDim
                     : Config.Theme.overlay
            }
        }
    }
}

Visual States:

StateSizeColor
Active8x24Accent
Occupied8x8Dim foreground
Empty8x8Overlay

Hyprland Integration:

  • activeWsIdForMonitor(screen) - Gets active workspace per monitor
  • workspaceHasWindows(wsId) - Checks if workspace has windows

Adding New Modules

See Adding Modules for a step-by-step guide.

Files

  • /fern/modules/Clock.qml
  • /fern/modules/Workspaces.qml
  • /fern/components/ModuleContainer.qml
  • /fern/services/Hyprland.qml

Theme Tokens

Theme.qml is a singleton that provides design tokens to all components.

Three-Tier Architecture

┌─────────────────────────────────────┐
│  Tier 1: Primitives                 │
│  _darkPalette, _lightPalette        │
│  (internal, not configurable)       │
└─────────────────┬───────────────────┘
                  │
┌─────────────────▼───────────────────┐
│  Tier 2: Semantic Tokens            │
│  background, surface, accent, etc.  │
│  (configurable via config.toml)     │
└─────────────────┬───────────────────┘
                  │
┌─────────────────▼───────────────────┐
│  Tier 3: Component Tokens           │
│  barBackground, moduleRadius, etc.  │
│  (internal mappings)                │
└─────────────────────────────────────┘

Tier 1: Primitives

Built-in color palettes (Catppuccin):

readonly property var _darkPalette: ({
    base: "#1e1e2e",
    surface: "#313244",
    text: "#cdd6f4",
    blue: "#89b4fa",
    // ...
})

readonly property var _lightPalette: ({
    base: "#eff1f5",
    surface: "#e6e9ef",
    text: "#4c4f69",
    blue: "#1e66f5",
    // ...
})

Tier 2: Semantic Tokens

Configurable through config.toml:

// Colors
readonly property color background: _palette.base
readonly property color surface: _palette.surface
readonly property color accent: config.appearance?.accent ?? _palette.blue

// Typography
readonly property string fontFamily: config.appearance?.font_family ?? "Inter"

// Spacing (fixed scale)
readonly property var spacing: ({
    xs: 2, sm: 4, md: 8, lg: 12, xl: 16, xxl: 24
})

// Animation
readonly property var duration: ({
    instant: 0, fast: 100, normal: 200, slow: 300
})

Tier 3: Component Tokens

Internal mappings used by components:

// Bar
readonly property color barBackground: background
readonly property int barWidth: config.bar?.width ?? 48

// Module
readonly property color moduleBackground: surface
readonly property int moduleRadius: radius.md

// Button
readonly property color buttonBackgroundHover: surfaceHover

Using Tokens

Import the config module and access via Config.Theme:

import "../config" as Config

Rectangle {
    color: Config.Theme.barBackground
    radius: Config.Theme.moduleRadius

    Text {
        color: Config.Theme.foreground
        font.family: Config.Theme.fontFamily
        font.pixelSize: Config.Theme.fontSize.md
    }
}

Why Three Tiers?

TierWho ControlsPurpose
1Fern developersConsistent base colors
2UsersCustomization without breaking
3Component authorsSemantic meaning for UI

Benefits:

  • Users can't break layouts by changing primitives
  • Components use meaningful names, not raw colors
  • Theme switching is automatic (just change _palette)

File

  • /fern/config/Theme.qml

Development Setup

Get your development environment ready for contributing to Fern Shell.

Prerequisites

  • Nix with flakes enabled
  • Hyprland compositor
  • A code editor with QML support (recommended: VS Code with QML extension)

Clone and Enter Dev Shell

git clone https://github.com/adanoelle/fern-shell
cd fern-shell
nix develop

The dev shell provides:

  • QuickShell for running QML
  • Qt6 development tools
  • Rust toolchain for fernctl
  • mdbook for documentation
  • Formatting tools (nixfmt, rustfmt)

Running the Shell

# Live preview with hot-reload
qs -p fern/shell.qml

Edit any QML file and save - changes appear immediately.

Building

# Build fernctl (Rust CLI)
cargo build -p fernctl

# Build everything via Nix
nix build

# Run CI checks locally
nix flake check

Project Structure

fern-shell/
├── fern/           # QML frontend
├── fernctl/        # Rust backend (CLI)
├── book/           # Documentation (mdbook)
├── flake-parts/    # Nix modules
└── tests/          # Test infrastructure

Next Steps

Architecture

Fern Shell uses a hybrid QML + Rust architecture with clear separation of concerns.

High-Level Overview

┌─────────────────────────────────────────────┐
│           User's NixOS/Home-Manager         │
│      programs.fern-shell.enable = true      │
└────────────────────┬────────────────────────┘
                     │
┌────────────────────▼────────────────────────┐
│              Fern Shell                     │
│  ┌────────────────────────────────────────┐ │
│  │        QML/QuickShell Frontend         │ │
│  │  - Panel with modules                  │ │
│  │  - Live-reloadable                     │ │
│  │  - Wayland layer-shell                 │ │
│  └────────────────────────────────────────┘ │
│  ┌────────────────────────────────────────┐ │
│  │        Rust Backend (fernctl)          │ │
│  │  - Configuration management            │ │
│  │  - Theme token generation              │ │
│  │  - File watching                       │ │
│  └────────────────────────────────────────┘ │
└─────────────────────────────────────────────┘

Dual-Window System

Each screen has two Wayland windows:

WindowPurposeExclusive Zone
panelWindowVisual renderingNone (Ignore)
exclusionWindowSpace reservationDynamic (bar width)

Why two windows?

  • Visual effects (curved border) need full-screen coverage
  • Exclusive zones are rectangular (just the bar area)
  • Separating them avoids compositor edge cases

Hexagonal Architecture (Rust)

The fernctl crate uses ports & adapters:

┌─────────────────────────────────────────────┐
│                  Domain                     │
│  (pure business logic, zero dependencies)   │
│  - Theme composition                        │
│  - Design tokens                            │
│  - User config mapping                      │
└──────────────────┬──────────────────────────┘
                   │
     ┌─────────────┴─────────────┐
     │                           │
┌────▼────┐                 ┌────▼────┐
│ Inbound │                 │ Outbound│
│  Ports  │                 │  Ports  │
│─────────│                 │─────────│
│ Config  │                 │ Persist │
│ Query   │                 │ Notify  │
│Validate │                 │   IPC   │
└────┬────┘                 └────┬────┘
     │                           │
┌────▼───────────────────────────▼────┐
│              Adapters               │
│  - TOML parser                      │
│  - JSON serializer                  │
│  - File system                      │
│  - D-Bus (future)                   │
└─────────────────────────────────────┘

State Flow

User hovers left edge
  → BarInteractions.containsMouse = true
    → bar.isHovered = true
      → BarWrapper state: "" → "visible"
        → implicitWidth: 4 → 48
          → Border mask updates
          → Backgrounds width updates
          → exclusionWindow.exclusiveZone updates
            → Compositor pushes windows right

All updates happen through QML property bindings - no imperative code.

Key Design Decisions

QML + QuickShell over GTK

  • Live reload during development
  • Declarative UI with reactive bindings
  • Strong animation support

Hyprland-Specific

  • Direct workspace integration via IPC
  • Layer-shell protocol for panel windows
  • No abstraction layers for other compositors

Nix Flakes

  • Reproducible builds
  • Easy distribution via flake inputs
  • Home-Manager and NixOS modules

Files

  • /fern/shell.qml - Window setup, screen variants
  • /fernctl/src/lib.rs - Rust crate entry point
  • /fernctl/src/ports/ - Hexagonal interfaces
  • /flake.nix - Nix flake entry point

Adding Modules

Step-by-step guide to creating a new bar module.

Module Structure

Each module is a QML file in /fern/modules/:

// fern/modules/MyModule.qml
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import "../config" as Config
import "../components"

ModuleContainer {
    id: root

    // Required for screen-specific data
    required property ShellScreen screen

    // Size to fit content
    implicitWidth: Config.Theme.barWidth - Config.Theme.spacing.sm * 2
    implicitHeight: content.implicitHeight + padding * 2

    // Your content here
    Item {
        id: content
        anchors.centerIn: parent
        // ...
    }
}

Step 1: Create the File

Create fern/modules/MyModule.qml with the template above.

Step 2: Register in qmldir

Add to /fern/modules/qmldir:

MyModule 1.0 MyModule.qml

Step 3: Add to Bar.qml

Edit /fern/bar/Bar.qml to add your module:

// Add component
Component {
    id: myModuleComponent
    MyModule {
        screen: root.screen
    }
}

// Add to switch statement
sourceComponent: {
    switch (modelData) {
        case "workspaces":
            return workspacesComponent;
        case "clock":
            return clockComponent;
        case "mymodule":              // Add this
            return myModuleComponent;
        case "spacer":
            return spacerComponent;
        default:
            return null;
    }
}

Step 4: Configure

Add to config:

[bar]
modules = ["workspaces", "mymodule", "spacer", "clock"]

[modules.mymodule]
# Your module's options

Example: Battery Module

pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import "../config" as Config
import "../components"

ModuleContainer {
    id: root

    required property ShellScreen screen

    // Battery percentage (mock data for now)
    property int percentage: 75

    implicitWidth: Config.Theme.barWidth - Config.Theme.spacing.sm * 2
    implicitHeight: layout.implicitHeight + padding * 2

    ColumnLayout {
        id: layout
        anchors.centerIn: parent
        spacing: Config.Theme.spacing.xs

        // Battery icon
        Text {
            Layout.alignment: Qt.AlignHCenter
            text: root.percentage > 20 ? "󰁹" : "󰁺"
            font.family: Config.Theme.fontIcon
            font.pixelSize: Config.Theme.iconSize
            color: root.percentage > 20
                ? Config.Theme.foreground
                : Config.Theme.error
        }

        // Percentage
        Text {
            Layout.alignment: Qt.AlignHCenter
            text: root.percentage + "%"
            font.family: Config.Theme.fontMono
            font.pixelSize: Config.Theme.fontSize.sm
            color: Config.Theme.foregroundDim
        }
    }
}

Best Practices

  1. Use required property for explicit dependencies
  2. Use readonly property for computed values
  3. Bind to Theme tokens - never hardcode colors/sizes
  4. Use Behaviors for smooth animations
  5. Use Loader for expensive content that can be unloaded

Testing

Run with live reload:

qs -p fern/shell.qml

Edit your module file - changes appear immediately.

Rust Services

Building backend integrations with the fernctl crate.

Architecture

The fernctl crate uses hexagonal architecture:

Domain (pure logic)
  ↓
Ports (interfaces)
  ↓
Adapters (implementations)

Adding a New Adapter

Step 1: Define the Port

In /fernctl/src/ports/outbound.rs:

#![allow(unused)]
fn main() {
/// Port for battery status monitoring
pub trait BatteryPort {
    /// Get current battery percentage (0-100)
    fn get_percentage(&self) -> Result<u8, FernError>;

    /// Check if charging
    fn is_charging(&self) -> Result<bool, FernError>;
}
}

Step 2: Implement the Adapter

Create /fernctl/src/adapters/battery.rs:

#![allow(unused)]
fn main() {
use crate::error::FernError;
use crate::ports::outbound::BatteryPort;

/// UPower-based battery adapter
pub struct UPowerBattery {
    // Connection state
}

impl UPowerBattery {
    pub fn new() -> Result<Self, FernError> {
        // Initialize UPower connection
        Ok(Self { })
    }
}

impl BatteryPort for UPowerBattery {
    fn get_percentage(&self) -> Result<u8, FernError> {
        // Read from UPower D-Bus
        Ok(75)
    }

    fn is_charging(&self) -> Result<bool, FernError> {
        Ok(false)
    }
}
}

Step 3: Register in mod.rs

Add to /fernctl/src/adapters/mod.rs:

#![allow(unused)]
fn main() {
pub mod battery;
pub use battery::UPowerBattery;
}

Step 4: Feature Gate (Optional)

In Cargo.toml:

[features]
battery = ["dep:zbus"]

[dependencies]
zbus = { version = "4", optional = true }

Error Handling

Use the FernError type with miette integration:

#![allow(unused)]
fn main() {
use crate::error::{FernError, ConfigError};

fn do_something() -> Result<(), FernError> {
    // Convert errors with ?
    let data = read_file()?;

    // Create domain errors
    if data.is_empty() {
        return Err(ConfigError::Empty {
            path: path.to_path_buf(),
        }.into());
    }

    Ok(())
}
}

D-Bus Integration

For system services, use zbus:

#![allow(unused)]
fn main() {
use zbus::blocking::Connection;

pub struct DBusAdapter {
    connection: Connection,
}

impl DBusAdapter {
    pub fn new() -> Result<Self, FernError> {
        let connection = Connection::system()
            .map_err(|e| FernError::Dbus(e.to_string()))?;
        Ok(Self { connection })
    }
}
}

Testing

Use trait objects for mocking:

#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
    use super::*;

    struct MockBattery;

    impl BatteryPort for MockBattery {
        fn get_percentage(&self) -> Result<u8, FernError> {
            Ok(50)
        }

        fn is_charging(&self) -> Result<bool, FernError> {
            Ok(true)
        }
    }

    #[test]
    fn test_battery_logic() {
        let battery = MockBattery;
        assert_eq!(battery.get_percentage().unwrap(), 50);
    }
}
}

Files

  • /fernctl/src/ports/ - Interface definitions
  • /fernctl/src/adapters/ - Concrete implementations
  • /fernctl/src/error/ - Error types

Testing

Test patterns for Fern Shell.

QML Testing

Manual Testing

The primary testing method is visual verification with live reload:

qs -p fern/shell.qml

Edit files and observe changes immediately.

QML Lint

Check for syntax errors and type issues:

nix develop -c qmllint fern/**/*.qml

This runs automatically in CI.

Rust Testing

Unit Tests

cargo test -p fernctl

Tests live alongside code in #[cfg(test)] modules:

#![allow(unused)]
fn main() {
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_theme_composition() {
        let config = UserConfig::default();
        let theme = Theme::from_config(&config);
        assert_eq!(theme.accent, "#89b4fa");
    }
}
}

Integration Tests

Located in /fernctl/tests/:

cargo test --test integration

Doc Tests

Examples in documentation are tested:

#![allow(unused)]
fn main() {
/// Convert user config to theme.
///
/// # Example
///
/// ```
/// use fernctl::domain::UserConfig;
/// let config = UserConfig::default();
/// assert!(config.appearance.theme == "dark");
/// ```
pub fn example() {}
}

Nix Checks

Run all CI checks locally:

nix flake check

This includes:

  • qmllint - QML syntax/type checking
  • cargo test - Rust tests
  • cargo clippy - Rust lints
  • nix build - Package builds successfully

CI/CD

GitHub Actions runs on every push:

# .github/workflows/ci.yml
- name: Run checks
  run: nix flake check

Test Patterns

Mock Services

Use trait objects for testing without real system services:

#![allow(unused)]
fn main() {
trait HyprlandPort {
    fn get_workspaces(&self) -> Vec<Workspace>;
}

struct MockHyprland {
    workspaces: Vec<Workspace>,
}

impl HyprlandPort for MockHyprland {
    fn get_workspaces(&self) -> Vec<Workspace> {
        self.workspaces.clone()
    }
}
}

Snapshot Testing

For configuration output, use insta:

#![allow(unused)]
fn main() {
#[test]
fn test_config_serialization() {
    let config = UserConfig::default();
    let json = serde_json::to_string_pretty(&config).unwrap();
    insta::assert_snapshot!(json);
}
}

Coverage

Generate coverage report:

cargo tarpaulin --out Html
open tarpaulin-report.html

API Reference

Complete API documentation for Fern Shell.

Rust API (fernctl)

The fernctl crate provides the Rust backend for configuration management and system integration.

Key Modules

ModuleDescription
domainPure business logic - themes, tokens, config
portsHexagonal architecture interfaces
adaptersConcrete implementations
commandsCLI command handlers
errorError types with diagnostics

Domain Types

#![allow(unused)]
fn main() {
// Theme composition
use fernctl::domain::Theme;

// Design tokens
use fernctl::domain::tokens::{ColorToken, SpacingToken, RadiusToken};

// User configuration
use fernctl::domain::UserConfig;
}

Port Traits

#![allow(unused)]
fn main() {
// Inbound (what the domain accepts)
use fernctl::ports::inbound::{ConfigPort, QueryPort, ValidatePort};

// Outbound (what the domain needs)
use fernctl::ports::outbound::{PersistPort, NotifyPort, IpcPort};
}

Adapter Implementations

#![allow(unused)]
fn main() {
// TOML configuration
use fernctl::adapters::TomlConfigAdapter;

// JSON serialization
use fernctl::adapters::JsonThemeAdapter;

// File system
use fernctl::adapters::FileSystemPersist;
}

QML API

QML components don't have generated documentation. See the QML Components section for manual documentation.

Key Singletons

SingletonImportPurpose
Theme"../config" as ConfigDesign tokens
Hyprland"../services" as ServicesHyprland IPC

Common Patterns

// Access theme tokens
Config.Theme.accent
Config.Theme.barWidth
Config.Theme.spacing.md

// Access Hyprland state
Services.Hyprland.activeWsId
Services.Hyprland.workspaces

CLI Reference

fernctl --help
CommandDescription
validateCheck config file for errors
convertConvert between formats
queryQuery config values
watchWatch for config changes

See fernctl <command> --help for detailed usage.