forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB055a94dIvan Molodetskikh1 year ago2247 commits

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