BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / linux_desktop.rs

linux_desktop.rs

linux_desktop.rs 13.6 KiB Download Raw
1//! Desktop integration on Linux: the install folder (`~/.local/share/rusty-teams`),
2//! the `.desktop` entry and the menu icon.
3
4use std::fs;
5use std::io;
6use std::path::{Path, PathBuf};
7
8/// Matches the window's app id, so KDE pairs the window with the entry.
9pub const DESKTOP_ID: &str = "rusty-teams";
10/// Name the `.desktop` entry, the tray and `hicolor` use for the icon.
11pub const ICON_NAME: &str = "rusty-teams";
12pub const BINARY_FILE_NAME: &str = "teams";
13pub const ICON_SIZES: [u32; 5] = [256, 128, 64, 48, 32];
14const INSTALL_FOLDER: &str = "rusty-teams";
15const DONT_ASK_META_KEY: &str = "linux.install.dont_ask";
16
17/// Cargo marks its target folder with `CACHEDIR.TAG`; a binary in
18/// `target/<profile>/` is build output and is copied, not moved, on install.
19pub fn is_build_output(executable: &Path) -> bool {
20 executable
21 .parent()
22 .and_then(Path::parent)
23 .is_some_and(|target| target.join("CACHEDIR.TAG").is_file())
24}
25
26/// Paths below the XDG data folder (`~/.local/share`).
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct Layout {
29 data_dir: PathBuf,
30}
31
32impl Layout {
33 pub fn new(data_dir: impl Into<PathBuf>) -> Layout {
34 Layout {
35 data_dir: data_dir.into(),
36 }
37 }
38
39 pub fn current() -> Option<Layout> {
40 directories::BaseDirs::new().map(|base| Layout::new(base.data_dir()))
41 }
42
43 pub fn applications_dir(&self) -> PathBuf {
44 self.data_dir.join("applications")
45 }
46
47 pub fn install_dir(&self) -> PathBuf {
48 self.data_dir.join(INSTALL_FOLDER)
49 }
50
51 pub fn installed_binary(&self) -> PathBuf {
52 self.install_dir().join(BINARY_FILE_NAME)
53 }
54
55 pub fn desktop_file(&self) -> PathBuf {
56 self.applications_dir()
57 .join(format!("{DESKTOP_ID}.desktop"))
58 }
59
60 pub fn icons_dir(&self) -> PathBuf {
61 self.data_dir.join("icons").join("hicolor")
62 }
63
64 pub fn icon_file(&self, size: u32) -> PathBuf {
65 self.icons_dir()
66 .join(format!("{size}x{size}"))
67 .join("apps")
68 .join(format!("{ICON_NAME}.png"))
69 }
70
71 pub fn largest_icon(&self) -> PathBuf {
72 self.icon_file(ICON_SIZES[0])
73 }
74}
75
76pub fn is_installed(executable: &Path, layout: &Layout) -> bool {
77 let install_dir = layout.install_dir();
78 let canonical = |path: &Path| fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
79 executable
80 .parent()
81 .is_some_and(|parent| canonical(parent) == canonical(&install_dir))
82}
83
84pub fn should_offer_install(executable: &Path, layout: &Layout, dont_ask: bool) -> bool {
85 !dont_ask && !is_installed(executable, layout)
86}
87
88pub fn dont_ask_again(store: &store::Store) -> bool {
89 store.meta(DONT_ASK_META_KEY).ok().flatten().as_deref() == Some("1")
90}
91
92pub fn set_dont_ask_again(store: &store::Store) {
93 let _ = store.set_meta(DONT_ASK_META_KEY, "1");
94}
95
96/// Brings the install question back on the next start.
97pub fn ask_again(store: &store::Store) {
98 let _ = store.set_meta(DONT_ASK_META_KEY, "0");
99}
100
101/// Removes the menu entry and the installed binary (with a staged update). Sign-in
102/// and cache stay. A running installed copy keeps running.
103pub fn uninstall(layout: &Layout) -> io::Result<()> {
104 let remove = |path: PathBuf| match fs::remove_file(&path) {
105 Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
106 _ => Ok(()),
107 };
108 remove(layout.desktop_file())?;
109 let install_dir = layout.install_dir();
110 remove(layout.installed_binary())?;
111 remove(install_dir.join(format!("{BINARY_FILE_NAME}.old")))?;
112 if install_dir.join("update").is_dir() {
113 fs::remove_dir_all(install_dir.join("update"))?;
114 }
115 // Only when empty: anything else in there belongs to the user.
116 let _ = fs::remove_dir(&install_dir);
117 refresh_desktop_caches(layout);
118 Ok(())
119}
120
121/// Puts the binary into the install folder (copied when it is build output, moved
122/// otherwise), writes the `.desktop` entry and returns the new path. An older
123/// installed binary is replaced.
124pub fn install_binary(executable: &Path, layout: &Layout) -> io::Result<PathBuf> {
125 let target = layout.installed_binary();
126 fs::create_dir_all(layout.install_dir())?;
127 if fs::canonicalize(executable).ok() != fs::canonicalize(&target).ok() {
128 if is_build_output(executable) {
129 copy_file(executable, &target)?;
130 } else {
131 move_file(executable, &target)?;
132 }
133 }
134 make_executable(&target)?;
135 install_icon(layout, crate::appearance::AppIcon::RustyTeams.png()).map_err(io::Error::other)?;
136 write_desktop_entry(layout, &target)?;
137 refresh_desktop_caches(layout);
138 Ok(target)
139}
140
141/// `rename`, or copy and delete when the source is on another file system.
142fn move_file(from: &Path, to: &Path) -> io::Result<()> {
143 if fs::rename(from, to).is_ok() {
144 return Ok(());
145 }
146 copy_file(from, to)?;
147 let _ = fs::remove_file(from);
148 Ok(())
149}
150
151/// Copies through a temporary file and renames it into place, so a running older
152/// binary at `to` is replaced instead of written over.
153fn copy_file(from: &Path, to: &Path) -> io::Result<()> {
154 let partial = to.with_extension("partial");
155 fs::copy(from, &partial)?;
156 fs::rename(&partial, to).inspect_err(|_| {
157 let _ = fs::remove_file(&partial);
158 })
159}
160
161fn make_executable(path: &Path) -> io::Result<()> {
162 use std::os::unix::fs::PermissionsExt as _;
163 let mut permissions = fs::metadata(path)?.permissions();
164 permissions.set_mode(permissions.mode() | 0o755);
165 fs::set_permissions(path, permissions)
166}
167
168/// Quotes a path for the `Exec` key of a desktop entry.
169fn exec_quoted(path: &Path) -> String {
170 let mut quoted = String::from("\"");
171 for character in path.display().to_string().chars() {
172 if matches!(character, '"' | '`' | '$' | '\\') {
173 quoted.push('\\');
174 }
175 if character == '%' {
176 quoted.push('%');
177 }
178 quoted.push(character);
179 }
180 quoted.push('"');
181 quoted
182}
183
184pub fn desktop_entry(executable: &Path) -> String {
185 format!(
186 "[Desktop Entry]\n\
187 Type=Application\n\
188 Name={name}\n\
189 GenericName=Microsoft Teams client\n\
190 Comment=A fast, native Microsoft Teams chat client\n\
191 Exec={exec}\n\
192 TryExec={try_exec}\n\
193 Icon={ICON_NAME}\n\
194 StartupWMClass={DESKTOP_ID}\n\
195 Terminal=false\n\
196 Categories=Network;InstantMessaging;Chat;\n\
197 Keywords=Teams;Chat;Microsoft;\n",
198 name = crate::APP_NAME,
199 exec = exec_quoted(executable),
200 try_exec = executable.display(),
201 )
202}
203
204pub fn write_desktop_entry(layout: &Layout, executable: &Path) -> io::Result<()> {
205 fs::create_dir_all(layout.applications_dir())?;
206 fs::write(layout.desktop_file(), desktop_entry(executable))
207}
208
209/// Lets the menu and task manager pick up a new entry or icon right away. Every tool
210/// is optional; whatever is missing is skipped.
211pub fn refresh_desktop_caches(layout: &Layout) {
212 let applications = layout.applications_dir();
213 let icons = layout.icons_dir();
214 std::thread::spawn(move || {
215 let run = |program: &str, arguments: &[&std::ffi::OsStr]| {
216 let _ = std::process::Command::new(program)
217 .args(arguments)
218 .stdin(std::process::Stdio::null())
219 .stdout(std::process::Stdio::null())
220 .stderr(std::process::Stdio::null())
221 .status();
222 };
223 run("update-desktop-database", &[applications.as_os_str()]);
224 run(
225 "gtk-update-icon-cache",
226 &["-f".as_ref(), "-t".as_ref(), icons.as_os_str()],
227 );
228 run("kbuildsycoca6", &[]);
229 run("kbuildsycoca5", &[]);
230 });
231}
232
233/// Writes the menu icon into `hicolor` in every size of [`ICON_SIZES`].
234pub fn install_icon(layout: &Layout, bytes: &[u8]) -> Result<(), String> {
235 let decoded = image::load_from_memory(bytes).map_err(|error| error.to_string())?;
236 for size in ICON_SIZES {
237 let resized = decoded.resize_exact(size, size, image::imageops::FilterType::Lanczos3);
238 let mut png = Vec::new();
239 resized
240 .write_to(&mut io::Cursor::new(&mut png), image::ImageFormat::Png)
241 .map_err(|error| error.to_string())?;
242 let path = layout.icon_file(size);
243 if let Some(directory) = path.parent() {
244 fs::create_dir_all(directory).map_err(|error| error.to_string())?;
245 }
246 let partial = path.with_extension("partial");
247 fs::write(&partial, &png).map_err(|error| error.to_string())?;
248 fs::rename(&partial, &path).map_err(|error| error.to_string())?;
249 }
250 Ok(())
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256
257 fn png(size: u32) -> Vec<u8> {
258 let image = image::RgbaImage::from_pixel(size, size, image::Rgba([80, 90, 200, 255]));
259 let mut bytes = Vec::new();
260 image::DynamicImage::ImageRgba8(image)
261 .write_to(&mut io::Cursor::new(&mut bytes), image::ImageFormat::Png)
262 .unwrap();
263 bytes
264 }
265
266 #[test]
267 fn layout_follows_the_xdg_data_folder() {
268 let layout = Layout::new("/home/a/.local/share");
269 assert_eq!(
270 layout.installed_binary(),
271 Path::new("/home/a/.local/share/rusty-teams/teams")
272 );
273 assert_eq!(
274 layout.desktop_file(),
275 Path::new("/home/a/.local/share/applications/rusty-teams.desktop")
276 );
277 assert_eq!(
278 layout.icon_file(48),
279 Path::new("/home/a/.local/share/icons/hicolor/48x48/apps/rusty-teams.png")
280 );
281 }
282
283 #[test]
284 fn the_entry_starts_the_binary_and_matches_the_window() {
285 let entry = desktop_entry(Path::new("/home/a/my apps/te\"a$ms"));
286 assert!(entry.starts_with("[Desktop Entry]\n"));
287 assert!(entry.contains("Exec=\"/home/a/my apps/te\\\"a\\$ms\"\n"));
288 assert!(entry.contains("Icon=rusty-teams\n"));
289 assert!(entry.contains("StartupWMClass=rusty-teams\n"));
290 }
291
292 fn assert_installed(installed: &Path, layout: &Layout, content: &[u8]) {
293 use std::os::unix::fs::PermissionsExt as _;
294 assert_eq!(installed, layout.installed_binary());
295 assert_eq!(fs::read(installed).unwrap(), content);
296 assert_eq!(
297 fs::metadata(installed).unwrap().permissions().mode() & 0o111,
298 0o111
299 );
300 let entry = fs::read_to_string(layout.desktop_file()).unwrap();
301 assert!(entry.contains(&installed.display().to_string()));
302 assert!(!should_offer_install(installed, layout, false));
303 }
304
305 #[test]
306 fn install_moves_a_downloaded_binary_and_writes_the_entry() {
307 let home = tempfile::tempdir().unwrap();
308 let downloads = home.path().join("Downloads");
309 fs::create_dir_all(&downloads).unwrap();
310 let binary = downloads.join("teams");
311 fs::write(&binary, b"v1").unwrap();
312 let layout = Layout::new(home.path().join("share"));
313 assert!(should_offer_install(&binary, &layout, false));
314 assert!(!should_offer_install(&binary, &layout, true));
315
316 let installed = install_binary(&binary, &layout).unwrap();
317
318 assert!(!binary.exists());
319 assert_installed(&installed, &layout, b"v1");
320 assert_eq!(install_binary(&installed, &layout).unwrap(), installed);
321 assert_eq!(fs::read(&installed).unwrap(), b"v1");
322 }
323
324 #[test]
325 fn install_copies_build_output_and_replaces_an_older_install() {
326 let home = tempfile::tempdir().unwrap();
327 let target = home.path().join("repo").join("target");
328 fs::create_dir_all(target.join("release")).unwrap();
329 fs::write(
330 target.join("CACHEDIR.TAG"),
331 b"Signature: 8a477f597d28d172789f06886806bc55",
332 )
333 .unwrap();
334 let binary = target.join("release").join("teams");
335 let layout = Layout::new(home.path().join("share"));
336 fs::write(&binary, b"v1").unwrap();
337 install_binary(&binary, &layout).unwrap();
338 fs::write(&binary, b"v2").unwrap();
339
340 let installed = install_binary(&binary, &layout).unwrap();
341
342 assert!(is_build_output(&binary));
343 assert!(binary.exists());
344 assert_installed(&installed, &layout, b"v2");
345 assert!(!layout.install_dir().join("teams.partial").exists());
346 }
347
348 #[test]
349 fn uninstall_removes_entry_binary_and_update_but_keeps_other_files() {
350 let home = tempfile::tempdir().unwrap();
351 let layout = Layout::new(home.path().join("share"));
352 let downloads = home.path().join("Downloads");
353 fs::create_dir_all(&downloads).unwrap();
354 fs::write(downloads.join("teams"), b"v1").unwrap();
355 install_binary(&downloads.join("teams"), &layout).unwrap();
356 fs::create_dir_all(layout.install_dir().join("update")).unwrap();
357 fs::write(layout.install_dir().join("update").join("teams"), b"v2").unwrap();
358
359 uninstall(&layout).unwrap();
360
361 assert!(!layout.desktop_file().exists());
362 assert!(!layout.install_dir().exists());
363 uninstall(&layout).unwrap();
364
365 fs::create_dir_all(layout.install_dir()).unwrap();
366 fs::write(layout.install_dir().join("notes.txt"), b"mine").unwrap();
367 uninstall(&layout).unwrap();
368 assert!(layout.install_dir().join("notes.txt").exists());
369 }
370
371 #[test]
372 fn the_icon_lands_in_every_size() {
373 let home = tempfile::tempdir().unwrap();
374 let layout = Layout::new(home.path());
375 install_icon(&layout, &png(300)).unwrap();
376 for size in ICON_SIZES {
377 let written = image::open(layout.icon_file(size)).unwrap();
378 assert_eq!((written.width(), written.height()), (size, size));
379 }
380 assert!(install_icon(&layout, b"not an image").is_err());
381 }
382}