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
64 changes: 63 additions & 1 deletion src-tauri/src/cloud.rs
Original file line number Diff line number Diff line change
Expand Up @@ -575,12 +575,21 @@ fn own_saves(st: &App, id: &str) -> Option<crate::GamePick> {
/// Where this game's saves are, best first.
pub fn spots_of(st: &App, id: &str, g: &Installed) -> Vec<Spot> {
if let Some(p) = own_saves(st, id) {
// Only the game's own: the recomp's other places are the other games'.
// Only the game's own: the recomp's other places are the other games'. Its override too:
// that's the recomp's, and one folder can't stand in for every game's.
let mut g = g.clone();
g.save_place = Default::default();
g.more_save_places.clear();
return named_spots(p.game.saves, vec![], &g);
}
let named = named_of(st, id, g);
// Asked only with an override set: most games have none, and it takes the library's lock.
let Some(over) = g.save_override.as_deref() else { return named };
saves::with_override(named, Some(over), crate::player_sets_up(st, id))
}

/// Where its developer, the catalog or the player's own picks say it saves, without the override.
fn named_of(st: &App, id: &str, g: &Installed) -> Vec<Spot> {
let cat = crate::cached_catalog(st);
let entry = catalog::app(&cat, id).cloned().unwrap_or(Value::Null);
let profile_saves = crate::profile::find(&g.path, &g.repo, &entry).map(|p| p.saves).unwrap_or_default();
Expand Down Expand Up @@ -1459,6 +1468,7 @@ pub async fn saves_info(app: AppHandle, id: String) -> Res<Value> {
SpotInfo { exists: shown.exists(), path: p.to_string_lossy().to_string(), template: s.template, from: s.from }
})
.collect();
let swap = override_info(&st, &id, &g);
let local = saves::list(&st.dir, &id, &g);
let state = saves::state(&st.dir, &id);
let mut cloud = Value::Null;
Expand Down Expand Up @@ -1491,9 +1501,24 @@ pub async fn saves_info(app: AppHandle, id: String) -> Res<Value> {
// Seconds until a copy that didn't get through is tried again, and whether the account's
// cloud saves are full (no uploads until there's room).
"retryIn": state.pending.as_deref().and_then(|p| copy_wait_left(&id, p)), "full": full_now(),
"override": swap,
}))
}

/// Whether the Saves tab offers Change on the folder its developer or RecompLauncher named, and
/// that folder (still shown while the player's own is used). Null when it doesn't.
fn override_info(st: &App, id: &str, g: &Installed) -> Value {
if own_saves(st, id).is_some() {
return Value::Null;
}
let named = named_of(st, id, g);
if !saves::can_override(&named, crate::player_sets_up(st, id)) {
return Value::Null;
}
let path = saves::resolve_for(&named[0].template, g);
json!({ "on": g.save_override.is_some(), "by": named[0].from, "path": path.to_string_lossy() })
}

/// Where players see whether the site is having trouble on our side.
const STATUS_PAGE: &str = "https://recomplauncher.com/status";

Expand Down Expand Up @@ -1865,6 +1890,43 @@ pub fn saves_set_place(st: State<'_, App>, id: String, path: Option<String>) ->
Ok(g)
}

/// The player's folder in place of the one its developer or RecompLauncher named (a
/// recomplauncher.json that still names an old folder), or None to use the named one again. Only
/// for a game set up without Easy Setup, whose saves are in one named folder (saves::can_override).
#[tauri::command(async)]
pub fn saves_set_override(st: State<'_, App>, id: String, path: Option<String>) -> Res<Installed> {
let g = game(&st, &id)?;
let path = path.filter(|p| !p.trim().is_empty());
let template = match path {
Some(p) => Some(override_template(&st, &id, &g, &PathBuf::from(p))?),
None => None,
};
let mut l = st.lib.lock().unwrap();
let g = l.installed.get_mut(&id).ok_or_else(|| Error::Msg("It isn't installed.".into()))?;
g.save_override = template;
let g = g.clone();
let _ = l.save(&st.dir);
Ok(g)
}

/// `dir` as the game's override, or why it can't be (saves::override_refused).
fn override_template(st: &App, id: &str, g: &Installed, dir: &Path) -> Res<String> {
let named = named_of(st, id, g);
if own_saves(st, id).is_some() || !saves::can_override(&named, crate::player_sets_up(st, id)) {
return Err(Error::Msg(OVERRIDE_NOT_HERE.into()));
}
if !dir.is_dir() {
return Err(Error::Msg("That folder couldn't be found.".into()));
}
if let Some(why) = saves::override_refused(dir, &g.path, dirs::home_dir().as_deref()) {
return Err(Error::Msg(why.into()));
}
Ok(saves::templatize_for(dir, g))
}

/// A fixed text, so the window can translate it.
pub(crate) const OVERRIDE_NOT_HERE: &str = "Its save folder can only be changed when Easy Setup is skipped for it.";

/// One more folder where the game saves (a launcher with several games in it, each saving in its
/// own folder): the ones it has now stay, and backups and cloud saves cover all of them.
#[tauri::command(async)]
Expand Down
5 changes: 3 additions & 2 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -905,6 +905,7 @@ async fn do_install(app: &AppHandle, st: &App, id: &str, dir: Option<PathBuf>, t
look_amount: prev.as_ref().map(|p| p.look_amount).unwrap_or(50),
cloud: prev.as_ref().and_then(|p| p.cloud),
save_place: prev.as_ref().and_then(|p| p.save_place.clone()),
save_override: prev.as_ref().and_then(|p| p.save_override.clone()),
more_save_places: prev.as_ref().map(|p| p.more_save_places.clone()).unwrap_or_default(),
cover_file: prev.as_ref().and_then(|p| p.cover_file.clone()),
hero_file: prev.as_ref().and_then(|p| p.hero_file.clone()),
Expand Down Expand Up @@ -4851,7 +4852,7 @@ fn fresh_install_skips(ui: &mut Value, id: &str) -> bool {

/// The player sets this game up their own way (Skip Easy Setup): its own mode once installed, or
/// its tick or the Settings switch before. A game of several in one recomp follows its recomp.
fn player_sets_up(st: &App, id: &str) -> bool {
pub(crate) fn player_sets_up(st: &App, id: &str) -> bool {
let rid = setup_record_id(st, id);
let l = st.lib.lock().unwrap();
match l.installed.get(&rid) {
Expand Down Expand Up @@ -10629,7 +10630,7 @@ pub fn run() {
convert_copy,
convert_cancel, looks_info, set_look, look_picture, ui_data,
reset_settings, tray::tray_words, tray::quit_launcher, ach::ach_access, ach::ach_status, ach::ach_apply, ach::ach_profile, ach::ach_games, ach::ach_board, ach::ach_game_web, ach::ach_report, ach::ach_tracker_get, ach::ach_game, ach::ach_set_disc, ach::ach_set_folder, ach::ach_sound, ach::ach_log, ach::ach_peek, ach::ach_rule, ach::ach_reset, ach::ach_test_toast, ach::ach_toast_take, ach::ach_toast_done, cloud::account_start, cloud::account_poll, cloud::account_cancel, cloud::account_state, cloud::account_signout,
cloud::saves_check, cloud::saves_pick, cloud::saves_play_without_cloud, cloud::saves_cloud, cloud::saves_cloud_follow_all, download_history, report_counts, play_reports, want_count, cloud::saves_info, cloud::saves_status, cloud::saves_peek, cloud::saves_upload_now, cloud::cloud_retry, cloud::saves_overview, cloud::saves_backup, cloud::saves_restore, cloud::saves_cloud_delete, cloud::saves_share, cloud::saves_set_place, cloud::saves_add_place, cloud::saves_remove_place, cloud::saves_open, saves_set_root, saves_open_root, missing_files, missing_made, dll_check, dll_aside, gpu_choice, prefer_fast_gpu, copy_check, wine_tools, deck_scores, latest_counts, team_notes, trending, ig_info, ig_view, usage::pc_specs, usage::recomp_request,
cloud::saves_check, cloud::saves_pick, cloud::saves_play_without_cloud, cloud::saves_cloud, cloud::saves_cloud_follow_all, download_history, report_counts, play_reports, want_count, cloud::saves_info, cloud::saves_status, cloud::saves_peek, cloud::saves_upload_now, cloud::cloud_retry, cloud::saves_overview, cloud::saves_backup, cloud::saves_restore, cloud::saves_cloud_delete, cloud::saves_share, cloud::saves_set_place, cloud::saves_set_override, cloud::saves_add_place, cloud::saves_remove_place, cloud::saves_open, saves_set_root, saves_open_root, missing_files, missing_made, dll_check, dll_aside, gpu_choice, prefer_fast_gpu, copy_check, wine_tools, deck_scores, latest_counts, team_notes, trending, ig_info, ig_view, usage::pc_specs, usage::recomp_request,
adopt::adopt_scan, adopt::migrate_scan, adopt::migrate_pick, adopt::adopt_pick, adopt::adopt_add, adopt::adopt_check, adopt::set_project, usage::usage_hello, usage::usage_event, usage::data_ids, usage::reset_ids, ping::usage_open, ping::usage_mode, usage::run_report, cloud::inbox, cloud::inbox_done, cloud::betas, cloud::beta_join, cloud::beta_leave, launcher_notes, scan_info, devtools::dev_add, devtools::add_any, devtools::dev_check, devtools::dev_starter, fs_places, fs_list, fs_extract, gb_mods, gb_mod, gb_install
])
.build(tauri::generate_context!())
Expand Down
8 changes: 7 additions & 1 deletion src-tauri/src/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,9 +190,15 @@ pub struct Installed {
/// what they picked for every game (see `cloud_on`).
#[serde(default)]
pub cloud: Option<bool>,
/// Where the player says the game saves (Saves, Change): ahead of everything else.
/// Where the player says the game saves (Saves, Change). Only used while neither its developer
/// nor the catalog names a folder (saves::spots): a pick made before one was named is stale.
#[serde(default)]
pub save_place: Option<String>,
/// The player's folder in place of the one its developer or the catalog names (Saves, Change
/// on that folder), for a game they set up themselves. Its own field, not `save_place`: old
/// stale picks there must not come back. Ignored while Easy Setup is on (saves::with_override).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub save_override: Option<String>,
/// More folders the player added (a launcher with several games, each saving in its own).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub more_save_places: Vec<String>,
Expand Down
174 changes: 170 additions & 4 deletions src-tauri/src/saves.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,26 @@ pub fn spots(dev: &[String], catalog: &[String], g: &Installed) -> Vec<Spot> {
mine.into_iter().map(|template| Spot { template, from: "player" }).collect()
}

/// The player may put their own folder in place of the one the developer or RecompLauncher named
/// (a recomplauncher.json that names an old folder) only for a game they set up themselves: Easy
/// Setup is hands-off. Only over one named folder: restore matches a copy's folders by position,
/// so one folder standing in for several would put files in the wrong place.
pub fn can_override(named: &[Spot], sets_up: bool) -> bool {
let [one] = named else { return false };
sets_up && matches!(one.from, "developer" | "catalog")
}

/// The game's save places with the player's override (`over`) in place of the named folder, when
/// `can_override` allows it. A "player" place: it's the player's folder, and restore and sharing
/// treat it as one.
pub fn with_override(named: Vec<Spot>, over: Option<&str>, sets_up: bool) -> Vec<Spot> {
let Some(over) = over.map(str::trim).filter(|t| !t.is_empty()) else { return named };
if !can_override(&named, sets_up) {
return named;
}
vec![Spot { template: over.to_string(), from: "player" }]
}

/// The player's save folders with `dir` added to `now` (the ones it has): refused when it's one of
/// them already, or inside one or around one (its files would be in two places).
pub fn add_place(now: &[String], dir: &Path, g: &Installed) -> Result<Vec<String>, String> {
Expand Down Expand Up @@ -187,14 +207,25 @@ const BIN_SAVE_MAX: u64 = 16 * 1024 * 1024;
/// A folder with programs in it (a runtime a game downloads on its first start, like Java or
/// Python, or its own tools): never a save place, even when the game writes small files there.
pub fn holds_programs(dir: &Path) -> bool {
programs_in(dir).unwrap_or(false)
}

/// Whether `dir` has programs in it, or None when it holds too much to look through (a home
/// folder, a drive). holds_programs takes that as no; a folder the player picks doesn't.
fn programs_in(dir: &Path) -> Option<bool> {
programs_within(dir, 4000)
}

/// programs_in, looking at no more than `most` entries.
fn programs_within(dir: &Path, most: usize) -> Option<bool> {
const PROGRAMS: [&str; 7] = [".exe", ".dll", ".so", ".dylib", ".jar", ".jmod", ".pyd"];
let mut stack = vec![(dir.to_path_buf(), 0usize)];
let mut seen = 0usize;
while let Some((d, depth)) = stack.pop() {
for e in fs::read_dir(&d).into_iter().flatten().flatten() {
seen += 1;
if seen > 4000 {
return false;
if seen > most {
return None;
}
let Ok(t) = e.file_type() else { continue };
let n = e.file_name().to_string_lossy().to_lowercase();
Expand All @@ -203,13 +234,39 @@ pub fn holds_programs(dir: &Path) -> bool {
stack.push((e.path(), depth + 1));
}
} else if PROGRAMS.iter().any(|x| n.ends_with(x)) || n.contains(".so.") || crate::proton::elf_arch(&e.path()).is_some() {
return true;
return Some(true);
}
}
}
false
Some(false)
}

/// Why a folder the player picks can't stand in for the named save folder, or None when it can.
/// Backups, cloud uploads and restore's clearing would take everything in it for saves, so not
/// the game's folder or one around it, a home folder, a drive, one with programs, or one too big
/// to look through.
pub fn override_refused(dir: &Path, game: &Path, home: Option<&Path>) -> Option<&'static str> {
let dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
let game = game.canonicalize().unwrap_or_else(|_| game.to_path_buf());
// A home folder or a drive holds the game's folder too: said as too big, which it is.
let is_home = home.and_then(|h| h.canonicalize().ok()).is_some_and(|h| h == dir);
if is_home || dir.parent().is_none() {
return Some(OVERRIDE_TOO_BIG);
}
if game.starts_with(&dir) {
return Some(OVERRIDE_GAME_FOLDER);
}
match programs_in(&dir) {
Some(false) => None,
Some(true) => Some(OVERRIDE_GAME_FOLDER),
None => Some(OVERRIDE_TOO_BIG),
}
}

/// Fixed texts, so the window can translate them.
pub(crate) const OVERRIDE_GAME_FOLDER: &str = "That's the game's own folder, or it holds programs. Pick the folder its saves are in.";
pub(crate) const OVERRIDE_TOO_BIG: &str = "That folder holds far too much to be a save folder, like your home folder or a whole drive. Pick the folder its saves are in.";

fn is_save_file(name: &str, size: u64) -> bool {
let n = name.to_lowercase();
if n.starts_with(".recomplauncher-input-") { return false; }
Expand Down Expand Up @@ -1589,6 +1646,104 @@ mod tests {
assert_eq!(s.iter().map(|x| (x.template.as_str(), x.from)).collect::<Vec<_>>(), vec![("{install}/mine", "player")]);
}

#[test]
fn the_override_replaces_the_developers_folder_when_the_player_sets_up() {
let g = game(Path::new("/games/test"));
let named = spots(&["{install}/save".into()], &[], &g);
let s = with_override(named, Some("{install}/real"), true);
assert_eq!(s.iter().map(|x| (x.template.as_str(), x.from)).collect::<Vec<_>>(), vec![("{install}/real", "player")]);
}

#[test]
fn the_override_replaces_recomplaunchers_folder_when_the_player_sets_up() {
let g = game(Path::new("/games/test"));
let named = spots(&[], &["{local}/Test/saves".into()], &g);
let s = with_override(named, Some("{install}/real"), true);
assert_eq!(s.iter().map(|x| (x.template.as_str(), x.from)).collect::<Vec<_>>(), vec![("{install}/real", "player")]);
}

#[test]
fn easy_setup_ignores_a_left_over_override() {
let g = game(Path::new("/games/test"));
let named = spots(&["{install}/save".into()], &[], &g);
let s = with_override(named, Some("{install}/real"), false);
assert_eq!(s.iter().map(|x| (x.template.as_str(), x.from)).collect::<Vec<_>>(), vec![("{install}/save", "developer")]);
}

#[test]
fn the_override_is_not_used_over_several_named_folders() {
let g = game(Path::new("/games/test"));
let named = spots(&["{install}/one".into(), "{install}/two".into()], &[], &g);
let s = with_override(named, Some("{install}/real"), true);
assert_eq!(s.len(), 2);
}

#[test]
fn an_override_can_be_a_plain_save_folder() {
let d = tmp("override-plain");
fs::create_dir_all(d.join("game")).unwrap();
fs::create_dir_all(d.join("saves")).unwrap();
fs::write(d.join("saves/slot.sav"), "save").unwrap();
assert_eq!(override_refused(&d.join("saves"), &d.join("game"), None), None);
}

#[test]
fn an_override_is_not_the_games_own_folder() {
let d = tmp("override-game");
assert_eq!(override_refused(&d, &d, None), Some(OVERRIDE_GAME_FOLDER));
}

#[test]
fn an_override_is_not_a_folder_around_the_game() {
let d = tmp("override-around");
fs::create_dir_all(d.join("lib/game")).unwrap();
assert_eq!(override_refused(&d.join("lib"), &d.join("lib/game"), None), Some(OVERRIDE_GAME_FOLDER));
}

#[test]
fn an_override_is_not_the_home_folder() {
let d = tmp("override-home");
fs::create_dir_all(d.join("home")).unwrap();
assert_eq!(override_refused(&d.join("home"), &d.join("game"), Some(&d.join("home"))), Some(OVERRIDE_TOO_BIG));
}

#[test]
fn an_override_is_not_a_whole_drive() {
let root = Path::new(if cfg!(windows) { "C:\\" } else { "/" });
assert_eq!(override_refused(root, Path::new("/nowhere/game"), None), Some(OVERRIDE_TOO_BIG));
}

#[test]
fn a_folder_too_big_to_look_through_is_not_said_to_be_free_of_programs() {
// A small limit, not 4000 files: writing that many slows the tests that time a restart.
let d = tmp("override-big");
for i in 0..4 {
fs::write(d.join(format!("{i}.txt")), "").unwrap();
}
assert_eq!(programs_within(&d, 3), None);
}

#[test]
fn an_override_is_not_a_folder_with_programs() {
let d = tmp("override-programs");
fs::write(d.join("tool.dll"), "").unwrap();
assert_eq!(override_refused(&d, Path::new("/nowhere/game"), None), Some(OVERRIDE_GAME_FOLDER));
}

#[test]
fn the_override_is_not_used_when_nobody_named_a_folder() {
assert!(!can_override(&[Spot { template: "{install}/mine".into(), from: "player" }], true));
}

#[test]
fn an_old_pick_does_not_come_back_without_an_override() {
let mut g = game(Path::new("/games/test"));
g.save_place = Some("{install}/mine".into());
let named = spots(&["{install}/save".into()], &[], &g);
let s = with_override(named, None, true);
assert_eq!(s.iter().map(|x| (x.template.as_str(), x.from)).collect::<Vec<_>>(), vec![("{install}/save", "developer")]);
}

#[test]
fn sharing_keeps_the_previous_save_and_the_source() {
let d = tmp("sharing-copy");
Expand Down Expand Up @@ -2201,6 +2356,17 @@ mod tests {
assert!(second.contains("saves"), "{why}");
}

#[test]
fn restore_puts_a_copy_of_the_developers_folder_into_the_override() {
let d = tmp("restore-override");
let (g, archive) = copy_from_old_folder(&d);
let named = spots(&["{install}/old".into()], &[], &g);
let now = with_override(named, Some("{install}/real"), true);

assert_eq!(restore(&d.join("app"), "g", &archive, &now, &g).unwrap(), 1);
assert_eq!(fs::read_to_string(g.path.join("real/progress.sav")).unwrap(), "progress");
}

#[test]
fn restore_keeps_the_copys_folder_when_the_folder_count_changed() {
let d = tmp("restore-moved-count");
Expand Down
Loading
Loading