Address title-bar review findings (#24)
CI / core (pull_request) Successful in 1m9s

This commit is contained in:
nessar committed 2026-11-18 23:24:23 +01:00
1 parent 23eb933a68
commit 797b7e83e0
5 files changed
+303 -111

No files matched your search

+21 -25
View File
@@ -22,7 +22,7 @@ use gpui_kit::*;
use settings::{KeyEvent, KeyForm, KeyStore, apply_theme};
use stats_page::StatsPage;
use title_bar::{action_button, title_bar};
use title_bar::{MIN_WINDOW_SIZE, refresh_button, settings_button, title_bar, track_maximized};
use worker::{Msg, spawn_follower};
#[derive(Clone, Copy, PartialEq)]
@@ -37,12 +37,13 @@ struct RootView {
page: Entity<StatsPage>,
form: Entity<KeyForm>,
focus: FocusHandle,
maximized: Entity<bool>,
screen: Screen,
tracker: Arc<Tracker>,
/// The configured Riot ID, used when the game client is closed on first launch.
fallback_riot_id: String,
tx: Sender<Msg>,
_subscriptions: [Subscription; 2],
_form_events: Subscription,
}
impl RootView {
@@ -69,15 +70,7 @@ impl RootView {
)
});
let form = cx.new(|cx| KeyForm::new(store, first_launch, window, cx));
let mut busy = page.read(cx).busy();
let subscriptions = [
cx.observe(&page, move |_, page, cx| {
let next = page.read(cx).busy();
if next != busy {
busy = next;
cx.notify();
}
}),
let form_events =
cx.subscribe_in(&form, window, |this, _, event: &KeyEvent, window, cx| {
match event {
KeyEvent::Saved if this.screen == Screen::Prompt => {
@@ -87,14 +80,13 @@ impl RootView {
spawn_follower(tracker, riot_id, this.tx.clone());
this.page.update(cx, |page, cx| page.following(cx));
}
KeyEvent::Saved => this.page.update(cx, |page, cx| page.begin_refresh(cx)),
KeyEvent::Saved => this.page.update(cx, |page, cx| page.request_refresh(cx)),
KeyEvent::Back => {}
}
this.screen = Screen::Page;
this.focus.focus(window, cx);
cx.notify();
}),
];
});
let screen = if first_launch {
Screen::Prompt
} else {
@@ -105,11 +97,12 @@ impl RootView {
page,
form,
focus: initial_focus(window, cx),
maximized: track_maximized(window, cx),
screen,
tracker,
fallback_riot_id: riot_id,
tx,
_subscriptions: subscriptions,
_form_events: form_events,
}
}
@@ -119,15 +112,16 @@ impl RootView {
}
impl Render for RootView {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let refresh = action_button("refresh", IconName::RefreshCw, "Actualiser")
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let refresh = refresh_button()
.disabled(!self.can_refresh(cx))
.on_click(cx.listener(|this, _, _, cx| {
if this.can_refresh(cx) {
this.page.update(cx, |page, cx| page.begin_refresh(cx));
this.page
.update(cx, |page, cx| page.request_manual_refresh(cx));
}
}));
let settings = action_button("settings", IconName::Settings, "Paramètres")
let settings = settings_button()
.disabled(self.screen != Screen::Page)
.on_click(cx.listener(|this, _, window, cx| {
if this.screen == Screen::Page {
@@ -146,7 +140,7 @@ impl Render for RootView {
.track_focus(&self.focus)
.v_flex()
.size_full()
.child(title_bar(refresh, settings, window, cx))
.child(title_bar(refresh, settings, *self.maximized.read(cx), cx))
.child(div().flex_1().min_h_0().child(content))
}
}
@@ -155,19 +149,20 @@ impl Render for RootView {
struct Unavailable {
lines: Vec<String>,
focus: FocusHandle,
maximized: Entity<bool>,
}
impl Render for Unavailable {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.id("unavailable")
.track_focus(&self.focus)
.v_flex()
.size_full()
.child(title_bar(
action_button("refresh", IconName::RefreshCw, "Actualiser").disabled(true),
action_button("settings", IconName::Settings, "Paramètres").disabled(true),
window,
refresh_button().disabled(true),
settings_button().disabled(true),
*self.maximized.read(cx),
cx,
))
.child(
@@ -252,7 +247,7 @@ fn main() {
size(px(1280.), px(860.)),
cx,
))),
window_min_size: Some(size(px(540.), px(360.))),
window_min_size: Some(MIN_WINDOW_SIZE),
..Default::default()
};
match startup() {
@@ -271,6 +266,7 @@ fn main() {
cx.new(|cx| Unavailable {
lines,
focus: initial_focus(window, cx),
maximized: track_maximized(window, cx),
})
})
.map(drop),
+55 -18
View File
@@ -82,12 +82,15 @@ pub enum KeyEvent {
pub struct KeyForm {
store: KeyStore,
input: Entity<InputState>,
scroll: ScrollHandle,
key_focus: FocusHandle,
preferences_focus: FocusHandle,
/// The first-launch prompt (no key and nothing stored yet) has no way back.
first_launch: bool,
error: Option<String>,
preference_error: Option<&'static str>,
tray: Option<Rc<Tray>>,
_subscriptions: [Subscription; 2],
_subscriptions: [Subscription; 4],
}
impl EventEmitter<KeyEvent> for KeyForm {}
@@ -125,14 +128,31 @@ impl KeyForm {
this.save(window, cx);
}
});
let key_focus = cx.focus_handle();
let preferences_focus = cx.focus_handle();
let reveal_key = cx.on_focus_in(&key_focus, window, |this, window, cx| {
if this.scroll.max_offset().y > px(0.) {
this.scroll.scroll_to_bottom();
window.defer(cx, |window, _| window.refresh());
}
});
let reveal_preferences = cx.on_focus_in(&preferences_focus, window, |this, window, cx| {
if this.scroll.offset().y < px(0.) {
this.scroll.set_offset(point(px(0.), px(0.)));
window.defer(cx, |window, _| window.refresh());
}
});
KeyForm {
first_launch,
store,
input,
scroll: ScrollHandle::new(),
key_focus,
preferences_focus,
error: None,
preference_error: None,
tray,
_subscriptions: [subscription, appearance],
_subscriptions: [subscription, appearance, reveal_key, reveal_preferences],
}
}
@@ -140,6 +160,7 @@ impl KeyForm {
pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.error = None;
self.preference_error = None;
self.scroll.set_offset(point(px(0.), px(0.)));
self.clear(window, cx);
cx.notify();
}
@@ -180,6 +201,8 @@ impl KeyForm {
let preferences = self.store.config.preferences;
let danger = cx.theme().danger;
div()
.id("preferences")
.track_focus(&self.preferences_focus)
.v_flex()
.gap_3()
.child(
@@ -288,26 +311,26 @@ impl Render for KeyForm {
.label("Retour")
.on_click(cx.listener(|_, _, _, cx| cx.emit(KeyEvent::Back)))
}));
div()
.size_full()
.flex()
.items_center()
.justify_center()
let fields = div()
.v_flex()
.w(px(520.))
.max_w_full()
.px_4()
.gap_3()
.child(
div()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.child(title),
)
.children((!self.first_launch).then(|| self.preferences(cx)))
.child(div().text_color(muted).child(explanation))
.child(
div()
.id("key-form-controls")
.track_focus(&self.key_focus)
.v_flex()
.w(px(520.))
.max_w_full()
.px_4()
.gap_3()
.child(
div()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.child(title),
)
.children((!self.first_launch).then(|| self.preferences(cx)))
.child(div().text_color(muted).child(explanation))
.child(Input::new(&self.input).mask_toggle())
.children(
self.error
@@ -315,6 +338,20 @@ impl Render for KeyForm {
.map(|error| div().text_color(danger).child(error)),
)
.child(buttons),
);
div()
.id("key-form")
.size_full()
.overflow_y_scroll()
.track_scroll(&self.scroll)
.child(
div()
.v_flex()
.min_h_full()
.items_center()
.justify_center()
.py_4()
.child(fields),
)
}
}
+185 -54
View File
@@ -28,6 +28,7 @@ const NO_MATCH: &str = "Aucune Partie";
/// Fixed, as a cached view's height must be. With `card`'s padding, gap and title, it leaves
/// each chart 150 px: change them together.
const CHARTS_HEIGHT: f32 = 206.;
const NARROW_WIDTH: Pixels = px(540.);
/// While an import runs, the page is recomputed at most this often.
const RELOAD_EVERY: Duration = Duration::from_secs(1);
@@ -86,6 +87,8 @@ pub struct StatsPage {
last_active: Option<Account>,
/// The Account the user picked instead of following the one being updated.
pinned: Option<String>,
/// The Account held in view until a manual refresh finishes.
refresh_account: Option<String>,
/// The Account of the last requested statistics.
shown: Option<String>,
progress: Option<SyncProgress>,
@@ -193,6 +196,7 @@ impl StatsPage {
.updating
.as_ref()
.is_some_and(|a| a.puuid == *puuid);
this.refresh_account = None;
this.pinned = (!following).then(|| puuid.clone());
this.reload(window, cx);
},
@@ -246,6 +250,7 @@ impl StatsPage {
accounts: Vec::new(),
last_active: None,
pinned: None,
refresh_account: None,
shown: None,
progress: None,
refresh: RefreshGate::default(),
@@ -283,8 +288,14 @@ impl StatsPage {
cx.notify();
}
/// Starts a manual refresh without changing the Account on screen.
pub fn request_manual_refresh(&mut self, cx: &mut Context<Self>) {
self.refresh_account = self.viewed().map(|account| account.puuid.clone());
self.request_refresh(cx);
}
/// Starts a refresh, or queues one behind the refresh already running.
pub fn begin_refresh(&mut self, cx: &mut Context<Self>) {
pub fn request_refresh(&mut self, cx: &mut Context<Self>) {
if self.refresh.request() {
spawn_refresh(self.tracker.clone(), self.tx.clone());
}
@@ -300,10 +311,11 @@ impl StatsPage {
matches!(self.season, SeasonScope::Season(_))
}
/// The Account shown: the pinned one, else the one being updated.
/// The Account shown: held during refresh, pinned, or following updates.
fn viewed(&self) -> Option<&Account> {
self.pinned
self.refresh_account
.as_ref()
.or(self.pinned.as_ref())
.and_then(|puuid| self.accounts.iter().find(|a| a.puuid == *puuid))
.or(self.status.updating.as_ref())
.or(self.last_active.as_ref())
@@ -360,9 +372,10 @@ impl StatsPage {
self.status = status;
self.progress = None;
self.crashed = false;
self.reload_in_background(window, cx);
// A request made while this one ran (a key saved meanwhile) is served now.
if self.refresh.finished() {
let queued = self.refresh.finished();
self.reload_in_background(window, cx);
if queued {
spawn_refresh(self.tracker.clone(), self.tx.clone());
}
}
@@ -381,8 +394,11 @@ impl StatsPage {
self.recompute_in_background(true, window, cx);
}
}
Msg::Crashed => {
self.refresh.reset();
Msg::Crashed | Msg::RefreshCrashed => {
if matches!(msg, Msg::RefreshCrashed) {
self.refresh.reset();
self.release_refresh_account();
}
self.pending_round = false;
self.progress = None;
self.crashed = true;
@@ -412,6 +428,9 @@ impl StatsPage {
if self.pinned.as_ref() == self.status.updating.as_ref().map(|a| &a.puuid) {
self.pinned = None;
}
if !self.refresh.running() {
self.release_refresh_account();
}
let items: Vec<AccountItem> = self
.accounts
.iter()
@@ -435,6 +454,14 @@ impl StatsPage {
});
}
fn release_refresh_account(&mut self) {
if let Some(puuid) = self.refresh_account.take()
&& self.viewed().is_none_or(|account| account.puuid != puuid)
{
self.pinned = Some(puuid);
}
}
/// Settles the scope of the next statistics. Earlier results become stale when they are
/// computed again (`computing`) or when the viewed Account changed; a request merely queued
/// behind a running job keeps that job's result for the same scope.
@@ -599,6 +626,7 @@ fn tile(
div()
.v_flex()
.flex_1()
.min_w(px(120.))
.gap_1()
.p_3()
.border_1()
@@ -630,6 +658,8 @@ fn challenge_tiles(
};
div()
.h_flex()
.flex_wrap()
.flex_shrink_0()
.gap_3()
.child(tile(
"Champions validés",
@@ -683,7 +713,6 @@ fn card(
.v_flex()
.flex_1()
.min_w_0()
.h_full()
.gap_2()
.p_3()
.border_1()
@@ -736,7 +765,7 @@ impl ChartsRow {
}
impl Render for ChartsRow {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
#[cfg(test)]
{
self.renders += 1;
@@ -790,7 +819,15 @@ impl Render for ChartsRow {
.into_any_element(),
);
}
div().h_flex().size_full().gap_3().children(cards)
div()
.h_flex()
.items_stretch()
.when(window.viewport_size().width < NARROW_WIDTH, |row| {
row.flex_col()
})
.size_full()
.gap_3()
.children(cards)
}
}
@@ -850,7 +887,7 @@ fn attempts_chart(charts: &Charts) -> Option<AnyElement> {
}
impl Render for StatsPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (border, muted) = {
let theme = cx.theme();
(theme.border, theme.muted_foreground)
@@ -860,57 +897,59 @@ impl Render for StatsPage {
let challenge = self.stats.as_ref().and_then(|s| s.challenge.as_ref());
let busy = self.busy();
let status_line = sync_line(busy, self.progress, self.crashed, self.stored);
let viewport = window.viewport_size();
let narrow = viewport.width < NARROW_WIDTH;
let charts_height = if narrow && self.in_season() {
px(3. * CHARTS_HEIGHT + 24.)
} else {
px(CHARTS_HEIGHT)
};
div()
.id("statistics")
.v_flex()
.size_full()
.overflow_y_scroll()
.gap_3()
.p_3()
.when(shown("header"), |page| {
page.child(
// The status wraps below the selectors on a narrow window.
div()
.h_flex()
.flex_wrap()
.items_center()
.justify_between()
.when(narrow, |header| header.flex_col().items_start())
.when(!narrow, |header| header.flex_wrap())
.flex_shrink_0()
.gap_x_3()
.gap_y_2()
.child(
Select::new(&self.account_select)
.id("account")
.placeholder("Aucun Compte")
.w(px(260.))
.min_w(px(150.)),
)
.children(self.stale().then(|| {
div()
.h_flex()
.items_center()
.gap_3()
.min_w_0()
.child(
Select::new(&self.account_select)
.id("account")
.placeholder("Aucun Compte")
.w(px(260.))
.min_w(px(150.)),
)
.children(self.stale().then(|| {
div()
.text_sm()
.whitespace_nowrap()
.text_color(muted)
.child("Non mis à jour")
}))
.child(
Select::new(&self.season_select)
.id("season")
.w(px(220.))
.min_w(px(130.)),
)
.child(
Select::new(&self.format_select)
.id("format")
.w(px(220.))
.min_w(px(130.)),
),
.text_sm()
.whitespace_nowrap()
.text_color(muted)
.child("Non mis à jour")
}))
.child(
Select::new(&self.season_select)
.id("season")
.w(px(220.))
.min_w(px(130.)),
)
.child(
Select::new(&self.format_select)
.id("format")
.w(px(220.))
.min_w(px(130.)),
)
.child(
div()
.ml_auto()
.text_sm()
.whitespace_nowrap()
.text_color(muted)
@@ -919,20 +958,32 @@ impl Render for StatsPage {
)
})
.when(shown("banners"), |page| {
page.child(div().v_flex().gap_1().children(self.banners()))
page.child(
div()
.v_flex()
.flex_shrink_0()
.gap_1()
.children(self.banners()),
)
})
.when(shown("tiles"), |page| {
page.children(challenge.map(|c| challenge_tiles(c, self.official(), border, muted)))
})
.child(
self.charts
.clone()
.cached(StyleRefinement::default().w_full().h(px(CHARTS_HEIGHT))),
self.charts.clone().cached(
StyleRefinement::default()
.w_full()
.h(charts_height)
.flex_shrink_0(),
),
)
.when(shown("tabs"), |page| {
page.child(
div()
.h_flex()
.when(narrow, |filters| filters.flex_col().items_start())
.when(!narrow, |filters| filters.flex_wrap())
.flex_shrink_0()
.items_center()
.justify_between()
.gap_3()
@@ -958,7 +1009,14 @@ impl Render for StatsPage {
)
})
.when(shown("table"), |page| {
page.child(div().flex_1().min_h(px(240.)).child(self.table.clone()))
page.child(
div()
.flex_1()
.min_h(px(240.))
// The champion list handles its own wheel events.
.on_scroll(|_, _, cx| cx.stop_propagation())
.child(self.table.clone()),
)
})
}
}
@@ -971,7 +1029,8 @@ mod tests {
use std::sync::Arc;
use arena_tracker_core::{
Champion, ChampionRow, ChampionState, Charts, RiotApi, StateFilter, Statistics, Tracker,
Account, Champion, ChampionRow, ChampionState, Charts, Format, MatchHistorySource, RiotApi,
SourceError, StateFilter, Statistics, Tracker,
};
use gpui_kit::base::async_util::unbounded;
use gpui_kit::{
@@ -983,15 +1042,23 @@ mod tests {
use crate::champion_table::tests::row;
fn open_page(cx: &mut TestAppContext) -> (Entity<StatsPage>, VisualTestContext) {
cx.update(gpui_kit::init);
let tracker = Arc::new(
open_page_with_tracker(
cx,
Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(Vec::new()),
);
)
}
fn open_page_with_tracker(
cx: &mut TestAppContext,
tracker: Tracker,
) -> (Entity<StatsPage>, VisualTestContext) {
cx.update(gpui_kit::init);
let tracker = Arc::new(tracker);
let (window, page) = cx.update(|cx| {
let (tx, rx) = unbounded();
let bounds = Bounds {
@@ -1010,6 +1077,70 @@ mod tests {
(page, VisualTestContext::from_window(window, cx))
}
struct RefreshHistory;
impl MatchHistorySource for RefreshHistory {
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError> {
Ok(Account {
puuid: game_name.into(),
game_name: game_name.into(),
tag_line: tag_line.into(),
})
}
fn match_ids(
&self,
puuid: &str,
queue_id: u32,
start: usize,
_: usize,
_: Option<i64>,
) -> Result<Vec<String>, SourceError> {
Ok(if puuid == "Alice" && queue_id == 1750 && start == 0 {
vec!["EUW1_9000000006".into()]
} else {
Vec::new()
})
}
fn fetch_match(&self, _: &str) -> Result<String, SourceError> {
Ok(
include_str!("../../core/tests/fixtures/riot/match_1750_EUW1_9000000006.json")
.replace("fixture-puuid-self", "Alice"),
)
}
}
#[gpui::test]
async fn a_manual_refresh_keeps_the_displayed_account_and_format(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory))
.unwrap()
.with_seasons(Vec::new());
tracker.sync("Alice#EUW", &mut |_| {}).unwrap();
let (page, mut window) = open_page_with_tracker(cx, tracker);
window.update(|window, cx| {
page.update(cx, |page, cx| {
assert_eq!(page.viewed().unwrap().puuid, "Alice");
assert_eq!(page.stats.as_ref().unwrap().formats, [Format::Arena3x6]);
page.format = Some(Format::Arena3x6);
page.recompute(window, cx);
// The refresh worker sees the newly adopted Account before the UI does.
page.tracker.follow_client(0, Some("Bob#EUW"), &mut |_| {});
page.request_manual_refresh(cx);
});
});
cx.condition(&page, |page, _| !page.busy()).await;
page.read_with(cx, |page, cx| {
assert_eq!(page.status.updating.as_ref().unwrap().puuid, "Bob");
assert_eq!(
page.account_select.read(cx).selected_value().unwrap(),
"Alice"
);
assert_eq!(page.format, Some(Format::Arena3x6));
});
}
#[gpui::test]
fn typing_in_the_search_field_filters_the_table(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
+27 -4
View File
@@ -11,8 +11,12 @@ use windows::Win32::{
const BUTTON_WIDTH: Pixels = px(36.);
const BUTTON_HEIGHT: Pixels = px(28.);
const BAR_HEIGHT: Pixels = px(36.);
pub fn action_button(id: &'static str, icon: IconName, label: &'static str) -> Button {
// Leave room for the centered title and both groups in narrow Windows Snap zones.
pub const MIN_WINDOW_SIZE: Size<Pixels> = size(px(330.), px(216.));
fn action_button(id: &'static str, icon: IconName, label: &'static str) -> Button {
Button::new(id)
.ghost()
.small()
@@ -23,9 +27,28 @@ pub fn action_button(id: &'static str, icon: IconName, label: &'static str) -> B
.accessibility_label(label)
}
pub fn title_bar(refresh: Button, settings: Button, window: &Window, cx: &App) -> impl IntoElement {
pub fn refresh_button() -> Button {
action_button("refresh", IconName::RefreshCw, "Actualiser")
}
pub fn settings_button() -> Button {
action_button("settings", IconName::Settings, "Paramètres")
}
pub fn track_maximized(window: &mut Window, cx: &mut App) -> Entity<bool> {
cx.new(|cx| {
cx.observe_window_bounds(window, |maximized, window, _| {
// GPUI has already scheduled a redraw for this bounds change.
*maximized = window.is_maximized();
})
.detach();
window.is_maximized()
})
}
pub fn title_bar(refresh: Button, settings: Button, maximized: bool, cx: &App) -> impl IntoElement {
let theme = cx.theme();
let (icon, label) = if window.is_maximized() {
let (icon, label) = if maximized {
(IconName::WindowRestore, "Restaurer")
} else {
(IconName::WindowMaximize, "Agrandir")
@@ -33,7 +56,7 @@ pub fn title_bar(refresh: Button, settings: Button, window: &Window, cx: &App) -
div()
.h_flex()
.w_full()
.h(px(36.))
.h(BAR_HEIGHT)
.flex_shrink_0()
.bg(theme.title_bar)
.border_b_1()
+15 -10
View File
@@ -26,6 +26,8 @@ pub enum Msg {
},
/// A worker thread panicked.
Crashed,
/// The refresh worker panicked.
RefreshCrashed,
}
/// At most one job at a time. A request made while one runs is served once, when it reports back.
@@ -92,11 +94,11 @@ fn lower_priority() {
}
/// Runs `body` on its own thread; a panic is reported instead of leaving the page waiting.
fn spawn_guarded(tx: Sender<Msg>, body: impl FnOnce(&Sender<Msg>) + Send + 'static) {
fn spawn_guarded(tx: Sender<Msg>, on_panic: Msg, body: impl FnOnce(&Sender<Msg>) + Send + 'static) {
thread::spawn(move || {
lower_priority();
if catch_unwind(AssertUnwindSafe(|| body(&tx))).is_err() {
let _ = tx.try_send(Msg::Crashed);
let _ = tx.try_send(on_panic);
}
});
}
@@ -107,11 +109,11 @@ fn spawn_guarded(tx: Sender<Msg>, body: impl FnOnce(&Sender<Msg>) + Send + 'stat
/// import never waits for them.
pub fn spawn_follower(tracker: Arc<Tracker>, fallback_riot_id: String, tx: Sender<Msg>) {
let champions = tracker.clone();
spawn_guarded(tx.clone(), move |tx| {
spawn_guarded(tx.clone(), Msg::Crashed, move |tx| {
let _ = champions.refresh_champions();
let _ = tx.try_send(Msg::Champions);
});
spawn_guarded(tx, move |tx| {
spawn_guarded(tx, Msg::Crashed, move |tx| {
let fallback = Some(fallback_riot_id.as_str()).filter(|id| !id.trim().is_empty());
let mut first = true;
loop {
@@ -131,7 +133,7 @@ pub fn spawn_follower(tracker: Arc<Tracker>, fallback_riot_id: String, tx: Sende
/// The refresh button: one sync of the Account being kept up to date.
pub fn spawn_refresh(tracker: Arc<Tracker>, tx: Sender<Msg>) {
spawn_guarded(tx, move |tx| {
spawn_guarded(tx, Msg::RefreshCrashed, move |tx| {
// A failure is recorded in the status, which the page shows as a banner.
let _ = tracker.refresh(&mut |progress| {
let _ = tx.try_send(Msg::Progress(progress));
@@ -148,7 +150,7 @@ pub fn spawn_statistics(
generation: u64,
tx: Sender<Msg>,
) {
spawn_guarded(tx, move |tx| {
spawn_guarded(tx, Msg::Crashed, move |tx| {
// A panic is reported as this job's result, not as `Crashed`: the page's statistics job
// must end with a result whatever happens, and a crash banner is for the other workers.
let (stats, stored) = catch_unwind(AssertUnwindSafe(|| {
@@ -183,13 +185,16 @@ mod tests {
#[test]
fn guarded_workers_deliver_messages_and_report_panics() {
let (tx, rx) = unbounded();
spawn_guarded(tx.clone(), |tx| {
spawn_guarded(tx.clone(), Msg::Crashed, |tx| {
let _ = tx.try_send(Msg::Champions);
});
assert!(matches!(gpui_kit::block_on(rx.recv()), Ok(Msg::Champions)));
spawn_guarded(tx, |_| panic!("worker panic"));
assert!(matches!(gpui_kit::block_on(rx.recv()), Ok(Msg::Crashed)));
spawn_guarded(tx, Msg::RefreshCrashed, |_| panic!("worker panic"));
assert!(matches!(
gpui_kit::block_on(rx.recv()),
Ok(Msg::RefreshCrashed)
));
assert!(gpui_kit::block_on(rx.recv()).is_err());
}
@@ -273,7 +278,7 @@ mod tests {
fn guarded_threads_run_below_normal_priority() {
let (tx, _rx) = unbounded();
let (priority_tx, priority_rx) = std::sync::mpsc::channel();
spawn_guarded(tx, move |_| {
spawn_guarded(tx, Msg::Crashed, move |_| {
let priority = unsafe { GetThreadPriority(GetCurrentThread()) };
priority_tx.send(priority).unwrap();
});