diff --git a/src-tauri/src/cloud.rs b/src-tauri/src/cloud.rs index 96d6781a..502774c1 100644 --- a/src-tauri/src/cloud.rs +++ b/src-tauri/src/cloud.rs @@ -576,7 +576,7 @@ fn phase(app: &AppHandle, id: &str, what: &str) { } /// Says "idle" when the work it covers ends, on every way out of it (errors included). -struct Working { +pub(crate) struct Working { app: AppHandle, id: String, } @@ -847,6 +847,7 @@ pub async fn after_session(app: &AppHandle, id: &str) -> Res let g = game(&st, id)?; let spots = spots_of(&st, id, &g); let (dir, id2, g2) = (st.dir.clone(), id.to_string(), g.clone()); + // The copy ends the session's wait (saves::backup); one that fails to go up is kept as pending. let copy = blocking(move || saves::backup(&dir, &id2, &spots, &g2)).await??; if g.cloud == Some(true) && signed_in(&st.dir) { let s = saves::state(&st.dir, id); @@ -883,6 +884,62 @@ pub async fn after_session(app: &AppHandle, id: &str) -> Res Ok(copy) } +/// When this PC's save was made, for the "which save?" choice: the time of the first copy holding +/// it (the same save is copied again before a restore or a cloud save replaces it). The files' +/// own time is only the fallback: restoring a copy writes them anew, which made an older save look +/// newer than the cloud's. +fn local_save_time(copies: &[saves::Copy], hash: &str, files_time: u64) -> u64 { + copies.iter().filter(|c| c.hash == hash).map(|c| c.when).min().unwrap_or(files_time) +} + +/// Marks a game's session as started (true) or its save as copied after it (false). A session +/// still marked when the launcher starts is finished then (finish_open_sessions). +pub(crate) fn set_after_play(dir: &Path, id: &str, open: bool) { + let mut s = saves::state(dir, id); + if s.after_play == open { + return; + } + s.after_play = open; + saves::set_state(dir, id, &s); +} + +/// The step after a game closes, from its end to its save copied (and sent): the status above +/// Play keeps saying "Syncs after you play" until then, instead of an "Up to date" that the +/// session's save may already have made untrue. Ends (idle) on every way out. +pub(crate) fn after_play_step(app: &AppHandle, id: &str) -> Working { + working(app, id, "after") +} + +/// Sessions the launcher didn't see to the end (it closed or crashed while a game ran, or before +/// the copy after it was made): their saves are copied and sent now. A game that's running again +/// is left to its own session. +pub(crate) async fn finish_open_sessions(app: &AppHandle) { + let st = app.state::(); + for id in open_sessions(&st.dir.join("saves")) { + if st.running.lock().unwrap().contains_key(&id) || game(&st, &id).is_err() { + continue; + } + let _step = after_play_step(app, &id); + match after_session(app, &id).await { + Ok(Some(_)) => { + let _ = app.emit("saves", json!({"id": id})); + } + Ok(None) => {} + Err(e) => eprintln!("Save copy for {id} after an unfinished session: {e}"), + } + } +} + +/// The games whose sync notes still mark a session open, by their folders under `saves`. +fn open_sessions(saves_dir: &Path) -> Vec { + let Ok(rd) = std::fs::read_dir(saves_dir) else { return vec![] }; + let app_dir = saves_dir.parent().unwrap_or(saves_dir); + rd.flatten() + .filter_map(|e| e.file_name().to_str().map(String::from)) + .filter(|id| saves::state(app_dir, id).after_play) + .collect() +} + /// Gets a cloud copy and puts it in place (what's there now is kept as a local copy first). async fn take_cloud(app: &AppHandle, id: &str, c: &CloudCopy) -> Res { let st = app.state::(); @@ -1067,7 +1124,8 @@ async fn check_saves(app: AppHandle, id: String, manual: bool) -> Res { s.conflict = Some(top.v.clone()); saves::set_state(&st.dir, &id, &s); let newest = entries.iter().filter_map(|e| std::fs::metadata(&e.abs).ok()?.modified().ok()).max(); - let when = newest.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs()).unwrap_or(0); + let files_time = newest.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs()).unwrap_or(0); + let when = local_save_time(&saves::list(&st.dir, &id, &g), &local, files_time); Ok(json!({"action": "conflict", "local": {"when": when, "device": saves::device_name(), "played": g.played_secs, "hash": local}, "cloud": top})) } @@ -1938,6 +1996,43 @@ mod status_tests { d } + fn copy_made(when: u64, hash: &str) -> saves::Copy { + saves::Copy { name: format!("{when}.zip"), when, size: 1, files: 1, hash: hash.into(), device: String::new(), played: 0 } + } + + #[test] + fn a_restored_save_is_dated_by_its_copy_not_by_when_it_was_written_back() { + let copies = [copy_made(300, "new"), copy_made(100, "old")]; + assert_eq!(local_save_time(&copies, "old", 500), 100); + } + + #[test] + fn a_save_copied_twice_is_dated_by_its_first_copy() { + let copies = [copy_made(400, "old"), copy_made(300, "new"), copy_made(100, "old")]; + assert_eq!(local_save_time(&copies, "old", 500), 100); + } + + #[test] + fn a_save_no_copy_holds_is_dated_by_its_files() { + assert_eq!(local_save_time(&[copy_made(300, "new")], "changed", 500), 500); + } + + #[test] + fn a_session_started_is_open_until_its_save_is_copied() { + let d = tmp("after-play"); + set_after_play(&d, "g", true); + assert_eq!(open_sessions(&d.join("saves")), vec!["g".to_string()]); + set_after_play(&d, "g", false); + assert!(open_sessions(&d.join("saves")).is_empty()); + } + + #[test] + fn a_game_with_no_open_session_is_not_finished_at_start() { + let d = tmp("after-play-none"); + saves::set_state(&d, "g", &saves::State { last_hash: "a".into(), ..Default::default() }); + assert!(open_sessions(&d.join("saves")).is_empty()); + } + #[test] fn a_full_cloud_is_its_own_problem() { assert_eq!(problem_kind(&Error::Msg(FULL_TEXT.into())), "full"); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index f647f43f..8e293737 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -3253,6 +3253,9 @@ fn start_game_with_monitor_context( let _ = std::fs::create_dir_all(marker.parent().unwrap_or(&st.dir)); // The launcher's own process id: a marker whose process is gone is stale (see marker_alive). let _ = std::fs::write(&marker, std::process::id().to_string()); + // Its save may change from here: copied after the session, or at the next start if the + // launcher closes before that. + cloud::set_after_play(&st.dir, &save_id, true); ingame::set_hotkeys(app, true, quick_menu); let _ = app.emit("game", json!({"id": id, "game": game_full, "state": "running"})); // From Big Picture mode the launcher fills the screen, so it steps aside for the game (its first @@ -3333,6 +3336,9 @@ fn start_game_with_monitor_context( } let secs = start.elapsed().as_secs(); let st = app2.state::(); + // From the game closing to its save copied, the status above Play says so, not an "Up to + // date" the session may have made untrue. Said before the window hears the game stopped. + let after_step = (secs >= 5).then(|| cloud::after_play_step(&app2, &save_id)); // A game that closes with the same code every time it's quit normally (its profile or the // catalog says which): that's a normal close, not a crash. let code = code.map(|c| if quit_code(&st, &id, prof.as_ref(), c) { 0 } else { c }); @@ -3367,6 +3373,10 @@ fn start_game_with_monitor_context( pads::PLAYING.store(!st.running.lock().unwrap().is_empty(), Ordering::Relaxed); if !st.running.lock().unwrap().contains_key(&id) { let _ = std::fs::remove_file(playing_file(&st.dir, &id)); + // Under five seconds there's no copy after it (below): nothing left to finish. + if secs < 5 { + cloud::set_after_play(&st.dir, &save_id, false); + } } if let Some(g) = st.lib.lock().unwrap().installed.get_mut(&id) { g.played_secs += secs; @@ -3423,6 +3433,7 @@ fn start_game_with_monitor_context( Err(e) => eprintln!("Save copy for {id}: {e}"), } } + drop(after_step); // Started from a shortcut with no window: the launcher's job is done. if st.headless.load(Ordering::Relaxed) && st.running.lock().unwrap().is_empty() { app2.exit(0); @@ -9997,10 +10008,14 @@ pub fn run() { repair_lost_setups(&st); }); } - // Save copies that didn't reach the cloud last time. + // Sessions the launcher didn't see to the end (it closed or crashed before their saves + // were copied) are finished first, then save copies that didn't reach the cloud. { let h = app.handle().clone(); - tauri::async_runtime::spawn(async move { cloud::upload_pending(&h).await }); + tauri::async_runtime::spawn(async move { + cloud::finish_open_sessions(&h).await; + cloud::upload_pending(&h).await; + }); } // Screenshots show in the window straight from their folder, wherever Pictures is. The // folder itself is only made when the first screenshot is taken. diff --git a/src-tauri/src/saves.rs b/src-tauri/src/saves.rs index 227d1de9..d447a2ae 100644 --- a/src-tauri/src/saves.rs +++ b/src-tauri/src/saves.rs @@ -698,6 +698,11 @@ pub struct State { /// Why the last sync didn't go through. Kept until one does. #[serde(default, skip_serializing_if = "Option::is_none")] pub problem: Option, + /// A session started and its save hasn't been copied since: set at Play, cleared once the + /// copy after it is made. Still set when the launcher closed (or crashed) before that, so the + /// next start makes the copy and sends it. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub after_play: bool, } /// Why a game's saves didn't reach the cloud. `kind` is one of: offline, full, paused, @@ -744,7 +749,9 @@ impl State { if kind == "too-big-folder" { return "problem"; } - if !self.behind() { + // A session whose save hasn't been copied yet may have changed it: not up to date until the + // copy after it is made. + if !self.behind() && !self.after_play { return if self.synced_hash.is_empty() && self.last_hash.is_empty() { "none" } else { "up-to-date" }; } // No connection is only waiting: it goes up by itself once the website answers. @@ -814,6 +821,19 @@ pub fn list(app_dir: &Path, id: &str, g: &Installed) -> Vec { out } +/// The save as it is now has a copy (or there is none to copy): no session waits on it anymore. +/// Every copy clears it, whatever made it (after a session, Sync Now, Back Up Now, before a restore +/// or a cloud save), so "Waiting to upload" can't outlive the copy. All of those run with the game +/// closed, so none ends a session that's still going. +fn copied(app_dir: &Path, id: &str) { + let mut st = state(app_dir, id); + if !st.after_play { + return; + } + st.after_play = false; + set_state(app_dir, id, &st); +} + /// Writes a copy of the saves as they are now. None when there are none, or nothing changed since /// the last copy. pub fn backup(app_dir: &Path, id: &str, spots: &[Spot], g: &Installed) -> Result, Error> { @@ -824,15 +844,18 @@ pub fn backup(app_dir: &Path, id: &str, spots: &[Spot], g: &Installed) -> Result return Err(too_big_error(g, spots, &too_big)); } if pre.is_empty() { + copied(app_dir, id); return Ok(None); } let (entries, infos, hash, _) = current(spots, g); if entries.is_empty() { + copied(app_dir, id); return Ok(None); } let mut st = state(app_dir, id); let all = list(app_dir, id, g); if st.last_hash == hash && all.first().map(|c| c.hash == hash).unwrap_or(false) { + copied(app_dir, id); return Ok(None); } let d = dir_of(app_dir, id, g); @@ -874,6 +897,7 @@ pub fn backup(app_dir: &Path, id: &str, spots: &[Spot], g: &Installed) -> Result } } st.last_hash = hash.clone(); + st.after_play = false; set_state(app_dir, id, &st); let size = fs::metadata(&file).map(|m| m.len()).unwrap_or(0); Ok(Some(Copy { name: format!("{when}.zip"), when, size, files: infos.len(), hash, device: man.device, played: man.played })) @@ -1308,6 +1332,36 @@ mod tests { Installed { id: "g".into(), name: "Test Game".into(), path: dir.to_path_buf(), files: vec![PathBuf::from("game.exe"), PathBuf::from("data/a.bin")], played_secs: 60, ..Default::default() } } + // A game whose saves are in {install}/save, with one save file in it. + fn game_with_a_save(d: &Path) -> (Installed, Vec, PathBuf) { + let g = game(&d.join("lib/Game")); + fs::create_dir_all(d.join("lib/Game/save")).unwrap(); + fs::write(d.join("lib/Game/save/slot.sav"), b"one").unwrap(); + let s = spots(&["{install}/save".into()], &[], &g); + (g, s, d.join("app")) + } + + #[test] + fn a_copy_of_the_save_ends_the_open_session() { + let d = tmp("copy-ends-session"); + let (g, s, app) = game_with_a_save(&d); + set_state(&app, "g", &State { after_play: true, ..Default::default() }); + backup(&app, "g", &s, &g).unwrap(); + assert!(!state(&app, "g").after_play); + } + + #[test] + fn a_save_already_copied_ends_the_open_session_too() { + let d = tmp("copied-ends-session"); + let (g, s, app) = game_with_a_save(&d); + backup(&app, "g", &s, &g).unwrap(); + let mut st = state(&app, "g"); + st.after_play = true; + set_state(&app, "g", &st); + assert!(backup(&app, "g", &s, &g).unwrap().is_none()); + assert!(!state(&app, "g").after_play); + } + #[test] fn nothing_known_means_no_save_places() { let g = game(Path::new("/games/test")); @@ -2019,6 +2073,24 @@ mod sync_state_tests { Some(Problem { kind: kind.into(), text: String::new(), at: 1 }) } + #[test] + fn a_session_not_copied_yet_is_waiting_not_up_to_date() { + let s = State { last_hash: "a".into(), synced_hash: "a".into(), after_play: true, ..Default::default() }; + assert_eq!(s.sync_state(true, true), "waiting"); + } + + #[test] + fn a_first_session_not_copied_yet_is_waiting_not_none() { + let s = State { after_play: true, ..Default::default() }; + assert_eq!(s.sync_state(true, true), "waiting"); + } + + #[test] + fn a_session_not_copied_yet_is_left_out_of_the_file_when_there_is_none() { + let s = State { last_hash: "a".into(), ..Default::default() }; + assert!(!serde_json::to_string(&s).unwrap().contains("after_play")); + } + #[test] fn signed_out_comes_first() { let s = State { last_hash: "a".into(), synced_hash: "a".into(), ..Default::default() }; diff --git a/tests/save-badge.test.cjs b/tests/save-badge.test.cjs new file mode 100644 index 00000000..9d74bfc6 --- /dev/null +++ b/tests/save-badge.test.cjs @@ -0,0 +1,155 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const account = fs.readFileSync(path.join(__dirname, '../ui/account.js'), 'utf8'); + +// Everything from `start` to the brace that closes the first one after it (a function, or a +// const object), out of account.js. +function block(start) { + const at = account.indexOf(start); + assert.ok(at >= 0, start); + let i = account.indexOf('{', at), depth = 0; + for (; i < account.length; i++) { + if (account[i] === '{') depth++; + if (account[i] === '}' && --depth === 0) break; + } + return account.slice(at, i + 1); +} +const line = (start) => { + const at = account.indexOf(start); + assert.ok(at >= 0, start); + return account.slice(at, account.indexOf('\n', at)); +}; + +// The status line's info for a status, with the window's helpers kept to plain English. +const info = new Function(` + const N_ = (x) => x, t = (x) => x, tf = (x) => x; + const tn = (n, one, many) => (n === 1 ? one : many).replace('{n}', n); + const ago = () => 'this week', whenText = (ts) => 'at ' + ts; + ${block('const PROBLEM_BADGE = ')} + ${block('const PHASE_BADGE = ')} + ${block('function sinceText(')} + ${block('function saveBadgeInfo(')} + ${block('function problemBadge(')} + ${block('function waitingBadge(')} + ${line('const badgeTip = ')} + return { saveBadgeInfo, sinceText, badgeTip };`)(); + +const now = () => Math.floor(Date.now() / 1000); +const status = (state, more = {}) => ({ state, syncedAt: 0, waiting: 0, retryIn: null, problem: null, newest: null, ...more }); + +test('the same save here and in the cloud is green, with how long ago', () => { + const b = info.saveBadgeInfo(status('up-to-date', { syncedAt: now() - 12 * 60, syncedDevice: 'Desk PC' }), undefined, false); + assert.equal(b.tone, 'ok'); + assert.equal(b.label, 'Up to date'); + assert.equal(b.note, '12 min ago'); +}); + +test('an upload running shows over what the status says', () => { + const b = info.saveBadgeInfo(status('waiting', { waiting: 1 }), 'up', false); + assert.equal(b.label, 'Uploading…'); + assert.equal(b.tone, 'cy'); +}); + +test('a game being played says its save goes up after', () => { + const b = info.saveBadgeInfo(status('up-to-date', { syncedAt: now() }), undefined, true); + assert.equal(b.label, 'Syncs after you play'); +}); + +test('with cloud saves off, the copy after a session is not called a sync', () => { + const b = info.saveBadgeInfo(status('off'), 'after', false); + assert.equal(b.label, 'Cloud saves off'); +}); + +test('signed out, the copy after a session is not called a sync', () => { + const b = info.saveBadgeInfo(status('signed-out'), 'after', false); + assert.equal(b.label, 'Not signed in'); +}); + +test('right after the game closes it still says the save goes up after play, not up to date', () => { + const b = info.saveBadgeInfo(status('up-to-date', { syncedAt: now() }), 'after', false); + assert.equal(b.label, 'Syncs after you play'); +}); + +test('a session the launcher has not copied yet is waiting, not up to date', () => { + const b = info.saveBadgeInfo(status('waiting'), undefined, false); + assert.equal(b.tone, 'warn'); +}); + +test('a conflict still asks for a choice while the game runs', () => { + const b = info.saveBadgeInfo(status('conflict'), undefined, true); + assert.equal(b.label, 'Choose a save'); + assert.equal(b.note, 'press Play to pick'); + assert.equal(b.tone, 'warn'); +}); + +test('a copy queued while offline says so', () => { + const b = info.saveBadgeInfo(status('waiting', { waiting: 1, problem: { kind: 'offline', text: '' } }), undefined, false); + assert.equal(b.tone, 'warn'); + assert.equal(b.note, 'offline'); +}); + +test('a copy waiting its next try says when', () => { + const b = info.saveBadgeInfo(status('waiting', { waiting: 2, retryIn: 230 }), undefined, false); + assert.equal(b.note, 'next try in 4 min'); +}); + +test('a newer save that goes up after the next session has no note', () => { + const b = info.saveBadgeInfo(status('waiting'), undefined, false); + assert.equal(b.label, 'Waiting to upload'); + assert.equal(b.note, ''); +}); + +test('a copy too big to send is red and named', () => { + const b = info.saveBadgeInfo(status('problem', { problem: { kind: 'too-big-copy', text: 'Over 95 MB.' } }), undefined, false); + assert.equal(b.tone, 'bad'); + assert.equal(b.label, 'Too big for the cloud'); + assert.equal(b.text, 'Over 95 MB.'); +}); + +test('a problem of a kind it does not know reads as an upload that failed', () => { + const b = info.saveBadgeInfo(status('problem', { problem: { kind: 'something-new', text: '' } }), undefined, false); + assert.equal(b.label, 'Can\'t upload'); +}); + +test('cloud saves off is grey', () => { + const b = info.saveBadgeInfo(status('off'), undefined, false); + assert.equal(b.tone, 'dim'); + assert.equal(b.label, 'Cloud saves off'); +}); + +test('signed out says so', () => { + const b = info.saveBadgeInfo(status('signed-out'), undefined, false); + assert.equal(b.label, 'Not signed in'); +}); + +test('a game never played has nothing to sync', () => { + const b = info.saveBadgeInfo(status('none'), undefined, false); + assert.equal(b.label, 'No saves yet'); +}); + +test('the tooltip says what it means, then when it last synced and where', () => { + const b = info.saveBadgeInfo(status('up-to-date', { syncedAt: 100, syncedDevice: 'Desk PC' }), undefined, false); + const tip = info.badgeTip(b); + assert.equal(tip, 'Your save is in the cloud\nThis PC and the cloud have the same save.\nLast synced: at 100\nSaved on: Desk PC'); +}); + +test('a sync over a day ago falls back to the coarse wording', () => { + assert.equal(info.sinceText(now() - 3 * 86400), 'this week'); +}); + +// Which save the conflict dialog marks Newer. +const newerSave = new Function(`${block('function newerSave(')} return newerSave;`)(); + +test('this PC saved after the cloud copy: this PC is newer', () => { + assert.equal(newerSave({ when: 200 }, { made: 100 }), 'local'); +}); + +test('the cloud copy saved after this PC: the cloud one is newer', () => { + assert.equal(newerSave({ when: 100 }, { made: 200 }), 'cloud'); +}); + +test('saved at the same second: neither is marked', () => { + assert.equal(newerSave({ when: 100 }, { made: 100 }), ''); +}); diff --git a/ui/account.js b/ui/account.js index 0f4725d1..ecd94c55 100644 --- a/ui/account.js +++ b/ui/account.js @@ -20,7 +20,7 @@ async function loadAccount(fresh) { const was = !!(S.account && S.account.signedIn); try { S.account = await invoke('account_state', { fresh: !!fresh }); } catch (e) { S.account = S.account || { signedIn: false }; } // Signed in (or out) just now: what each game's Saves tab knew is out of date. - if (was !== !!S.account.signedIn) { S.saves = {}; S.savesAll = null; S.myReports = null; } + if (was !== !!S.account.signedIn) { S.saves = {}; S.savesAll = null; S.myReports = null; forgetSaveStatus(); } renderAccountBits(); if (S.account.signedIn && !S.myReports && !S.account.offline) loadMyReports(); // Notify Me: the games they're waiting on (none when signed out). @@ -125,6 +125,7 @@ async function signOut() { try { await invoke('account_signout'); } catch (e) { /* signed out here anyway */ } S.account = { signedIn: false }; S.saves = {}; + forgetSaveStatus(); // The next sign-in merges this PC's saved list with that account's again. saveUi({ lib_synced: null, lib_queue: [] }, true).catch(() => {}); toast(t('Signed out. Your saves stay on this PC.')); @@ -184,6 +185,8 @@ async function loadSaves(id) { S.saves[id] = S.saves[id] && S.saves[id] !== 'loading' ? Object.assign(S.saves[id], { busy: true }) : 'loading'; try { S.saves[id] = await invoke('saves_info', { id }); } catch (e) { S.saves[id] = { error: String(e && e.message ? e.message : e) }; } if (S.view === 'game' && S.arg === id && S.tab === 'saves') refreshGame(); + // Whatever just changed the tab (Sync Now, Back Up Now, the cloud switch) changed the badge too. + loadSaveStatus(saveIdOf(id)); } const FROM = { player: N_('You picked this folder'), developer: N_('Its developer says it saves here'), catalog: N_('RecompLauncher knows it saves here') }; // Nobody (the player, its developer or RecompLauncher) has said where this game saves. Nothing is @@ -251,6 +254,169 @@ function copyRow(id, c, k, v, current) { const savesChanged = (id) => { delete S.saves[id]; if (S.view === 'game' && S.arg === id && S.tab === 'saves') loadSaves(id); }; +// ---------- the cloud save status above Play ---------- +// Where a game's saves stand, on its page above Play and above Big Picture's game buttons, so the +// player doesn't have to open the Saves tab to see whether the last save reached the cloud. Only +// a coloured line, not a button: what to do about it is on the Saves tab. Hovering it says more. +// saves_status answers from this PC alone (it never asks the website); the save-sync event says +// when something runs or ends, and the status is asked again then. +S.saveStat = {}; +S.savePhase = {}; +const statLoading = new Set(); + +// A game of several that keeps its own saves goes by its own id; any other by its recomp's. +function saveIdOf(id) { + const s = subOf(id); + const own = s && Array.isArray(s.game.saves) && s.game.saves.length; + return own ? id : parentId(id); +} + +async function loadSaveStatus(sid) { + if (statLoading.has(sid)) return; + statLoading.add(sid); + try { S.saveStat[sid] = await invoke('saves_status', { id: sid }); } catch (e) { S.saveStat[sid] = null; } + statLoading.delete(sid); + paintSaveBadges(sid); +} + +// "12 min ago" for the last sync: ago() only goes down to "today", too coarse for "did that +// session's save go up?". +function sinceText(ts) { + if (!ts) return ''; + const secs = Math.max(0, Date.now() / 1000 - ts); + if (secs < 60) return t('just now'); + if (secs < 3600) return tn(Math.floor(secs / 60), '1 min ago', '{n} min ago'); + if (secs < 86400) return tn(Math.floor(secs / 3600), '1 hour ago', '{n} hours ago'); + return ago(ts); +} + +// What a problem kept by the last sync looks like, by its kind. The backend's own words say why +// (in the tooltip); these say it short. +const PROBLEM_BADGE = { + full: { label: N_('Can\'t upload'), note: N_('cloud full'), head: N_('Your cloud saves are full') }, + 'too-big-copy': { label: N_('Too big for the cloud'), head: N_('This save is too big for the cloud') }, + 'too-big-folder': { label: N_('Sync paused'), head: N_('Cloud saves are paused for this game') }, + paused: { label: N_('Cloud saves paused'), head: N_('Cloud saves are paused for now') }, + error: { label: N_('Can\'t upload'), head: N_('The last upload didn\'t go through') }, +}; + +// While something runs (from the save-sync event): checking before Play, a save going up or one +// coming down. +const PHASE_BADGE = { + check: { mark: 'check-run', label: N_('Checking cloud…'), head: N_('Looking for a newer save'), text: N_('Before the game starts, the launcher checks whether another PC saved after this one.') }, + up: { mark: 'up', label: N_('Uploading…'), head: N_('Sending your save'), text: N_('Your newest save is going to the cloud.') }, + down: { mark: 'down', label: N_('Getting cloud save…'), head: N_('Bringing in a newer save'), text: N_('Another PC saved after this one. Your current save is kept as a backup first.') }, + // The game just closed (or crashed, or the launcher is finishing a session it didn't see end): + // its save is being copied, and sent when cloud saves are on. + after: { mark: 'play', label: N_('Syncs after you play'), head: N_('Saving after you played'), text: N_('Its save is being copied, and sent to the cloud when cloud saves are on.') }, +}; + +// What the status line shows for a game: its tone (ok, cy, warn, bad, dim), the mark inside the +// cloud, a label and a short note, and for the tooltip a heading, a line and rows ([label, value]). +// `phase` is what's running now, `running` whether the game is. +function saveBadgeInfo(st, phase, running) { + // The copy after a session runs for every game; it's only shown for one that syncs. Signed out + // or with cloud saves off, the line keeps saying so instead of a sync that isn't happening. + const syncs = st.state !== 'signed-out' && st.state !== 'off' && st.known !== false; + const p = syncs && PHASE_BADGE[phase]; + if (p) return { tone: 'cy', mark: p.mark, label: t(p.label), note: '', head: t(p.head), text: t(p.text), rows: [] }; + const synced = st.syncedAt ? [[t('Last synced'), whenText(st.syncedAt)], [t('Saved on'), st.syncedDevice || t('this PC')]] : []; + const newest = st.newest ? [[t('Last backup'), `${whenText(st.newest.when)}${st.newest.device ? ' · ' + st.newest.device : ''}`]] : []; + if (st.state === 'signed-out') return { tone: 'dim', mark: 'dash', label: t('Not signed in'), note: '', head: t('Keep this save on any PC'), text: t('Sign in to RecompStore and your saves go to the cloud after you play. It\'s free.'), rows: newest }; + if (st.state === 'off') return { tone: 'dim', mark: 'off', label: t('Cloud saves off'), note: '', head: t('Saves stay on this PC'), text: t('The launcher still keeps a copy after every session. Turn cloud saves on in its Saves tab.'), rows: newest }; + if (st.state === 'conflict') return { tone: 'warn', mark: 'conflict', label: t('Choose a save'), note: t('press Play to pick'), head: t('Both saves changed'), text: t('This PC and the cloud both changed since they last synced. Press Play, or Sync Now in its Saves tab, to pick the one to keep; the other stays as a backup on this PC.'), rows: synced }; + if (st.state === 'problem') return problemBadge(st, synced); + if (running) return { tone: 'cy', mark: 'play', label: t('Syncs after you play'), note: '', head: t('Playing now'), text: t('Its save goes to the cloud when you close the game.'), rows: synced }; + if (st.state === 'waiting') return waitingBadge(st, synced); + if (st.state === 'up-to-date') return { tone: 'ok', mark: 'check', label: t('Up to date'), note: sinceText(st.syncedAt), head: t('Your save is in the cloud'), text: t('This PC and the cloud have the same save.'), rows: synced }; + return { tone: 'dim', mark: 'dash', label: t('No saves yet'), note: '', head: t('Nothing to sync yet'), text: t('Play it once. Its saves are backed up after, and go to the cloud too.'), rows: [] }; +} + +function problemBadge(st, synced) { + const kind = (st.problem && st.problem.kind) || 'error'; + const b = PROBLEM_BADGE[kind] || PROBLEM_BADGE.error; + const text = st.problem && st.problem.text ? t(st.problem.text) : ''; + return { tone: 'bad', mark: 'alert', label: t(b.label), note: b.note ? t(b.note) : '', head: t(b.head), text, rows: synced }; +} + +// Saved here and not in the cloud yet: queued after a try that didn't get through (with when the +// next one is), or going up after the next session. +function waitingBadge(st, synced) { + const queued = st.waiting > 0; + const offline = st.problem && st.problem.kind === 'offline'; + const minutes = st.retryIn ? Math.max(1, Math.ceil(st.retryIn / 60)) : 0; + const note = minutes ? tn(minutes, 'next try in 1 min', 'next try in {n} min') : offline ? t('offline') : ''; + const text = !queued ? t('It goes up after you play next, or now with Sync Now in its Saves tab.') + : offline ? t('The website can\'t be reached right now. Your save is safe here and goes up by itself when it can.') + : t('It goes up by itself on the next try.'); + const rows = queued ? [[t('Waiting'), tn(st.waiting, '1 copy', '{n} copies')], ...synced] : synced; + return { tone: 'warn', mark: 'clock', label: t('Waiting to upload'), note, head: t('Saved on this PC, not in the cloud yet'), text, rows }; +} + +// The cloud, with a mark inside it for the state. Drawn the same in both modes. +const BADGE_MARKS = { + check: '', + 'check-run': '', + up: '', + down: '', + clock: '', + alert: '', + conflict: '', + off: '', + dash: '', + play: '', +}; +const badgeIcon = (mark, size = 18) => ``; + +// The tooltip: the heading, its line, then each row on its own line. +const badgeTip = (b) => [b.head, b.text, ...b.rows.map(([k, v]) => `${k}: ${v}`)].filter(Boolean).join('\n'); + +// The status for a game page id, or null while it's not known (or not installed). +function saveBadgeFor(id) { + if (!S.library[parentId(id)]) return null; + const sid = saveIdOf(id); + const st = S.saveStat[sid]; + if (st === undefined) loadSaveStatus(sid); + if (!st) return null; + const b = saveBadgeInfo(st, S.savePhase[sid], S.running.has(parentId(sid))); + return { ...b, tip: badgeTip(b) }; +} + +function badgeInner(pageId) { + const b = saveBadgeFor(pageId); + if (!b) return ''; + const note = b.note ? `${esc(b.note)}` : ''; + return `${badgeIcon(b.mark)}${esc(b.label)}${note}`; +} + +// The status on a game page, above Play. It says changes out loud to a screen reader. +function saveBadge(a) { + if (!S.library[parentId(a.id)]) return ''; + const sid = saveIdOf(a.id); + return `
${badgeInner(a.id)}
`; +} + +// Redraws the status lines on screen (one game's, or all of them), and Big Picture's game page. +function paintSaveBadges(sid) { + for (const el of $$('[data-save-badge]')) { + if (sid && el.dataset.saveBadge !== sid) continue; + el.innerHTML = badgeInner(el.dataset.page); + } + if (window.tvRefresh && inTV()) window.tvRefresh(); +} + +// Signed in or out, or the cloud changed: every game's status is asked again. +function forgetSaveStatus() { + S.saveStat = {}; + S.savePhase = {}; + paintSaveBadges(); +} + +window.saveBadge = saveBadge; +window.saveBadgeFor = saveBadgeFor; +window.saveBadgeIcon = badgeIcon; +window.paintSaveBadges = paintSaveBadges; + // ---------- the Saves page: every game's saves in one place ---------- const CARD_ICON = ''; let savesAllBusy = null; @@ -322,16 +488,21 @@ window.loadSavesAll = loadSavesAll; // ---------- before Play ---------- // Asks once per game, while signed in, whether its saves go to the cloud; then brings in a newer // save from another PC, or asks which to keep. false: don't start it. -async function ask(title, text, buttons) { +// `cards`: on the desktop the choices are big cards to click (a heading, a green tag such as +// Newer, and their `lines`), not buttons under the text. Big Picture's sheet is the same either way. +async function ask(title, text, buttons, cards) { if (inTV() && window.tvAsk) { // A button marked last (one that changes things for good) goes to the end of the list, away from the first focus. const list = buttons.filter((b) => !b.last).concat(buttons.filter((b) => b.last)); - const i = await window.tvAsk(title, list.map((b) => ({ label: b.label, sub: b.sub, icon: b.icon }))); + const i = await window.tvAsk(title, list.map((b) => ({ label: b.label, sub: b.sub, tag: b.tag, icon: b.icon }))); return i == null || i < 0 ? null : list[i].v; } + const card = (b, i) => ``; + const button = (b, i) => ``; + const choices = cards ? `
${buttons.map(card).join('')}
` : `
${buttons.map(button).join('')}
`; return new Promise((res) => { let picked = null; - const box = modal(`

${esc(title)}

${text}
${buttons.map((b, i) => ``).join('')}
`, (x, close) => { + const box = modal(`

${esc(title)}

${text}${choices}`, (x, close) => { const i = Number(String(x.dataset.x).slice(1)); if (!isNaN(i) && buttons[i]) { picked = buttons[i].v; close(); } }, title); @@ -391,15 +562,34 @@ async function beforeCloudPlay(id) { } async function pickCloudSave(id, { local, cloud }) { - const card = (h, when, dev, played) => `
${esc(h)}${esc(whenText(when))}${esc(dev)}${esc(tf('Played {time} in all', { time: fmtTime(played) }))}
`; - const v = await ask(t('Which save do you want?'), `
${card(t('This PC'), local.when, local.device, local.played)}${card(t('Cloud'), cloud.made, cloud.device, cloud.played)}

${esc(t('The other one is kept as a copy on its Saves tab, so nothing is lost.'))}

`, - [{ label: t('Keep this PC\'s'), sub: `${whenText(local.when)} · ${local.device}`, icon: 'desk', v: 'local' }, { label: t('Use the cloud one'), sub: `${whenText(cloud.made)} · ${cloud.device}`, icon: 'check', v: 'cloud' }]); - if (v == null) return false; + const v = await chooseSave(local, cloud); + if (v !== 'local' && v !== 'cloud') return false; await invoke('saves_pick', { id, keep: v, localHash: local.hash, cloudVersion: cloud.v }); toast(t(v === 'cloud' ? 'The cloud save is in place.' : 'Your save is in the cloud.')); return true; } +// Which of the two saves is newer ('local' or 'cloud'), or '' when they were saved at the same time. +function newerSave(local, cloud) { + if (local.when > cloud.made) return 'local'; + if (cloud.made > local.when) return 'cloud'; + return ''; +} + +// Both saves changed: the player picks one. On the desktop the two saves are the choices +// themselves (cards to click, no buttons under them); in Big Picture they're the sheet's two +// items. The newer one says so, and what happens to the other is said under the question. +function chooseSave(local, cloud) { + const newer = newerSave(local, cloud); + const tag = (k) => (k === newer ? t('Newer') : ''); + const played = (secs) => tf('Played {time} in all', { time: fmtTime(secs) }); + const note = `

${esc(t('The other one is kept as a copy on its Saves tab, so nothing is lost.'))}

`; + return ask(t('Which save do you want?'), note, [ + { label: t('Keep this PC\'s'), sub: `${whenText(local.when)} · ${local.device}`, lines: [whenText(local.when), local.device, played(local.played)], tag: tag('local'), icon: 'desk', v: 'local' }, + { label: t('Use the cloud one'), sub: `${whenText(cloud.made)} · ${cloud.device}`, lines: [whenText(cloud.made), cloud.device, played(cloud.played)], tag: tag('cloud'), icon: 'cloud', v: 'cloud' }, + ], true); +} + async function syncCloudNow(id) { const r = await invoke('saves_check', { id, manual: true }); switch (r.action) { @@ -520,8 +710,20 @@ window.accountAct = async (act, el) => { return null; }; -T.event.listen('account', ({ payload }) => { if (payload && payload.signedIn === false) { S.account = { signedIn: false }; S.saves = {}; renderAccountBits(); if (window.afterSignIn) window.afterSignIn(); } else loadAccount(true); }); -T.event.listen('saves', ({ payload }) => { if (S.view === 'saves') loadSavesAll(); if (payload && payload.id) { delete S.saves[payload.id]; if (S.view === 'game' && S.arg === payload.id && S.tab === 'saves') loadSaves(payload.id); } }); +T.event.listen('account', ({ payload }) => { if (payload && payload.signedIn === false) { S.account = { signedIn: false }; S.saves = {}; forgetSaveStatus(); renderAccountBits(); if (window.afterSignIn) window.afterSignIn(); } else loadAccount(true); }); +T.event.listen('saves', ({ payload }) => { if (S.view === 'saves') loadSavesAll(); if (payload && payload.id) { delete S.saves[payload.id]; loadSaveStatus(payload.id); if (S.view === 'game' && S.arg === payload.id && S.tab === 'saves') loadSaves(payload.id); } }); +// A check, upload or download for a game started or ended: the badge says so, and asks for the +// outcome once it's over. +T.event.listen('save-sync', ({ payload }) => { + const sid = payload && payload.id; + if (!sid) return; + if (payload.phase !== 'idle') { + S.savePhase[sid] = payload.phase; + return paintSaveBadges(sid); + } + delete S.savePhase[sid]; + loadSaveStatus(sid); +}); // Who's signed in: what's remembered first, then the website's answer. loadAccount(false).then(() => loadAccount(true)); diff --git a/ui/app.css b/ui/app.css index dcb97948..1141d484 100644 --- a/ui/app.css +++ b/ui/app.css @@ -2571,3 +2571,22 @@ body.light .su-req{color:#8a5300} .poster.cvl-on .badge.tl,.poster.cvl-on .badge.tr,.poster.cvl-on .badge.rank{top:calc(var(--cvl-top) * 100% + 9px)} .poster.cvl-on .badge.tl.low{top:calc(var(--cvl-top) * 100% + 41px)} .tv-poster.cvl-on .tv-badge,.tv-poster.cvl-on .tv-rank{top:calc(var(--cvl-top) * 100% + 12px)} +/* The cloud save status above Play (account.js): a coloured line, not a button. Its colour says + the state: green in the cloud, cyan working, amber waiting or a choice, red stuck, grey no + cloud. The tooltip says more. */ +.sbadge{--sb-ok:#3ee08f;--sb-warn:var(--warn);--sb-bad:var(--bad);min-height:20px} +body.light .sbadge{--sb-ok:#127a45;--sb-warn:#9a6200;--sb-bad:#c53030} +.sbadge .sb-ok{--c:var(--sb-ok)}.sbadge .sb-cy{--c:var(--cyan)}.sbadge .sb-warn{--c:var(--sb-warn)}.sbadge .sb-bad{--c:var(--sb-bad)}.sbadge .sb-dim{--c:var(--dim)} +.sbadge-line{display:inline-flex;align-items:center;gap:7px;font:700 13.5px Figtree,sans-serif;color:var(--c);white-space:nowrap;cursor:default} +.sbadge-line svg{flex:none} +.sbadge-line small{font-weight:500;font-size:12.5px;color:var(--muted)} +.sbadge-line small::before{content:"· "} +.sb-spin{animation:sbspin 1.1s linear infinite;transform-origin:12px 13px} +.sb-bob{animation:sbbob 1.2s ease-in-out infinite} +@keyframes sbspin{to{transform:rotate(360deg)}} +@keyframes sbbob{50%{transform:translateY(-1.5px)}} +@media (prefers-reduced-motion:reduce){.sb-spin,.sb-bob{animation:none}} +/* "Newer" on the save that was made later, when both changed: a green word, not a pill. */ +.pick-newer{margin-left:6px;font-style:normal;font-size:12.5px;font-weight:700;color:#3ee08f} +body.light .pick-newer{color:#127a45} +.pick-note{margin:-4px 0 14px;font-size:13px} diff --git a/ui/app.js b/ui/app.js index d9355aa2..0fee6d8c 100644 --- a/ui/app.js +++ b/ui/app.js @@ -2109,7 +2109,7 @@ function pageGame(id) {
${pic(thumbOf(a.cover))}
${kick ? `${esc(kick)}` : ''}

${esc(a.name)}

${partOfLine(a)}${based(a)}${devLine(a)}${verPill(a)}${chips ? `
${chips}
` : ''}${tagsOf(a).length ? `
${tagsOf(a).map((tg) => ``).join('')}
` : ''}
-
${actions(a)}
${replacedNote(a) || betterNote(a) || reinstallNote(a) || badNote(a) || stateNote(a)}${S.library[id] && S.library[id].from_backup ? `

${esc(t('Downloaded from the RecompLauncher backup'))}

` : ''}
${igCard(a)}
+
${window.saveBadge ? window.saveBadge(a) : ''}
${actions(a)}
${replacedNote(a) || betterNote(a) || reinstallNote(a) || badNote(a) || stateNote(a)}${S.library[id] && S.library[id].from_backup ? `

${esc(t('Downloaded from the RecompLauncher backup'))}

` : ''}
${igCard(a)}
${includesBox(a)}
${gameTabs(a).map(([k, n, x]) => ``).join('')}
${gameBody(a)}
`; @@ -2634,6 +2634,8 @@ function refreshGame() { $$('.tabs-in button').forEach((b) => { const on = b.dataset.tab === S.tab; b.classList.toggle('on', on); b.setAttribute('aria-selected', String(on)); }); const acts = $(`.gp-acts`); if (acts) morph(acts, actions(a)); + // The cloud save badge: the game started or closed, or its saves changed. + if (window.paintSaveBadges) window.paintSaveBadges(); const main = $('#main'), top = main.scrollTop; const body = $('#g-body'); body.classList.add('still'); diff --git a/ui/tv.css b/ui/tv.css index 3e150459..c3d14860 100644 --- a/ui/tv.css +++ b/ui/tv.css @@ -1026,3 +1026,12 @@ body.linux .tv-boot .aurora i{filter:none;mix-blend-mode:normal} .tv-rail.box{right:auto;bottom:auto} .tv-rail i{position:absolute;left:0;top:0;width:100%;border-radius:6px;background:var(--acc,#34F2E8);opacity:.75;transition:transform .35s cubic-bezier(.2,.8,.2,1),height .2s} .tv-rail[hidden]{display:none} +/* The cloud save status above a game's buttons (account.js decides the state): a coloured line, + not a button, as on the desktop. */ +.tv-sbadge{--c:#8B97AA;margin:0;display:inline-flex;align-items:center;gap:10px;font-size:22px;font-weight:700;color:var(--c)} +.tv-sbadge.sb-ok{--c:#3ee08f}.tv-sbadge.sb-cy{--c:#34F2E8}.tv-sbadge.sb-warn{--c:#f5b83d}.tv-sbadge.sb-bad{--c:#ff7a7a} +.tv-sbadge svg{flex:none} +.tv-sbadge small{font-size:20px;font-weight:600;color:var(--tvsoft,#c9d3e0)} +.tv-sbadge small::before{content:"· "} +/* "Newer" beside a sheet item's label (the save made later, when both changed): green text. */ +.tv-newer{margin-left:12px;font-style:normal;font-size:19px;font-weight:700;color:#3ee08f} diff --git a/ui/tv.js b/ui/tv.js index 5f98c6b4..be2e5132 100644 --- a/ui/tv.js +++ b/ui/tv.js @@ -1467,6 +1467,10 @@ ...(modsOk && g ? [[esc(t('Mods')), esc(tf('{n} installed', { n: (S.mods[id].installed || []).length }))]] : []), ]; const bad = checks.filter((r) => r.v === false).length; + // Where its saves stand (account.js), above the buttons as on the desktop: a line, not a button. + const sb = g && window.saveBadgeFor ? window.saveBadgeFor(id) : null; + const sbNote = sb && sb.note ? `${esc(sb.note)}` : ''; + const sbLine = sb ? `

${window.saveBadgeIcon(sb.mark, 26)}${esc(sb.label)}${sbNote}

` : ''; const acts = [ mainButton(a, 'g-main'), // Set Up Again beside Play, marked New while its project has options not answered yet. @@ -1503,6 +1507,7 @@ ${a.parent ? `

${a.menuPick ? `${esc(t('Pick the game in its menu when it starts.'))}` : ''}

` : ''} ${a.game && !a.parent ? `

${DISC_S.replace(/14/g, '24')}${htmlIn(t('Based on {game}'), { game: `${esc(a.game)}` })}${needsSetup(a) && !setupDone(id) ? `${svg('wrench', 20)}${esc(t('Setup Required'))}` : S.easy.has(id) ? `${esc(t('Easy Setup'))}` : ''}

` : ''} ${play?.last_played ? `

${esc(tf('{time} played · last played {when}', { time: playedFor(play), when: ago(play.last_played) }))}

` : ''} + ${sbLine}
${acts}
${stNote} ${tagsOf(a).length ? `
${tagsOf(a).map((tg) => ``).join('')}
` : ''} @@ -1733,7 +1738,7 @@ TV.sheet = { items, prev: (focused() || {}).dataset?.key }; const el = document.createElement('div'); el.className = 'tv-sheet' + (cls ? ' ' + cls : ''); - el.innerHTML = `
${head || `

${esc(title)}

`}${items.map((x, i) => `${x.gap ? '
' : ''}`).join('')}
`; + el.innerHTML = `
${head || `

${esc(title)}

`}${items.map((x, i) => `${x.gap ? '
' : ''}`).join('')}
`; stage().append(el); focus($('[data-sheet="0"]', el), true); sfx('open');