Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 97 additions & 2 deletions src-tauri/src/cloud.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down Expand Up @@ -847,6 +847,7 @@ pub async fn after_session(app: &AppHandle, id: &str) -> Res<Option<saves::Copy>
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);
Expand Down Expand Up @@ -883,6 +884,62 @@ pub async fn after_session(app: &AppHandle, id: &str) -> Res<Option<saves::Copy>
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::<App>();
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<String> {
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<usize> {
let st = app.state::<App>();
Expand Down Expand Up @@ -1067,7 +1124,8 @@ async fn check_saves(app: AppHandle, id: String, manual: bool) -> Res<Value> {
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}))
}

Expand Down Expand Up @@ -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");
Expand Down
19 changes: 17 additions & 2 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -3333,6 +3336,9 @@ fn start_game_with_monitor_context(
}
let secs = start.elapsed().as_secs();
let st = app2.state::<App>();
// 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 });
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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.
Expand Down
74 changes: 73 additions & 1 deletion src-tauri/src/saves.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Problem>,
/// 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,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -814,6 +821,19 @@ pub fn list(app_dir: &Path, id: &str, g: &Installed) -> Vec<Copy> {
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<Option<Copy>, Error> {
Expand All @@ -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);
Expand Down Expand Up @@ -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 }))
Expand Down Expand Up @@ -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<Spot>, 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"));
Expand Down Expand Up @@ -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() };
Expand Down
Loading
Loading