niri
Clone
https://git.tahinli.com/Tahinli/niri.git
0 watching·0 forks·Rust·GPL-3.0·12.1 MiB·9d8f4f8·Ivan Molodetskikh·1 month ago·2997 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 { |
| 110 | msg, |
| 111 | json, |
| 112 | print_request, |
| 113 | } => { |
| 114 | handle_msg(msg, json, print_request)?; |
| 115 | return Ok(()); |
| 116 | } |
| 117 | Sub::Panic => cause_panic(), |
| 118 | Sub::Completions { shell } => { |
| 119 | match shell { |
| 120 | CompletionShell::Nushell => { |
| 121 | clap_complete::generate( |
| 122 | Nushell, |
| 123 | &mut Cli::command(), |
| 124 | "niri", |
| 125 | &mut io::stdout(), |
| 126 | ); |
| 127 | } |
| 128 | other => { |
| 129 | let generator = Shell::try_from(other).unwrap(); |
| 130 | clap_complete::generate( |
| 131 | generator, |
| 132 | &mut Cli::command(), |
| 133 | "niri", |
| 134 | &mut io::stdout(), |
| 135 | ); |
| 136 | } |
| 137 | } |
| 138 | return Ok(()); |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | // Needs to be done before starting Tracy, so that it applies to Tracy's threads. |
| 144 | niri::utils::signals::block_early().unwrap(); |
| 145 | |
| 146 | // Avoid starting Tracy for the `niri msg` code path since starting/stopping Tracy is a bit |
| 147 | // slow. |
| 148 | tracy_client::Client::start(); |
| 149 | |
| 150 | // In on-demand mode, we must shut down Tracy manually to terminate the connection cleanly. |
| 151 | // Do it from a Drop impl here, so that it runs after the Drop code for all of the state created |
| 152 | // below, because some of those Drop impls themselves create Tracy spans. |
| 153 | let _shutdown_tracy = ShutdownTracy; |
| 154 | |
| 155 | info!("starting version {}", &version()); |
| 156 | |
| 157 | // Load the config. |
| 158 | let config_path = config_path(cli.config); |
| 159 | env::remove_var("NIRI_CONFIG"); |
| 160 | let (config_created_at, config_load_result) = config_path.load_or_create(); |
| 161 | let config_errored = config_load_result.config.is_err(); |
| 162 | let mut config = config_load_result.config.unwrap_or_else(|err| { |
| 163 | warn!("{err:?}"); |
| 164 | Config::load_default() |
| 165 | }); |
| 166 | let config_includes = config_load_result.includes; |
| 167 | |
| 168 | let spawn_at_startup = mem::take(&mut config.spawn_at_startup); |
| 169 | let spawn_sh_at_startup = mem::take(&mut config.spawn_sh_at_startup); |
| 170 | *CHILD_ENV.write().unwrap() = mem::take(&mut config.environment); |
| 171 | |
| 172 | store_and_increase_nofile_rlimit(); |
| 173 | |
| 174 | // Create the main event loop. |
| 175 | let mut event_loop = EventLoop::<State>::try_new().unwrap(); |
| 176 | |
| 177 | // Handle Ctrl+C and other signals. |
| 178 | niri::utils::signals::listen(&event_loop.handle()); |
| 179 | |
| 180 | // Create the compositor. |
| 181 | let display = Display::new().unwrap(); |
| 182 | |
| 183 | // Increase the buffer size so that it's harder to crash a frozen client with a 1000 Hz mouse. |
| 184 | set_default_max_buffer_size(&display, 1024 * 1024); |
| 185 | |
| 186 | let mut state = State::new( |
| 187 | config, |
| 188 | event_loop.handle(), |
| 189 | event_loop.get_signal(), |
| 190 | display, |
| 191 | false, |
| 192 | true, |
| 193 | cli.session, |
| 194 | ) |
| 195 | .unwrap(); |
| 196 | |
| 197 | // Set WAYLAND_DISPLAY for children. |
| 198 | let socket_name = state.niri.socket_name.as_deref().unwrap(); |
| 199 | env::set_var("WAYLAND_DISPLAY", socket_name); |
| 200 | info!( |
| 201 | "listening on Wayland socket: {}", |
| 202 | socket_name.to_string_lossy() |
| 203 | ); |
| 204 | |
| 205 | // Set NIRI_SOCKET for children. |
| 206 | if let Some(ipc) = &state.niri.ipc_server { |
| 207 | let socket_path = ipc.socket_path.as_deref().unwrap(); |
| 208 | env::set_var(SOCKET_PATH_ENV, socket_path); |
| 209 | info!("IPC listening on: {}", socket_path.to_string_lossy()); |
| 210 | } |
| 211 | |
| 212 | // Setup xwayland-satellite integration. |
| 213 | xwayland::satellite::setup(&mut state); |
| 214 | if let Some(satellite) = &state.niri.satellite { |
| 215 | let name = satellite.display_name(); |
| 216 | *CHILD_DISPLAY.write().unwrap() = Some(name.to_owned()); |
| 217 | env::set_var("DISPLAY", name); |
| 218 | info!("listening on X11 socket: {name}"); |
| 219 | } else { |
| 220 | // Avoid spawning children in the host X11. |
| 221 | env::remove_var("DISPLAY"); |
| 222 | } |
| 223 | |
| 224 | if cli.session { |
| 225 | // We're starting as a session. Import our variables. |
| 226 | import_environment(); |
| 227 | |
| 228 | // Inhibit power key handling so we can suspend on it. |
| 229 | #[cfg(feature = "dbus")] |
| 230 | if !state.niri.config.borrow().input.disable_power_key_handling { |
| 231 | if let Err(err) = state.niri.inhibit_power_key() { |
| 232 | warn!("error inhibiting power key: {err:?}"); |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | #[cfg(feature = "dbus")] |
| 238 | dbus::DBusServers::start(&mut state, cli.session); |
| 239 | |
| 240 | #[cfg(feature = "dbus")] |
| 241 | if cli.session { |
| 242 | state.niri.a11y.start(); |
| 243 | } |
| 244 | |
| 245 | if env::var_os("NIRI_DISABLE_SYSTEM_MANAGER_NOTIFY").is_none_or(|x| x != "1") { |
| 246 | // Notify systemd we're ready. |
| 247 | if let Err(err) = sd_notify::notify(&[NotifyState::Ready]) { |
| 248 | warn!("error notifying systemd: {err:?}"); |
| 249 | }; |
| 250 | |
| 251 | // Send ready notification to the NOTIFY_FD file descriptor. |
| 252 | if let Err(err) = notify_fd() { |
| 253 | warn!("error notifying fd: {err:?}"); |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | watcher::setup(&mut state, &config_path, config_includes); |
| 258 | |
| 259 | // Spawn commands from cli and auto-start. |
| 260 | spawn(cli.command, None); |
| 261 | |
| 262 | for elem in spawn_at_startup { |
| 263 | spawn(elem.command, None); |
| 264 | } |
| 265 | for elem in spawn_sh_at_startup { |
| 266 | spawn_sh(elem.command, None); |
| 267 | } |
| 268 | |
| 269 | // Show the config error notification right away if needed. |
| 270 | if config_errored { |
| 271 | state.niri.config_error_notification.show(); |
| 272 | state.ipc_config_loaded(true); |
| 273 | } else if let Some(path) = config_created_at { |
| 274 | state.niri.config_error_notification.show_created(path); |
| 275 | } |
| 276 | |
| 277 | // Run the compositor. |
| 278 | event_loop |
| 279 | .run(None, &mut state, |state| state.refresh_and_flush_clients()) |
| 280 | .unwrap(); |
| 281 | |
| 282 | Ok(()) |
| 283 | } |
| 284 | |
| 285 | fn import_environment() { |
| 286 | let variables = [ |
| 287 | "WAYLAND_DISPLAY", |
| 288 | "DISPLAY", |
| 289 | "XDG_CURRENT_DESKTOP", |
| 290 | "XDG_SESSION_TYPE", |
| 291 | SOCKET_PATH_ENV, |
| 292 | ] |
| 293 | .join(" "); |
| 294 | |
| 295 | let mut init_system_import = String::new(); |
| 296 | if cfg!(feature = "systemd") { |
| 297 | write!( |
| 298 | init_system_import, |
| 299 | "systemctl --user import-environment {variables};" |
| 300 | ) |
| 301 | .unwrap(); |
| 302 | } |
| 303 | if cfg!(feature = "dinit") { |
| 304 | write!(init_system_import, "dinitctl setenv {variables};").unwrap(); |
| 305 | } |
| 306 | |
| 307 | let rv = Command::new("/bin/sh") |
| 308 | .args([ |
| 309 | "-c", |
| 310 | &format!( |
| 311 | "{init_system_import}\ |
| 312 | hash dbus-update-activation-environment 2>/dev/null && \ |
| 313 | dbus-update-activation-environment {variables}" |
| 314 | ), |
| 315 | ]) |
| 316 | .spawn(); |
| 317 | // Wait for the import process to complete, otherwise services will start too fast without |
| 318 | // environment variables available. |
| 319 | match rv { |
| 320 | Ok(mut child) => match child.wait() { |
| 321 | Ok(status) => { |
| 322 | if !status.success() { |
| 323 | warn!("import environment shell exited with {status}"); |
| 324 | } |
| 325 | } |
| 326 | Err(err) => { |
| 327 | warn!("error waiting for import environment shell: {err:?}"); |
| 328 | } |
| 329 | }, |
| 330 | Err(err) => { |
| 331 | warn!("error spawning shell to import environment: {err:?}"); |
| 332 | } |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | fn env_config_path() -> Option<PathBuf> { |
| 337 | env::var_os("NIRI_CONFIG") |
| 338 | .filter(|x| !x.is_empty()) |
| 339 | .map(PathBuf::from) |
| 340 | } |
| 341 | |
| 342 | fn default_config_path() -> Option<PathBuf> { |
| 343 | let Some(dirs) = ProjectDirs::from("", "", "niri") else { |
| 344 | warn!("error retrieving home directory"); |
| 345 | return None; |
| 346 | }; |
| 347 | |
| 348 | let mut path = dirs.config_dir().to_owned(); |
| 349 | path.push("config.kdl"); |
| 350 | Some(path) |
| 351 | } |
| 352 | |
| 353 | fn system_config_path() -> PathBuf { |
| 354 | PathBuf::from("/etc/niri/config.kdl") |
| 355 | } |
| 356 | |
| 357 | fn config_path(cli_path: Option<PathBuf>) -> ConfigPath { |
| 358 | if let Some(explicit) = cli_path.or_else(env_config_path) { |
| 359 | return ConfigPath::Explicit(explicit); |
| 360 | } |
| 361 | |
| 362 | let system_path = system_config_path(); |
| 363 | |
| 364 | if let Some(user_path) = default_config_path() { |
| 365 | ConfigPath::Regular { |
| 366 | user_path, |
| 367 | system_path, |
| 368 | } |
| 369 | } else { |
| 370 | // Couldn't find the home directory, or whatever. |
| 371 | ConfigPath::Explicit(system_path) |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | fn notify_fd() -> anyhow::Result<()> { |
| 376 | let fd = match env::var("NOTIFY_FD") { |
| 377 | Ok(notify_fd) => notify_fd.parse()?, |
| 378 | Err(env::VarError::NotPresent) => return Ok(()), |
| 379 | Err(err) => return Err(err.into()), |
| 380 | }; |
| 381 | env::remove_var("NOTIFY_FD"); |
| 382 | let mut notif = unsafe { File::from_raw_fd(fd) }; |
| 383 | notif.write_all(b"READY=1\n")?; |
| 384 | Ok(()) |
| 385 | } |
| 386 | |
| 387 | // The wayland-server crate has set_default_max_buffer_size() under a libwayland_1_23 feature, but |
| 388 | // this hard-requires libwayland-server >= 1.23 which is not present on e.g. Ubuntu 24.04. Since |
| 389 | // calling this is an optional enhancement, do it optionally at runtime. |
| 390 | fn set_default_max_buffer_size(display: &Display<State>, size: usize) { |
| 391 | use std::ffi::c_void; |
| 392 | |
| 393 | unsafe { |
| 394 | // RTLD_NOLOAD ensures we only get a handle to the libwayland-server that wayland-rs has |
| 395 | // already loaded into this process, rather than potentially pulling in a different copy. |
| 396 | let lib = libc::dlopen( |
| 397 | c"libwayland-server.so.0".as_ptr(), |
| 398 | libc::RTLD_LAZY | libc::RTLD_NOLOAD, |
| 399 | ); |
| 400 | if lib.is_null() { |
| 401 | // It's not really expected that this can happen, maybe if some distro changes the |
| 402 | // library name? |
| 403 | warn!("cannot set default max buffer size: libwayland-server.so.0 is not loaded"); |
| 404 | return; |
| 405 | } |
| 406 | |
| 407 | let sym = libc::dlsym(lib, c"wl_display_set_default_max_buffer_size".as_ptr()); |
| 408 | if sym.is_null() { |
| 409 | // Expected on libwayland-server < 1.23. |
| 410 | trace!("wl_display_set_default_max_buffer_size is missing; skipping"); |
| 411 | } else { |
| 412 | let func: unsafe extern "C" fn(*mut c_void, libc::size_t) = std::mem::transmute(sym); |
| 413 | let display_ptr = display.handle().backend_handle().display_ptr(); |
| 414 | func(display_ptr.cast(), size); |
| 415 | } |
| 416 | |
| 417 | libc::dlclose(lib); |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | struct ShutdownTracy; |
| 422 | impl Drop for ShutdownTracy { |
| 423 | fn drop(&mut self) { |
| 424 | #[cfg(feature = "profile-with-tracy-ondemand")] |
| 425 | unsafe { |
| 426 | tracy_client::sys::___tracy_shutdown_profiler(); |
| 427 | } |
| 428 | } |
| 429 | } |