forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB99bf2dfIvan Molodetskikh1 year ago2106 commits

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