niri
Clone
https://git.tahinli.com/Tahinli/niri.git
0 watching·0 forks·Rust·GPL-3.0·12.1 MiB·64a9351·Ivan Molodetskikh·2 years ago·1319 commits
| 1 | #[macro_use] |
| 2 | extern crate tracing; |
| 3 | |
| 4 | use std::fmt::Write as _; |
| 5 | use std::fs::{self, 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::{env, mem}; |
| 11 | |
| 12 | use clap::Parser; |
| 13 | use directories::ProjectDirs; |
| 14 | use niri::animation; |
| 15 | use niri::cli::{Cli, Sub}; |
| 16 | #[cfg(feature = "dbus")] |
| 17 | use niri::dbus; |
| 18 | use niri::ipc::client::handle_msg; |
| 19 | use niri::niri::State; |
| 20 | use niri::utils::spawning::{ |
| 21 | spawn, store_and_increase_nofile_rlimit, CHILD_ENV, REMOVE_ENV_RUST_BACKTRACE, |
| 22 | REMOVE_ENV_RUST_LIB_BACKTRACE, |
| 23 | }; |
| 24 | use niri::utils::watcher::Watcher; |
| 25 | use niri::utils::{cause_panic, version, IS_SYSTEMD_SERVICE}; |
| 26 | use niri_config::Config; |
| 27 | use portable_atomic::Ordering; |
| 28 | use sd_notify::NotifyState; |
| 29 | use smithay::reexports::calloop::EventLoop; |
| 30 | use smithay::reexports::wayland_server::Display; |
| 31 | use tracing_subscriber::EnvFilter; |
| 32 | |
| 33 | const DEFAULT_LOG_FILTER: &str = "niri=debug,smithay::backend::renderer::gles=error"; |
| 34 | |
| 35 | fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 36 | // Set backtrace defaults if not set. |
| 37 | if env::var_os("RUST_BACKTRACE").is_none() { |
| 38 | env::set_var("RUST_BACKTRACE", "1"); |
| 39 | REMOVE_ENV_RUST_BACKTRACE.store(true, Ordering::Relaxed); |
| 40 | } |
| 41 | if env::var_os("RUST_LIB_BACKTRACE").is_none() { |
| 42 | env::set_var("RUST_LIB_BACKTRACE", "0"); |
| 43 | REMOVE_ENV_RUST_LIB_BACKTRACE.store(true, Ordering::Relaxed); |
| 44 | } |
| 45 | |
| 46 | if env::var_os("NOTIFY_SOCKET").is_some() { |
| 47 | IS_SYSTEMD_SERVICE.store(true, Ordering::Relaxed); |
| 48 | |
| 49 | #[cfg(not(feature = "systemd"))] |
| 50 | warn!( |
| 51 | "running as a systemd service, but systemd support is compiled out. \ |
| 52 | Are you sure you did not forget to set `--features systemd`?" |
| 53 | ); |
| 54 | } |
| 55 | |
| 56 | let directives = env::var("RUST_LOG").unwrap_or_else(|_| DEFAULT_LOG_FILTER.to_owned()); |
| 57 | let env_filter = EnvFilter::builder().parse_lossy(directives); |
| 58 | tracing_subscriber::fmt() |
| 59 | .compact() |
| 60 | .with_env_filter(env_filter) |
| 61 | .init(); |
| 62 | |
| 63 | let cli = Cli::parse(); |
| 64 | |
| 65 | if cli.session { |
| 66 | // If we're starting as a session, assume that the intention is to start on a TTY. Remove |
| 67 | // DISPLAY or WAYLAND_DISPLAY from our environment if they are set, since they will cause |
| 68 | // the winit backend to be selected instead. |
| 69 | if env::var_os("DISPLAY").is_some() { |
| 70 | warn!("running as a session but DISPLAY is set, removing it"); |
| 71 | env::remove_var("DISPLAY"); |
| 72 | } |
| 73 | if env::var_os("WAYLAND_DISPLAY").is_some() { |
| 74 | warn!("running as a session but WAYLAND_DISPLAY is set, removing it"); |
| 75 | env::remove_var("WAYLAND_DISPLAY"); |
| 76 | } |
| 77 | |
| 78 | // Set the current desktop for xdg-desktop-portal. |
| 79 | env::set_var("XDG_CURRENT_DESKTOP", "niri"); |
| 80 | // Ensure the session type is set to Wayland for xdg-autostart and Qt apps. |
| 81 | env::set_var("XDG_SESSION_TYPE", "wayland"); |
| 82 | } |
| 83 | |
| 84 | // Set a better error printer for config loading. |
| 85 | niri_config::set_miette_hook().unwrap(); |
| 86 | |
| 87 | // Handle subcommands. |
| 88 | if let Some(subcommand) = cli.subcommand { |
| 89 | match subcommand { |
| 90 | Sub::Validate { config } => { |
| 91 | tracy_client::Client::start(); |
| 92 | |
| 93 | let path = config |
| 94 | .or_else(env_config_path) |
| 95 | .or_else(default_config_path) |
| 96 | .expect("error getting config path"); |
| 97 | Config::load(&path)?; |
| 98 | info!("config is valid"); |
| 99 | return Ok(()); |
| 100 | } |
| 101 | Sub::Msg { msg, json } => { |
| 102 | handle_msg(msg, json)?; |
| 103 | return Ok(()); |
| 104 | } |
| 105 | Sub::Panic => cause_panic(), |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | // Avoid starting Tracy for the `niri msg` code path since starting/stopping Tracy is a bit |
| 110 | // slow. |
| 111 | tracy_client::Client::start(); |
| 112 | |
| 113 | info!("starting version {}", &version()); |
| 114 | |
| 115 | // Load the config. |
| 116 | let mut config_created = false; |
| 117 | let path = cli.config.or_else(env_config_path); |
| 118 | env::remove_var("NIRI_CONFIG"); |
| 119 | let path = path.or_else(|| { |
| 120 | let default_path = default_config_path()?; |
| 121 | let default_parent = default_path.parent().unwrap(); |
| 122 | |
| 123 | if let Err(err) = fs::create_dir_all(default_parent) { |
| 124 | warn!( |
| 125 | "error creating config directories {:?}: {err:?}", |
| 126 | default_parent |
| 127 | ); |
| 128 | return Some(default_path); |
| 129 | } |
| 130 | |
| 131 | // Create the config and fill it with the default config if it doesn't exist. |
| 132 | let new_file = File::options() |
| 133 | .read(true) |
| 134 | .write(true) |
| 135 | .create_new(true) |
| 136 | .open(&default_path); |
| 137 | match new_file { |
| 138 | Ok(mut new_file) => { |
| 139 | let default = include_bytes!("../resources/default-config.kdl"); |
| 140 | match new_file.write_all(default) { |
| 141 | Ok(()) => { |
| 142 | config_created = true; |
| 143 | info!("wrote default config to {:?}", &default_path); |
| 144 | } |
| 145 | Err(err) => { |
| 146 | warn!("error writing config file at {:?}: {err:?}", &default_path) |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {} |
| 151 | Err(err) => warn!("error creating config file at {:?}: {err:?}", &default_path), |
| 152 | } |
| 153 | |
| 154 | Some(default_path) |
| 155 | }); |
| 156 | |
| 157 | let mut config_errored = false; |
| 158 | let mut config = path |
| 159 | .as_deref() |
| 160 | .and_then(|path| match Config::load(path) { |
| 161 | Ok(config) => Some(config), |
| 162 | Err(err) => { |
| 163 | warn!("{err:?}"); |
| 164 | config_errored = true; |
| 165 | None |
| 166 | } |
| 167 | }) |
| 168 | .unwrap_or_default(); |
| 169 | |
| 170 | let slowdown = if config.animations.off { |
| 171 | 0. |
| 172 | } else { |
| 173 | config.animations.slowdown.clamp(0., 100.) |
| 174 | }; |
| 175 | animation::ANIMATION_SLOWDOWN.store(slowdown, Ordering::Relaxed); |
| 176 | |
| 177 | let spawn_at_startup = mem::take(&mut config.spawn_at_startup); |
| 178 | *CHILD_ENV.write().unwrap() = mem::take(&mut config.environment); |
| 179 | |
| 180 | store_and_increase_nofile_rlimit(); |
| 181 | |
| 182 | // Create the compositor. |
| 183 | let mut event_loop = EventLoop::try_new().unwrap(); |
| 184 | let display = Display::new().unwrap(); |
| 185 | let mut state = State::new( |
| 186 | config, |
| 187 | event_loop.handle(), |
| 188 | event_loop.get_signal(), |
| 189 | display, |
| 190 | ) |
| 191 | .unwrap(); |
| 192 | |
| 193 | // Set WAYLAND_DISPLAY for children. |
| 194 | let socket_name = &state.niri.socket_name; |
| 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 | env::set_var(niri_ipc::SOCKET_PATH_ENV, &ipc.socket_path); |
| 204 | info!("IPC listening on: {}", ipc.socket_path.to_string_lossy()); |
| 205 | } |
| 206 | |
| 207 | if cli.session { |
| 208 | // We're starting as a session. Import our variables. |
| 209 | import_environment(); |
| 210 | |
| 211 | // Inhibit power key handling so we can suspend on it. |
| 212 | #[cfg(feature = "dbus")] |
| 213 | if !state.niri.config.borrow().input.disable_power_key_handling { |
| 214 | if let Err(err) = state.niri.inhibit_power_key() { |
| 215 | warn!("error inhibiting power key: {err:?}"); |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | #[cfg(feature = "dbus")] |
| 221 | dbus::DBusServers::start(&mut state, cli.session); |
| 222 | |
| 223 | // Notify systemd we're ready. |
| 224 | if let Err(err) = sd_notify::notify(true, &[NotifyState::Ready]) { |
| 225 | warn!("error notifying systemd: {err:?}"); |
| 226 | }; |
| 227 | |
| 228 | // Send ready notification to the NOTIFY_FD file descriptor. |
| 229 | if let Err(err) = notify_fd() { |
| 230 | warn!("error notifying fd: {err:?}"); |
| 231 | } |
| 232 | |
| 233 | // Set up config file watcher. |
| 234 | let _watcher = if let Some(path) = path.clone() { |
| 235 | let (tx, rx) = calloop::channel::sync_channel(1); |
| 236 | let watcher = Watcher::new(path.clone(), tx); |
| 237 | event_loop |
| 238 | .handle() |
| 239 | .insert_source(rx, move |event, _, state| match event { |
| 240 | calloop::channel::Event::Msg(()) => state.reload_config(path.clone()), |
| 241 | calloop::channel::Event::Closed => (), |
| 242 | }) |
| 243 | .unwrap(); |
| 244 | Some(watcher) |
| 245 | } else { |
| 246 | None |
| 247 | }; |
| 248 | |
| 249 | // Spawn commands from cli and auto-start. |
| 250 | spawn(cli.command); |
| 251 | |
| 252 | for elem in spawn_at_startup { |
| 253 | spawn(elem.command); |
| 254 | } |
| 255 | |
| 256 | // Show the config error notification right away if needed. |
| 257 | if config_errored { |
| 258 | state.niri.config_error_notification.show(); |
| 259 | } else if config_created { |
| 260 | state.niri.config_error_notification.show_created(path); |
| 261 | } |
| 262 | |
| 263 | // Run the compositor. |
| 264 | event_loop |
| 265 | .run(None, &mut state, |state| state.refresh_and_flush_clients()) |
| 266 | .unwrap(); |
| 267 | |
| 268 | Ok(()) |
| 269 | } |
| 270 | |
| 271 | fn import_environment() { |
| 272 | let variables = [ |
| 273 | "WAYLAND_DISPLAY", |
| 274 | "XDG_CURRENT_DESKTOP", |
| 275 | "XDG_SESSION_TYPE", |
| 276 | niri_ipc::SOCKET_PATH_ENV, |
| 277 | ] |
| 278 | .join(" "); |
| 279 | |
| 280 | let mut init_system_import = String::new(); |
| 281 | if cfg!(feature = "systemd") { |
| 282 | write!( |
| 283 | init_system_import, |
| 284 | "systemctl --user import-environment {variables};" |
| 285 | ) |
| 286 | .unwrap(); |
| 287 | } |
| 288 | if cfg!(feature = "dinit") { |
| 289 | write!(init_system_import, "dinitctl setenv {variables};").unwrap(); |
| 290 | } |
| 291 | |
| 292 | let rv = Command::new("/bin/sh") |
| 293 | .args([ |
| 294 | "-c", |
| 295 | &format!( |
| 296 | "{init_system_import}\ |
| 297 | hash dbus-update-activation-environment 2>/dev/null && \ |
| 298 | dbus-update-activation-environment {variables}" |
| 299 | ), |
| 300 | ]) |
| 301 | .spawn(); |
| 302 | // Wait for the import process to complete, otherwise services will start too fast without |
| 303 | // environment variables available. |
| 304 | match rv { |
| 305 | Ok(mut child) => match child.wait() { |
| 306 | Ok(status) => { |
| 307 | if !status.success() { |
| 308 | warn!("import environment shell exited with {status}"); |
| 309 | } |
| 310 | } |
| 311 | Err(err) => { |
| 312 | warn!("error waiting for import environment shell: {err:?}"); |
| 313 | } |
| 314 | }, |
| 315 | Err(err) => { |
| 316 | warn!("error spawning shell to import environment: {err:?}"); |
| 317 | } |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | fn env_config_path() -> Option<PathBuf> { |
| 322 | env::var_os("NIRI_CONFIG") |
| 323 | .filter(|x| !x.is_empty()) |
| 324 | .map(PathBuf::from) |
| 325 | } |
| 326 | |
| 327 | fn default_config_path() -> Option<PathBuf> { |
| 328 | let Some(dirs) = ProjectDirs::from("", "", "niri") else { |
| 329 | warn!("error retrieving home directory"); |
| 330 | return None; |
| 331 | }; |
| 332 | |
| 333 | let mut path = dirs.config_dir().to_owned(); |
| 334 | path.push("config.kdl"); |
| 335 | Some(path) |
| 336 | } |
| 337 | |
| 338 | fn notify_fd() -> anyhow::Result<()> { |
| 339 | let fd = match env::var("NOTIFY_FD") { |
| 340 | Ok(notify_fd) => notify_fd.parse()?, |
| 341 | Err(env::VarError::NotPresent) => return Ok(()), |
| 342 | Err(err) => return Err(err.into()), |
| 343 | }; |
| 344 | env::remove_var("NOTIFY_FD"); |
| 345 | let mut notif = unsafe { File::from_raw_fd(fd) }; |
| 346 | notif.write_all(b"READY=1\n")?; |
| 347 | Ok(()) |
| 348 | } |