niri
Clone
https://git.tahinli.com/Tahinli/niri.git
0 watching·0 forks·Rust·GPL-3.0·12.1 MiB·b0eb8ad·Ivan Molodetskikh·3 months ago·2857 commits
| 1 | #[macro_use] |
| 2 | extern crate tracing; |
| 3 | |
| 4 | use std::fmt::Write as _; |
| 5 | use std::fs::File; |
| 6 | use std::io::{self, Write}; |
| 7 | use std::os::fd::FromRawFd; |
| 8 | use std::path::PathBuf; |
| 9 | use std::process::Command; |
| 10 | use std::sync::atomic::Ordering; |
| 11 | use std::{env, mem}; |
| 12 | |
| 13 | use calloop::EventLoop; |
| 14 | use clap::{CommandFactory, Parser}; |
| 15 | use clap_complete::Shell; |
| 16 | use clap_complete_nushell::Nushell; |
| 17 | use directories::ProjectDirs; |
| 18 | use niri::cli::{Cli, CompletionShell, Sub}; |
| 19 | #[cfg(feature = "dbus")] |
| 20 | use niri::dbus; |
| 21 | use niri::ipc::client::handle_msg; |
| 22 | use niri::niri::State; |
| 23 | use niri::utils::spawning::{ |
| 24 | spawn, spawn_sh, store_and_increase_nofile_rlimit, CHILD_DISPLAY, CHILD_ENV, |
| 25 | REMOVE_ENV_RUST_BACKTRACE, REMOVE_ENV_RUST_LIB_BACKTRACE, |
| 26 | }; |
| 27 | use niri::utils::{cause_panic, version, watcher, xwayland, IS_SYSTEMD_SERVICE}; |
| 28 | use niri_config::{Config, ConfigPath}; |
| 29 | use niri_ipc::socket::SOCKET_PATH_ENV; |
| 30 | use sd_notify::NotifyState; |
| 31 | use smithay::reexports::wayland_server::Display; |
| 32 | use tracing_subscriber::EnvFilter; |
| 33 | |
| 34 | const DEFAULT_LOG_FILTER: &str = "niri=debug,smithay::backend::renderer::gles=error"; |
| 35 | |
| 36 | #[cfg(feature = "profile-with-tracy-allocations")] |
| 37 | #[global_allocator] |
| 38 | static GLOBAL: tracy_client::ProfiledAllocator<std::alloc::System> = |
| 39 | tracy_client::ProfiledAllocator::new(std::alloc::System, 100); |
| 40 | |
| 41 | fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 42 | // Set backtrace defaults if not set. |
| 43 | if env::var_os("RUST_BACKTRACE").is_none() { |
| 44 | env::set_var("RUST_BACKTRACE", "1"); |
| 45 | REMOVE_ENV_RUST_BACKTRACE.store(true, Ordering::Relaxed); |
| 46 | } |
| 47 | if env::var_os("RUST_LIB_BACKTRACE").is_none() { |
| 48 | env::set_var("RUST_LIB_BACKTRACE", "0"); |
| 49 | REMOVE_ENV_RUST_LIB_BACKTRACE.store(true, Ordering::Relaxed); |
| 50 | } |
| 51 | |
| 52 | let directives = env::var("RUST_LOG").unwrap_or_else(|_| DEFAULT_LOG_FILTER.to_owned()); |
| 53 | let env_filter = EnvFilter::builder().parse_lossy(directives); |
| 54 | tracing_subscriber::fmt() |
| 55 | .compact() |
| 56 | .with_writer(io::stderr) |
| 57 | .with_env_filter(env_filter) |
| 58 | .with_ansi_sanitization(false) |
| 59 | .init(); |
| 60 | |
| 61 | if env::var_os("NOTIFY_SOCKET").is_some() { |
| 62 | IS_SYSTEMD_SERVICE.store(true, Ordering::Relaxed); |
| 63 | |
| 64 | #[cfg(not(feature = "systemd"))] |
| 65 | warn!( |
| 66 | "running as a systemd service, but systemd support is compiled out. \ |
| 67 | Are you sure you did not forget to set `--features systemd`?" |
| 68 | ); |
| 69 | } |
| 70 | |
| 71 | let cli = Cli::parse(); |
| 72 | |
| 73 | if cli.session { |
| 74 | // If we're starting as a session, assume that the intention is to start on a TTY unless |
| 75 | // this is a WSL environment. Remove DISPLAY, WAYLAND_DISPLAY or WAYLAND_SOCKET from our |
| 76 | // environment if they are set, since they will cause the winit backend to be selected |
| 77 | // instead. |
| 78 | if env::var_os("WSL_DISTRO_NAME").is_none() { |
| 79 | if env::var_os("DISPLAY").is_some() { |
| 80 | warn!("running as a session but DISPLAY is set, removing it"); |
| 81 | env::remove_var("DISPLAY"); |
| 82 | } |
| 83 | if env::var_os("WAYLAND_DISPLAY").is_some() { |
| 84 | warn!("running as a session but WAYLAND_DISPLAY is set, removing it"); |
| 85 | env::remove_var("WAYLAND_DISPLAY"); |
| 86 | } |
| 87 | if env::var_os("WAYLAND_SOCKET").is_some() { |
| 88 | warn!("running as a session but WAYLAND_SOCKET is set, removing it"); |
| 89 | env::remove_var("WAYLAND_SOCKET"); |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | // Set the current desktop for xdg-desktop-portal. |
| 94 | env::set_var("XDG_CURRENT_DESKTOP", "niri"); |
| 95 | // Ensure the session type is set to Wayland for xdg-autostart and Qt apps. |
| 96 | env::set_var("XDG_SESSION_TYPE", "wayland"); |
| 97 | } |
| 98 | |
| 99 | // Handle subcommands. |
| 100 | if let Some(subcommand) = cli.subcommand { |
| 101 | match subcommand { |
| 102 | Sub::Validate { config } => { |
| 103 | tracy_client::Client::start(); |
| 104 | |
| 105 | config_path(config).load().config?; |
| 106 | info!("config is valid"); |
| 107 | return Ok(()); |
| 108 | } |
| 109 | Sub::Msg { msg, json } => { |
| 110 | handle_msg(msg, json)?; |
| 111 | return Ok(()); |
| 112 | } |
| 113 | Sub::Panic => cause_panic(), |
| 114 | Sub::Completions { shell } => { |
| 115 | match shell { |
| 116 | CompletionShell::Nushell => { |
| 117 | clap_complete::generate( |
| 118 | Nushell, |
| 119 | &mut Cli::command(), |
| 120 | "niri", |
| 121 | &mut io::stdout(), |
| 122 | ); |
| 123 | } |
| 124 | other => { |
| 125 | let generator = Shell::try_from(other).unwrap(); |
| 126 | clap_complete::generate( |
| 127 | generator, |
| 128 | &mut Cli::command(), |
| 129 | "niri", |
| 130 | &mut io::stdout(), |
| 131 | ); |
| 132 | } |
| 133 | } |
| 134 | return Ok(()); |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | // Needs to be done before starting Tracy, so that it applies to Tracy's threads. |
| 140 | niri::utils::signals::block_early().unwrap(); |
| 141 | |
| 142 | // Avoid starting Tracy for the `niri msg` code path since starting/stopping Tracy is a bit |
| 143 | // slow. |
| 144 | tracy_client::Client::start(); |
| 145 | |
| 146 | // In on-demand mode, we must shut down Tracy manually to terminate the connection cleanly. |
| 147 | // Do it from a Drop impl here, so that it runs after the Drop code for all of the state created |
| 148 | // below, because some of those Drop impls themselves create Tracy spans. |
| 149 | let _shutdown_tracy = ShutdownTracy; |
| 150 | |
| 151 | info!("starting version {}", &version()); |
| 152 | |
| 153 | // Load the config. |
| 154 | let config_path = config_path(cli.config); |
| 155 | env::remove_var("NIRI_CONFIG"); |
| 156 | let (config_created_at, config_load_result) = config_path.load_or_create(); |
| 157 | let config_errored = config_load_result.config.is_err(); |
| 158 | let mut config = config_load_result.config.unwrap_or_else(|err| { |
| 159 | warn!("{err:?}"); |
| 160 | Config::load_default() |
| 161 | }); |
| 162 | let config_includes = config_load_result.includes; |
| 163 | |
| 164 | let spawn_at_startup = mem::take(&mut config.spawn_at_startup); |
| 165 | let spawn_sh_at_startup = mem::take(&mut config.spawn_sh_at_startup); |
| 166 | *CHILD_ENV.write().unwrap() = mem::take(&mut config.environment); |
| 167 | |
| 168 | store_and_increase_nofile_rlimit(); |
| 169 | |
| 170 | // Create the main event loop. |
| 171 | let mut event_loop = EventLoop::<State>::try_new().unwrap(); |
| 172 | |
| 173 | // Handle Ctrl+C and other signals. |
| 174 | niri::utils::signals::listen(&event_loop.handle()); |
| 175 | |
| 176 | // Create the compositor. |
| 177 | let display = Display::new().unwrap(); |
| 178 | |
| 179 | // Increase the buffer size so that it's harder to crash a frozen client with a 1000 Hz mouse. |
| 180 | set_default_max_buffer_size(&display, 1024 * 1024); |
| 181 | |
| 182 | let mut state = State::new( |
| 183 | config, |
| 184 | event_loop.handle(), |
| 185 | event_loop.get_signal(), |
| 186 | display, |
| 187 | false, |
| 188 | true, |
| 189 | cli.session, |
| 190 | ) |
| 191 | .unwrap(); |
| 192 | |
| 193 | // Set WAYLAND_DISPLAY for children. |
| 194 | let socket_name = state.niri.socket_name.as_deref().unwrap(); |
| 195 | env::set_var("WAYLAND_DISPLAY", socket_name); |
| 196 | info!( |
| 197 | "listening on Wayland socket: {}", |
| 198 | socket_name.to_string_lossy() |
| 199 | ); |
| 200 | |
| 201 | // Set NIRI_SOCKET for children. |
| 202 | if let Some(ipc) = &state.niri.ipc_server { |
| 203 | let socket_path = ipc.socket_path.as_deref().unwrap(); |
| 204 | env::set_var(SOCKET_PATH_ENV, socket_path); |
| 205 | info!("IPC listening on: {}", socket_path.to_string_lossy()); |
| 206 | } |
| 207 | |
| 208 | // Setup xwayland-satellite integration. |
| 209 | xwayland::satellite::setup(&mut state); |
| 210 | if let Some(satellite) = &state.niri.satellite { |
| 211 | let name = satellite.display_name(); |
| 212 | *CHILD_DISPLAY.write().unwrap() = Some(name.to_owned()); |
| 213 | env::set_var("DISPLAY", name); |
| 214 | info!("listening on X11 socket: {name}"); |
| 215 | } else { |
| 216 | // Avoid spawning children in the host X11. |
| 217 | env::remove_var("DISPLAY"); |
| 218 | } |
| 219 | |
| 220 | if cli.session { |
| 221 | // We're starting as a session. Import our variables. |
| 222 | import_environment(); |
| 223 | |
| 224 | // Inhibit power key handling so we can suspend on it. |
| 225 | #[cfg(feature = "dbus")] |
| 226 | if !state.niri.config.borrow().input.disable_power_key_handling { |
| 227 | if let Err(err) = state.niri.inhibit_power_key() { |
| 228 | warn!("error inhibiting power key: {err:?}"); |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | #[cfg(feature = "dbus")] |
| 234 | dbus::DBusServers::start(&mut state, cli.session); |
| 235 | |
| 236 | #[cfg(feature = "dbus")] |
| 237 | if cli.session { |
| 238 | state.niri.a11y.start(); |
| 239 | } |
| 240 | |
| 241 | if env::var_os("NIRI_DISABLE_SYSTEM_MANAGER_NOTIFY").is_none_or(|x| x != "1") { |
| 242 | // Notify systemd we're ready. |
| 243 | if let Err(err) = sd_notify::notify(&[NotifyState::Ready]) { |
| 244 | warn!("error notifying systemd: {err:?}"); |
| 245 | }; |
| 246 | |
| 247 | // Send ready notification to the NOTIFY_FD file descriptor. |
| 248 | if let Err(err) = notify_fd() { |
| 249 | warn!("error notifying fd: {err:?}"); |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | watcher::setup(&mut state, &config_path, config_includes); |
| 254 | |
| 255 | // Spawn commands from cli and auto-start. |
| 256 | spawn(cli.command, None); |
| 257 | |
| 258 | for elem in spawn_at_startup { |
| 259 | spawn(elem.command, None); |
| 260 | } |
| 261 | for elem in spawn_sh_at_startup { |
| 262 | spawn_sh(elem.command, None); |
| 263 | } |
| 264 | |
| 265 | // Show the config error notification right away if needed. |
| 266 | if config_errored { |
| 267 | state.niri.config_error_notification.show(); |
| 268 | state.ipc_config_loaded(true); |
| 269 | } else if let Some(path) = config_created_at { |
| 270 | state.niri.config_error_notification.show_created(path); |
| 271 | } |
| 272 | |
| 273 | // Run the compositor. |
| 274 | event_loop |
| 275 | .run(None, &mut state, |state| state.refresh_and_flush_clients()) |
| 276 | .unwrap(); |
| 277 | |
| 278 | Ok(()) |
| 279 | } |
| 280 | |
| 281 | fn import_environment() { |
| 282 | let variables = [ |
| 283 | "WAYLAND_DISPLAY", |
| 284 | "DISPLAY", |
| 285 | "XDG_CURRENT_DESKTOP", |
| 286 | "XDG_SESSION_TYPE", |
| 287 | SOCKET_PATH_ENV, |
| 288 | ] |
| 289 | .join(" "); |
| 290 | |
| 291 | let mut init_system_import = String::new(); |
| 292 | if cfg!(feature = "systemd") { |
| 293 | write!( |
| 294 | init_system_import, |
| 295 | "systemctl --user import-environment {variables};" |
| 296 | ) |
| 297 | .unwrap(); |
| 298 | } |
| 299 | if cfg!(feature = "dinit") { |
| 300 | write!(init_system_import, "dinitctl setenv {variables};").unwrap(); |
| 301 | } |
| 302 | |
| 303 | let rv = Command::new("/bin/sh") |
| 304 | .args([ |
| 305 | "-c", |
| 306 | &format!( |
| 307 | "{init_system_import}\ |
| 308 | hash dbus-update-activation-environment 2>/dev/null && \ |
| 309 | dbus-update-activation-environment {variables}" |
| 310 | ), |
| 311 | ]) |
| 312 | .spawn(); |
| 313 | // Wait for the import process to complete, otherwise services will start too fast without |
| 314 | // environment variables available. |
| 315 | match rv { |
| 316 | Ok(mut child) => match child.wait() { |
| 317 | Ok(status) => { |
| 318 | if !status.success() { |
| 319 | warn!("import environment shell exited with {status}"); |
| 320 | } |
| 321 | } |
| 322 | Err(err) => { |
| 323 | warn!("error waiting for import environment shell: {err:?}"); |
| 324 | } |
| 325 | }, |
| 326 | Err(err) => { |
| 327 | warn!("error spawning shell to import environment: {err:?}"); |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | fn env_config_path() -> Option<PathBuf> { |
| 333 | env::var_os("NIRI_CONFIG") |
| 334 | .filter(|x| !x.is_empty()) |
| 335 | .map(PathBuf::from) |
| 336 | } |
| 337 | |
| 338 | fn default_config_path() -> Option<PathBuf> { |
| 339 | let Some(dirs) = ProjectDirs::from("", "", "niri") else { |
| 340 | warn!("error retrieving home directory"); |
| 341 | return None; |
| 342 | }; |
| 343 | |
| 344 | let mut path = dirs.config_dir().to_owned(); |
| 345 | path.push("config.kdl"); |
| 346 | Some(path) |
| 347 | } |
| 348 | |
| 349 | fn system_config_path() -> PathBuf { |
| 350 | PathBuf::from("/etc/niri/config.kdl") |
| 351 | } |
| 352 | |
| 353 | fn config_path(cli_path: Option<PathBuf>) -> ConfigPath { |
| 354 | if let Some(explicit) = cli_path.or_else(env_config_path) { |
| 355 | return ConfigPath::Explicit(explicit); |
| 356 | } |
| 357 | |
| 358 | let system_path = system_config_path(); |
| 359 | |
| 360 | if let Some(user_path) = default_config_path() { |
| 361 | ConfigPath::Regular { |
| 362 | user_path, |
| 363 | system_path, |
| 364 | } |
| 365 | } else { |
| 366 | // Couldn't find the home directory, or whatever. |
| 367 | ConfigPath::Explicit(system_path) |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | fn notify_fd() -> anyhow::Result<()> { |
| 372 | let fd = match env::var("NOTIFY_FD") { |
| 373 | Ok(notify_fd) => notify_fd.parse()?, |
| 374 | Err(env::VarError::NotPresent) => return Ok(()), |
| 375 | Err(err) => return Err(err.into()), |
| 376 | }; |
| 377 | env::remove_var("NOTIFY_FD"); |
| 378 | let mut notif = unsafe { File::from_raw_fd(fd) }; |
| 379 | notif.write_all(b"READY=1\n")?; |
| 380 | Ok(()) |
| 381 | } |
| 382 | |
| 383 | // The wayland-server crate has set_default_max_buffer_size() under a libwayland_1_23 feature, but |
| 384 | // this hard-requires libwayland-server >= 1.23 which is not present on e.g. Ubuntu 24.04. Since |
| 385 | // calling this is an optional enhancement, do it optionally at runtime. |
| 386 | fn set_default_max_buffer_size(display: &Display<State>, size: usize) { |
| 387 | use std::ffi::c_void; |
| 388 | |
| 389 | unsafe { |
| 390 | // RTLD_NOLOAD ensures we only get a handle to the libwayland-server that wayland-rs has |
| 391 | // already loaded into this process, rather than potentially pulling in a different copy. |
| 392 | let lib = libc::dlopen( |
| 393 | c"libwayland-server.so.0".as_ptr(), |
| 394 | libc::RTLD_LAZY | libc::RTLD_NOLOAD, |
| 395 | ); |
| 396 | if lib.is_null() { |
| 397 | // It's not really expected that this can happen, maybe if some distro changes the |
| 398 | // library name? |
| 399 | warn!("cannot set default max buffer size: libwayland-server.so.0 is not loaded"); |
| 400 | return; |
| 401 | } |
| 402 | |
| 403 | let sym = libc::dlsym(lib, c"wl_display_set_default_max_buffer_size".as_ptr()); |
| 404 | if sym.is_null() { |
| 405 | // Expected on libwayland-server < 1.23. |
| 406 | trace!("wl_display_set_default_max_buffer_size is missing; skipping"); |
| 407 | } else { |
| 408 | let func: unsafe extern "C" fn(*mut c_void, libc::size_t) = std::mem::transmute(sym); |
| 409 | let display_ptr = display.handle().backend_handle().display_ptr(); |
| 410 | func(display_ptr.cast(), size); |
| 411 | } |
| 412 | |
| 413 | libc::dlclose(lib); |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | struct ShutdownTracy; |
| 418 | impl Drop for ShutdownTracy { |
| 419 | fn drop(&mut self) { |
| 420 | #[cfg(feature = "profile-with-tracy-ondemand")] |
| 421 | unsafe { |
| 422 | tracy_client::sys::___tracy_shutdown_profiler(); |
| 423 | } |
| 424 | } |
| 425 | } |