BlueGit

ict rusty-teams

Files

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

linux_desktop.rs

feat(packaging): Linux AppImage, deb, rpm and Flatpak
metis Samuel David Merlin Kemper · pushed by metis · 2 weeks ago
228f36c5 History
linux_desktop.rs 14.8 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
84/// Installed by a deb/rpm (under `/usr` or `/opt`) or started from an AppImage, whose
85/// runtime sets `APPIMAGE`. Those bring their own menu entry and updates, so the app
86/// does not offer to install itself (and, outside the install folder, never updates itself).
87pub fn is_packaged(executable: &Path, appimage: Option<&std::ffi::OsStr>) -> bool {
88 appimage.is_some_and(|path| !path.is_empty())
89 || executable.starts_with("/usr")
90 || executable.starts_with("/opt")
91}
92
93pub fn should_offer_install(executable: &Path, layout: &Layout, dont_ask: bool) -> bool {
94 !dont_ask && !is_installed(executable, layout)
95}
96
97pub fn dont_ask_again(store: &store::Store) -> bool {
98 store.meta(DONT_ASK_META_KEY).ok().flatten().as_deref() == Some("1")
99}
100
101pub fn set_dont_ask_again(store: &store::Store) {
102 let _ = store.set_meta(DONT_ASK_META_KEY, "1");
103}
104
105/// Brings the install question back on the next start.
106pub fn ask_again(store: &store::Store) {
107 let _ = store.set_meta(DONT_ASK_META_KEY, "0");
108}
109
110/// Removes the menu entry and the installed binary (with a staged update). Sign-in
111/// and cache stay. A running installed copy keeps running.
112pub fn uninstall(layout: &Layout) -> io::Result<()> {
113 let remove = |path: PathBuf| match fs::remove_file(&path) {
114 Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error),
115 _ => Ok(()),
116 };
117 remove(layout.desktop_file())?;
118 let install_dir = layout.install_dir();
119 remove(layout.installed_binary())?;
120 remove(install_dir.join(format!("{BINARY_FILE_NAME}.old")))?;
121 if install_dir.join("update").is_dir() {
122 fs::remove_dir_all(install_dir.join("update"))?;
123 }
124 for size in ICON_SIZES {
125 remove(layout.icon_file(size))?;
126 }
127 // Only when empty: anything else in there belongs to the user.
128 let _ = fs::remove_dir(&install_dir);
129 refresh_desktop_caches(layout);
130 Ok(())
131}
132
133/// Puts the binary into the install folder (copied when it is build output, moved
134/// otherwise), writes the `.desktop` entry and returns the new path. An older
135/// installed binary is replaced.
136pub fn install_binary(executable: &Path, layout: &Layout) -> io::Result<PathBuf> {
137 let target = layout.installed_binary();
138 fs::create_dir_all(layout.install_dir())?;
139 if fs::canonicalize(executable).ok() != fs::canonicalize(&target).ok() {
140 if is_build_output(executable) {
141 copy_file(executable, &target)?;
142 } else {
143 move_file(executable, &target)?;
144 }
145 }
146 make_executable(&target)?;
147 install_icon(layout, crate::appearance::AppIcon::RustyTeams.png()).map_err(io::Error::other)?;
148 write_desktop_entry(layout, &target)?;
149 refresh_desktop_caches(layout);
150 Ok(target)
151}
152
153/// `rename`, or copy and delete when the source is on another file system.
154fn move_file(from: &Path, to: &Path) -> io::Result<()> {
155 if fs::rename(from, to).is_ok() {
156 return Ok(());
157 }
158 copy_file(from, to)?;
159 let _ = fs::remove_file(from);
160 Ok(())
161}
162
163/// Copies through a temporary file and renames it into place, so a running older
164/// binary at `to` is replaced instead of written over.
165fn copy_file(from: &Path, to: &Path) -> io::Result<()> {
166 let partial = to.with_extension("partial");
167 fs::copy(from, &partial)?;
168 fs::rename(&partial, to).inspect_err(|_| {
169 let _ = fs::remove_file(&partial);
170 })
171}
172
173fn make_executable(path: &Path) -> io::Result<()> {
174 use std::os::unix::fs::PermissionsExt as _;
175 let mut permissions = fs::metadata(path)?.permissions();
176 permissions.set_mode(permissions.mode() | 0o755);
177 fs::set_permissions(path, permissions)
178}
179
180/// Quotes a path for the `Exec` key of a desktop entry.
181fn exec_quoted(path: &Path) -> String {
182 let mut quoted = String::from("\"");
183 for character in path.display().to_string().chars() {
184 if matches!(character, '"' | '`' | '$' | '\\') {
185 quoted.push('\\');
186 }
187 if character == '%' {
188 quoted.push('%');
189 }
190 quoted.push(character);
191 }
192 quoted.push('"');
193 quoted
194}
195
196pub fn desktop_entry(executable: &Path) -> String {
197 format!(
198 "[Desktop Entry]\n\
199 Type=Application\n\
200 Name={name}\n\
201 GenericName=Microsoft Teams client\n\
202 Comment=A fast, native Microsoft Teams chat client\n\
203 Exec={exec}\n\
204 TryExec={try_exec}\n\
205 Icon={ICON_NAME}\n\
206 StartupWMClass={DESKTOP_ID}\n\
207 Terminal=false\n\
208 Categories=Network;InstantMessaging;Chat;\n\
209 Keywords=Teams;Chat;Microsoft;\n",
210 name = crate::APP_NAME,
211 exec = exec_quoted(executable),
212 try_exec = executable.display(),
213 )
214}
215
216pub fn write_desktop_entry(layout: &Layout, executable: &Path) -> io::Result<()> {
217 fs::create_dir_all(layout.applications_dir())?;
218 fs::write(layout.desktop_file(), desktop_entry(executable))
219}
220
221/// Lets the menu and task manager pick up a new entry or icon right away. Every tool
222/// is optional; whatever is missing is skipped.
223pub fn refresh_desktop_caches(layout: &Layout) {
224 let applications = layout.applications_dir();
225 let icons = layout.icons_dir();
226 std::thread::spawn(move || {
227 let run = |program: &str, arguments: &[&std::ffi::OsStr]| {
228 let _ = std::process::Command::new(program)
229 .args(arguments)
230 .stdin(std::process::Stdio::null())
231 .stdout(std::process::Stdio::null())
232 .stderr(std::process::Stdio::null())
233 .status();
234 };
235 run("update-desktop-database", &[applications.as_os_str()]);
236 run(
237 "gtk-update-icon-cache",
238 &["-f".as_ref(), "-t".as_ref(), icons.as_os_str()],
239 );
240 run("kbuildsycoca6", &[]);
241 run("kbuildsycoca5", &[]);
242 });
243}
244
245/// Writes the menu icon into `hicolor` in every size of [`ICON_SIZES`].
246pub fn install_icon(layout: &Layout, bytes: &[u8]) -> Result<(), String> {
247 let decoded = image::load_from_memory(bytes).map_err(|error| error.to_string())?;
248 for size in ICON_SIZES {
249 let resized = decoded.resize_exact(size, size, image::imageops::FilterType::Lanczos3);
250 let mut png = Vec::new();
251 resized
252 .write_to(&mut io::Cursor::new(&mut png), image::ImageFormat::Png)
253 .map_err(|error| error.to_string())?;
254 let path = layout.icon_file(size);
255 if let Some(directory) = path.parent() {
256 fs::create_dir_all(directory).map_err(|error| error.to_string())?;
257 }
258 let partial = path.with_extension("partial");
259 fs::write(&partial, &png).map_err(|error| error.to_string())?;
260 fs::rename(&partial, &path).map_err(|error| error.to_string())?;
261 }
262 Ok(())
263}
264
265#[cfg(test)]
266mod tests {
267 use super::*;
268
269 fn png(size: u32) -> Vec<u8> {
270 let image = image::RgbaImage::from_pixel(size, size, image::Rgba([80, 90, 200, 255]));
271 let mut bytes = Vec::new();
272 image::DynamicImage::ImageRgba8(image)
273 .write_to(&mut io::Cursor::new(&mut bytes), image::ImageFormat::Png)
274 .unwrap();
275 bytes
276 }
277
278 #[test]
279 fn layout_follows_the_xdg_data_folder() {
280 let layout = Layout::new("/home/a/.local/share");
281 assert_eq!(
282 layout.installed_binary(),
283 Path::new("/home/a/.local/share/rusty-teams/teams")
284 );
285 assert_eq!(
286 layout.desktop_file(),
287 Path::new("/home/a/.local/share/applications/rusty-teams.desktop")
288 );
289 assert_eq!(
290 layout.icon_file(48),
291 Path::new("/home/a/.local/share/icons/hicolor/48x48/apps/rusty-teams.png")
292 );
293 }
294
295 #[test]
296 fn package_and_appimage_installs_count_as_packaged() {
297 use std::ffi::OsStr;
298 assert!(is_packaged(Path::new("/usr/bin/teams"), None));
299 assert!(is_packaged(Path::new("/opt/rusty-teams/teams"), None));
300 assert!(is_packaged(
301 Path::new("/tmp/.mount_teamsAbc/usr/bin/teams"),
302 Some(OsStr::new("/home/a/Apps/rusty-teams.AppImage"))
303 ));
304 assert!(!is_packaged(Path::new("/home/a/Downloads/teams"), None));
305 assert!(!is_packaged(
306 Path::new("/home/a/.local/share/rusty-teams/teams"),
307 Some(OsStr::new(""))
308 ));
309 assert!(!is_packaged(Path::new("/usrlocal/teams"), None));
310 }
311
312 #[test]
313 fn the_entry_starts_the_binary_and_matches_the_window() {
314 let entry = desktop_entry(Path::new("/home/a/my apps/te\"a$ms"));
315 assert!(entry.starts_with("[Desktop Entry]\n"));
316 assert!(entry.contains("Exec=\"/home/a/my apps/te\\\"a\\$ms\"\n"));
317 assert!(entry.contains("Icon=rusty-teams\n"));
318 assert!(entry.contains("StartupWMClass=rusty-teams\n"));
319 }
320
321 fn assert_installed(installed: &Path, layout: &Layout, content: &[u8]) {
322 use std::os::unix::fs::PermissionsExt as _;
323 assert_eq!(installed, layout.installed_binary());
324 assert_eq!(fs::read(installed).unwrap(), content);
325 assert_eq!(
326 fs::metadata(installed).unwrap().permissions().mode() & 0o111,
327 0o111
328 );
329 let entry = fs::read_to_string(layout.desktop_file()).unwrap();
330 assert!(entry.contains(&installed.display().to_string()));
331 assert!(!should_offer_install(installed, layout, false));
332 }
333
334 #[test]
335 fn install_moves_a_downloaded_binary_and_writes_the_entry() {
336 let home = tempfile::tempdir().unwrap();
337 let downloads = home.path().join("Downloads");
338 fs::create_dir_all(&downloads).unwrap();
339 let binary = downloads.join("teams");
340 fs::write(&binary, b"v1").unwrap();
341 let layout = Layout::new(home.path().join("share"));
342 assert!(should_offer_install(&binary, &layout, false));
343 assert!(!should_offer_install(&binary, &layout, true));
344
345 let installed = install_binary(&binary, &layout).unwrap();
346
347 assert!(!binary.exists());
348 assert_installed(&installed, &layout, b"v1");
349 assert_eq!(install_binary(&installed, &layout).unwrap(), installed);
350 assert_eq!(fs::read(&installed).unwrap(), b"v1");
351 }
352
353 #[test]
354 fn install_copies_build_output_and_replaces_an_older_install() {
355 let home = tempfile::tempdir().unwrap();
356 let target = home.path().join("repo").join("target");
357 fs::create_dir_all(target.join("release")).unwrap();
358 fs::write(
359 target.join("CACHEDIR.TAG"),
360 b"Signature: 8a477f597d28d172789f06886806bc55",
361 )
362 .unwrap();
363 let binary = target.join("release").join("teams");
364 let layout = Layout::new(home.path().join("share"));
365 fs::write(&binary, b"v1").unwrap();
366 install_binary(&binary, &layout).unwrap();
367 fs::write(&binary, b"v2").unwrap();
368
369 let installed = install_binary(&binary, &layout).unwrap();
370
371 assert!(is_build_output(&binary));
372 assert!(binary.exists());
373 assert_installed(&installed, &layout, b"v2");
374 assert!(!layout.install_dir().join("teams.partial").exists());
375 }
376
377 #[test]
378 fn uninstall_removes_entry_binary_and_update_but_keeps_other_files() {
379 let home = tempfile::tempdir().unwrap();
380 let layout = Layout::new(home.path().join("share"));
381 let downloads = home.path().join("Downloads");
382 fs::create_dir_all(&downloads).unwrap();
383 fs::write(downloads.join("teams"), b"v1").unwrap();
384 install_binary(&downloads.join("teams"), &layout).unwrap();
385 fs::create_dir_all(layout.install_dir().join("update")).unwrap();
386 fs::write(layout.install_dir().join("update").join("teams"), b"v2").unwrap();
387
388 uninstall(&layout).unwrap();
389
390 assert!(!layout.desktop_file().exists());
391 assert!(!layout.install_dir().exists());
392 assert!(!layout.largest_icon().exists());
393 uninstall(&layout).unwrap();
394
395 fs::create_dir_all(layout.install_dir()).unwrap();
396 fs::write(layout.install_dir().join("notes.txt"), b"mine").unwrap();
397 uninstall(&layout).unwrap();
398 assert!(layout.install_dir().join("notes.txt").exists());
399 }
400
401 #[test]
402 fn the_icon_lands_in_every_size() {
403 let home = tempfile::tempdir().unwrap();
404 let layout = Layout::new(home.path());
405 install_icon(&layout, &png(300)).unwrap();
406 for size in ICON_SIZES {
407 let written = image::open(layout.icon_file(size)).unwrap();
408 assert_eq!((written.width(), written.height()), (size, size));
409 }
410 assert!(install_icon(&layout, b"not an image").is_err());
411 }
412}