microfetch_lib/
desktop.rs

1use std::{ffi::CStr, fmt::Write};
2
3#[must_use]
4#[cfg_attr(feature = "hotpath", hotpath::measure)]
5pub fn get_desktop_info() -> String {
6  // Retrieve the environment variables and handle Result types
7  let desktop_str = unsafe {
8    let ptr = libc::getenv(c"XDG_CURRENT_DESKTOP".as_ptr());
9    if ptr.is_null() {
10      "Unknown"
11    } else {
12      let s = CStr::from_ptr(ptr).to_str().unwrap_or("Unknown");
13      s.strip_prefix("none+").unwrap_or(s)
14    }
15  };
16
17  let backend_str = unsafe {
18    let ptr = libc::getenv(c"XDG_SESSION_TYPE".as_ptr());
19    if ptr.is_null() {
20      "Unknown"
21    } else {
22      let s = CStr::from_ptr(ptr).to_str().unwrap_or("Unknown");
23      if s.is_empty() { "Unknown" } else { s }
24    }
25  };
26
27  // Pre-calculate capacity: desktop_len + " (" + backend_len + ")"
28  // Capitalize first char needs temporary allocation only if backend exists
29  let mut result =
30    String::with_capacity(desktop_str.len() + backend_str.len() + 3);
31  result.push_str(desktop_str);
32  result.push_str(" (");
33
34  // Capitalize first character of backend
35  if let Some(first_char) = backend_str.chars().next() {
36    let _ = write!(result, "{}", first_char.to_ascii_uppercase());
37    result.push_str(&backend_str[first_char.len_utf8()..]);
38  }
39
40  result.push(')');
41  result
42}