diff --git a/crates/app/src/card.rs b/crates/app/src/card.rs index cde24f0..7e11533 100644 --- a/crates/app/src/card.rs +++ b/crates/app/src/card.rs @@ -396,6 +396,7 @@ mod tests { }, portrait: None, card_portrait: None, + splash: None, matches: 0, best_placement: None, top1: 0, diff --git a/crates/app/src/champion_table.rs b/crates/app/src/champion_table.rs index e6a3420..0a048ed 100644 --- a/crates/app/src/champion_table.rs +++ b/crates/app/src/champion_table.rs @@ -298,6 +298,7 @@ pub(crate) mod tests { }, portrait: None, card_portrait: None, + splash: None, matches: 0, best_placement: None, top1: 0, diff --git a/crates/app/src/page.rs b/crates/app/src/page.rs index f7b53df..a21a4d9 100644 --- a/crates/app/src/page.rs +++ b/crates/app/src/page.rs @@ -2690,6 +2690,10 @@ mod tests { fn card_portrait(&self, _: &str) -> Result, SourceError> { Err(SourceError::NotFound) } + + fn splash(&self, _: &str) -> Result, SourceError> { + Err(SourceError::NotFound) + } } /// The tracker of Joueur (and of Autre, who has played nothing), on the catalog. diff --git a/crates/app/src/worker.rs b/crates/app/src/worker.rs index 875a7b9..37aff07 100644 --- a/crates/app/src/worker.rs +++ b/crates/app/src/worker.rs @@ -77,46 +77,31 @@ impl RefreshGate { } } -/// While card portraits keep arriving, how often the page is told: each time, it reloads its +/// While champion art keeps 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); -/// Spaces out what saved portraits 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. +/// Shares the catalog notification's deadline across the card and splash passes. struct Throttle { - every: Duration, - last_told: Option, + last_told: Instant, untold: bool, } impl Throttle { - fn new(every: Duration) -> Throttle { - Throttle { - every, - last_told: None, - untold: false, - } - } - - /// An attempt ended at `now`, with a portrait 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; - let due = self - .last_told - .is_none_or(|last| now.duration_since(last) >= self.every); - if self.untold && due { - self.last_told = Some(now); + if self.untold && now.duration_since(self.last_told) >= PORTRAITS_TOLD_EVERY { + self.last_told = now; self.untold = false; return true; } false } - /// The pass ended: true when a save is still untold. - fn finished(self) -> bool { + /// A final batch needs one wake at its deadline, even when the pass ends early. + fn final_delay(self, now: Instant) -> Option { self.untold + .then(|| PORTRAITS_TOLD_EVERY.saturating_sub(now.duration_since(self.last_told))) } } @@ -177,15 +162,17 @@ pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sende if refreshed.is_err() { return; } - // The tall card portraits after the square ones, which the Statistiques table uses. They - // show as they arrive, without a restart, the page reloading at most once a second. - let mut throttle = Throttle::new(PORTRAITS_TOLD_EVERY); - let _ = champions.refresh_card_portraits(&mut |saved| { + let mut throttle = Throttle { + last_told: Instant::now(), + untold: false, + }; + let _ = champions.refresh_champion_art(&mut |saved| { if throttle.attempted(saved, Instant::now()) { let _ = tx.try_send(Msg::Champions); } }); - if throttle.finished() { + if let Some(delay) = throttle.final_delay(Instant::now()) { + thread::sleep(delay); let _ = tx.try_send(Msg::Champions); } }); @@ -448,39 +435,29 @@ mod tests { } #[test] - fn saved_portraits_are_told_once_a_second_after_any_attempt_and_the_last_ones_at_the_end() { + fn saved_art_is_told_at_most_once_a_second_including_the_final_batch() { let start = Instant::now(); let at = |ms: u64| start + Duration::from_millis(ms); - 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))); + let mut throttle = Throttle { + last_told: start, + untold: false, + }; + assert!(!throttle.attempted(true, at(0))); 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.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)) ); - assert!(!throttle.finished()); - // 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()); + let empty = Throttle { + last_told: start, + untold: false, + }; + assert_eq!(empty.final_delay(at(100)), None); } #[test] diff --git a/crates/core/src/champions.rs b/crates/core/src/champions.rs index 5fc73ee..34639ed 100644 --- a/crates/core/src/champions.rs +++ b/crates/core/src/champions.rs @@ -1,4 +1,5 @@ use std::collections::BTreeMap; +use std::ffi::OsString; use std::path::{Path, PathBuf}; use image::codecs::jpeg::JpegEncoder; @@ -35,6 +36,8 @@ pub trait ChampionSource: Send + Sync { fn portrait(&self, version: &str, key: &str) -> Result, SourceError>; /// JPEG bytes of the tall loading-screen art (308 x 560 px), used on the cards. fn card_portrait(&self, key: &str) -> Result, SourceError>; + /// Original landscape splash JPEG (1215 x 717 px). + fn splash(&self, key: &str) -> Result, SourceError>; } const HOST: &str = "https://ddragon.leagueoflegends.com"; @@ -84,6 +87,11 @@ impl ChampionSource for DataDragon { let url = format!("{HOST}/cdn/img/champion/loading/{}_0.jpg", encode(key)); get(&self.agent, &url, None, |b| b.read_to_vec()) } + + fn splash(&self, key: &str) -> Result, SourceError> { + let url = format!("{HOST}/cdn/img/champion/splash/{}_0.jpg", encode(key)); + get(&self.agent, &url, None, |b| b.read_to_vec()) + } } /// Width of a stored card portrait: the loading art's own width, about the largest card @@ -100,6 +108,11 @@ const CARD_FOCUS_X: f64 = 0.5; const CARD_FOCUS_Y: f64 = 0.24; const CARD_JPEG_QUALITY: u8 = 85; +/// Data Dragon keys become local file names. +pub(crate) fn valid_art_key(key: &str) -> bool { + !key.is_empty() && key.bytes().all(|c| c.is_ascii_alphanumeric()) +} + /// The folder of the card portraits, in the portraits folder. pub(crate) fn cards_dir(portraits_dir: &Path) -> PathBuf { portraits_dir.join("cards") @@ -132,10 +145,7 @@ fn card_crop(width: u32, height: u32) -> (u32, u32, u32, u32) { /// Crops the loading art to the card's shape, shrinks it to the stored size when larger /// (never upscales) and encodes it as JPEG. -fn process_card_portrait(jpeg: &[u8]) -> Result, String> { - let art = image::load_from_memory_with_format(jpeg, ImageFormat::Jpeg) - .map_err(|e| format!("Portrait illisible : {e}"))? - .into_rgb8(); +fn process_card_portrait(art: RgbImage) -> Result, String> { let (x, y, w, h) = card_crop(art.width(), art.height()); let mut card: RgbImage = imageops::crop_imm(&art, x, y, w, h).to_image(); drop(art); @@ -159,6 +169,25 @@ fn process_card_portrait(jpeg: &[u8]) -> Result, String> { Ok(out) } +/// The names of the files in `dir`; none when it is missing or unreadable. +pub(crate) fn file_names(dir: &Path) -> impl Iterator { + std::fs::read_dir(dir) + .into_iter() + .flatten() + .filter_map(Result::ok) + .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file())) + .map(|entry| entry.file_name()) +} + +pub(crate) fn save_image(path: &Path, bytes: &[u8]) -> bool { + let partial = path.with_extension("part"); + let saved = std::fs::write(&partial, bytes).is_ok() && std::fs::rename(&partial, path).is_ok(); + if !saved { + let _ = std::fs::remove_file(partial); + } + saved +} + fn decode_latest_version(body: &str) -> Result { let versions: Vec = serde_json::from_str(body) .map_err(|e| SourceError::Other(format!("Versions illisibles : {e}")))?; @@ -233,16 +262,11 @@ impl Tracker { .map_err(|e| Error::Storage(format!("{} : {e}", portraits_dir.display())))?; for champion in self.cached_champions()? { let path = portraits_dir.join(format!("{}.png", champion.key)); - // The key becomes a file name: only trust plain names. - if path.exists() || !champion.key.chars().all(|c| c.is_ascii_alphanumeric()) { + if !valid_art_key(&champion.key) || path.exists() { continue; } if let Ok(png) = source.portrait(&version, &champion.key) { - // Written under another name first so a cut download is never taken for a portrait. - let partial = path.with_extension("part"); - if std::fs::write(&partial, png).is_ok() { - let _ = std::fs::rename(&partial, &path); - } + save_image(&path, &png); } } Ok(()) @@ -253,45 +277,50 @@ impl Tracker { /// download of one champion (not found, an unreadable image) is skipped and retried by the /// next pass; a network error stops the pass, as every other request would fail as well. /// `on_attempt` is called after each download attempt, with whether a portrait was saved. - /// Meant to run after `refresh_champions`. pub fn refresh_card_portraits(&self, on_attempt: &mut dyn FnMut(bool)) -> Result<(), Error> { + self.download_cards(on_attempt, |_, _| {}).map(|_| ()) + } + + /// Shares the uncropped loading art with the splash pass. False means the network went away. + pub(crate) fn download_cards( + &self, + on_attempt: &mut dyn FnMut(bool), + mut on_loading: impl FnMut(&str, &image::DynamicImage), + ) -> Result { let Some((source, portraits_dir)) = &self.champions else { - return Ok(()); + return Ok(true); }; let cards_dir = cards_dir(portraits_dir); std::fs::create_dir_all(&cards_dir) .map_err(|e| Error::Storage(format!("{} : {e}", cards_dir.display())))?; for champion in self.cached_champions()? { let path = card_portrait_path(portraits_dir, &champion.key); - // The key becomes a file name: only trust plain names. - if path.exists() || !champion.key.chars().all(|c| c.is_ascii_alphanumeric()) { + if !valid_art_key(&champion.key) || path.exists() { continue; } let art = match source.card_portrait(&champion.key) { Ok(art) => art, Err(SourceError::Network(_)) => { on_attempt(false); - break; + return Ok(false); } Err(_) => { on_attempt(false); continue; } }; - let Ok(card) = process_card_portrait(&art) else { + let Ok(art) = image::load_from_memory_with_format(&art, ImageFormat::Jpeg) else { on_attempt(false); continue; }; - // Written under another name first so a cut write is never taken for a portrait. - let partial = path.with_extension("part"); - let saved = - std::fs::write(&partial, card).is_ok() && std::fs::rename(&partial, &path).is_ok(); - if !saved { - let _ = std::fs::remove_file(&partial); - } - on_attempt(saved); + on_loading(&champion.key, &art); + let Ok(card) = process_card_portrait(art.into_rgb8()) else { + on_attempt(false); + continue; + }; + on_attempt(save_image(&path, &card)); } - Ok(()) + Ok(true) } pub(crate) fn cached_champions(&self) -> Result, Error> { @@ -386,6 +415,12 @@ mod tests { out } + fn process_card_portrait(jpeg: &[u8]) -> Result, String> { + let art = image::load_from_memory_with_format(jpeg, ImageFormat::Jpeg) + .map_err(|e| e.to_string())?; + super::process_card_portrait(art.into_rgb8()) + } + fn decoded(jpeg: &[u8]) -> RgbImage { image::load_from_memory_with_format(jpeg, ImageFormat::Jpeg) .unwrap() diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 49d846b..50f171c 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -10,6 +10,7 @@ mod league_client; mod model; mod riot; mod seasons; +mod splash; mod statistics; mod tracker; mod update_package; @@ -29,6 +30,7 @@ pub use league_client::{LeagueClient, decode_gameflow}; pub use model::{Account, Format, Match, SyncProgress, SyncReport}; pub use riot::RiotApi; pub use seasons::{Season, default_seasons, load_seasons}; +pub use splash::{BannerFrame, Splash, SplashFocus}; pub use statistics::{ ChallengeSummary, ChampionChallenge, ChampionRow, ChampionState, Charts, Column, Marks, Scope, SeasonScope, StateFilter, Statistics, sort_rows, diff --git a/crates/core/src/splash.rs b/crates/core/src/splash.rs new file mode 100644 index 0000000..774e60c --- /dev/null +++ b/crates/core/src/splash.rs @@ -0,0 +1,258 @@ +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use crate::champions::{card_portrait_path, file_names, save_image, valid_art_key}; +use crate::{ChampionSource, Error, SourceError, Tracker}; +use image::imageops::{self, FilterType}; +use image::{DynamicImage, GrayImage}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Splash { + pub path: PathBuf, + pub focus: SplashFocus, +} + +/// 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) + .filter_map(|name| { + let stem = name.to_str()?.strip_suffix(".jpg")?; + let (key, point) = stem.split_once('.')?; + let (x, y) = point.split_once('.')?; + let focus = SplashFocus { + x: x.parse().ok()?, + y: y.parse().ok()?, + }; + (focus.x <= 100 && focus.y <= 100).then(|| { + ( + key.to_owned(), + Splash { + path: dir.join(&name), + focus, + }, + ) + }) + }) + .collect() +} + +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> { + 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)); + })? { + return Ok(()); + } + let dir = portraits_dir.join("splashes"); + std::fs::create_dir_all(&dir) + .map_err(|e| Error::Storage(format!("{} : {e}", dir.display())))?; + let cached = cached_splashes(&dir); + for champion in self.cached_champions()? { + let key = champion.key; + if !valid_art_key(&key) || cached.contains_key(&key) { + continue; + } + let saved = download_splash( + source.as_ref(), + &dir, + &key, + loading.remove(&key), + &card_portrait_path(portraits_dir, &key), + ); + on_attempt(matches!(saved, Ok(true))); + if matches!(saved, Err(SourceError::Network(_))) { + break; + } + } + Ok(()) + } +} + +fn download_splash( + source: &dyn ChampionSource, + dir: &Path, + key: &str, + template: Option, + card: &Path, +) -> Result { + let template = match template { + Some(template) => template, + // 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 => return Ok(false), + }; + let jpeg = source.splash(key)?; + let Some(image) = decode_jpeg(&jpeg) else { + return Ok(false); + }; + let focus = locate(&image, &template); + let path = dir.join(format!("{key}.{}.{}.jpg", focus.x, focus.y)); + Ok(save_image(&path, &jpeg)) +} + +/// Point on the champion, in whole percentages from the splash's top left. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SplashFocus { + pub x: u8, + pub y: u8, +} + +const FALLBACK: SplashFocus = SplashFocus { x: 50, y: 30 }; + +/// Position and size of the full splash relative to the banner's image area. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BannerFrame { + pub left: f32, + pub top: f32, + pub width: f32, + pub height: f32, +} + +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; + let offset = |area: f32, size: f32, percent: u8| { + (area * 0.5 - size * f32::from(percent) / 100.0) + .max(area - size) + .min(0.0) + }; + BannerFrame { + left: offset(area_width, width, self.x), + top: offset(area_height, height, self.y), + width, + height, + } + } +} + +fn decode_jpeg(bytes: &[u8]) -> Option { + image::load_from_memory_with_format(bytes, image::ImageFormat::Jpeg).ok() +} + +fn loading_template(image: &DynamicImage) -> GrayImage { + image.resize(64, 64, FilterType::CatmullRom).into_luma8() +} + +/// Match the full loading art at 70–100% of splash height using zero-mean normalized correlation. +fn locate(image: &DynamicImage, template: &GrayImage) -> SplashFocus { + let (w, h) = template.dimensions(); + let mut best = FALLBACK; + let mut best_score = 0.6; + let n = f64::from(w * h); + let sum: u32 = template.iter().map(|&v| u32::from(v)).sum(); + let squares: u32 = template.iter().map(|&v| u32::from(v).pow(2)).sum(); + let variance = f64::from(squares) - f64::from(sum).powi(2) / n; + if variance <= 0.0 { + return FALLBACK; + } + let splash = image.resize(160, 96, FilterType::CatmullRom).into_luma8(); + for step in 14..=20 { + let sh = (h * 20 + step / 2) / step; + let sw = (sh as f32 * image.width() as f32 / image.height() as f32).round() as u32; + if sw < w || sw > 160 { + continue; + } + let splash = imageops::resize(&splash, sw, sh, FilterType::Triangle); + for y in 0..=sh - h { + for x in 0..=sw - w { + let mut window_sum = 0u32; + let mut window_squares = 0u32; + let mut dot = 0u32; + for (dy, row) in template.as_raw().chunks_exact(w as usize).enumerate() { + let start = (y as usize + dy) * sw as usize + x as usize; + for (&a, &b) in row.iter().zip(&splash.as_raw()[start..start + w as usize]) { + let b = u32::from(b); + window_sum += b; + window_squares += b * b; + dot += u32::from(a) * b; + } + } + let window_variance = f64::from(window_squares) - f64::from(window_sum).powi(2) / n; + if window_variance <= 0.0 { + continue; + } + let covariance = f64::from(dot) - f64::from(sum) * f64::from(window_sum) / n; + let score = covariance / (variance * window_variance).sqrt(); + if score >= best_score { + best_score = score; + best = SplashFocus { + x: ((x as f32 + 0.5 * w as f32) * 100.0 / sw as f32).round() as u8, + y: ((y as f32 + 0.30 * h as f32) * 100.0 / sh as f32).round() as u8, + }; + } + } + } + } + best +} + +#[cfg(test)] +mod tests { + use super::*; + use image::{GrayImage, Luma}; + + #[test] + fn unrelated_images_and_featureless_art_use_the_fixed_focus() { + let splash = GrayImage::from_fn(96, 60, |x, _| Luma([(x * 2) as u8])); + let stripes = GrayImage::from_fn(27, 40, |_, y| Luma([(y * 5) as u8])); + let flat = GrayImage::new(27, 40); + for card in [&stripes, &flat] { + assert_eq!( + locate(&DynamicImage::ImageLuma8(splash.clone()), card), + SplashFocus { x: 50, y: 30 } + ); + } + } + + #[test] + fn the_banner_centres_the_focus_and_stops_at_each_edge() { + for (x, left) in [(5, 0.0), (50, -121.5), (95, -243.0)] { + let frame = SplashFocus { x, y: 30 }.banner_frame(972.0, 200.0); + assert_eq!( + (frame.left, frame.width, frame.height), + (left, 1215.0, 717.0) + ); + assert!((frame.top + 115.1).abs() < 0.01); + } + let narrow = SplashFocus { x: 50, y: 95 }.banner_frame(100.0, 717.0); + assert_eq!( + (narrow.left, narrow.top, narrow.width, narrow.height), + (-557.5, 0.0, 1215.0, 717.0) + ); + assert_eq!( + SplashFocus { x: 50, y: 0 }.banner_frame(972.0, 200.0).top, + 0.0 + ); + assert_eq!( + SplashFocus { x: 50, y: 100 }.banner_frame(972.0, 200.0).top, + -517.0 + ); + } + + #[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]) + }); + 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])); + } + 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 cbc37a0..e31fed0 100644 --- a/crates/core/src/statistics.rs +++ b/crates/core/src/statistics.rs @@ -1,11 +1,11 @@ //! Challenge figures and champion statistics, computed on demand from stored Matches. use std::cmp::Ordering; use std::collections::{BTreeMap, HashMap, HashSet}; -use std::ffi::{OsStr, OsString}; +use std::ffi::OsStr; use std::ops::Range; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; -use crate::champions::{Champion, card_portrait_path, cards_dir}; +use crate::champions::{Champion, card_portrait_path, cards_dir, file_names}; use crate::date::Date; use crate::error::Error; use crate::model::{Format, Match}; @@ -62,6 +62,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, // In scope (Season and Format filter): pub matches: usize, pub best_placement: Option, @@ -334,6 +335,7 @@ pub(crate) fn compute( ChampionRow { portrait: None, card_portrait: None, + splash: None, matches: mine.len(), best_placement: mine.iter().map(|m| m.placement).min(), top1: mine.iter().filter(|m| m.placement == 1).count(), @@ -404,18 +406,6 @@ pub(crate) fn compute( } } -/// The names of the files in `dir`; none when it is missing or unreadable. -fn file_names(dir: &Path) -> HashSet { - let Ok(entries) = std::fs::read_dir(dir) else { - return HashSet::new(); - }; - entries - .filter_map(Result::ok) - .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file())) - .map(|entry| entry.file_name()) - .collect() -} - impl Tracker { /// Replaces the Season table; Matches are assigned to Seasons on demand, so already /// stored Matches move accordingly. @@ -460,9 +450,11 @@ impl Tracker { } if let Some((_, dir)) = &self.champions { // One read of each folder rather than a file check per champion and per portrait. - let squares = file_names(dir); - let cards = file_names(&cards_dir(dir)); + 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")); for row in &mut stats.rows { + row.splash = splashes.remove(&row.champion.key); let name = format!("{}.png", row.champion.key); row.portrait = squares.contains(OsStr::new(&name)).then(|| dir.join(name)); let card = card_portrait_path(dir, &row.champion.key); diff --git a/crates/core/tests/champions.rs b/crates/core/tests/champions.rs index 8dd0804..3f7b336 100644 --- a/crates/core/tests/champions.rs +++ b/crates/core/tests/champions.rs @@ -383,6 +383,101 @@ fn refreshing_without_a_champion_source_does_nothing() { assert!(!dir.path().join("portraits").exists()); } +#[test] +fn splash_downloads_resume_after_a_network_error_and_only_fetch_new_champions() { + let dir = tempfile::tempdir().unwrap(); + let source = FakeChampions::new("1", &CATALOG[..3]); + let failure = source.card_failure(); + 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| { + attempts.push(saved); + // Three cards, then one splash. The next splash loses the network. + if attempts.len() == 4 { + failure.store(true, Ordering::SeqCst); + } + }) + .unwrap(); + assert_eq!(attempts, [true, true, true, true, false]); + assert_eq!(splash_calls.load(Ordering::SeqCst), 2); + assert_eq!(loading_calls.load(Ordering::SeqCst), 3); + let first = statistics(&tracker) + .rows + .into_iter() + .filter_map(|r| r.splash) + .collect::>(); + assert_eq!(first.len(), 1); + // (59 + 40/2, 6 + 0.30*60) in a 112 x 75 splash. + assert!( + first[0].focus.x.abs_diff(71) <= 1 && first[0].focus.y.abs_diff(32) <= 1, + "{:?}", + first[0].focus + ); + assert_eq!(std::fs::read(&first[0].path).unwrap(), common::splash_art()); + + drop(tracker); + let next = FakeChampions::new("2", &CATALOG[..4]); + 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(); + let splashes = statistics(&tracker) + .rows + .into_iter() + .filter_map(|r| r.splash) + .collect::>(); + assert_eq!(splashes.len(), 4); + assert!(splashes.contains(&first[0])); + tracker + .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 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(); + 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)) + .unwrap(); + assert!(statistics(&tracker).rows.iter().all(|r| r.splash.is_some())); +} + +#[test] +fn losing_the_network_during_cards_skips_all_splashes() { + let dir = tempfile::tempdir().unwrap(); + let source = FakeChampions::new("1", &CATALOG); + 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)) + .unwrap(); + assert_eq!(attempts, [false]); + assert_eq!(calls.load(Ordering::SeqCst), 0); + open_tracker(dir.path(), &[]) + .refresh_champion_art(&mut |_| panic!("no source")) + .unwrap(); +} + #[test] fn load_seasons_writes_the_shipped_table_when_the_file_is_missing() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/core/tests/common/mod.rs b/crates/core/tests/common/mod.rs index 070650d..892f54d 100644 --- a/crates/core/tests/common/mod.rs +++ b/crates/core/tests/common/mod.rs @@ -410,6 +410,7 @@ pub struct FakeChampions { /// The card portrait downloads fail with a network error while this is set. card_failure: Arc, card_calls: Arc, + pub splash_calls: Arc, } /// A small valid JPEG, tall like the loading art (40 x 60 px). @@ -422,6 +423,18 @@ pub fn card_art() -> Vec { out } +/// The loading art at (59, 6) in a landscape JPEG. +pub fn splash_art() -> Vec { + let card = image::load_from_memory(&card_art()).unwrap().into_rgb8(); + let mut splash = image::RgbImage::new(112, 75); + image::imageops::replace(&mut splash, &card, 59, 6); + let mut out = Vec::new(); + image::codecs::jpeg::JpegEncoder::new(&mut out) + .encode_image(&splash) + .unwrap(); + out +} + impl FakeChampions { /// `champions`: (id, key, display name). pub fn new(version: &str, champions: &[(u32, &str, &str)]) -> FakeChampions { @@ -441,6 +454,7 @@ impl FakeChampions { card_art: card_art(), card_failure: Arc::default(), card_calls: Arc::default(), + splash_calls: Arc::default(), } } @@ -519,6 +533,15 @@ impl ChampionSource for FakeChampions { } Ok(self.card_art.clone()) } + + fn splash(&self, _: &str) -> Result, SourceError> { + self.splash_calls.fetch_add(1, Ordering::SeqCst); + self.check()?; + if self.card_failure.load(Ordering::SeqCst) { + return Err(SourceError::Network("coupé".into())); + } + Ok(splash_art()) + } } // Statistics scenarios: a small catalog, two Seasons and Matches described by champion and Placement. diff --git a/crates/core/tests/statistics.rs b/crates/core/tests/statistics.rs index 7c8faab..082ace2 100644 --- a/crates/core/tests/statistics.rs +++ b/crates/core/tests/statistics.rs @@ -423,6 +423,7 @@ fn bare_row(name: &str, id: u32) -> ChampionRow { }, portrait: None, card_portrait: None, + splash: None, matches: 0, best_placement: None, top1: 0,