halley-wl 0.2.0

Wayland backend and rendering implementation for the Halley Wayland compositor.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use std::env;
use std::error::Error;
use std::fs;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;

use halley_config::{RuntimeTuning, ViewportOutputConfig};

use eventline::{
    FileSetup, LogLevel, LogPolicy, RunHeader, Setup, debug, enable_console_color,
    enable_console_duration, info, scope, warn,
};
use once_cell::sync::OnceCell;
use rustix::process::Signal;
use rustix::runtime::{KernelSigSet, KernelSigaction, kernel_sigaction};

use crate::compositor::interaction::state::ViewportPanAnim;
use crate::compositor::root::Halley;
use crate::input::spawn_command;

mod common;
mod ipc;

pub(crate) use common::{
    RuntimeBackend, auto_backend, ensure_dbus_session_bus_address, ensure_host_display,
    ensure_xdg_runtime_dir, ensure_xwayland_satellite, halley_runtime_dir,
    refresh_portal_services_nonblocking, sync_portal_activation_environment,
};
pub(crate) use ipc::{drain_ipc_commands, init_ipc, publish_outputs, shutdown_ipc};

static XWAYLAND_REQUEST_TX: OnceCell<mpsc::Sender<()>> = OnceCell::new();

// Set to true by the SIGTERM/SIGINT handler so the event loop can exit cleanly,
// allowing Drop impls (including the spawned-children cleanup) to run.
static SHUTDOWN_REQUESTED: AtomicBool = AtomicBool::new(false);

pub(crate) struct LiveCameraState {
    viewport: halley_core::viewport::Viewport,
    zoom_ref_size: halley_core::field::Vec2,
    camera_target_center: halley_core::field::Vec2,
    camera_target_view_size: halley_core::field::Vec2,
    viewport_pan_anim: Option<ViewportPanAnim>,
}

unsafe extern "C" fn handle_shutdown_signal(_: rustix::ffi::c_int) {
    SHUTDOWN_REQUESTED.store(true, Ordering::Relaxed);
}

pub(crate) fn shutdown_requested() -> bool {
    SHUTDOWN_REQUESTED.load(Ordering::Relaxed)
}

pub(crate) fn register_xwayland_request_channel(tx: mpsc::Sender<()>) {
    let _ = XWAYLAND_REQUEST_TX.set(tx);
}

pub(crate) fn request_xwayland_start() {
    if let Some(tx) = XWAYLAND_REQUEST_TX.get() {
        let _ = tx.send(());
    }
}

/// Spawns autostart commands and pushes the resulting Child handles into
/// `st.runtime.spawned_children` so they are tracked for cleanup on exit.
pub(crate) fn run_autostart_commands(
    st: &mut Halley,
    commands: &[String],
    wayland_display: &str,
    label: &str,
) {
    for command in commands {
        let command = command.trim();
        if command.is_empty() {
            continue;
        }
        if let Some(child) = spawn_command(
            command,
            wayland_display,
            &st.runtime.tuning.cursor,
            None,
            label,
        ) {
            st.runtime.spawned_children.push(child);
        }
    }
}

pub(crate) fn capture_live_camera_state(st: &mut Halley) -> LiveCameraState {
    LiveCameraState {
        viewport: st.model.viewport,
        zoom_ref_size: st.model.zoom_ref_size,
        camera_target_center: st.model.camera_target_center,
        camera_target_view_size: st.model.camera_target_view_size,
        viewport_pan_anim: st.input.interaction_state.viewport_pan_anim.take(),
    }
}

pub(crate) fn restore_live_camera_state(st: &mut Halley, state: LiveCameraState) {
    st.model.viewport = state.viewport;
    st.model.zoom_ref_size = state.zoom_ref_size;
    st.model.camera_target_center = state.camera_target_center;
    st.model.camera_target_view_size = state.camera_target_view_size;
    st.input.interaction_state.viewport_pan_anim = state.viewport_pan_anim;
    st.runtime.tuning.viewport_center = st.model.viewport.center;
    st.runtime.tuning.viewport_size = st.model.viewport.size;
}

pub(crate) fn apply_reloaded_tuning(
    st: &mut Halley,
    next: RuntimeTuning,
    config_path: &str,
    wayland_display: &str,
    reason: &str,
) {
    let live_camera = capture_live_camera_state(st);
    st.apply_tuning(next);
    restore_live_camera_state(st, live_camera);
    // Clone to avoid borrow conflict when passing st mutably below.
    let reload_commands = st.runtime.tuning.autostart_on_reload.clone();
    run_autostart_commands(st, &reload_commands, wayland_display, "autostart");
    debug!("{reason}: reloaded config from {}", config_path);
    debug!(
        "resolved zoom: {}",
        st.runtime.tuning.zoom_resolved_summary()
    );
}

fn normalized_tty_viewports(
    tuning: &RuntimeTuning,
) -> Vec<(
    String,
    bool,
    i32,
    i32,
    u32,
    u32,
    Option<i64>,
    u16,
    &'static str,
)> {
    let mut out: Vec<_> = tuning
        .tty_viewports
        .iter()
        .map(|viewport| {
            let refresh_millihz = viewport
                .refresh_rate
                .map(|hz: f64| (hz * 1000.0).round() as i64);
            (
                viewport.connector.clone(),
                viewport.enabled,
                viewport.offset_x,
                viewport.offset_y,
                viewport.width,
                viewport.height,
                refresh_millihz,
                viewport.transform_degrees,
                viewport.vrr.as_str(),
            )
        })
        .collect();
    out.sort_by(|a, b| a.0.cmp(&b.0));
    out
}

pub(crate) fn viewport_section_changed(prev: &RuntimeTuning, next: &RuntimeTuning) -> bool {
    normalized_tty_viewports(prev) != normalized_tty_viewports(next)
}

pub(crate) fn preserve_viewport_section(
    prev: &RuntimeTuning,
    mut next: RuntimeTuning,
) -> RuntimeTuning {
    next.viewport_center = prev.viewport_center;
    next.viewport_size = prev.viewport_size;
    let prev_viewports: std::collections::HashMap<_, _> = prev
        .tty_viewports
        .iter()
        .map(|viewport| (viewport.connector.clone(), viewport.clone()))
        .collect();
    next.tty_viewports = next
        .tty_viewports
        .into_iter()
        .map(|mut viewport| {
            if let Some(prev_viewport) = prev_viewports.get(&viewport.connector) {
                viewport.enabled = prev_viewport.enabled;
                viewport.offset_x = prev_viewport.offset_x;
                viewport.offset_y = prev_viewport.offset_y;
                viewport.width = prev_viewport.width;
                viewport.height = prev_viewport.height;
                viewport.refresh_rate = prev_viewport.refresh_rate;
                viewport.transform_degrees = prev_viewport.transform_degrees;
                viewport.vrr = prev_viewport.vrr;
            }
            viewport
        })
        .collect();
    next
}

pub(crate) fn ensure_default_user_config(tty_viewports: Option<&[ViewportOutputConfig]>) {
    if env::var("HALLEY_WL_CONFIG").is_ok() {
        return;
    }

    let home_path = PathBuf::from(RuntimeTuning::default_home_config_path());
    if home_path.exists() {
        let raw = match fs::read_to_string(&home_path) {
            Ok(raw) => raw,
            Err(err) => {
                warn!(
                    "bootstrap: failed to read existing config {}: {}",
                    home_path.display(),
                    err
                );
                return;
            }
        };

        match RuntimeTuning::update_user_config_text(&raw, tty_viewports.unwrap_or(&[])) {
            Ok(Some(updated)) => {
                if let Err(err) = fs::write(&home_path, updated) {
                    warn!(
                        "bootstrap: failed to update existing config {}: {}",
                        home_path.display(),
                        err
                    );
                } else {
                    info!(
                        "bootstrap: updated existing config {} with missing template entries",
                        home_path.display()
                    );
                }
            }
            Ok(None) => {}
            Err(err) => {
                warn!(
                    "bootstrap: skipped config update for {}: {}",
                    home_path.display(),
                    err
                );
            }
        }
        return;
    }

    let Some(parent) = home_path.parent() else {
        warn!(
            "bootstrap: unable to determine config directory for {}",
            home_path.display()
        );
        return;
    };
    if let Err(err) = fs::create_dir_all(parent) {
        warn!(
            "bootstrap: failed to create config directory {}: {}",
            parent.display(),
            err
        );
        return;
    }

    let rendered = RuntimeTuning::render_fresh_config(tty_viewports.unwrap_or(&[]));
    if let Err(err) = fs::write(&home_path, rendered) {
        warn!(
            "bootstrap: failed to write {} from internal template: {}",
            home_path.display(),
            err
        );
        return;
    }

    info!(
        "bootstrap: wrote {} using internal template",
        home_path.display()
    );
}

pub fn run() -> Result<(), Box<dyn Error>> {
    // Register signal handlers before anything else so that SIGTERM (the
    // default signal sent by `pkill`/`kill`) triggers a clean shutdown.
    // This lets Drop run, which kills all spawned child process groups.
    // Note: SIGKILL (-9) cannot be caught — use plain `pkill` for clean exit.
    SHUTDOWN_REQUESTED.store(false, Ordering::Relaxed);
    unsafe {
        let action = KernelSigaction {
            sa_handler_kernel: Some(handle_shutdown_signal),
            sa_flags: Default::default(),
            sa_mask: KernelSigSet::empty(),
            ..Default::default()
        };
        let _ = kernel_sigaction(Signal::TERM, Some(action.clone()));
        let _ = kernel_sigaction(Signal::INT, Some(action));
    }

    ensure_xdg_runtime_dir()?;
    init_ipc()?;

    let result = match RuntimeBackend::from_env()? {
        RuntimeBackend::Auto => match auto_backend() {
            RuntimeBackend::Tty => run_tty(),
            RuntimeBackend::Winit | RuntimeBackend::Auto => run_winit(),
        },
        RuntimeBackend::Winit => run_winit(),
        RuntimeBackend::Tty => run_tty(),
    };

    shutdown_ipc();
    result
}

pub fn run_session() -> Result<(), Box<dyn Error>> {
    unsafe {
        env::set_var("HALLEY_WL_BACKEND", "tty");
        env::set_var("XDG_SESSION_TYPE", "wayland");
        env::set_var("XDG_CURRENT_DESKTOP", "Halley");
        env::set_var("XDG_SESSION_DESKTOP", "Halley");
        env::set_var("DESKTOP_SESSION", "Halley");
        env::remove_var("DISPLAY");
        env::remove_var("WAYLAND_DISPLAY");
        env::remove_var("WAYLAND_SOCKET");
    }

    run()
}

pub fn run_winit() -> Result<(), Box<dyn Error>> {
    crate::backend::winit::run_winit_backend()
}

pub fn run_tty() -> Result<(), Box<dyn Error>> {
    crate::backend::tty::run_tty_backend()
}

pub(crate) fn init_logging() -> Result<(), Box<dyn Error>> {
    scope!("logging-init", success = "ready", {
        let shared_level = env::var("HALLEY_WL_LOG")
            .ok()
            .and_then(|v| parse_log_level(v.as_str()))
            .unwrap_or(LogLevel::Info);

        let log_file = configured_halley_log_file();
        let file = match log_file.as_ref() {
            Some(None) => Some(FileSetup::Off),
            Some(Some(path)) => Some(FileSetup::Rotating {
                path: path.clone(),
                policy: LogPolicy::default(),
                header: Some(RunHeader::new("halley-wl")),
            }),
            None => default_halley_log_path().map(|path| FileSetup::Rotating {
                path,
                policy: LogPolicy::default(),
                header: Some(RunHeader::new("halley-wl")),
            }),
        };

        if let Err(err) = pollster::block_on(eventline::setup(Setup {
            verbose: true,
            level: Some(shared_level),
            file,
        })) {
            warn!("failed to configure logging: {}", err);
        }

        enable_console_color(true);
        enable_console_duration(false);

        match log_file {
            Some(None) => info!("file logging disabled via HALLEY_WL_LOG_FILE"),
            Some(Some(path)) => info!("file logging enabled: {}", path.display()),
            None => {
                if let Some(path) = default_halley_log_path() {
                    info!("file logging enabled: {}", path.display());
                }
            }
        }

        Ok(())
    })
}

fn parse_log_level(raw: &str) -> Option<LogLevel> {
    match raw.trim().to_ascii_lowercase().as_str() {
        "trace" | "debug" => Some(LogLevel::Debug),
        "info" => Some(LogLevel::Info),
        "warn" | "warning" => Some(LogLevel::Warning),
        "error" => Some(LogLevel::Error),
        "off" => Some(LogLevel::Off),
        _ => None,
    }
}

fn configured_halley_log_file() -> Option<Option<PathBuf>> {
    let raw = env::var("HALLEY_WL_LOG_FILE").ok()?;
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return None;
    }
    if matches!(trimmed.to_ascii_lowercase().as_str(), "off" | "false" | "0") {
        return Some(None);
    }
    Some(Some(expand_user_path(trimmed)))
}

fn default_halley_log_path() -> Option<PathBuf> {
    halley_runtime_dir().ok().map(|dir| dir.join("halley.log"))
}

fn expand_user_path(raw: &str) -> PathBuf {
    if raw == "~" {
        return env::var_os("HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from(raw));
    }
    if let Some(rest) = raw.strip_prefix("~/") {
        return env::var_os("HOME")
            .map(|home| PathBuf::from(home).join(rest))
            .unwrap_or_else(|| PathBuf::from(raw));
    }
    PathBuf::from(raw)
}