| 1 | //! Linux self-update, always with consent: a newer GitHub release is offered in a |
| 2 | //! dialog; "Update" downloads it with progress and "Restart now" swaps the binary |
| 3 | //! and relaunches. Nothing restarts without a click. Settings > General turns the |
| 4 | //! periodic check off; "Check now" works either way. |
| 5 | |
| 6 | use std::collections::HashMap; |
| 7 | use std::sync::Arc; |
| 8 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 9 | use std::time::Duration; |
| 10 | |
| 11 | use app_base::release_feed::{self, AvailableUpdate}; |
| 12 | use gpui_kit::component::button::{Button, ButtonVariants as _}; |
| 13 | use gpui_kit::component::dialog::{Dialog, DialogFooter}; |
| 14 | use gpui_kit::component::{WindowExt as _, v_flex}; |
| 15 | use gpui_kit::*; |
| 16 | |
| 17 | use crate::app_state::AppHandle; |
| 18 | use crate::i18n::{tr, tr_args}; |
| 19 | use crate::theme; |
| 20 | use crate::updater; |
| 21 | |
| 22 | const ENABLED_META_KEY: &str = "linux.updates.enabled"; |
| 23 | /// How often an offer waits for a main window closed into the tray to come back. |
| 24 | const WINDOW_WAIT: Duration = Duration::from_secs(30); |
| 25 | /// How often the progress dialog redraws while downloading. |
| 26 | const PROGRESS_REDRAW: Duration = Duration::from_millis(250); |
| 27 | const DIALOG_WIDTH: f32 = 460.; |
| 28 | |
| 29 | #[derive(Clone)] |
| 30 | enum Stage { |
| 31 | Idle, |
| 32 | Offer(AvailableUpdate), |
| 33 | Downloading { |
| 34 | update: AvailableUpdate, |
| 35 | progress: Arc<AtomicU64>, |
| 36 | }, |
| 37 | Ready(String), |
| 38 | Failed(String), |
| 39 | } |
| 40 | |
| 41 | struct LinuxUpdates { |
| 42 | stage: Stage, |
| 43 | dialog_window: Option<WindowId>, |
| 44 | /// "Not now" holds for this run only; the next start asks again. |
| 45 | declined: Option<String>, |
| 46 | } |
| 47 | |
| 48 | impl Global for LinuxUpdates {} |
| 49 | |
| 50 | fn stage(cx: &App) -> Stage { |
| 51 | cx.try_global::<LinuxUpdates>() |
| 52 | .map(|updates| updates.stage.clone()) |
| 53 | .unwrap_or(Stage::Idle) |
| 54 | } |
| 55 | |
| 56 | fn set_stage(stage: Stage, cx: &mut App) { |
| 57 | if cx.has_global::<LinuxUpdates>() { |
| 58 | cx.global_mut::<LinuxUpdates>().stage = stage; |
| 59 | } |
| 60 | cx.refresh_windows(); |
| 61 | } |
| 62 | |
| 63 | fn with_store<R>(cx: &App, read: impl FnOnce(&store::Store) -> R) -> Option<R> { |
| 64 | cx.try_global::<AppHandle>() |
| 65 | .map(|handle| read(&handle.0.read(cx).store)) |
| 66 | } |
| 67 | |
| 68 | /// The periodic check; on by default. |
| 69 | pub fn enabled(cx: &App) -> bool { |
| 70 | with_store(cx, |store| { |
| 71 | store.meta(ENABLED_META_KEY).ok().flatten().as_deref() != Some("0") |
| 72 | }) |
| 73 | .unwrap_or(true) |
| 74 | } |
| 75 | |
| 76 | pub fn set_enabled(enabled: bool, cx: &mut App) { |
| 77 | with_store(cx, |store| { |
| 78 | let _ = store.set_meta(ENABLED_META_KEY, if enabled { "1" } else { "0" }); |
| 79 | }); |
| 80 | cx.refresh_windows(); |
| 81 | } |
| 82 | |
| 83 | fn declined(cx: &App) -> Option<String> { |
| 84 | cx.try_global::<LinuxUpdates>() |
| 85 | .and_then(|updates| updates.declined.clone()) |
| 86 | } |
| 87 | |
| 88 | fn decline(tag: &str, cx: &mut App) { |
| 89 | if cx.has_global::<LinuxUpdates>() { |
| 90 | cx.global_mut::<LinuxUpdates>().declined = Some(tag.to_owned()); |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// A newer release a previous run downloaded but did not install ("Later"). |
| 95 | fn staged_update(running_tag: &str) -> Option<String> { |
| 96 | let paths = updater::current_paths()?; |
| 97 | if !updater::check(&paths) { |
| 98 | return None; |
| 99 | } |
| 100 | let tag = std::fs::read_to_string(&paths.version_file).ok()?; |
| 101 | let tag = tag.trim(); |
| 102 | if release_feed::is_newer(tag, running_tag) { |
| 103 | return Some(tag.to_owned()); |
| 104 | } |
| 105 | // Same or older than this build, e.g. after installing a release by hand. |
| 106 | let _ = std::fs::remove_file(&paths.version_file); |
| 107 | let _ = std::fs::remove_file(&paths.update_exe); |
| 108 | None |
| 109 | } |
| 110 | |
| 111 | fn args(name: &str, value: impl Into<String>) -> HashMap<String, String> { |
| 112 | HashMap::from([(name.to_owned(), value.into())]) |
| 113 | } |
| 114 | |
| 115 | fn notice(text: String, cx: &mut App) { |
| 116 | if let Some(handle) = cx.try_global::<AppHandle>() { |
| 117 | handle |
| 118 | .0 |
| 119 | .clone() |
| 120 | .update(cx, |state, cx| state.raise_notice(text, None, cx)); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | fn ensure_state(cx: &mut App) { |
| 125 | if !cx.has_global::<LinuxUpdates>() { |
| 126 | cx.set_global(LinuxUpdates { |
| 127 | stage: Stage::Idle, |
| 128 | dialog_window: None, |
| 129 | declined: None, |
| 130 | }); |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | /// Starts the periodic check. Only the installed copy of a release build updates. |
| 135 | pub fn start(cx: &mut App) { |
| 136 | if crate::linux_install::updatable_release().is_none() { |
| 137 | return; |
| 138 | } |
| 139 | ensure_state(cx); |
| 140 | if let Some(running_tag) = crate::linux_install::updatable_release() |
| 141 | && let Some(tag) = staged_update(running_tag) |
| 142 | { |
| 143 | set_stage(Stage::Ready(tag), cx); |
| 144 | show_when_window_is_open(cx); |
| 145 | } |
| 146 | cx.spawn(async move |cx| { |
| 147 | cx.background_executor() |
| 148 | .timer(release_feed::FIRST_CHECK_DELAY) |
| 149 | .await; |
| 150 | loop { |
| 151 | let waiting = cx.update(|cx| matches!(stage(cx), Stage::Ready(_))); |
| 152 | if !waiting && cx.update(|cx| enabled(cx)) { |
| 153 | cx.update(|cx| check(false, cx)); |
| 154 | } |
| 155 | cx.background_executor() |
| 156 | .timer(release_feed::CHECK_INTERVAL) |
| 157 | .await; |
| 158 | } |
| 159 | }) |
| 160 | .detach(); |
| 161 | } |
| 162 | |
| 163 | /// Looks for a newer release. `manual` (Settings > Check now) also offers a version |
| 164 | /// declined with "Not now" in this run and reports "up to date" and errors. |
| 165 | pub fn check(manual: bool, cx: &mut App) { |
| 166 | let Some(running_tag) = crate::linux_install::updatable_release() else { |
| 167 | if manual { |
| 168 | notice(tr("install.updates_need_install"), cx); |
| 169 | } |
| 170 | return; |
| 171 | }; |
| 172 | ensure_state(cx); |
| 173 | match stage(cx) { |
| 174 | Stage::Downloading { .. } | Stage::Ready(_) => { |
| 175 | open_dialog(cx); |
| 176 | return; |
| 177 | } |
| 178 | Stage::Idle | Stage::Offer(_) | Stage::Failed(_) => {} |
| 179 | } |
| 180 | if manual { |
| 181 | notice(tr("install.update_checking"), cx); |
| 182 | } |
| 183 | let find = release_feed::find_update(running_tag, cx); |
| 184 | cx.spawn(async move |cx| { |
| 185 | let found = find.await; |
| 186 | cx.update(|cx| match found { |
| 187 | Ok(Some(update)) if manual || declined(cx).as_deref() != Some(&update.tag) => { |
| 188 | offer(update, cx) |
| 189 | } |
| 190 | Ok(Some(_)) => {} |
| 191 | Ok(None) if manual => notice(tr("install.up_to_date"), cx), |
| 192 | Ok(None) => {} |
| 193 | Err(error) if manual => { |
| 194 | notice(tr_args("install.update_failed", &args("detail", error)), cx) |
| 195 | } |
| 196 | Err(error) => log::warn!("update check failed: {error}"), |
| 197 | }); |
| 198 | }) |
| 199 | .detach(); |
| 200 | } |
| 201 | |
| 202 | fn offer(update: AvailableUpdate, cx: &mut App) { |
| 203 | set_stage(Stage::Offer(update), cx); |
| 204 | show_when_window_is_open(cx); |
| 205 | } |
| 206 | |
| 207 | /// Opens the dialog for the current stage, waiting for the main window if it is |
| 208 | /// closed into the tray. |
| 209 | fn show_when_window_is_open(cx: &mut App) { |
| 210 | cx.spawn(async move |cx| { |
| 211 | while cx.update(|cx| crate::main_window::current(cx).is_none()) { |
| 212 | cx.background_executor().timer(WINDOW_WAIT).await; |
| 213 | } |
| 214 | cx.update(|cx| { |
| 215 | if matches!(stage(cx), Stage::Offer(_) | Stage::Ready(_)) { |
| 216 | open_dialog(cx); |
| 217 | } |
| 218 | }); |
| 219 | }) |
| 220 | .detach(); |
| 221 | } |
| 222 | |
| 223 | fn download(update: AvailableUpdate, cx: &mut App) { |
| 224 | let Some(paths) = updater::current_paths() else { |
| 225 | return; |
| 226 | }; |
| 227 | let progress = Arc::new(AtomicU64::new(0)); |
| 228 | set_stage( |
| 229 | Stage::Downloading { |
| 230 | update: update.clone(), |
| 231 | progress: progress.clone(), |
| 232 | }, |
| 233 | cx, |
| 234 | ); |
| 235 | let tag = update.tag.clone(); |
| 236 | let task = release_feed::download_update(update, paths, progress, cx); |
| 237 | cx.spawn(async move |cx| { |
| 238 | let redraw = cx.spawn(async move |cx| { |
| 239 | loop { |
| 240 | cx.background_executor().timer(PROGRESS_REDRAW).await; |
| 241 | cx.update(|cx| cx.refresh_windows()); |
| 242 | } |
| 243 | }); |
| 244 | let result = task.await; |
| 245 | drop(redraw); |
| 246 | cx.update(|cx| { |
| 247 | match result { |
| 248 | Ok(()) => set_stage(Stage::Ready(tag), cx), |
| 249 | Err(error) => { |
| 250 | log::warn!("update download failed: {error}"); |
| 251 | set_stage(Stage::Failed(error), cx); |
| 252 | } |
| 253 | } |
| 254 | open_dialog(cx); |
| 255 | }); |
| 256 | }) |
| 257 | .detach(); |
| 258 | } |
| 259 | |
| 260 | fn restart(cx: &mut App) { |
| 261 | let Some(paths) = updater::current_paths() else { |
| 262 | return; |
| 263 | }; |
| 264 | match updater::install_and_relaunch(&paths) { |
| 265 | Ok(()) => cx.quit(), |
| 266 | Err(error) => set_stage(Stage::Failed(error), cx), |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | /// Opens the update dialog on the main window unless it is already open. It redraws |
| 271 | /// from the current stage, so one dialog walks through offer, progress and restart. |
| 272 | fn open_dialog(cx: &mut App) { |
| 273 | let Some(window) = crate::main_window::current(cx) else { |
| 274 | return; |
| 275 | }; |
| 276 | if !cx.has_global::<LinuxUpdates>() |
| 277 | || cx.global::<LinuxUpdates>().dialog_window == Some(window.window_id()) |
| 278 | { |
| 279 | return; |
| 280 | } |
| 281 | cx.global_mut::<LinuxUpdates>().dialog_window = Some(window.window_id()); |
| 282 | let opened = window.update(cx, |_, window, cx| { |
| 283 | window.open_dialog(cx, |dialog: Dialog, _, cx| build_dialog(dialog, cx)); |
| 284 | }); |
| 285 | if opened.is_err() { |
| 286 | cx.global_mut::<LinuxUpdates>().dialog_window = None; |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | fn close_dialog(window: &mut Window, cx: &mut App) { |
| 291 | if cx.has_global::<LinuxUpdates>() { |
| 292 | cx.global_mut::<LinuxUpdates>().dialog_window = None; |
| 293 | } |
| 294 | window.close_dialog(cx); |
| 295 | } |
| 296 | |
| 297 | fn percent(progress: &AtomicU64, size: u64) -> u64 { |
| 298 | (progress.load(Ordering::Relaxed) * 100) |
| 299 | .checked_div(size) |
| 300 | .unwrap_or(0) |
| 301 | .min(100) |
| 302 | } |
| 303 | |
| 304 | fn build_dialog(dialog: Dialog, cx: &App) -> Dialog { |
| 305 | let running = app_base::version::release_tag().unwrap_or_default(); |
| 306 | let (title, body, footer) = match stage(cx) { |
| 307 | Stage::Offer(update) => { |
| 308 | let mut text_args = args("version", update.tag.clone()); |
| 309 | text_args.insert("current".to_owned(), running.to_owned()); |
| 310 | let tag = update.tag.clone(); |
| 311 | ( |
| 312 | tr("install.update_available_title"), |
| 313 | tr_args("install.update_available_body", &text_args), |
| 314 | DialogFooter::new() |
| 315 | .child( |
| 316 | Button::new("update-not-now") |
| 317 | .label(tr("install.not_now")) |
| 318 | .on_click(move |_, window, cx| { |
| 319 | decline(&tag, cx); |
| 320 | set_stage(Stage::Idle, cx); |
| 321 | close_dialog(window, cx); |
| 322 | }), |
| 323 | ) |
| 324 | .child( |
| 325 | Button::new("update-start") |
| 326 | .primary() |
| 327 | .label(tr("install.update_now")) |
| 328 | .on_click(move |_, _, cx| download(update.clone(), cx)), |
| 329 | ), |
| 330 | ) |
| 331 | } |
| 332 | Stage::Downloading { update, progress } => { |
| 333 | let mut text_args = args("version", update.tag.clone()); |
| 334 | text_args.insert( |
| 335 | "percent".to_owned(), |
| 336 | percent(&progress, update.asset.size).to_string(), |
| 337 | ); |
| 338 | ( |
| 339 | tr("install.update_available_title"), |
| 340 | tr_args("install.update_downloading", &text_args), |
| 341 | DialogFooter::new().child( |
| 342 | Button::new("update-hide") |
| 343 | .label(tr("install.hide")) |
| 344 | .on_click(|_, window, cx| close_dialog(window, cx)), |
| 345 | ), |
| 346 | ) |
| 347 | } |
| 348 | Stage::Ready(tag) => ( |
| 349 | tr("install.update_ready_title"), |
| 350 | tr_args("install.update_ready_body", &args("version", tag)), |
| 351 | DialogFooter::new() |
| 352 | .child( |
| 353 | Button::new("update-later") |
| 354 | .label(tr("install.later")) |
| 355 | .on_click(|_, window, cx| close_dialog(window, cx)), |
| 356 | ) |
| 357 | .child( |
| 358 | Button::new("update-restart") |
| 359 | .primary() |
| 360 | .label(tr("install.restart_now")) |
| 361 | .on_click(|_, _, cx| restart(cx)), |
| 362 | ), |
| 363 | ), |
| 364 | Stage::Failed(error) => ( |
| 365 | tr("install.update_available_title"), |
| 366 | tr_args("install.update_failed", &args("detail", error)), |
| 367 | DialogFooter::new().child( |
| 368 | Button::new("update-close") |
| 369 | .label(tr("common.close")) |
| 370 | .on_click(|_, window, cx| { |
| 371 | set_stage(Stage::Idle, cx); |
| 372 | close_dialog(window, cx); |
| 373 | }), |
| 374 | ), |
| 375 | ), |
| 376 | Stage::Idle => (String::new(), String::new(), DialogFooter::new()), |
| 377 | }; |
| 378 | // Only the buttons close it, so the stage and the open flag stay in step. |
| 379 | dialog |
| 380 | .title(title) |
| 381 | .w(px(DIALOG_WIDTH)) |
| 382 | .keyboard(false) |
| 383 | .overlay_closable(false) |
| 384 | .close_button(false) |
| 385 | .child(v_flex().gap(px(8.)).text_color(theme::text()).child(body)) |
| 386 | .footer(footer) |
| 387 | } |
| 388 | |
| 389 | #[cfg(test)] |
| 390 | mod tests { |
| 391 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 392 | |
| 393 | use super::percent; |
| 394 | |
| 395 | #[test] |
| 396 | fn percent_is_clamped_and_safe_without_a_size() { |
| 397 | let progress = AtomicU64::new(50); |
| 398 | assert_eq!(percent(&progress, 200), 25); |
| 399 | assert_eq!(percent(&progress, 0), 0); |
| 400 | progress.store(500, Ordering::Relaxed); |
| 401 | assert_eq!(percent(&progress, 200), 100); |
| 402 | } |
| 403 | } |