diff --git a/crates/app/src/worker.rs b/crates/app/src/worker.rs index 37aff07..7fef024 100644 --- a/crates/app/src/worker.rs +++ b/crates/app/src/worker.rs @@ -77,31 +77,46 @@ impl RefreshGate { } } -/// While champion art keeps arriving, how often the page is told: each time, it reloads its +/// While cards and splashes keep arriving, how often the page is told: each time, it reloads its /// statistics to show them. -const PORTRAITS_TOLD_EVERY: Duration = Duration::from_secs(1); +const ART_TOLD_EVERY: Duration = Duration::from_secs(1); -/// Shares the catalog notification's deadline across the card and splash passes. +/// Spaces out what saved images cause: the first save is told at once, the next ones when +/// `every` has passed since the last message, and one still untold when the pass ends is told +/// then. No timer: each attempt of the pass, saved or not, and its end are what tell. struct Throttle { - last_told: Instant, + every: Duration, + last_told: Option, untold: bool, } impl Throttle { + fn new(every: Duration) -> Throttle { + Throttle { + every, + last_told: None, + untold: false, + } + } + + /// An attempt ended at `now`, with an image saved or not: true when the page must be told + /// now, as a save is untold and `every` has passed since the last message. fn attempted(&mut self, saved: bool, now: Instant) -> bool { self.untold |= saved; - if self.untold && now.duration_since(self.last_told) >= PORTRAITS_TOLD_EVERY { - self.last_told = now; + let due = self + .last_told + .is_none_or(|last| now.duration_since(last) >= self.every); + if self.untold && due { + self.last_told = Some(now); self.untold = false; return true; } false } - /// A final batch needs one wake at its deadline, even when the pass ends early. - fn final_delay(self, now: Instant) -> Option { + /// The pass ended: true when a save is still untold. + fn finished(self) -> bool { self.untold - .then(|| PORTRAITS_TOLD_EVERY.saturating_sub(now.duration_since(self.last_told))) } } @@ -156,24 +171,17 @@ fn spawn_guarded( pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sender) { let champions = tracker.clone(); spawn_guarded(tx.clone(), Msg::Crashed, move |tx| { - let refreshed = champions.refresh_champions(); - let _ = tx.try_send(Msg::Champions); - // Offline, the catalog call failed and so would every portrait request. - if refreshed.is_err() { - return; - } - let mut throttle = Throttle { - last_told: Instant::now(), - untold: false, + let mut throttle = Throttle::new(ART_TOLD_EVERY); + let notify = || { + let _ = tx.try_send(Msg::Champions); }; - let _ = champions.refresh_champion_art(&mut |saved| { + let _ = champions.refresh_champion_art(notify, &mut |saved| { if throttle.attempted(saved, Instant::now()) { - let _ = tx.try_send(Msg::Champions); + notify(); } }); - if let Some(delay) = throttle.final_delay(Instant::now()) { - thread::sleep(delay); - let _ = tx.try_send(Msg::Champions); + if throttle.finished() { + notify(); } }); // Coalesce history updates while Riot is busy; the WebSocket keeps delivering live picks. @@ -435,29 +443,39 @@ mod tests { } #[test] - fn saved_art_is_told_at_most_once_a_second_including_the_final_batch() { + fn saved_art_is_told_once_a_second_after_any_attempt_and_the_last_ones_at_the_end() { let start = Instant::now(); let at = |ms: u64| start + Duration::from_millis(ms); - let mut throttle = Throttle { - last_told: start, - untold: false, - }; - assert!(!throttle.attempted(true, at(0))); - assert!(!throttle.attempted(true, at(999))); - assert!(throttle.attempted(false, at(1000))); - assert!(!throttle.attempted(false, at(2000))); - assert!(throttle.attempted(true, at(2100))); - assert!(!throttle.attempted(true, at(2110))); - assert_eq!( - throttle.final_delay(at(2300)), - Some(Duration::from_millis(800)) + let mut throttle = Throttle::new(Duration::from_secs(1)); + assert!( + throttle.attempted(true, at(0)), + "the first save is told at once" ); + assert!(!throttle.attempted(true, at(300))); + assert!(!throttle.attempted(true, at(999))); + assert!(throttle.attempted(true, at(1000))); + assert!(!throttle.attempted(true, at(1500))); + // A failed attempt tells nothing before the second is over, then the save at 1.5 s is. + assert!(!throttle.attempted(false, at(1900))); + assert!(throttle.attempted(false, at(2000))); + assert!( + !throttle.attempted(false, at(5000)), + "nothing is untold any more" + ); + assert!(!throttle.finished()); - let empty = Throttle { - last_told: start, - untold: false, - }; - assert_eq!(empty.final_delay(at(100)), None); + // The last save was told late or never: the end of the pass tells it. + let mut throttle = Throttle::new(Duration::from_secs(1)); + assert!(throttle.attempted(true, at(0))); + assert!(!throttle.attempted(true, at(10))); + assert!(!throttle.attempted(false, at(20))); + assert!(throttle.finished()); + + // Nothing saved, nothing told. + let mut throttle = Throttle::new(Duration::from_secs(1)); + assert!(!throttle.attempted(false, at(0))); + assert!(!throttle.attempted(false, at(5000))); + assert!(!throttle.finished()); } #[test] diff --git a/crates/core/src/champions.rs b/crates/core/src/champions.rs index 34639ed..021e4fa 100644 --- a/crates/core/src/champions.rs +++ b/crates/core/src/champions.rs @@ -281,11 +281,11 @@ impl Tracker { self.download_cards(on_attempt, |_, _| {}).map(|_| ()) } - /// Shares the uncropped loading art with the splash pass. False means the network went away. + /// Shares decoded loading art or a confirmed 404 with the splash pass. False stops both passes offline. pub(crate) fn download_cards( &self, on_attempt: &mut dyn FnMut(bool), - mut on_loading: impl FnMut(&str, &image::DynamicImage), + mut on_loading: impl FnMut(&str, Option<&image::DynamicImage>), ) -> Result { let Some((source, portraits_dir)) = &self.champions else { return Ok(true); @@ -304,7 +304,10 @@ impl Tracker { on_attempt(false); return Ok(false); } - Err(_) => { + Err(error) => { + if error == SourceError::NotFound { + on_loading(&champion.key, None); + } on_attempt(false); continue; } @@ -313,7 +316,7 @@ impl Tracker { on_attempt(false); continue; }; - on_loading(&champion.key, &art); + on_loading(&champion.key, Some(&art)); let Ok(card) = process_card_portrait(art.into_rgb8()) else { on_attempt(false); continue; diff --git a/crates/core/src/splash.rs b/crates/core/src/splash.rs index 774e60c..5d7751b 100644 --- a/crates/core/src/splash.rs +++ b/crates/core/src/splash.rs @@ -12,6 +12,10 @@ pub struct Splash { pub focus: SplashFocus, } +pub(crate) fn splashes_dir(portraits: &Path) -> PathBuf { + portraits.join("splashes") +} + /// A single rename publishes both the original JPEG and its focus: key.x.y.jpg. pub(crate) fn cached_splashes(dir: &Path) -> HashMap { file_names(dir) @@ -36,19 +40,36 @@ pub(crate) fn cached_splashes(dir: &Path) -> HashMap { .collect() } +enum LoadingArt { + Template(GrayImage), + NotFound, +} + impl Tracker { - /// Runs after the catalog refresh on the image worker, sharing one stream of save notifications. - pub fn refresh_champion_art(&self, on_attempt: &mut dyn FnMut(bool)) -> Result<(), Error> { + /// Notifies the worker when the catalog refresh ends (cached data is usable offline), + /// then reports each card and splash attempt while online. + pub fn refresh_champion_art( + &self, + catalog_ready: impl FnOnce(), + on_attempt: &mut dyn FnMut(bool), + ) -> Result<(), Error> { + let catalog = self.refresh_champions(); + catalog_ready(); + catalog?; let Some((source, portraits_dir)) = &self.champions else { return Ok(()); }; let mut loading = HashMap::new(); if !self.download_cards(on_attempt, |key, image| { - loading.insert(key.to_owned(), loading_template(image)); + let art = match image { + Some(image) => LoadingArt::Template(loading_template(image)), + None => LoadingArt::NotFound, + }; + loading.insert(key.to_owned(), art); })? { return Ok(()); } - let dir = portraits_dir.join("splashes"); + let dir = splashes_dir(portraits_dir); std::fs::create_dir_all(&dir) .map_err(|e| Error::Storage(format!("{} : {e}", dir.display())))?; let cached = cached_splashes(&dir); @@ -77,25 +98,30 @@ fn download_splash( source: &dyn ChampionSource, dir: &Path, key: &str, - template: Option, + loading: Option, card: &Path, ) -> Result { - let template = match template { - Some(template) => template, + let template = match loading { + Some(LoadingArt::Template(template)) => Some(template), + Some(LoadingArt::NotFound) => None, // Cards from earlier launches only contain the cropped art. - None if card.is_file() => { - let Some(art) = decode_jpeg(&source.card_portrait(key)?) else { - return Ok(false); - }; - loading_template(&art) - } + None if card.is_file() => match source.card_portrait(key) { + Ok(bytes) => { + let Some(art) = decode_jpeg(&bytes) else { + return Ok(false); + }; + Some(loading_template(&art)) + } + Err(SourceError::NotFound) => None, + Err(error) => return Err(error), + }, None => return Ok(false), }; let jpeg = source.splash(key)?; let Some(image) = decode_jpeg(&jpeg) else { return Ok(false); }; - let focus = locate(&image, &template); + let focus = template.map_or(FALLBACK, |art| locate(&image, &art)); let path = dir.join(format!("{key}.{}.{}.jpg", focus.x, focus.y)); Ok(save_image(&path, &jpeg)) } @@ -120,9 +146,13 @@ pub struct BannerFrame { impl SplashFocus { pub fn banner_frame(self, area_width: f32, area_height: f32) -> BannerFrame { - let scale = (area_width / (1215.0 * 0.8)).max(area_height / 717.0); - let width = 1215.0 * scale; - let height = 717.0 * scale; + const SPLASH_WIDTH: f32 = 1215.0; + const SPLASH_HEIGHT: f32 = 717.0; + const VISIBLE_WIDTH_FRACTION: f32 = 0.8; + let scale = + (area_width / (SPLASH_WIDTH * VISIBLE_WIDTH_FRACTION)).max(area_height / SPLASH_HEIGHT); + let width = SPLASH_WIDTH * scale; + let height = SPLASH_HEIGHT * scale; let offset = |area: f32, size: f32, percent: u8| { (area * 0.5 - size * f32::from(percent) / 100.0) .max(area - size) @@ -242,17 +272,27 @@ mod tests { } #[test] - fn locates_the_loading_art_even_with_different_brightness() { - let art = GrayImage::from_fn(35, 64, |x, y| { - Luma([((((x / 4) * 71) ^ ((y / 4) * 59)) % 150) as u8]) + fn locates_full_size_loading_art_at_both_ends_of_the_scale_range() { + let art = image::RgbImage::from_fn(308, 560, |x, y| { + let value = ((((x / 32) * 71) ^ ((y / 32) * 59)) % 150) as u8; + image::Rgb([value, 150 - value, value / 2]) }); - let mut splash = GrayImage::new(145, 80); - for (x, y, pixel) in art.enumerate_pixels() { - splash.put_pixel(x + 90, y + 9, Luma([pixel[0] + 70])); + let template = loading_template(&DynamicImage::ImageRgb8(art.clone())); + for (w, h, x, y, expected) in [ + (276, 502, 735, 108, SplashFocus { x: 72, y: 36 }), + (394, 717, 180, 0, SplashFocus { x: 31, y: 30 }), + ] { + let mut patch = imageops::resize(&art, w, h, FilterType::Triangle); + for pixel in patch.as_mut() { + *pixel += 60; + } + let mut splash = image::RgbImage::new(1215, 717); + imageops::replace(&mut splash, &patch, x, y); + let focus = locate(&DynamicImage::ImageRgb8(splash), &template); + assert!( + focus.x.abs_diff(expected.x) <= 1 && focus.y.abs_diff(expected.y) <= 1, + "{focus:?}, expected {expected:?}" + ); } - assert_eq!( - locate(&DynamicImage::ImageLuma8(splash), &art), - SplashFocus { x: 74, y: 35 } - ); } } diff --git a/crates/core/src/statistics.rs b/crates/core/src/statistics.rs index e31fed0..c70ca27 100644 --- a/crates/core/src/statistics.rs +++ b/crates/core/src/statistics.rs @@ -10,6 +10,7 @@ use crate::date::Date; use crate::error::Error; use crate::model::{Format, Match}; use crate::seasons::{Season, period}; +use crate::splash::{Splash, cached_splashes, splashes_dir}; use crate::tracker::Tracker; #[derive(Clone, Debug, PartialEq)] @@ -62,7 +63,7 @@ pub struct ChampionRow { pub portrait: Option, /// Only when the file exists in the portraits dir's `cards` folder. pub card_portrait: Option, - pub splash: Option, + pub splash: Option, // In scope (Season and Format filter): pub matches: usize, pub best_placement: Option, @@ -452,7 +453,7 @@ impl Tracker { // One read of each folder rather than a file check per champion and per portrait. let squares: HashSet<_> = file_names(dir).collect(); let cards: HashSet<_> = file_names(&cards_dir(dir)).collect(); - let mut splashes = crate::splash::cached_splashes(&dir.join("splashes")); + let mut splashes = cached_splashes(&splashes_dir(dir)); for row in &mut stats.rows { row.splash = splashes.remove(&row.champion.key); let name = format!("{}.png", row.champion.key); diff --git a/crates/core/tests/champions.rs b/crates/core/tests/champions.rs index 3f7b336..f7c5ad0 100644 --- a/crates/core/tests/champions.rs +++ b/crates/core/tests/champions.rs @@ -391,11 +391,10 @@ fn splash_downloads_resume_after_a_network_error_and_only_fetch_new_champions() let splash_calls = source.splash_calls.clone(); let loading_calls = source.card_counter(); let tracker = reopen(dir.path(), source); - tracker.refresh_champions().unwrap(); let mut attempts = Vec::new(); tracker - .refresh_champion_art(&mut |saved| { + .refresh_champion_art(|| {}, &mut |saved| { attempts.push(saved); // Three cards, then one splash. The next splash loses the network. if attempts.len() == 4 { @@ -425,8 +424,9 @@ fn splash_downloads_resume_after_a_network_error_and_only_fetch_new_champions() let calls = next.splash_calls.clone(); let loading_calls = next.card_counter(); let tracker = reopen(dir.path(), next); - tracker.refresh_champions().unwrap(); - tracker.refresh_champion_art(&mut |ok| assert!(ok)).unwrap(); + tracker + .refresh_champion_art(|| {}, &mut |ok| assert!(ok)) + .unwrap(); let splashes = statistics(&tracker) .rows .into_iter() @@ -435,30 +435,73 @@ fn splash_downloads_resume_after_a_network_error_and_only_fetch_new_champions() assert_eq!(splashes.len(), 4); assert!(splashes.contains(&first[0])); tracker - .refresh_champion_art(&mut |_| panic!("already cached")) + .refresh_champion_art(|| {}, &mut |_| panic!("already cached")) .unwrap(); assert_eq!(calls.load(Ordering::SeqCst), 3); assert_eq!(loading_calls.load(Ordering::SeqCst), 3); } +#[test] +fn missing_loading_art_still_saves_the_original_splash_once_with_fixed_focus() { + for cached_card in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let catalog = &CATALOG[..1]; + if cached_card { + let tracker = reopen(dir.path(), FakeChampions::new("1", catalog)); + tracker.refresh_champions().unwrap(); + tracker.refresh_card_portraits(&mut |_| {}).unwrap(); + } + let source = FakeChampions::new("1", catalog).without_portrait("Annie"); + let calls = source.splash_calls.clone(); + let tracker = reopen(dir.path(), source); + tracker.refresh_champion_art(|| {}, &mut |_| {}).unwrap(); + let splash = statistics(&tracker).rows.remove(0).splash.unwrap(); + assert_eq!((splash.focus.x, splash.focus.y), (50, 30)); + assert_eq!(std::fs::read(splash.path).unwrap(), common::splash_art()); + tracker.refresh_champion_art(|| {}, &mut |_| {}).unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } +} + #[test] fn a_temporarily_unreadable_loading_image_is_retried_before_caching_the_splash() { let dir = tempfile::tempdir().unwrap(); let source = FakeChampions::new("1", &CATALOG[..1]).with_card_art(b"not a JPEG".to_vec()); let splash_calls = source.splash_calls.clone(); let tracker = reopen(dir.path(), source); - tracker.refresh_champions().unwrap(); - tracker.refresh_champion_art(&mut |_| {}).unwrap(); + tracker.refresh_champion_art(|| {}, &mut |_| {}).unwrap(); assert!(statistics(&tracker).rows.iter().all(|r| r.splash.is_none())); assert_eq!(splash_calls.load(Ordering::SeqCst), 0); let tracker = reopen(dir.path(), FakeChampions::new("1", &CATALOG[..1])); tracker - .refresh_champion_art(&mut |saved| assert!(saved)) + .refresh_champion_art(|| {}, &mut |saved| assert!(saved)) .unwrap(); assert!(statistics(&tracker).rows.iter().all(|r| r.splash.is_some())); } +#[test] +fn an_offline_launch_keeps_the_cached_catalog_and_makes_no_art_requests() { + let dir = tempfile::tempdir().unwrap(); + reopen(dir.path(), FakeChampions::new("1", &CATALOG)) + .refresh_champions() + .unwrap(); + let source = FakeChampions::new("1", &CATALOG).failing(); + let cards = source.card_counter(); + let splashes = source.splash_calls.clone(); + let tracker = reopen(dir.path(), source); + let mut notified = false; + assert!( + tracker + .refresh_champion_art(|| notified = true, &mut |_| panic!("offline art attempt")) + .is_err() + ); + assert!(notified); + assert_eq!(statistics(&tracker).rows.len(), CATALOG.len()); + assert_eq!(cards.load(Ordering::SeqCst), 0); + assert_eq!(splashes.load(Ordering::SeqCst), 0); +} + #[test] fn losing_the_network_during_cards_skips_all_splashes() { let dir = tempfile::tempdir().unwrap(); @@ -466,15 +509,14 @@ fn losing_the_network_during_cards_skips_all_splashes() { source.card_failure().store(true, Ordering::SeqCst); let calls = source.splash_calls.clone(); let tracker = reopen(dir.path(), source); - tracker.refresh_champions().unwrap(); let mut attempts = Vec::new(); tracker - .refresh_champion_art(&mut |saved| attempts.push(saved)) + .refresh_champion_art(|| {}, &mut |saved| attempts.push(saved)) .unwrap(); assert_eq!(attempts, [false]); assert_eq!(calls.load(Ordering::SeqCst), 0); open_tracker(dir.path(), &[]) - .refresh_champion_art(&mut |_| panic!("no source")) + .refresh_champion_art(|| {}, &mut |_| panic!("no source")) .unwrap(); }