FERRAMENTAS LINUX: Understanding and Using Miracle-WM: A Guide to the WebAssembly-Powered Wayland Compositor

sexta-feira, 10 de abril de 2026

Understanding and Using Miracle-WM: A Guide to the WebAssembly-Powered Wayland Compositor

 

Wayland

Learn Miracle-WM's WASM plugin architecture. Step-by-step tutorial for writing custom window rules, keybindings, and animations. Rust API vs. WebAssembly explained.

What Is Miracle-WM and Why Does It Matter?

Miracle-WM is a Wayland compositor inspired by i3 and Sway, built on Canonical’s Mir project. Unlike traditional window managers that lock you into compiled binaries or fragile scripting, Miracle-WM introduces a WebAssembly (WASM) plugin system – allowing you to modify window management, animations, and keybindings with portable, sandboxed code.

This guide explains the core concepts of Miracle-WM’s plugin architecture, shows you how to write a simple plugin, and highlights safety practices. Target audience: intermediate Linux users comfortable with the command line and basic programming concepts.

Prerequisites

  • A Linux distribution with Wayland support (most modern distros)

  • Mir libraries (installed automatically with Miracle-WM on supported distros)
  • Basic familiarity with Rust or WebAssembly (not mandatory, but helpful)
  • A text editor

Core Concepts: Why WebAssembly?

Traditional window managers use:

  • Static configuration files (JSON, YAML) – limited logic
  • IPC sockets – powerful but insecure and fragile
  • Built-in scripting – vendor-specific and often deprecated

Miracle-WM’s WASM approach gives you:

  • Sandboxed execution – plugins cannot crash the compositor or access arbitrary files
  • Language choice – write in Rust, C++, TinyGo, or any language targeting WASM
  • Hot reloading – change behavior without restarting your session

While WASM is sandboxed, a malicious plugin could still disrupt window management. Only load plugins from trusted sources.


Step-by-Step: Your First Miracle-WM Plugin


1. Install Miracle-WM

The project distributes via GitHub releases. Check your distro’s community repositories first, then build from source if needed:

bash
# Example for Debian/Ubuntu (adjust for your distro)
sudo apt install meson ninja-build libmir-dev libwayland-dev
git clone https://github.com/miracle-wm-org/miracle-wm
cd miracle-wm
meson build && ninja -C build
sudo ninja -C build install


RHEL/Fedora note: Use dnf install meson ninja-build mir-devel wayland-devel instead.


2. Understand the Plugin API (Rust)

Miracle-WM 0.9+ provides a Rust API. Create a new Rust project:

bash
cargo new my-miracle-plugin --lib
cd my-miracle-plugin


toml
[package]
name = "my-miracle-plugin"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[dependencies]
miracle-wm-api = "0.9"


3. Write a Simple Plugin

Replace src/lib.rs with:

rust
use miracle_wm_api::prelude::*;

#[no_mangle]
pub extern "C" fn on_window_created(window: &mut Window) -> PluginResult {
    // Log when a window appears (viewable in miracle-wm logs)
    eprintln!("New window created: {}", window.title());
    
    // Resize all new windows to 800x600
    window.set_size(800, 600);
    
    PluginResult::Success
}

#[no_mangle]
pub extern "C" fn on_key_press(key: &KeyEvent) -> PluginResult {
    if key.modifiers.contains(Modifiers::SUPER) && key.sym == "q" {
        // Close focused window when Super+Q is pressed
        let focused = get_focused_window();
        if let Some(mut win) = focused {
            win.close();
        }
    }
    PluginResult::Success
}


4. Compile to WebAssembly

bash
rustup target add wasm32-unknown-unknown
cargo build --target wasm32-unknown-unknown --release


Your plugin will be at target/wasm32-unknown-unknown/release/my_miracle_plugin.wasm.


5. Load the Plugin in Miracle-WM

Create or edit ~/.config/miracle-wm/config.toml:

toml
[plugins]
paths = [
    "/home/<username>/my-miracle-plugin/target/wasm32-unknown-unknown/release/my_miracle_plugin.wasm"
]

[plugins.settings]
enable_logging = true


Verify the plugin loaded:

bash
# Check Miracle-WM logs
journalctl --user -u miracle-wm -f



Expected output on window creation:

text
New window created: Terminal


Safety tip: Use Super+Shift+R to reload config and plugins instead of killing the compositor. This preserves your running applications.

Common Pitfalls and How to Avoid Them

1. Plugin crashes silently

  • Why: WASM traps (e.g., out-of-bounds memory) are caught but may not be logged clearly.
  • Fix: Wrap plugin logic in try/catch (Rust catch_unwind) and return PluginResult::Error.

2. Keybindings conflict with native shortcuts
  • Why: Miracle-WM processes plugins after internal bindings by default.
  • Fix: Set priority = 10 in config under [plugins.settings] to run plugins first.

3. Performance degradation with many plugins
  • Why: Each window event triggers all plugins synchronously.
  • Fix: Use async plugin stubs (if your language supports WASM async) or combine logic into fewer plugins.

4. Cursor theme ignored after plugin load

  • Why: Some plugins override cursor settings inadvertently.
  • Fix: Set [cursor] theme explicitly in config:

  • toml
    [cursor]
    theme = "Adwaita"
    size = 24

Beyond Basics: The New Rust API

Miracle-WM 0.9 introduces a native Rust API for those who don’t need WASM’s sandboxing. This offers:

  • Direct access to Mir internals (lower latency)
  • No WASM compilation step
  • Ability to use system libraries

Trade-off: Plugins become architecture-specific and can crash the compositor if miswritten.

Example Rust API plugin structure (without WASM):

rust
use miracle_wm_rust_api::{Compositor, Plugin};

struct MyPlugin;

impl Plugin for MyPlugin {
    fn init(&mut self, compositor: &mut Compositor) {
        compositor.on_window_created(|win| {
            println!("Window created: {}", win.title());
        });
    }
}

Compile as a cdylib and load via LD_PRELOAD or the same TOML config.



Recommendation: Use WASM for configuration, keybindings, and layout logic. Use Rust API only for performance-critical graphics manipulation.

Further Reading

  • Built-in documentation: man miracle-wm and miracle-wm --help-plugins
  • API reference: info miracle-wm-api (if installed)
  • Example plugins: /usr/share/doc/miracle-wm/examples/ (after installation)
  • Community: GitHub Discussions at github.com/miracle-wm-org/miracle-wm


Suggested reading: 


Linux Command Line and Shell Scripting Bible, 5th Edition by Richard Blum and Christine Bresnahan  

The gold standard in Linux shell scripting guides. Covers fundamentals and advanced topics including functions, sed, gawk, regular expressions, and alternative shells (zsh, tcsh, Korn). Includes new coverage for DevOps engineers deploying applications across distributions and cloud platforms. 704 pages .

Best for: Aspiring and practicing sysadmins needing automation skills


Linux Basics for Hackers by OccupyTheWeb - Amazon


Focuses on networking, scripting, and security in Kali Linux. Rated 4.7 stars with over 2,300 reviews. Great for understanding Linux from a security perspective .

Best for: Those interested in penetration testing and security

Mastering Linux Security and Hardening, 3rd Edition by Donald A. Tevault

A practical guide to protecting Linux systems from cyber attacks. Rated 4.8 stars


Segurança em servidores Linux: Ataque e Defesa por (Chris Binnie) – Novatec Editora, 209 páginas

Aborda a segurança sob a perspectiva de quem ataca e quem defende. Ensina como hackers exploram vulnerabilidades e, mais importante, como bloquear esses vetores de ataque. Tópicos incluem: tornar servidores "invisíveis", monitoramento de arquivos, scripts Nmap, defesa contra DDoS e proteção contra malware.

O livro não é um manual de pentest (teste de invasão), mas sim um guia para administradores que querem antecipar os movimentos do invasor e fortalecer a segurança de seus sistemas.

Melhor para: Administradores que já têm experiência com Linux e desejam aprofundar em segurança de servidores.



Final Notes

Miracle-WM’s WASM plugin system represents a shift toward safer, portable customization in Wayland compositors. By isolating plugin code, you gain flexibility without sacrificing stability. Start with simple keybinding overrides, then explore window rules and animations – all without recompiling the compositor or risking your session.

Remember: Always test new plugins with --dry-run equivalent (if available) or in a nested Wayland session using weston before loading into your primary environment.







Nenhum comentário:

Postar um comentário