BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / linux_update.rs

linux_update.rs

linux_update.rs 17.2 KiB Download Raw
1//! Release check for every install kind. A Linux copy under `~/.local` asks, then
2//! downloads and swaps. Windows downloads quietly from the shell poll. Every other
3//! release build opens the release page and leaves the binary in place. Flatpak and
4//! a build without a release tag stay quiet. Settings > General uses `updates.enabled`.
5
6use std::collections::HashMap;
7use std::sync::Arc;
8use std::sync::atomic::{AtomicU64, Ordering};
9use std::time::Duration;
10
11use app_base::release_feed::{self, AvailableUpdate};
12use gpui_kit::component::button::{Button, ButtonVariants as _};
13use gpui_kit::component::dialog::{Dialog, DialogFooter};
14use gpui_kit::component::{WindowExt as _, v_flex};
15use gpui_kit::*;
16
17use crate::app_state::AppHandle;
18use crate::i18n::{tr, tr_args};
19use crate::theme;
20use crate::updater;
21
22const ENABLED_META_KEY: &str = "updates.enabled";
23/// How often an offer waits for a main window closed into the tray to come back.
24const WINDOW_WAIT: Duration = Duration::from_secs(30);
25/// How often the progress dialog redraws while downloading.
26const PROGRESS_REDRAW: Duration = Duration::from_millis(250);
27const DIALOG_WIDTH: f32 = 460.;
28
29#[derive(Clone)]
30enum Stage {
31 Idle,
32 Offer(AvailableUpdate),
33 Downloading {
34 update: AvailableUpdate,
35 progress: Arc<AtomicU64>,
36 },
37 Ready(String),
38 Notice(String),
39 Failed(String),
40}
41
42struct LinuxUpdates {
43 stage: Stage,
44 dialog_window: Option<WindowId>,
45 /// "Not now" holds for this run only; the next start asks again.
46 declined: Option<String>,
47}
48
49impl Global for LinuxUpdates {}
50
51fn stage(cx: &App) -> Stage {
52 cx.try_global::<LinuxUpdates>()
53 .map(|updates| updates.stage.clone())
54 .unwrap_or(Stage::Idle)
55}
56
57fn set_stage(stage: Stage, cx: &mut App) {
58 if cx.has_global::<LinuxUpdates>() {
59 cx.global_mut::<LinuxUpdates>().stage = stage;
60 }
61 cx.refresh_windows();
62}
63
64fn with_store<R>(cx: &App, read: impl FnOnce(&store::Store) -> R) -> Option<R> {
65 cx.try_global::<AppHandle>()
66 .map(|handle| read(&handle.0.read(cx).store))
67}
68
69/// The periodic check; on by default.
70pub fn enabled(cx: &App) -> bool {
71 with_store(cx, |store| {
72 store.meta(ENABLED_META_KEY).ok().flatten().as_deref() != Some("0")
73 })
74 .unwrap_or(true)
75}
76
77pub fn set_enabled(enabled: bool, cx: &mut App) {
78 with_store(cx, |store| {
79 let _ = store.set_meta(ENABLED_META_KEY, if enabled { "1" } else { "0" });
80 });
81 cx.refresh_windows();
82}
83
84/// Flatpak updates through the package. A build without a release tag does not look.
85pub fn checks_releases() -> bool {
86 #[cfg(target_os = "linux")]
87 {
88 let flatpak = std::env::var_os("FLATPAK_ID");
89 if flatpak.is_some_and(|id| !id.is_empty()) {
90 return false;
91 }
92 }
93 app_base::version::release_tag().is_some()
94}
95
96/// Linux under `~/.local` replaces itself after the user agrees. Windows does that
97/// quietly from the shell poll, so this module does not download there.
98fn installed_release() -> Option<&'static str> {
99 #[cfg(target_os = "linux")]
100 {
101 crate::linux_install::updatable_release()
102 }
103 #[cfg(not(target_os = "linux"))]
104 {
105 None
106 }
107}
108
109fn declined(cx: &App) -> Option<String> {
110 cx.try_global::<LinuxUpdates>()
111 .and_then(|updates| updates.declined.clone())
112}
113
114fn decline(tag: &str, cx: &mut App) {
115 if cx.has_global::<LinuxUpdates>() {
116 cx.global_mut::<LinuxUpdates>().declined = Some(tag.to_owned());
117 }
118}
119
120/// A newer release a previous run downloaded but did not install ("Later").
121fn staged_update(running_tag: &str) -> Option<String> {
122 let paths = updater::current_paths()?;
123 if !updater::check(&paths) {
124 return None;
125 }
126 let tag = std::fs::read_to_string(&paths.version_file).ok()?;
127 let tag = tag.trim();
128 if release_feed::is_newer(tag, running_tag) {
129 return Some(tag.to_owned());
130 }
131 // Same or older than this build, e.g. after installing a release by hand.
132 let _ = std::fs::remove_file(&paths.version_file);
133 let _ = std::fs::remove_file(&paths.update_exe);
134 None
135}
136
137fn args(name: &str, value: impl Into<String>) -> HashMap<String, String> {
138 HashMap::from([(name.to_owned(), value.into())])
139}
140
141fn notice(text: String, cx: &mut App) {
142 if let Some(handle) = cx.try_global::<AppHandle>() {
143 handle
144 .0
145 .clone()
146 .update(cx, |state, cx| state.raise_notice(text, None, cx));
147 }
148}
149
150fn ensure_state(cx: &mut App) {
151 if !cx.has_global::<LinuxUpdates>() {
152 cx.set_global(LinuxUpdates {
153 stage: Stage::Idle,
154 dialog_window: None,
155 declined: None,
156 });
157 }
158}
159
160/// Starts the periodic check. Windows keeps its own quiet poll.
161pub fn start(cx: &mut App) {
162 if !checks_releases() || cfg!(windows) {
163 return;
164 }
165 ensure_state(cx);
166 if let Some(running_tag) = installed_release()
167 && let Some(tag) = staged_update(running_tag)
168 {
169 set_stage(Stage::Ready(tag), cx);
170 show_when_window_is_open(cx);
171 }
172 cx.spawn(async move |cx| {
173 cx.background_executor()
174 .timer(release_feed::FIRST_CHECK_DELAY)
175 .await;
176 loop {
177 let waiting = cx.update(|cx| matches!(stage(cx), Stage::Ready(_)));
178 if !waiting && cx.update(|cx| enabled(cx)) {
179 cx.update(|cx| check(false, cx));
180 }
181 cx.background_executor()
182 .timer(release_feed::CHECK_INTERVAL)
183 .await;
184 }
185 })
186 .detach();
187}
188
189/// Looks for a newer release. `manual` (Settings > Check now) also offers a version
190/// declined with "Not now" in this run and reports "up to date" and errors.
191pub fn check(manual: bool, cx: &mut App) {
192 if !checks_releases() {
193 return;
194 }
195 if cfg!(windows) {
196 check_windows(manual, cx);
197 return;
198 }
199 let Some(running_tag) = installed_release() else {
200 check_notice(manual, cx);
201 return;
202 };
203 ensure_state(cx);
204 match stage(cx) {
205 Stage::Downloading { .. } | Stage::Ready(_) => {
206 open_dialog(cx);
207 return;
208 }
209 Stage::Idle | Stage::Offer(_) | Stage::Notice(_) | Stage::Failed(_) => {}
210 }
211 if manual {
212 notice(tr("install.update_checking"), cx);
213 }
214 let find = release_feed::find_update(running_tag, cx);
215 cx.spawn(async move |cx| {
216 let found = find.await;
217 cx.update(|cx| match found {
218 Ok(Some(update)) if manual || declined(cx).as_deref() != Some(&update.tag) => {
219 offer(update, cx)
220 }
221 Ok(Some(_)) => {}
222 Ok(None) if manual => notice(tr("install.up_to_date"), cx),
223 Ok(None) => {}
224 Err(error) if manual => {
225 notice(tr_args("install.update_failed", &args("detail", error)), cx)
226 }
227 Err(error) => log::warn!("update check failed: {error}"),
228 });
229 })
230 .detach();
231}
232
233fn check_windows(manual: bool, cx: &mut App) {
234 if !manual && !enabled(cx) {
235 return;
236 }
237 let Some(running_tag) = app_base::version::release_tag() else {
238 return;
239 };
240 let Some(paths) = updater::current_paths() else {
241 return;
242 };
243 if manual {
244 notice(tr("install.update_checking"), cx);
245 }
246 let fetch = release_feed::fetch_update(running_tag, paths, cx);
247 cx.spawn(async move |cx| {
248 let found = fetch.await;
249 cx.update(|cx| match found {
250 Ok(Some(tag)) if manual => notice(
251 tr_args("install.update_ready_body", &args("version", tag)),
252 cx,
253 ),
254 Ok(_) if manual => notice(tr("install.up_to_date"), cx),
255 Ok(_) => {}
256 Err(error) if manual => {
257 notice(tr_args("install.update_failed", &args("detail", error)), cx)
258 }
259 Err(error) => log::warn!("update check failed: {error}"),
260 });
261 })
262 .detach();
263}
264
265fn check_notice(manual: bool, cx: &mut App) {
266 let Some(running_tag) = app_base::version::release_tag() else {
267 return;
268 };
269 ensure_state(cx);
270 if matches!(stage(cx), Stage::Notice(_)) {
271 open_dialog(cx);
272 return;
273 }
274 if manual {
275 notice(tr("install.update_checking"), cx);
276 }
277 let find = release_feed::find_release(running_tag, cx);
278 cx.spawn(async move |cx| {
279 let found = find.await;
280 cx.update(|cx| match found {
281 Ok(Some(update)) if manual || declined(cx).as_deref() != Some(&update.tag) => {
282 set_stage(Stage::Notice(update.tag), cx);
283 show_when_window_is_open(cx);
284 }
285 Ok(Some(_)) => {}
286 Ok(None) if manual => notice(tr("install.up_to_date"), cx),
287 Ok(None) => {}
288 Err(error) if manual => {
289 notice(tr_args("install.update_failed", &args("detail", error)), cx)
290 }
291 Err(error) => log::warn!("update check failed: {error}"),
292 });
293 })
294 .detach();
295}
296
297fn offer(update: AvailableUpdate, cx: &mut App) {
298 set_stage(Stage::Offer(update), cx);
299 show_when_window_is_open(cx);
300}
301
302/// Opens the dialog for the current stage, waiting for the main window if it is
303/// closed into the tray.
304fn show_when_window_is_open(cx: &mut App) {
305 cx.spawn(async move |cx| {
306 while cx.update(|cx| crate::main_window::current(cx).is_none()) {
307 cx.background_executor().timer(WINDOW_WAIT).await;
308 }
309 cx.update(|cx| {
310 if matches!(
311 stage(cx),
312 Stage::Offer(_) | Stage::Ready(_) | Stage::Notice(_)
313 ) {
314 open_dialog(cx);
315 }
316 });
317 })
318 .detach();
319}
320
321fn download(update: AvailableUpdate, cx: &mut App) {
322 let Some(paths) = updater::current_paths() else {
323 return;
324 };
325 let progress = Arc::new(AtomicU64::new(0));
326 set_stage(
327 Stage::Downloading {
328 update: update.clone(),
329 progress: progress.clone(),
330 },
331 cx,
332 );
333 let tag = update.tag.clone();
334 let task = release_feed::download_update(update, paths, progress, cx);
335 cx.spawn(async move |cx| {
336 let redraw = cx.spawn(async move |cx| {
337 loop {
338 cx.background_executor().timer(PROGRESS_REDRAW).await;
339 cx.update(|cx| cx.refresh_windows());
340 }
341 });
342 let result = task.await;
343 drop(redraw);
344 cx.update(|cx| {
345 match result {
346 Ok(()) => set_stage(Stage::Ready(tag), cx),
347 Err(error) => {
348 log::warn!("update download failed: {error}");
349 set_stage(Stage::Failed(error), cx);
350 }
351 }
352 open_dialog(cx);
353 });
354 })
355 .detach();
356}
357
358fn restart(cx: &mut App) {
359 let Some(paths) = updater::current_paths() else {
360 return;
361 };
362 match updater::install_and_relaunch(&paths) {
363 Ok(()) => cx.quit(),
364 Err(error) => set_stage(Stage::Failed(error), cx),
365 }
366}
367
368/// Opens the update dialog on the main window unless it is already open. It redraws
369/// from the current stage, so one dialog walks through offer, progress and restart.
370fn open_dialog(cx: &mut App) {
371 let Some(window) = crate::main_window::current(cx) else {
372 return;
373 };
374 if !cx.has_global::<LinuxUpdates>()
375 || cx.global::<LinuxUpdates>().dialog_window == Some(window.window_id())
376 {
377 return;
378 }
379 cx.global_mut::<LinuxUpdates>().dialog_window = Some(window.window_id());
380 let opened = window.update(cx, |_, window, cx| {
381 window.open_dialog(cx, |dialog: Dialog, _, cx| build_dialog(dialog, cx));
382 });
383 if opened.is_err() {
384 cx.global_mut::<LinuxUpdates>().dialog_window = None;
385 }
386}
387
388fn close_dialog(window: &mut Window, cx: &mut App) {
389 if cx.has_global::<LinuxUpdates>() {
390 cx.global_mut::<LinuxUpdates>().dialog_window = None;
391 }
392 window.close_dialog(cx);
393}
394
395fn percent(progress: &AtomicU64, size: u64) -> u64 {
396 (progress.load(Ordering::Relaxed) * 100)
397 .checked_div(size)
398 .unwrap_or(0)
399 .min(100)
400}
401
402fn build_dialog(dialog: Dialog, cx: &App) -> Dialog {
403 let running = app_base::version::release_tag().unwrap_or_default();
404 let (title, body, footer) = match stage(cx) {
405 Stage::Offer(update) => {
406 let mut text_args = args("version", update.tag.clone());
407 text_args.insert("current".to_owned(), running.to_owned());
408 let tag = update.tag.clone();
409 (
410 tr("install.update_available_title"),
411 tr_args("install.update_available_body", &text_args),
412 DialogFooter::new()
413 .child(
414 Button::new("update-not-now")
415 .label(tr("install.not_now"))
416 .on_click(move |_, window, cx| {
417 decline(&tag, cx);
418 set_stage(Stage::Idle, cx);
419 close_dialog(window, cx);
420 }),
421 )
422 .child(
423 Button::new("update-start")
424 .primary()
425 .label(tr("install.update_now"))
426 .on_click(move |_, _, cx| download(update.clone(), cx)),
427 ),
428 )
429 }
430 Stage::Downloading { update, progress } => {
431 let mut text_args = args("version", update.tag.clone());
432 text_args.insert(
433 "percent".to_owned(),
434 percent(&progress, update.asset.size).to_string(),
435 );
436 (
437 tr("install.update_available_title"),
438 tr_args("install.update_downloading", &text_args),
439 DialogFooter::new().child(
440 Button::new("update-hide")
441 .label(tr("install.hide"))
442 .on_click(|_, window, cx| close_dialog(window, cx)),
443 ),
444 )
445 }
446 Stage::Notice(tag) => {
447 let mut text_args = args("version", tag.clone());
448 text_args.insert("current".to_owned(), running.to_owned());
449 let open = tag.clone();
450 (
451 tr("install.update_available_title"),
452 tr_args("install.update_available_body", &text_args),
453 DialogFooter::new()
454 .child(
455 Button::new("update-not-now")
456 .label(tr("install.not_now"))
457 .on_click(move |_, window, cx| {
458 decline(&tag, cx);
459 set_stage(Stage::Idle, cx);
460 close_dialog(window, cx);
461 }),
462 )
463 .child(
464 Button::new("update-open-release")
465 .primary()
466 .label(tr("install.open_release"))
467 .on_click(move |_, window, cx| {
468 let url = release_feed::release_page_url(&open);
469 decline(&open, cx);
470 set_stage(Stage::Idle, cx);
471 close_dialog(window, cx);
472 cx.open_url(&url);
473 }),
474 ),
475 )
476 }
477 Stage::Ready(tag) => (
478 tr("install.update_ready_title"),
479 tr_args("install.update_ready_body", &args("version", tag)),
480 DialogFooter::new()
481 .child(
482 Button::new("update-later")
483 .label(tr("install.later"))
484 .on_click(|_, window, cx| close_dialog(window, cx)),
485 )
486 .child(
487 Button::new("update-restart")
488 .primary()
489 .label(tr("install.restart_now"))
490 .on_click(|_, _, cx| restart(cx)),
491 ),
492 ),
493 Stage::Failed(error) => (
494 tr("install.update_available_title"),
495 tr_args("install.update_failed", &args("detail", error)),
496 DialogFooter::new().child(
497 Button::new("update-close")
498 .label(tr("common.close"))
499 .on_click(|_, window, cx| {
500 set_stage(Stage::Idle, cx);
501 close_dialog(window, cx);
502 }),
503 ),
504 ),
505 Stage::Idle => (String::new(), String::new(), DialogFooter::new()),
506 };
507 // Only the buttons close it, so the stage and the open flag stay in step.
508 dialog
509 .title(title)
510 .w(px(DIALOG_WIDTH))
511 .keyboard(false)
512 .overlay_closable(false)
513 .close_button(false)
514 .child(v_flex().gap(px(8.)).text_color(theme::text()).child(body))
515 .footer(footer)
516}
517
518#[cfg(test)]
519mod tests {
520 use std::sync::atomic::{AtomicU64, Ordering};
521
522 use super::percent;
523
524 #[test]
525 fn percent_is_clamped_and_safe_without_a_size() {
526 let progress = AtomicU64::new(50);
527 assert_eq!(percent(&progress, 200), 25);
528 assert_eq!(percent(&progress, 0), 0);
529 progress.store(500, Ordering::Relaxed);
530 assert_eq!(percent(&progress, 200), 100);
531 }
532}