forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBf51dd67Ivan Molodetskikh2 years ago981 commits

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