|
| 1 | +--- |
| 2 | +title: Get Desktop Enviroment |
| 3 | +description: Get the Desktop Enviroment that the user is currently using. |
| 4 | +author: sponkurtus2 |
| 5 | +tags: linux,file |
| 6 | +--- |
| 7 | + |
| 8 | +```rust |
| 9 | +fn get_desktop_env() -> String { |
| 10 | + // Return empty string if no X display is available |
| 11 | + if env::var("DISPLAY").is_err() { |
| 12 | + return String::new(); |
| 13 | + } |
| 14 | + |
| 15 | + // Check common desktop environment variables. |
| 16 | + for env_var in &[ |
| 17 | + "XDG_SESSION_DESKTOP", |
| 18 | + "XDG_CURRENT_DESKTOP", |
| 19 | + "DESKTOP_SESSION", |
| 20 | + ] { |
| 21 | + if let Ok(de) = env::var(env_var) { |
| 22 | + return de; |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + // As fallback, try to get desktop name from last word of last line in .xinitrc |
| 27 | + let path = format!("{}/.xinitrc", env::var("HOME").unwrap_or_default()); |
| 28 | + if let Ok(mut file) = File::open(&path) { |
| 29 | + let mut buf = String::new(); |
| 30 | + if file.read_to_string(&mut buf).is_ok() { |
| 31 | + if let Some(last_line) = buf.lines().last() { |
| 32 | + let last_word = last_line.split(' ').last().unwrap_or(""); |
| 33 | + return last_word.to_string(); |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + // Return "N/A" if no desktop environment could be detected |
| 39 | + String::from("N/A") |
| 40 | +} |
| 41 | + |
| 42 | +// Usage: |
| 43 | +get_desktop_env(); // Returns: the desktop enviroment that the user actually has e.g. i3. |
| 44 | +``` |
0 commit comments