BlueGit

ict rusty-teams

Files

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

linux_update.rs

linux_update.rs 12.9 KiB Download Raw
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
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 = "linux.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 Failed(String),
39}
40
41struct LinuxUpdates {
42 stage: Stage,
43 dialog_open: bool,
44 /// "Not now" holds for this run only; the next start asks again.
45 declined: Option<String>,
46}
47
48impl Global for LinuxUpdates {}
49
50fn stage(cx: &App) -> Stage {
51 cx.try_global::<LinuxUpdates>()
52 .map(|updates| updates.stage.clone())
53 .unwrap_or(Stage::Idle)
54}
55
56fn 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
63fn 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.
69pub 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
76pub 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
83fn declined(cx: &App) -> Option<String> {
84 cx.try_global::<LinuxUpdates>()
85 .and_then(|updates| updates.declined.clone())
86}
87
88fn 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").
95fn 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
111fn args(name: &str, value: impl Into<String>) -> HashMap<String, String> {
112 HashMap::from([(name.to_owned(), value.into())])
113}
114
115fn 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
124fn ensure_state(cx: &mut App) {
125 if !cx.has_global::<LinuxUpdates>() {
126 cx.set_global(LinuxUpdates {
127 stage: Stage::Idle,
128 dialog_open: false,
129 declined: None,
130 });
131 }
132}
133
134/// Starts the periodic check. Only the installed copy of a release build updates.
135pub 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.
165pub 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
202fn 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.
209fn 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
223fn 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
260fn 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.
272fn open_dialog(cx: &mut App) {
273 let Some(window) = crate::main_window::current(cx) else {
274 return;
275 };
276 if !cx.has_global::<LinuxUpdates>() || cx.global::<LinuxUpdates>().dialog_open {
277 return;
278 }
279 cx.global_mut::<LinuxUpdates>().dialog_open = true;
280 let opened = window.update(cx, |_, window, cx| {
281 window.open_dialog(cx, |dialog: Dialog, _, cx| build_dialog(dialog, cx));
282 });
283 if opened.is_err() {
284 cx.global_mut::<LinuxUpdates>().dialog_open = false;
285 }
286}
287
288fn close_dialog(window: &mut Window, cx: &mut App) {
289 if cx.has_global::<LinuxUpdates>() {
290 cx.global_mut::<LinuxUpdates>().dialog_open = false;
291 }
292 window.close_dialog(cx);
293}
294
295fn percent(progress: &AtomicU64, size: u64) -> u64 {
296 (progress.load(Ordering::Relaxed) * 100)
297 .checked_div(size)
298 .unwrap_or(0)
299 .min(100)
300}
301
302fn build_dialog(dialog: Dialog, cx: &App) -> Dialog {
303 let running = app_base::version::release_tag().unwrap_or_default();
304 let (title, body, footer) = match stage(cx) {
305 Stage::Offer(update) => {
306 let mut text_args = args("version", update.tag.clone());
307 text_args.insert("current".to_owned(), running.to_owned());
308 let tag = update.tag.clone();
309 (
310 tr("install.update_available_title"),
311 tr_args("install.update_available_body", &text_args),
312 DialogFooter::new()
313 .child(
314 Button::new("update-not-now")
315 .label(tr("install.not_now"))
316 .on_click(move |_, window, cx| {
317 decline(&tag, cx);
318 set_stage(Stage::Idle, cx);
319 close_dialog(window, cx);
320 }),
321 )
322 .child(
323 Button::new("update-start")
324 .primary()
325 .label(tr("install.update_now"))
326 .on_click(move |_, _, cx| download(update.clone(), cx)),
327 ),
328 )
329 }
330 Stage::Downloading { update, progress } => {
331 let mut text_args = args("version", update.tag.clone());
332 text_args.insert(
333 "percent".to_owned(),
334 percent(&progress, update.asset.size).to_string(),
335 );
336 (
337 tr("install.update_available_title"),
338 tr_args("install.update_downloading", &text_args),
339 DialogFooter::new().child(
340 Button::new("update-hide")
341 .label(tr("install.hide"))
342 .on_click(|_, window, cx| close_dialog(window, cx)),
343 ),
344 )
345 }
346 Stage::Ready(tag) => (
347 tr("install.update_ready_title"),
348 tr_args("install.update_ready_body", &args("version", tag)),
349 DialogFooter::new()
350 .child(
351 Button::new("update-later")
352 .label(tr("install.later"))
353 .on_click(|_, window, cx| close_dialog(window, cx)),
354 )
355 .child(
356 Button::new("update-restart")
357 .primary()
358 .label(tr("install.restart_now"))
359 .on_click(|_, _, cx| restart(cx)),
360 ),
361 ),
362 Stage::Failed(error) => (
363 tr("install.update_available_title"),
364 tr_args("install.update_failed", &args("detail", error)),
365 DialogFooter::new().child(
366 Button::new("update-close")
367 .label(tr("common.close"))
368 .on_click(|_, window, cx| {
369 set_stage(Stage::Idle, cx);
370 close_dialog(window, cx);
371 }),
372 ),
373 ),
374 Stage::Idle => (String::new(), String::new(), DialogFooter::new()),
375 };
376 // Only the buttons close it, so the stage and the open flag stay in step.
377 dialog
378 .title(title)
379 .w(px(DIALOG_WIDTH))
380 .keyboard(false)
381 .overlay_closable(false)
382 .close_button(false)
383 .child(v_flex().gap(px(8.)).text_color(theme::text()).child(body))
384 .footer(footer)
385}
386
387#[cfg(test)]
388mod tests {
389 use std::sync::atomic::{AtomicU64, Ordering};
390
391 use super::percent;
392
393 #[test]
394 fn percent_is_clamped_and_safe_without_a_size() {
395 let progress = AtomicU64::new(50);
396 assert_eq!(percent(&progress, 200), 25);
397 assert_eq!(percent(&progress, 0), 0);
398 progress.store(500, Ordering::Relaxed);
399 assert_eq!(percent(&progress, 200), 100);
400 }
401}