diff --git a/CHANGELOG.md b/CHANGELOG.md index c8165be5..c2e4e8c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +### Added +- Co-op profiles in the launcher: each co-op group has its own save folder, private relay room code, recorded members and world version, with copy between singleplayer and co-op modes (#701) + - Before: co-op sessions shared ordinary singleplayer profiles, wrote Link Play choices to `pkp.ini`, and could open a co-op save in a normal launch + - Now: co-op profiles keep their own save folder, apply co-op settings in the launch environment only without touching `pkp.ini`, refuse normal launches of co-op saves and co-op launches of singleplayer saves, and copy between modes in Settings > Saves and on Link Play + - Still not: the game runtime does not yet read the private room code under `protocol = native` or the automatic session, host story ownership and post-session save sync rules (steps 2 to 4 of #701) + ### Changed - An update that stops now writes its error to setup.log, with the step it reached - A crash report now lists the render targets the game was drawing to when it crashed (#720) diff --git a/launcher/scripts/test-coop-model.mjs b/launcher/scripts/test-coop-model.mjs new file mode 100644 index 00000000..cdba00a8 --- /dev/null +++ b/launcher/scripts/test-coop-model.mjs @@ -0,0 +1,31 @@ +// Tests for the pure co-op profile helpers (src/coop-model.js). Run: node launcher/scripts/test-coop-model.mjs +import { activeProfileOf, coopProfiles, isCoopProfile, normalizeRoomCode, relayProblem, roomCodeProblem, singleplayerProfiles } from '../src/coop-model.js'; + +let bad = 0; +const check = (ok, what) => { if (!ok) { console.log(`FAIL ${what}`); bad++; } }; + +check(normalizeRoomCode('abcd ol12 efgh 3456') === 'ABCD-0112-EFGH-3456', 'normalizes Crockford look-alikes and spaces'); +check(normalizeRoomCode('ABCD-EFGH-JKMN-PQRS') === 'ABCD-EFGH-JKMN-PQRS', 'keeps normalized code'); +check(normalizeRoomCode('short') === '', 'rejects short room code'); +check(normalizeRoomCode('ABCD-EFGH-JKLM-NPQU') === '', 'rejects U'); + +check(roomCodeProblem('', { optional: true }) === '', 'optional empty room code allowed'); +check(roomCodeProblem('') !== '', 'required empty room code rejected'); +check(roomCodeProblem('abcd-efgh-jkmn-pqrs') === '', 'valid room code accepted'); + +check(relayProblem('') === '', 'empty relay means public relay'); +check(relayProblem('203.0.113.5:47610') === '', 'valid IPv4:port relay accepted'); +check(relayProblem('0.0.0.0:47610') !== '', '0.0.0.0 rejected'); +check(relayProblem('example.com:47610') !== '', 'hostname rejected'); + +const sp = { id: 'default', name: 'Player' }; +const cp = { id: 'p1', name: 'Island', coop: { room_code: 'ABCD-EFGH-JKMN-PQRS', world_version: 2, members: [] } }; +const store = { active: 'p1', profiles: [sp, cp] }; + +check(!isCoopProfile(sp) && isCoopProfile(cp), 'identifies co-op vs singleplayer profiles'); +check(activeProfileOf(store)?.id === 'p1', 'active profile lookup'); +check(coopProfiles(store).length === 1 && coopProfiles(store)[0].id === 'p1', 'filters co-op profiles'); +check(singleplayerProfiles(store).length === 1 && singleplayerProfiles(store)[0].id === 'default', 'filters singleplayer profiles'); + +console.log(bad ? `TEST FAILED (${bad})` : 'coop model tests passed'); +process.exit(bad ? 1 : 0); diff --git a/launcher/src-tauri/src/coop.rs b/launcher/src-tauri/src/coop.rs new file mode 100644 index 00000000..3d752050 --- /dev/null +++ b/launcher/src-tauri/src/coop.rs @@ -0,0 +1,248 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +//! Seamless co-op group rules, private room codes and per-launch environment (#701, step 1). +//! +//! A co-op profile keeps its save in its own account folder (profiles.rs) and never writes co-op settings or its account uid into +//! pkp.ini: each co-op launch receives its identity, relay, private room code and co-op flags through the process environment for that +//! launch only. On the relay, the group's room uses a room code (`XXXX-XXXX-XXXX-XXXX`, Crockford base32 matching pokopia-coop's +//! coop_auth.c), so it never enters the public room list. + +use std::process::Command; + +use crate::profiles::{clean_name, Member, Profile}; +use crate::saveimport; + +/// The project's public relay (same address as src/linkplay-model.js PUBLIC_RELAY). +pub const PUBLIC_RELAY: &str = "204.216.111.91:47610"; +const B32: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ"; +const ROOM_LEN: usize = 16; + +/// Generates a fresh 80-bit private room code formatted as `XXXX-XXXX-XXXX-XXXX`. +pub fn new_room_code() -> Result { + let mut bytes = [0u8; ROOM_LEN]; + pokopia_relay::random::os_random(&mut bytes).map_err(|e| format!("Cannot make a room code: {}", e))?; + let chars: Vec = bytes.iter().map(|b| B32[(b & 31) as usize] as char).collect(); + Ok(format_room(&chars)) +} + +fn format_room(chars: &[char]) -> String { + chars.chunks(4).map(|c| c.iter().collect::()).collect::>().join("-") +} + +/// Normalizes a Crockford base32 room code (case-insensitive, `-` and spaces ignored, O->0, I/L->1) into `XXXX-XXXX-XXXX-XXXX`. +pub fn normalize_room_code(raw: &str) -> Result { + let mut out = Vec::with_capacity(ROOM_LEN); + for ch in raw.chars() { + if ch == '-' || ch == ' ' { + continue; + } + let mut up = ch.to_ascii_uppercase(); + if up == 'O' { + up = '0'; + } else if up == 'I' || up == 'L' { + up = '1'; + } + if !up.is_ascii() || !B32.contains(&(up as u8)) || out.len() == ROOM_LEN { + return Err("Type a 16-character room code (XXXX-XXXX-XXXX-XXXX).".into()); + } + out.push(up); + } + if out.len() != ROOM_LEN { + return Err("Type a 16-character room code (XXXX-XXXX-XXXX-XXXX).".into()); + } + Ok(format_room(&out)) +} + +/// Validates an optional relay address (`[:]`); empty means the public relay. +/// Refuses 0.x, multicast and up, and port 0 (matching coop_cfg_parse_ex / linkplay-model.js parseAddr). +pub fn validate_relay(raw: &str) -> Result { + let s = raw.trim(); + if s.is_empty() { + return Ok(String::new()); + } + let (host, port) = match s.split_once(':') { + Some((h, p)) => (h, Some(p)), + None => (s, None), + }; + let octets: Vec<&str> = host.split('.').collect(); + if octets.len() != 4 { + return Err("Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.".into()); + } + let nums: Option> = octets.iter().map(|o| o.parse::().ok()).collect(); + let Some(nums) = nums else { + return Err("Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.".into()); + }; + if nums[0] == 0 || nums[0] >= 224 { + return Err("Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.".into()); + } + if let Some(p) = port { + let Ok(n) = p.parse::() else { + return Err("Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.".into()); + }; + if n == 0 { + return Err("Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.".into()); + } + } + Ok(s.to_string()) +} + +pub fn effective_relay(relay: &str) -> &str { + let r = relay.trim(); + if r.is_empty() { PUBLIC_RELAY } else { r } +} + +pub fn is_loopback_relay(relay: &str) -> bool { + relay.trim().starts_with("127.") +} + +fn is_hex32(s: &str) -> bool { + s.len() == 32 && s.chars().all(|c| c.is_ascii_hexdigit()) +} + +/// Validates and normalizes recorded group members. +pub fn validate_members(members: Vec) -> Result, String> { + let mut out: Vec = Vec::with_capacity(members.len()); + for m in members { + let name = clean_name(&m.name)?; + let net_uid = m.net_uid.trim().to_ascii_lowercase(); + if !net_uid.is_empty() && !is_hex32(&net_uid) { + return Err("A member's network ID must be 32 hex digits.".into()); + } + let role = match m.role.trim().to_ascii_lowercase().as_str() { + "" => String::new(), + "host" => "host".into(), + "visitor" => "visitor".into(), + _ => return Err("A member's role must be host or visitor.".into()), + }; + if out.iter().any(|x| x.name.eq_ignore_ascii_case(&name) && (!net_uid.is_empty() && x.net_uid == net_uid || net_uid.is_empty() && x.net_uid.is_empty())) { + return Err(format!("{} is already in the group.", name)); + } + out.push(Member { name, net_uid, role }); + } + Ok(out) +} + +fn env_nickname(p: &Profile) -> String { + if p.nickname.is_empty() || (cfg!(windows) && !p.nickname.is_ascii()) { + "Player".into() + } else { + p.nickname.clone() + } +} + +/// Everything a co-op launch hands to the game process and watchers without touching pkp.ini. +#[derive(Clone, Debug)] +pub struct Launch { + pub profile_id: String, + pub profile_name: String, + pub account_uid: String, + pub save_key: String, + pub relay: String, + env: Vec<(&'static str, String)>, +} + +impl Launch { + pub fn prepare(profile: &Profile) -> Result { + let coop = profile + .coop + .as_ref() + .ok_or_else(|| "This profile is a singleplayer save. Pick a co-op profile, or start co-op from a copy of it.".to_string())?; + let save_key = saveimport::uid_key(&profile.uid).ok_or_else(|| "This co-op profile has no valid account ID.".to_string())?; + let room_code = normalize_room_code(&coop.room_code)?; + let relay = effective_relay(&validate_relay(&coop.relay)?).to_string(); + let env = vec![ + ("NXRT_ACCOUNT_UID", profile.uid.clone()), + ("NXRT_ACCOUNT_NICKNAME", env_nickname(profile)), + ("NXRT_NET_UID", profile.net_uid.clone()), + ("NXRT_NET_PROTOCOL", "native".into()), + ("NXRT_NET_MODE", "auto".into()), + ("NXRT_NET_INTERNET", "true".into()), + ("NXRT_NET_RELAY", relay.clone()), + // Private room on the relay (never listed on the public room list once runtime reads room_code under protocol=native) + ("NXRT_NET_ROOM_CODE", room_code), + // Co-op mode overrides in the environment only (pkp.ini is left untouched) + ("NXRT_PKP_COOP", "1".into()), + ("NXRT_PKP_COOP_WORLD_VERSION", coop.world_version.to_string()), + ("NXRT_PKP_LINK_INTERACT_EVERYWHERE", "1".into()), + ("NXRT_PKP_LINK_STORY_COOP", "0".into()), + ]; + Ok(Self { + profile_id: profile.id.clone(), + profile_name: profile.name.clone(), + account_uid: profile.uid.clone(), + save_key, + relay, + env, + }) + } + + pub fn apply(&self, cmd: &mut Command) { + for (k, v) in &self.env { + cmd.env(k, v); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::profiles::Coop; + + fn env_of<'a>(l: &'a Launch, key: &str) -> Option<&'a str> { + l.env.iter().find(|(k, _)| *k == key).map(|(_, v)| v.as_str()) + } + + #[test] + fn room_codes_generate_and_normalize_crockford() { + let code = new_room_code().unwrap(); + assert_eq!(code.len(), 19); + assert_eq!(normalize_room_code(&code).unwrap(), code); + assert_eq!(normalize_room_code("abcd ol12 efgh 3456").unwrap(), "ABCD-0112-EFGH-3456"); + assert!(normalize_room_code("short").is_err()); + assert!(normalize_room_code("ABCD-EFGH-JKLM-NPQU").is_err(), "U is not in Crockford base32"); + } + + #[test] + fn relay_validation_accepts_empty_or_valid_ipv4() { + assert_eq!(validate_relay(" ").unwrap(), ""); + assert_eq!(validate_relay("127.0.0.1:47610").unwrap(), "127.0.0.1:47610"); + assert_eq!(validate_relay("203.0.113.5").unwrap(), "203.0.113.5"); + assert!(validate_relay("0.0.0.0:47610").is_err()); + assert!(validate_relay("224.0.0.1:47610").is_err()); + assert!(validate_relay("127.0.0.1:0").is_err()); + assert!(validate_relay("example.com:47610").is_err()); + } + + #[test] + fn prepare_refuses_singleplayer_profile_and_builds_env_for_coop() { + let sp = Profile { + id: "p1".into(), + name: "Ash".into(), + uid: "0123456789abcdef0123456789abcdef".into(), + nickname: "Ash".into(), + net_uid: "fedcba9876543210fedcba9876543210".into(), + coop: None, + }; + assert!(Launch::prepare(&sp).unwrap_err().contains("singleplayer")); + + let cp = Profile { + coop: Some(Coop { + room_code: "abcd-efgh-jkmn-pqrs".into(), + relay: String::new(), + members: vec![Member { name: "Ash".into(), net_uid: sp.net_uid.clone(), role: "host".into() }], + world_version: 3, + }), + ..sp + }; + let launch = Launch::prepare(&cp).unwrap(); + assert_eq!(env_of(&launch, "NXRT_ACCOUNT_UID"), Some("0123456789abcdef0123456789abcdef")); + assert_eq!(env_of(&launch, "NXRT_NET_PROTOCOL"), Some("native")); + assert_eq!(env_of(&launch, "NXRT_NET_MODE"), Some("auto")); + assert_eq!(env_of(&launch, "NXRT_NET_INTERNET"), Some("true")); + assert_eq!(env_of(&launch, "NXRT_NET_RELAY"), Some(PUBLIC_RELAY)); + assert_eq!(env_of(&launch, "NXRT_NET_ROOM_CODE"), Some("ABCD-EFGH-JKMN-PQRS")); + assert_eq!(env_of(&launch, "NXRT_PKP_COOP"), Some("1")); + assert_eq!(env_of(&launch, "NXRT_PKP_COOP_WORLD_VERSION"), Some("3")); + assert_eq!(env_of(&launch, "NXRT_PKP_LINK_INTERACT_EVERYWHERE"), Some("1")); + assert_eq!(env_of(&launch, "NXRT_PKP_LINK_STORY_COOP"), Some("0")); + } +} diff --git a/launcher/src-tauri/src/home_count.rs b/launcher/src-tauri/src/home_count.rs index 8a038b30..674a4252 100644 --- a/launcher/src-tauri/src/home_count.rs +++ b/launcher/src-tauri/src/home_count.rs @@ -47,10 +47,17 @@ pub fn count(file: &[u8]) -> Option { Some(at_home as u32) } +/// The count of `key`'s committed save in this game folder; None when there is no save, it is being written, or it is not +/// a layout this knows. +pub fn of_key(game_dir: &Path, key: &str) -> Option { + count(&crate::savebackup::read_committed_key(game_dir, key, FILE, Duration::from_secs(1))?) +} + /// The count of the active profile's committed save in this game folder; None when there is no save, it is being written, or it is not /// a layout this knows. pub fn home_count(game_dir: &Path) -> Option { - count(&crate::savebackup::read_committed(game_dir, FILE, Duration::from_secs(1))?) + let (_, key) = crate::saveimport::locate(game_dir); + of_key(game_dir, &key) } #[cfg(test)] diff --git a/launcher/src-tauri/src/launch.rs b/launcher/src-tauri/src/launch.rs index 22282c0a..32d3b073 100644 --- a/launcher/src-tauri/src/launch.rs +++ b/launcher/src-tauri/src/launch.rs @@ -1,23 +1,19 @@ // SPDX-License-Identifier: GPL-3.0-or-later //! Play and the game's state. +use std::path::PathBuf; use tauri::AppHandle; -use crate::states::{PlayArg, States}; -use crate::config::load_config; +use crate::config::{load_config, Config}; use crate::guard::{ensure_idle, Need}; use crate::paths::game_dir_of; use crate::readiness::readiness; -use crate::{play, profiles, settings}; +use crate::states::{PlayArg, States}; +use crate::{coop, play, profiles, relay_cmds, settings}; -/// `without_mods`: this one start runs without mods (the runtime's [mods] off, passed in the game's environment only). -#[tauri::command] -pub fn play(app: AppHandle, without_mods: Option) -> Result<(), String> { - // an update may be preparing: Play waits only for its swap, and holds it off until this game has started (play::start) - let updates = app.updates(); - let _swap = updates.hold_swap(); - ensure_idle(&app, &[Need::Swap, Need::Storage])?; - let cfg = load_config(&app); +fn ready_to_play(app: &AppHandle) -> Result<(PathBuf, Config), String> { + ensure_idle(app, &[Need::Swap, Need::Storage])?; + let cfg = load_config(app); let probe = readiness(&cfg); if probe.readiness.kind != "ready" { return Err(probe.readiness.detail); @@ -28,11 +24,89 @@ pub fn play(app: AppHandle, without_mods: Option) -> Result<(), String> { if let Some(paths) = probe.paths { settings::ensure_play_paths(&dir, &paths.exefs, &paths.romfs, &paths.romfs_base, &paths.aoc_dir)?; } + Ok((dir, cfg)) +} + +fn ensure_normal_profile(profile: &profiles::Profile) -> Result<(), String> { + if profile.coop.is_some() { + return Err("This profile is a co-op save. Start it from Co-op instead, or switch to a singleplayer profile.".into()); + } + Ok(()) +} + +fn prepare_coop_launch(store: &profiles::Store, id: Option<&str>) -> Result { + let profile = match id { + Some(pid) => store.get(pid).ok_or("That profile does not exist.")?, + None => store.active_profile(), + }; + coop::Launch::prepare(profile) +} + +/// `without_mods`: this one start runs without mods (the runtime's [mods] off, passed in the game's environment only). +#[tauri::command] +pub fn play(app: AppHandle, without_mods: Option) -> Result<(), String> { + // an update may be preparing: Play waits only for its swap, and holds it off until this game has started (play::start) + let updates = app.updates(); + let _swap = updates.hold_swap(); + let (dir, cfg) = ready_to_play(&app)?; + let store = profiles::load(&dir); + ensure_normal_profile(store.active_profile())?; profiles::apply_active(&dir)?; - play::start(&app, &dir, &cfg, without_mods.unwrap_or(false)) + play::start(&app, &dir, &cfg, without_mods.unwrap_or(false), None) +} + +/// Launches a co-op profile with its co-op settings in the process environment only (nothing written to pkp.ini). +#[tauri::command] +pub fn play_coop(app: AppHandle, id: Option, without_mods: Option) -> Result<(), String> { + let updates = app.updates(); + let _swap = updates.hold_swap(); + let (dir, cfg) = ready_to_play(&app)?; + let store = profiles::load(&dir); + let launch = prepare_coop_launch(&store, id.as_deref())?; + if coop::is_loopback_relay(&launch.relay) && !relay_cmds::is_running(&app) { + return Err("The relay on this PC is off. Turn on Run a relay on this PC on the Link Play page, or clear the relay address to use the public relay.".into()); + } + play::start(&app, &dir, &cfg, without_mods.unwrap_or(false), Some(launch)) } #[tauri::command] pub fn game_status(state: PlayArg) -> play::Status { state.0.lock().unwrap().clone() } + +#[cfg(test)] +mod tests { + use super::*; + + fn profile(id: &str, coop: Option) -> profiles::Profile { + profiles::Profile { + id: id.into(), + name: id.into(), + uid: "0123456789abcdef0123456789abcdef".into(), + nickname: id.into(), + net_uid: "fedcba9876543210fedcba9876543210".into(), + coop, + } + } + + #[test] + fn normal_launch_refuses_coop_save_and_coop_launch_refuses_singleplayer_save() { + let sp = profile("sp", None); + let cp = profile( + "cp", + Some(profiles::Coop { + room_code: "ABCD-EFGH-JKMN-PQRS".into(), + relay: String::new(), + members: vec![], + world_version: 1, + }), + ); + let store = profiles::Store { active: "cp".into(), profiles: vec![sp.clone(), cp.clone()] }; + + assert!(ensure_normal_profile(&sp).is_ok()); + assert!(ensure_normal_profile(&cp).unwrap_err().contains("co-op save")); + assert!(prepare_coop_launch(&store, Some("sp")).unwrap_err().contains("singleplayer save")); + assert!(prepare_coop_launch(&store, Some("cp")).is_ok()); + assert!(prepare_coop_launch(&store, None).is_ok()); + } +} diff --git a/launcher/src-tauri/src/main.rs b/launcher/src-tauri/src/main.rs index 7dfe56e5..24ef99c9 100644 --- a/launcher/src-tauri/src/main.rs +++ b/launcher/src-tauri/src/main.rs @@ -7,6 +7,7 @@ mod branding_cmds; mod child_lines; mod cli; mod config; +mod coop; mod dialogs; mod dlss; mod dlss_cmds; @@ -160,6 +161,7 @@ fn main() { settings_cmds::write_settings, settings_cmds::prompt_icon_pack, launch::play, + launch::play_coop, setup_job::setup_status, setup_job::start_setup, setup_job::preflight, @@ -181,6 +183,10 @@ fn main() { profile_cmds::profile_rename, profile_cmds::profile_remove, profile_cmds::profile_select, + profile_cmds::profile_add_coop, + profile_cmds::profile_start_coop_from, + profile_cmds::profile_copy_to_singleplayer, + profile_cmds::profile_coop_update, repair_cmds::repair_plan, repair_cmds::repair_apply, repair_cmds::repair_undo, diff --git a/launcher/src-tauri/src/online.rs b/launcher/src-tauri/src/online.rs index 24427692..4ac07864 100644 --- a/launcher/src-tauri/src/online.rs +++ b/launcher/src-tauri/src/online.rs @@ -79,13 +79,17 @@ impl Player { } } -/// The player for this run: the active profile's uid with the install's salt (made and saved now if there is none), the online name from +/// The player for `uid` with the install's salt (made and saved now if there is none), the online name from /// launcher.json and this launcher's version. None when no salt could be saved. -fn player_of(app: &tauri::AppHandle, game_dir: &Path) -> Option { +fn player_for(app: &tauri::AppHandle, uid: &str) -> Option { let salt = crate::config::online_salt(app)?; let cfg = crate::config::load_config(app); + Some(Player::new(uid, &salt, &cfg.online_name, &app.package_info().version.to_string())) +} + +fn player_of(app: &tauri::AppHandle, game_dir: &Path) -> Option { let uid = crate::profiles::load(game_dir).active_profile().uid.clone(); - Some(Player::new(&uid, &salt, &cfg.online_name, &app.package_info().version.to_string())) + player_for(app, &uid) } enum Failure { @@ -211,6 +215,19 @@ impl Watch { }) } + /// Presence for a specific launched profile (`uid`, `save_key`), used when launching co-op without writing pkp.ini. + pub fn start_for(app: &tauri::AppHandle, game_dir: &Path, uid: String, save_key: String) -> Watch { + let (app, dir) = (app.clone(), game_dir.to_path_buf()); + Watch::spawn(SERVER, move |client, stop| { + let inp = Inputs { + on: &|| switched_on(&dir), + player: &|| player_for(&app, &uid), + count: &|| crate::home_count::of_key(&dir, &save_key), + }; + run(client, &inp, stop, POLL, MIN_INTERVAL); + }) + } + fn spawn(base: &str, body: impl FnOnce(&Client, &Receiver<()>) + Send + 'static) -> Watch { let (stop_tx, stop_rx) = channel(); let (done_tx, done_rx) = channel(); diff --git a/launcher/src-tauri/src/play.rs b/launcher/src-tauri/src/play.rs index 0054ade2..08b22953 100644 --- a/launcher/src-tauri/src/play.rs +++ b/launcher/src-tauri/src/play.rs @@ -63,7 +63,7 @@ fn report_files(dir: &Path, started: SystemTime) -> Vec { .collect() } -pub fn start(app: &AppHandle, game_dir: &Path, cfg: &Config, without_mods: bool) -> Result<(), String> { +pub fn start(app: &AppHandle, game_dir: &Path, cfg: &Config, without_mods: bool, coop: Option) -> Result<(), String> { let (minimize, discord) = (cfg.minimize_on_play, cfg.discord_presence); let gentle = cfg.gentle_build; { @@ -122,6 +122,9 @@ pub fn start(app: &AppHandle, game_dir: &Path, cfg: &Config, without_mods: bool) return; } }; + if let Some(c) = &coop { + c.apply(&mut cmd); + } let started = SystemTime::now(); let mut child = match cmd.spawn() { Ok(c) => c, @@ -137,13 +140,24 @@ pub fn start(app: &AppHandle, game_dir: &Path, cfg: &Config, without_mods: bool) } } // the player's save backups: a timer while the game runs (when switched on), one more copy once it has ended - let backups = crate::savebackup::Watch::start(&dir); + let backups = match &coop { + Some(c) => crate::savebackup::Watch::start_for(&dir, c.save_key.clone(), c.profile_name.clone()), + None => crate::savebackup::Watch::start(&dir), + }; let presence = crate::presence::Watch::start(discord); - let online = crate::online::Watch::start(&app2, &dir); + let online = match &coop { + Some(c) => crate::online::Watch::start_for(&app2, &dir, c.account_uid.clone(), c.save_key.clone()), + None => crate::online::Watch::start(&app2, &dir), + }; let result = wait_with_memory_guard(&mut child); online.finish(); presence.finish(); backups.finish(); + if let Some(c) = &coop { + if let Err(e) = crate::profiles::bump_world_version(&dir, &c.profile_id) { + eprintln!("coop: world version not updated: {e}"); + } + } let (code, wait_err) = match result { Ok(s) => (s.code(), None), Err(e) => (None, Some(e.to_string())), @@ -250,6 +264,9 @@ pub fn run_cli(game_dir: &Path, tools: &Path) -> i32 { _ => {} } } + if crate::profiles::load(game_dir).active_profile().coop.is_some() { + return fail("This profile is a co-op save. Start it from Co-op in the launcher instead, or switch to a singleplayer profile.".into()); + } // the same rule as Play in the window: without the active profile in pkp.ini the game could start on another player's account and save if let Err(e) = crate::profiles::apply_active(game_dir) { return fail(format!("The profile could not be applied, so the game was not started: {}", e)); diff --git a/launcher/src-tauri/src/profile_cmds.rs b/launcher/src-tauri/src/profile_cmds.rs index d1ac9c9d..1625a6fc 100644 --- a/launcher/src-tauri/src/profile_cmds.rs +++ b/launcher/src-tauri/src/profile_cmds.rs @@ -54,3 +54,30 @@ pub fn profile_select(app: AppHandle, id: String) -> Result, relay: Option) -> Result { + profiles::add_coop(&profiles_guard(&app)?, &name, room_code.as_deref(), relay.as_deref()) +} + +#[tauri::command] +pub fn profile_start_coop_from(app: AppHandle, source_id: String, name: String, room_code: Option, relay: Option) -> Result { + profiles::start_coop_from(&profiles_guard(&app)?, &source_id, &name, room_code.as_deref(), relay.as_deref()) +} + +#[tauri::command] +pub fn profile_copy_to_singleplayer(app: AppHandle, source_id: String, name: String) -> Result { + profiles::copy_to_singleplayer(&profiles_guard(&app)?, &source_id, &name) +} + +#[tauri::command] +pub fn profile_coop_update( + app: AppHandle, + id: String, + room_code: Option, + relay: Option, + members: Option>, +) -> Result { + profiles::update_coop(&profiles_guard(&app)?, &id, room_code.as_deref(), relay.as_deref(), members) +} diff --git a/launcher/src-tauri/src/profiles.rs b/launcher/src-tauri/src/profiles.rs index 4ae94377..7ebaf9c9 100644 --- a/launcher/src-tauri/src/profiles.rs +++ b/launcher/src-tauri/src/profiles.rs @@ -24,6 +24,28 @@ const MAX_NICK_BYTES: usize = 32; /// The runtime's built-in user (saveimport.rs DEFAULT_UID): a new profile must never get it. const BUILT_IN_UID: &str = "000000000000000141434e4852656370"; +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +pub struct Member { + pub name: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub net_uid: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub role: String, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] +pub struct Coop { + /// Private room code on the relay (XXXX-XXXX-XXXX-XXXX, Crockford base32), never listed publicly. + pub room_code: String, + /// Optional custom relay address ([:]); empty means the public relay. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub relay: String, + #[serde(default)] + pub members: Vec, + #[serde(default)] + pub world_version: u64, +} + #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub struct Profile { pub id: String, @@ -34,6 +56,9 @@ pub struct Profile { pub nickname: String, /// [net] uid (Link Play identity): 32 hex digits, or empty to keep the one in the save folder pub net_uid: String, + /// Present when this profile is a co-op save (own folder, launched in co-op mode only). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub coop: Option, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] @@ -66,6 +91,7 @@ fn default_profile(ini: &Ini) -> Profile { uid: get("account", "uid"), nickname, net_uid: get("net", "uid"), + coop: None, } } @@ -160,15 +186,135 @@ fn taken(s: &Store, name: &str, except: Option<&str>) -> bool { } pub fn add(dir: &Path, name: &str) -> Result { - let name = clean_name(name)?; let mut s = load(dir); - if taken(&s, &name, None) { + let p = make_profile(&s, name, None)?; + s.profiles.push(p); + save(dir, &s)?; + Ok(s) +} + +fn make_profile(s: &Store, name: &str, coop: Option) -> Result { + let name = clean_name(name)?; + if taken(s, &name, None) { return Err(format!("There is already a profile called {}.", name)); } let uids: Vec<&str> = s.profiles.iter().flat_map(|p| [p.uid.as_str(), p.net_uid.as_str()]).collect(); let (uid, net_uid) = (new_uid(&uids)?, new_uid(&uids)?); let id = format!("p{}", &uid[..8]); - s.profiles.push(Profile { id, name: name.clone(), uid, nickname: nickname_of(&name), net_uid }); + Ok(Profile { id, name: name.clone(), uid, nickname: nickname_of(&name), net_uid, coop }) +} + +fn make_coop(room_code: Option<&str>, relay: Option<&str>, creator_name: &str, net_uid: &str, world_version: u64) -> Result { + let room_code = match room_code.map(str::trim).filter(|c| !c.is_empty()) { + Some(c) => crate::coop::normalize_room_code(c)?, + None => crate::coop::new_room_code()?, + }; + let relay = match relay { + Some(r) => crate::coop::validate_relay(r)?, + None => String::new(), + }; + let members = vec![Member { name: creator_name.to_string(), net_uid: net_uid.to_string(), role: "host".into() }]; + Ok(Coop { room_code, relay, members, world_version }) +} + +/// Creates a new co-op profile with its own save folder, private room code and recorded group metadata. +pub fn add_coop(dir: &Path, name: &str, room_code: Option<&str>, relay: Option<&str>) -> Result { + let mut s = load(dir); + let mut p = make_profile(&s, name, None)?; + p.coop = Some(make_coop(room_code, relay, &p.name, &p.net_uid, 0)?); + s.profiles.push(p); + save(dir, &s)?; + Ok(s) +} + +/// Account save folder key of `p`, falling back to `saveimport::locate` only for the default profile's legacy save folder. +fn account_key_for(save_dir: &Path, found_key: &str, p: &Profile) -> String { + let own = crate::saveimport::account_key_of(&p.uid); + if p.id != DEFAULT_ID || crate::saveimport::is_save_folder(&save_dir.join("account").join(&own)) { + own + } else { + found_key.to_string() + } +} + +fn check_copy_source(save_dir: &Path, key: &str) -> Result<(), String> { + let acc = save_dir.join("account"); + if !crate::saveimport::is_save_folder(&acc.join(key)) { + return Err("That profile has no save to copy yet.".into()); + } + if acc.join(format!("{}.commit", key)).exists() { + return Err("That save has a write the game did not finish. Start the game once on that profile, then try again.".into()); + } + Ok(()) +} + +/// "Start coop from my singleplayer save": creates a co-op profile from a copy of a singleplayer profile's save via saveimport::copy_account. +pub fn start_coop_from(dir: &Path, source_id: &str, name: &str, room_code: Option<&str>, relay: Option<&str>) -> Result { + let mut s = load(dir); + let src = s.get(source_id).ok_or("That profile does not exist.")?.clone(); + if src.coop.is_some() { + return Err("Pick a singleplayer profile to start co-op from.".into()); + } + let (save_dir, found_key) = crate::saveimport::locate(dir); + let from_key = account_key_for(&save_dir, &found_key, &src); + check_copy_source(&save_dir, &from_key)?; + + let mut p = make_profile(&s, name, None)?; + p.coop = Some(make_coop(room_code, relay, &p.name, &p.net_uid, 1)?); + let to_key = crate::saveimport::uid_key(&p.uid).ok_or("Cannot make an id for the profile.")?; + crate::saveimport::copy_account(&save_dir, &from_key, &to_key)?; + s.profiles.push(p); + save(dir, &s)?; + Ok(s) +} + +/// "Copy to singleplayer": creates a singleplayer profile from a copy of a co-op profile's save via saveimport::copy_account. +pub fn copy_to_singleplayer(dir: &Path, source_id: &str, name: &str) -> Result { + let mut s = load(dir); + let src = s.get(source_id).ok_or("That profile does not exist.")?.clone(); + if src.coop.is_none() { + return Err("That profile is already a singleplayer profile.".into()); + } + let (save_dir, found_key) = crate::saveimport::locate(dir); + let from_key = account_key_for(&save_dir, &found_key, &src); + check_copy_source(&save_dir, &from_key)?; + + let p = make_profile(&s, name, None)?; + let to_key = crate::saveimport::uid_key(&p.uid).ok_or("Cannot make an id for the profile.")?; + crate::saveimport::copy_account(&save_dir, &from_key, &to_key)?; + s.profiles.push(p); + save(dir, &s)?; + Ok(s) +} + +/// Updates a co-op profile's private room code (Some("") regenerates a fresh code), relay address, or member list. +pub fn update_coop(dir: &Path, id: &str, room_code: Option<&str>, relay: Option<&str>, members: Option>) -> Result { + let mut s = load(dir); + let p = s.profiles.iter_mut().find(|p| p.id == id).ok_or("That profile does not exist.")?; + let coop = p.coop.as_mut().ok_or("That profile is not a co-op profile.")?; + if let Some(code) = room_code { + coop.room_code = if code.trim().is_empty() { + crate::coop::new_room_code()? + } else { + crate::coop::normalize_room_code(code)? + }; + } + if let Some(r) = relay { + coop.relay = crate::coop::validate_relay(r)?; + } + if let Some(m) = members { + coop.members = crate::coop::validate_members(m)?; + } + save(dir, &s)?; + Ok(s) +} + +/// Increments a co-op profile's world version after a session finishes. +pub fn bump_world_version(dir: &Path, id: &str) -> Result { + let mut s = load(dir); + let p = s.profiles.iter_mut().find(|p| p.id == id).ok_or("That profile does not exist.")?; + let coop = p.coop.as_mut().ok_or("That profile is not a co-op profile.")?; + coop.world_version = coop.world_version.saturating_add(1); save(dir, &s)?; Ok(s) } @@ -219,13 +365,17 @@ pub fn select(dir: &Path, id: &str) -> Result { Ok(s) } -/// Writes the active profile's uid, nickname and Link Play uid into pkp.ini. Does nothing until the player has made a profile. +/// Writes the active singleplayer profile's uid, nickname and Link Play uid into pkp.ini. +/// Does nothing until the player has made a profile, and never writes a co-op profile's uid or settings into pkp.ini. pub fn apply_active(dir: &Path) -> Result<(), String> { if !exists(dir) { return Ok(()); } let s = load(dir); let p = s.active_profile().clone(); + if p.coop.is_some() { + return Ok(()); + } let path = dir.join(PKP_INI); let mut ini = load_ini(dir); let mut changed = !path.exists(); @@ -426,4 +576,96 @@ mod tests { assert!(err.contains("damaged"), "{}", err); assert_eq!(fs::read_to_string(d.join(FILE)).unwrap(), "broken", "the damaged file is untouched"); } + + fn write_save(d: &Path, uid: &str, tag: &[u8]) { + let key = crate::saveimport::account_key_of(uid); + let root = d.join("save").join("account").join(key); + fs::create_dir_all(root.join("G00")).unwrap(); + fs::create_dir_all(root.join("S00")).unwrap(); + fs::write(root.join("G00").join("CMNDAT.BIN"), tag).unwrap(); + fs::write(root.join("S00").join("SYDAT.BIN"), tag).unwrap(); + } + + #[test] + fn coop_profile_has_own_folder_members_version_and_never_touches_pkp_ini() { + let sp_uid = "0123456789abcdef0123456789abcdef"; + let d = tmp("coop", &format!("[account]\nuid = {}\nnickname = Ash\n[fs]\nsave_dir = save\n", sp_uid)); + let s = add_coop(&d, "Group One", None, None).unwrap(); + let cp = s.profiles.iter().find(|p| p.name == "Group One").unwrap().clone(); + let coop = cp.coop.as_ref().expect("coop metadata"); + assert_ne!(cp.uid, sp_uid); + assert_eq!(coop.room_code.len(), 19); + assert_eq!(coop.world_version, 0); + assert_eq!(coop.members.len(), 1); + assert_eq!(coop.members[0].name, "Group One"); + assert_eq!(coop.members[0].role, "host"); + + // selecting a co-op profile never writes its uid or co-op settings into pkp.ini + select(&d, &cp.id).unwrap(); + assert_eq!(ini_of(&d, "account", "uid").as_deref(), Some(sp_uid)); + assert_eq!(ini_of(&d, "account", "nickname").as_deref(), Some("Ash")); + assert_eq!(strict_save_key(&d), crate::saveimport::uid_key(&cp.uid)); + + // members, room code, relay, world version updates + let s = update_coop( + &d, + &cp.id, + Some("abcd 1234 efgh 5678"), + Some("203.0.113.5:47610"), + Some(vec![ + Member { name: "Group One".into(), net_uid: cp.net_uid.clone(), role: "host".into() }, + Member { name: "Misty".into(), net_uid: String::new(), role: "visitor".into() }, + ]), + ) + .unwrap(); + let updated = s.get(&cp.id).unwrap().coop.as_ref().unwrap(); + assert_eq!(updated.room_code, "ABCD-1234-EFGH-5678"); + assert_eq!(updated.relay, "203.0.113.5:47610"); + assert_eq!(updated.members.len(), 2); + + let s = bump_world_version(&d, &cp.id).unwrap(); + assert_eq!(s.get(&cp.id).unwrap().coop.as_ref().unwrap().world_version, 1); + } + + #[test] + fn copy_between_singleplayer_and_coop_modes_uses_copy_account() { + let sp_uid = "0123456789abcdef0123456789abcdef"; + let d = tmp("copy-modes", &format!("[account]\nuid = {}\nnickname = Ash\n[fs]\nsave_dir = save\n", sp_uid)); + write_save(&d, sp_uid, b"singleplayer-world"); + + let s = start_coop_from(&d, DEFAULT_ID, "Island Co-op", None, None).unwrap(); + let cp = s.profiles.iter().find(|p| p.name == "Island Co-op").unwrap().clone(); + let cp_coop = cp.coop.as_ref().unwrap(); + assert_eq!(cp_coop.world_version, 1); + let cp_key = crate::saveimport::uid_key(&cp.uid).unwrap(); + assert_eq!(fs::read(d.join("save").join("account").join(&cp_key).join("G00").join("CMNDAT.BIN")).unwrap(), b"singleplayer-world"); + + // cannot start co-op from a co-op profile, nor copy singleplayer to singleplayer + assert!(start_coop_from(&d, &cp.id, "Bad", None, None).is_err()); + assert!(copy_to_singleplayer(&d, DEFAULT_ID, "Bad2").is_err()); + + // modify co-op save and copy back to a new singleplayer profile + fs::write(d.join("save").join("account").join(&cp_key).join("G00").join("CMNDAT.BIN"), b"coop-progress").unwrap(); + let s = copy_to_singleplayer(&d, &cp.id, "Solo Copy").unwrap(); + let sp2 = s.profiles.iter().find(|p| p.name == "Solo Copy").unwrap(); + assert!(sp2.coop.is_none()); + let sp2_key = crate::saveimport::uid_key(&sp2.uid).unwrap(); + assert_eq!(fs::read(d.join("save").join("account").join(&sp2_key).join("G00").join("CMNDAT.BIN")).unwrap(), b"coop-progress"); + // original singleplayer save was untouched + let sp_key = crate::saveimport::uid_key(sp_uid).unwrap(); + assert_eq!(fs::read(d.join("save").join("account").join(&sp_key).join("G00").join("CMNDAT.BIN")).unwrap(), b"singleplayer-world"); + } + + #[test] + fn old_profiles_json_without_coop_field_loads_as_singleplayer() { + let d = tmp("compat", ""); + fs::write( + d.join(FILE), + r#"{"active":"default","profiles":[{"id":"default","name":"Player","uid":"","nickname":"Player","net_uid":""}]}"#, + ) + .unwrap(); + let s = load(&d); + assert_eq!(s.profiles.len(), 1); + assert!(s.profiles[0].coop.is_none()); + } } diff --git a/launcher/src-tauri/src/relay_cmds.rs b/launcher/src-tauri/src/relay_cmds.rs index febaa1a6..ce792c93 100644 --- a/launcher/src-tauri/src/relay_cmds.rs +++ b/launcher/src-tauri/src/relay_cmds.rs @@ -15,6 +15,10 @@ pub fn stop_relay(app: &AppHandle) { } } +pub fn is_running(app: &AppHandle) -> bool { + app.relay().0.lock().unwrap().is_some() +} + /// The relay server the launcher runs on a thread (Host button, phase 4). None: not running. #[derive(Default)] pub struct RelayState(Mutex>); diff --git a/launcher/src-tauri/src/savebackup.rs b/launcher/src-tauri/src/savebackup.rs index 99bdb88b..e45a8d51 100644 --- a/launcher/src-tauri/src/savebackup.rs +++ b/launcher/src-tauri/src/savebackup.rs @@ -236,16 +236,22 @@ pub fn snapshot_with(game_dir: &Path, kind: &str, retry_wait: Duration) -> Resul /// `game_closed`: nothing is writing the save, so a commit marker left by a game that was killed is not a reason to wait (a restore /// still wants the copy of what is there now); the folder listing must still be the same before and after. fn snapshot_impl(game_dir: &Path, kind: &str, retry_wait: Duration, game_closed: bool) -> Result { - let (sd, key) = locate(game_dir); - let live = sd.join("account").join(&key); + let (_, key) = locate(game_dir); + let name = profile_name(game_dir); + snapshot_for_impl(game_dir, &key, &name, kind, retry_wait, game_closed) +} + +fn snapshot_for_impl(game_dir: &Path, key: &str, profile: &str, kind: &str, retry_wait: Duration, game_closed: bool) -> Result { + let (sd, _) = locate(game_dir); + let live = sd.join("account").join(key); if !live.is_dir() { return Ok(Outcome::NoSave); } let meta = sd.join("account").join(format!("{}.meta", key)); - let root = root_of(game_dir, &key); + let root = root_of(game_dir, key); fs::create_dir_all(&root).map_err(|e| format!("Cannot create {}: {}", root.display(), e))?; for _ in 0..3 { - if !game_closed && commit_pending(&sd, &key) { + if !game_closed && commit_pending(&sd, key) { std::thread::sleep(retry_wait); continue; } @@ -259,14 +265,14 @@ fn snapshot_impl(game_dir: &Path, kind: &str, retry_wait: Duration, game_closed: } Ok(()) })(); - let stable = made.is_ok() && (game_closed || !commit_pending(&sd, &key)) && listing(&live).map_or(false, |after| after == before); + let stable = made.is_ok() && (game_closed || !commit_pending(&sd, key)) && listing(&live).map_or(false, |after| after == before); if !stable { let _ = fs::remove_dir_all(&tmp); std::thread::sleep(retry_wait); continue; } let (hash, files, bytes) = digest(&tmp.join(DATA), Some(&tmp.join(META))).map_err(|e| e.to_string())?; - if !is_safety(kind) && list_key(game_dir, &key).first().map_or(false, |e| e.hash == hash) { + if !is_safety(kind) && list_key(game_dir, key).first().map_or(false, |e| e.hash == hash) { let _ = fs::remove_dir_all(&tmp); return Ok(Outcome::Unchanged); } @@ -276,8 +282,8 @@ fn snapshot_impl(game_dir: &Path, kind: &str, retry_wait: Duration, game_closed: name: name.clone(), created: chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string(), kind: kind.to_string(), - key: key.clone(), - profile: profile_name(game_dir), + key: key.to_string(), + profile: profile.to_string(), files, bytes, hash, @@ -285,7 +291,7 @@ fn snapshot_impl(game_dir: &Path, kind: &str, retry_wait: Duration, game_closed: let text = serde_json::to_string_pretty(&entry).map_err(|e| e.to_string())?; crate::settings::write_atomic(&tmp.join(MANIFEST), &text)?; fs::rename(&tmp, root.join(&name)).map_err(|e| format!("Cannot finish the backup: {}", e))?; - prune(game_dir, &key, settings_of(game_dir).keep); + prune(game_dir, key, settings_of(game_dir).keep); return Ok(Outcome::Made { entry }); } Err("The save was being written. Nothing was copied; try again in a moment.".into()) @@ -295,16 +301,16 @@ pub fn snapshot(game_dir: &Path, kind: &str) -> Result { snapshot_with(game_dir, kind, Duration::from_secs(1)) } -/// One file of the active profile's committed save (`rel` inside `account//`, e.g. `G00/CMNDAT.BIN`), read under the same rule as a +/// One file of `key`'s committed save (`rel` inside `account//`, e.g. `G00/CMNDAT.BIN`), read under the same rule as a /// copy: no commit marker before or after, folder listing unchanged. None: no save, no such file, or still being written after three tries. -pub fn read_committed(game_dir: &Path, rel: &str, retry_wait: Duration) -> Option> { - let (sd, key) = locate(game_dir); - let live = sd.join("account").join(&key); +pub fn read_committed_key(game_dir: &Path, key: &str, rel: &str, retry_wait: Duration) -> Option> { + let (sd, _) = locate(game_dir); + let live = sd.join("account").join(key); for _ in 0..3 { - if !commit_pending(&sd, &key) { + if !commit_pending(&sd, key) { let before = listing(&live).ok()?; let data = fs::read(live.join(rel)).ok()?; - if !commit_pending(&sd, &key) && listing(&live).is_ok_and(|after| after == before) { + if !commit_pending(&sd, key) && listing(&live).is_ok_and(|after| after == before) { return Some(data); } } @@ -313,6 +319,13 @@ pub fn read_committed(game_dir: &Path, rel: &str, retry_wait: Duration) -> Optio None } +/// One file of the active profile's committed save. +#[cfg(test)] +pub fn read_committed(game_dir: &Path, rel: &str, retry_wait: Duration) -> Option> { + let (_, key) = locate(game_dir); + read_committed_key(game_dir, &key, rel, retry_wait) +} + // ---- restoring ------------------------------------------------------------------------------------------------------------------ #[derive(Serialize, Debug)] @@ -417,6 +430,7 @@ pub struct Watch { stop: Arc, handle: Option>, dir: PathBuf, + target: Option<(String, String)>, } const TICK: Duration = Duration::from_secs(5); @@ -425,8 +439,16 @@ impl Watch { pub fn start(game_dir: &Path) -> Watch { let stop = Arc::new(AtomicBool::new(false)); let (flag, dir) = (stop.clone(), game_dir.to_path_buf()); - let handle = std::thread::spawn(move || run(&dir, &flag, TICK, Duration::from_secs(1), Duration::from_secs(60))); - Watch { stop, handle: Some(handle), dir: game_dir.to_path_buf() } + let handle = std::thread::spawn(move || run(&dir, None, &flag, TICK, Duration::from_secs(1), Duration::from_secs(60))); + Watch { stop, handle: Some(handle), dir: game_dir.to_path_buf(), target: None } + } + + /// Watches a specific account folder and profile name (e.g. a co-op launch without changing active profile in pkp.ini). + pub fn start_for(game_dir: &Path, key: String, profile: String) -> Watch { + let stop = Arc::new(AtomicBool::new(false)); + let (flag, dir, tgt) = (stop.clone(), game_dir.to_path_buf(), (key.clone(), profile.clone())); + let handle = std::thread::spawn(move || run(&dir, Some(tgt), &flag, TICK, Duration::from_secs(1), Duration::from_secs(60))); + Watch { stop, handle: Some(handle), dir: game_dir.to_path_buf(), target: Some((key, profile)) } } /// The game has ended: stops the timer, then makes the closing copy (when backups are on). Call it after the process is gone. @@ -437,7 +459,11 @@ impl Watch { } let s = settings_of(&self.dir); if s.minutes > 0 && s.on_exit { - if let Err(e) = snapshot(&self.dir, KIND_EXIT) { + let res = match &self.target { + Some((key, profile)) => snapshot_for_impl(&self.dir, key, profile, KIND_EXIT, Duration::from_secs(1), false), + None => snapshot(&self.dir, KIND_EXIT), + }; + if let Err(e) = res { eprintln!("Save backup at exit: {}", e); } } @@ -454,7 +480,7 @@ fn sleep_unless(stop: &AtomicBool, total: Duration) { } /// The timer loop (a function so a test can run it with a short tick and a short "minute"). `retry_wait` is passed on to the copy. -fn run(dir: &Path, stop: &AtomicBool, tick: Duration, retry_wait: Duration, minute: Duration) { +fn run(dir: &Path, target: Option<(String, String)>, stop: &AtomicBool, tick: Duration, retry_wait: Duration, minute: Duration) { let mut last = Instant::now(); while !stop.load(Ordering::SeqCst) { sleep_unless(stop, tick); @@ -468,7 +494,11 @@ fn run(dir: &Path, stop: &AtomicBool, tick: Duration, retry_wait: Duration, minu } if last.elapsed() >= minute * s.minutes { last = Instant::now(); - if let Err(e) = snapshot_with(dir, KIND_AUTO, retry_wait) { + let res = match &target { + Some((key, profile)) => snapshot_for_impl(dir, key, profile, KIND_AUTO, retry_wait, false), + None => snapshot_with(dir, KIND_AUTO, retry_wait), + }; + if let Err(e) = res { eprintln!("Save backup: {}", e); } } @@ -664,7 +694,7 @@ mod tests { let run_for = |d: &PathBuf, ms: u64| { let stop = AtomicBool::new(false); std::thread::scope(|s| { - let h = s.spawn(|| run(d, &stop, Duration::from_millis(5), Duration::from_millis(5), Duration::from_millis(20))); + let h = s.spawn(|| run(d, None, &stop, Duration::from_millis(5), Duration::from_millis(5), Duration::from_millis(20))); std::thread::sleep(Duration::from_millis(ms)); stop.store(true, Ordering::SeqCst); h.join().unwrap(); diff --git a/launcher/src-tauri/src/saveimport.rs b/launcher/src-tauri/src/saveimport.rs index 64b6f165..3bf69cc4 100644 --- a/launcher/src-tauri/src/saveimport.rs +++ b/launcher/src-tauri/src/saveimport.rs @@ -266,15 +266,31 @@ fn put_back(old: &[PathBuf], bacc: &Path) { /// Brings `src` (a folder holding G00 and S00, optionally B00) in as the game's committed account save. The source is only read. The /// caller has checked that the game is not running. pub fn import(save_dir: &Path, key: &str, src: &Path) -> Result { + let canon = |p: &Path| fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + if is_save_folder(src) && canon(src).starts_with(canon(save_dir)) { + return Err(format!("{} is inside the save folder the game plays. Pick a copy outside it.", fwd(src))); + } + place(save_dir, key, src) +} + +/// One account's save as a copy of another's in the same save folder. +/// Only for an account that has no save yet: `to_key`'s folder must not exist. The source is only read; the caller has checked +/// that the game is not running. +pub fn copy_account(save_dir: &Path, from_key: &str, to_key: &str) -> Result { + let acc = save_dir.join("account"); + if from_key == to_key || acc.join(to_key).exists() { + return Err(format!("{} already holds a save.", fwd(&acc.join(to_key)))); + } + place(save_dir, to_key, &acc.join(from_key)) +} + +/// The copy itself: `src` staged beside the account folder, an old save moved aside, the copy put in its place, its .meta written. +fn place(save_dir: &Path, key: &str, src: &Path) -> Result { if !is_save_folder(src) { return Err(format!("{} holds no Pokopia save (no G00 and S00 folders).", fwd(src))); } let acc = save_dir.join("account"); let root = acc.join(key); - let canon = |p: &Path| fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); - if canon(src).starts_with(canon(save_dir)) { - return Err(format!("{} is inside the save folder the game plays. Pick a copy outside it.", fwd(src))); - } fs::create_dir_all(&acc).map_err(|e| format!("Cannot create {}: {}", fwd(&acc), e))?; let t = crate::fsutil::file_stamp(); @@ -427,4 +443,26 @@ save_dir = second late.push_str("éé"); assert!(late.len() >= 66 && !meta_with(&late)); } + + #[test] + fn copy_account_copies_an_existing_save_and_refuses_to_overwrite() { + let dir = std::env::temp_dir().join(format!("pkp-copy-account-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + let from = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let to = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + let src = dir.join("account").join(from); + fs::create_dir_all(src.join("G00")).unwrap(); + fs::create_dir_all(src.join("S00")).unwrap(); + fs::write(src.join("G00").join("CMNDAT.BIN"), b"common").unwrap(); + fs::write(src.join("S00").join("SYDAT.BIN"), b"system").unwrap(); + + let rep = copy_account(&dir, from, to).unwrap(); + assert_eq!(rep.files, 2); + assert_eq!(rep.backup, None); + assert_eq!(fs::read(dir.join("account").join(to).join("G00").join("CMNDAT.BIN")).unwrap(), b"common"); + assert!(dir.join("account").join(format!("{}.meta", to)).is_file()); + assert!(copy_account(&dir, from, to).unwrap_err().contains("already holds a save")); + assert!(copy_account(&dir, from, from).is_err()); + let _ = fs::remove_dir_all(&dir); + } } diff --git a/launcher/src/action.js b/launcher/src/action.js index 4e6d8d44..1fa801fc 100644 --- a/launcher/src/action.js +++ b/launcher/src/action.js @@ -135,6 +135,9 @@ export function primaryAction(s) { if (kind === 'resume') return on(t('Continue setup'), 'wrench', 'setup'); if (needsFinish(kind)) return on(t('Finish update'), 'wrench', 'setup'); if (kind === 'mods') return on(t('Set up again'), 'wrench', 'setup'); // the mods' hook points changed (Mods page) - if (kind === 'ready') return on(t('Play'), 'play', 'play'); + if (kind === 'ready') { + const active = s.profiles?.profiles?.find((p) => p.id === s.profiles.active); + return active?.coop ? on(t('Play co-op'), 'users', 'play-coop') : on(t('Play'), 'play', 'play'); + } return off(t('Not ready'), 'circle-alert', false); // a kind this build does not know must not fall through to Play } diff --git a/launcher/src/api.js b/launcher/src/api.js index 2da9be72..615fa1ce 100644 --- a/launcher/src/api.js +++ b/launcher/src/api.js @@ -41,6 +41,7 @@ export const api = { // Play and setup play: (args) => invoke('play', args), // { withoutMods } (optional: this one start runs without mods) + playCoop: (args) => invoke('play_coop', args), // { id, withoutMods } gameStatus: () => invoke('game_status'), setupStatus: () => invoke('setup_status'), startSetup: (args) => invoke('start_setup', args), // { gentle } @@ -76,6 +77,10 @@ export const api = { profileRename: (args) => invoke('profile_rename', args), // { id, name } profileRemove: (args) => invoke('profile_remove', args), // { id } profileSelect: (args) => invoke('profile_select', args), // { id } + profileAddCoop: (args) => invoke('profile_add_coop', args), // { name, roomCode, relay } + profileStartCoopFrom: (args) => invoke('profile_start_coop_from', args), // { sourceId, name, roomCode, relay } + profileCopyToSingleplayer: (args) => invoke('profile_copy_to_singleplayer', args), // { sourceId, name } + profileCoopUpdate: (args) => invoke('profile_coop_update', args), // { id, roomCode, relay, members } // Steam steamStatus: () => invoke('steam_status'), diff --git a/launcher/src/backend-text.js b/launcher/src/backend-text.js index 4b33960f..4dd2f921 100644 --- a/launcher/src/backend-text.js +++ b/launcher/src/backend-text.js @@ -169,6 +169,11 @@ const TEXTS = [ msg('pkp.exe in {1} is missing or from an older release: open the launcher and press Set up.'), msg('Setup has not finished: open the launcher and press Set up.'), msg('The profile could not be applied, so the game was not started: {1}'), + msg('This profile is a co-op save. Start it from Co-op instead, or switch to a singleplayer profile.'), + msg('This profile is a co-op save. Start it from Co-op in the launcher instead, or switch to a singleplayer profile.'), + msg('This profile is a singleplayer save. Pick a co-op profile, or start co-op from a copy of it.'), + msg('This co-op profile has no valid account ID.'), + msg('The relay on this PC is off. Turn on Run a relay on this PC on the Link Play page, or clear the relay address to use the public relay.'), // preflight.rs: the checks before Set up msg('Not enough free disk space'), @@ -203,7 +208,7 @@ const TEXTS = [ msg('{1} runs microcode {2}. These CPUs can become unstable, and crash Windows under long heavy loads like the shader translation (1 to 2 hours on every core), until the motherboard\'s BIOS carries Intel\'s microcode fix (0x12B or newer). Update the BIOS from your motherboard maker first, and turn on "Use fewer cores" below.'), msg('{1} has microcode that could not be read. These CPUs can become unstable, and crash Windows under long heavy loads like the shader translation (1 to 2 hours on every core), until the motherboard\'s BIOS carries Intel\'s microcode fix (0x12B or newer). Update the BIOS from your motherboard maker first, and turn on "Use fewer cores" below.'), - // profiles.rs + // profiles.rs, coop.rs msg('profiles.json is damaged and could not be copied aside ({1}), so nothing was changed.'), msg('Type a name for the profile.'), msg('The name can have at most {n1} characters.'), @@ -211,6 +216,18 @@ const TEXTS = [ msg('There is already a profile called {1}.'), msg('That profile does not exist.'), msg('The first profile holds the existing save and cannot be removed.'), + msg('Cannot make a room code: {1}'), + msg('Type a 16-character room code (XXXX-XXXX-XXXX-XXXX).'), + msg('Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.'), + msg("A member's network ID must be 32 hex digits."), + msg("A member's role must be host or visitor."), + msg('{1} is already in the group.'), + msg('That profile has no save to copy yet.'), + msg('That save has a write the game did not finish. Start the game once on that profile, then try again.'), + msg('Pick a singleplayer profile to start co-op from.'), + msg('Cannot make an id for the profile.'), + msg('That profile is already a singleplayer profile.'), + msg('That profile is not a co-op profile.'), // relay_cmds.rs msg('Cannot open port {1}: {2}'), @@ -234,6 +251,7 @@ const TEXTS = [ msg('Cannot put the backup in place: {1}. Your save was not changed.'), // saveimport.rs, saves.rs + msg('{1} already holds a save.'), msg('{1} holds no Pokopia save (no G00 and S00 folders).'), msg('{1} holds no Pokopia save (it needs the G00 and S00 folders).'), msg('{1} is inside the save folder the game plays. Pick a copy outside it.'), diff --git a/launcher/src/coop-model.js b/launcher/src/coop-model.js new file mode 100644 index 00000000..7858f6cf --- /dev/null +++ b/launcher/src/coop-model.js @@ -0,0 +1,46 @@ +// Co-op profile helpers: private room codes, relay address validation, mode filtering. Pure: no DOM, no Tauri. +import { t } from './i18n.js'; +import { validAddr } from './linkplay-model.js'; + +const B32 = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; +const ROOM_LEN = 16; + +/** Normalizes a Crockford base32 room code into `XXXX-XXXX-XXXX-XXXX`, or '' when invalid. */ +export function normalizeRoomCode(raw) { + let out = ''; + for (const ch of String(raw ?? '')) { + if (ch === '-' || ch === ' ') continue; + let up = ch.toUpperCase(); + if (up === 'O') up = '0'; + else if (up === 'I' || up === 'L') up = '1'; + if (!B32.includes(up) || out.length === ROOM_LEN) return ''; + out += up; + } + if (out.length !== ROOM_LEN) return ''; + return `${out.slice(0, 4)}-${out.slice(4, 8)}-${out.slice(8, 12)}-${out.slice(12, 16)}`; +} + +/** Validation message for a room code; '' when valid (or empty when `optional` is true). */ +export function roomCodeProblem(raw, { optional = false } = {}) { + const s = String(raw ?? '').trim(); + if (!s) return optional ? '' : t('Type a 16-character room code (XXXX-XXXX-XXXX-XXXX).'); + return normalizeRoomCode(s) ? '' : t('Type a 16-character room code (XXXX-XXXX-XXXX-XXXX).'); +} + +/** Validation message for an optional co-op relay address (`[:port]`), '' when empty or valid. */ +export function relayProblem(raw) { + const s = String(raw ?? '').trim(); + if (!s) return ''; + return validAddr(s) ? '' : t('Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.'); +} + +export const isCoopProfile = (p) => !!p?.coop; + +export function activeProfileOf(store) { + const list = store?.profiles ?? []; + return list.find((p) => p.id === store?.active) ?? list[0] ?? null; +} + +export const coopProfiles = (store) => (store?.profiles ?? []).filter(isCoopProfile); + +export const singleplayerProfiles = (store) => (store?.profiles ?? []).filter((p) => !isCoopProfile(p)); diff --git a/launcher/src/dev/mock.js b/launcher/src/dev/mock.js index 726f4faa..5d3f8ead 100644 --- a/launcher/src/dev/mock.js +++ b/launcher/src/dev/mock.js @@ -440,7 +440,16 @@ function handle(cmd, args) { case 'get_releases': return { releases: sc.releases ?? (mockChannel === 'testing' ? [{ ...release('v0.8.1-beta.2', 'Pokopia Recomp 0.8.1-beta.2 (Testing)', '2026-11-12T12:00:00Z'), prerelease: true }, { ...release('v0.8.1-beta.1', 'Pokopia Recomp 0.8.1-beta.1 (Testing)', '2026-11-10T12:00:00Z'), prerelease: true }, ...(sc.update ? [NEXT, ...RELEASES] : RELEASES)] : (sc.update ? [NEXT, ...RELEASES] : RELEASES)), update: sc.update && mockChannel !== 'testing' ? { tag: NEXT.tag, name: NEXT.name, url: NEXT.url, size: 148_000_000 } : null }; // Testing offers no update (update.rs Channel::offers_updates) case 'install_update': return runUpdate(); case 'cancel_update': return updateStop?.(); - case 'play': return runPlay(); + case 'play': { + const p = mockProfiles.profiles.find((x) => x.id === mockProfiles.active); + if (p?.coop) throw 'This profile is a co-op save. Start it from Co-op instead, or switch to a singleplayer profile.'; + return runPlay(); + } + case 'play_coop': { + const p = mockProfiles.profiles.find((x) => x.id === (args?.id || mockProfiles.active)); + if (!p?.coop) throw 'This profile is a singleplayer save. Pick a co-op profile, or start co-op from a copy of it.'; + return runPlay().then(() => { p.coop.world_version = (p.coop.world_version ?? 0) + 1; }); + } case 'preflight': return sleep(500).then(() => ({ ...PREFLIGHT[sc.preflight || 'ok'], need_bytes: (looseShaders ? 31 : 14) * 2 ** 30 })); case 'start_setup': return runSetup(); case 'cancel_setup': return pauseSetup(); @@ -516,6 +525,30 @@ function handle(cmd, args) { case 'profile_rename': mockProfiles.profiles.find((p) => p.id === args.id).name = args.name; return structuredClone(mockProfiles); case 'profile_remove': mockProfiles.profiles = mockProfiles.profiles.filter((p) => p.id !== args.id); mockProfiles.active = 'default'; return structuredClone(mockProfiles); case 'profile_select': mockProfiles.active = args.id; return structuredClone(mockProfiles); + case 'profile_add_coop': + mockProfiles.profiles.push({ + id: `p${mockProfiles.profiles.length}`, name: args.name, uid: '', nickname: args.name, net_uid: '', + coop: { room_code: args.roomCode || 'ABCD-EFGH-JKMN-PQRS', relay: args.relay || '', members: [{ name: args.name, role: 'host' }], world_version: 0 }, + }); + return structuredClone(mockProfiles); + case 'profile_start_coop_from': + mockProfiles.profiles.push({ + id: `p${mockProfiles.profiles.length}`, name: args.name, uid: '', nickname: args.name, net_uid: '', + coop: { room_code: args.roomCode || 'ABCD-EFGH-JKMN-PQRS', relay: args.relay || '', members: [{ name: args.name, role: 'host' }], world_version: 1 }, + }); + return structuredClone(mockProfiles); + case 'profile_copy_to_singleplayer': + mockProfiles.profiles.push({ id: `p${mockProfiles.profiles.length}`, name: args.name, uid: '', nickname: args.name, net_uid: '' }); + return structuredClone(mockProfiles); + case 'profile_coop_update': { + const p = mockProfiles.profiles.find((x) => x.id === args.id); + if (p?.coop) { + if (args.roomCode !== null && args.roomCode !== undefined) p.coop.room_code = args.roomCode || 'WXYZ-2345-6789-ABCD'; + if (args.relay !== null && args.relay !== undefined) p.coop.relay = args.relay; + if (args.members) p.coop.members = args.members; + } + return structuredClone(mockProfiles); + } case 'save_sources': return [{ label: 'Eden', path: 'C:/Users/player/AppData/Roaming/eden/nand/user/save/0000000000000000/1/0100F4300BF2C000' }]; case 'import_save': return { source: 'Eden', files: 12, backup: `${GAME_DIR}/save.backup-20261106`, target: `${GAME_DIR}/save` }; case 'relay_start': diff --git a/launcher/src/i18n/de.js b/launcher/src/i18n/de.js index d0081465..a5f28cb7 100644 --- a/launcher/src/i18n/de.js +++ b/launcher/src/i18n/de.js @@ -943,4 +943,62 @@ export default { 'You no longer show as online': 'Du wirst nicht mehr als online angezeigt', 'Online': 'Online', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': 'Derselbe Schalter ist auf der Startseite und in den Einstellungen des Spiels im Tab Online.', + 'Play co-op': 'Koop spielen', + 'This profile is a co-op save. Start it from Co-op instead, or switch to a singleplayer profile.': 'Dieses Profil ist ein Koop-Spielstand. Starte es über Koop oder wechsle zu einem Einzelspieler-Profil.', + 'This profile is a co-op save. Start it from Co-op in the launcher instead, or switch to a singleplayer profile.': 'Dieses Profil ist ein Koop-Spielstand. Starte es im Launcher über Koop oder wechsle zu einem Einzelspieler-Profil.', + 'This profile is a singleplayer save. Pick a co-op profile, or start co-op from a copy of it.': 'Dieses Profil ist ein Einzelspieler-Spielstand. Wähle ein Koop-Profil oder starte Koop aus einer Kopie davon.', + 'This co-op profile has no valid account ID.': 'Dieses Koop-Profil hat keine gültige Konto-ID.', + 'The relay on this PC is off. Turn on Run a relay on this PC on the Link Play page, or clear the relay address to use the public relay.': 'Das Relay auf diesem PC ist aus. Schalte auf der Link-Play-Seite „Relay auf diesem PC ausführen“ ein oder leere die Adresse für das öffentliche Relay.', + 'Cannot make a room code: {1}': 'Raumcode konnte nicht erstellt werden: {1}', + 'Type a 16-character room code (XXXX-XXXX-XXXX-XXXX).': 'Gib einen 16-stelligen Raumcode ein (XXXX-XXXX-XXXX-XXXX).', + 'Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.': 'Gib eine Relay-Adresse wie 203.0.113.5:47610 ein oder lass sie für das öffentliche Relay leer.', + 'A member\'s network ID must be 32 hex digits.': 'Die Netzwerk-ID eines Mitglieds muss 32 Hex-Zeichen lang sein.', + 'A member\'s role must be host or visitor.': 'Die Rolle eines Mitglieds muss Host oder Besucher sein.', + '{1} is already in the group.': '{1} ist bereits in der Gruppe.', + 'That profile has no save to copy yet.': 'Dieses Profil hat noch keinen Spielstand zum Kopieren.', + 'That save has a write the game did not finish. Start the game once on that profile, then try again.': 'Dieser Spielstand hat einen unvollständigen Schreibvorgang. Starte das Spiel einmal mit diesem Profil und versuche es erneut.', + 'Pick a singleplayer profile to start co-op from.': 'Wähle ein Einzelspieler-Profil, von dem aus Koop gestartet werden soll.', + 'Cannot make an id for the profile.': 'Für das Profil konnte keine ID erstellt werden.', + 'That profile is already a singleplayer profile.': 'Dieses Profil ist bereits ein Einzelspieler-Profil.', + 'That profile is not a co-op profile.': 'Dieses Profil ist kein Koop-Profil.', + '{1} already holds a save.': '{1} enthält bereits einen Spielstand.', + 'Co-op: {name}': 'Koop: {name}', + 'New co-op profile': 'Neues Koop-Profil', + 'Start coop from my singleplayer save': 'Koop aus meinem Einzelspieler-Spielstand starten', + 'Co-op': 'Koop', + 'Co-op saves': 'Koop-Spielstände', + 'Co-op saves use their own folder, apply co-op settings in the environment for that launch only (without touching pkp.ini), and connect to a private room on the relay.': 'Koop-Spielstände nutzen einen eigenen Ordner, wenden Koop-Einstellungen nur für diesen Start über die Umgebung an (ohne pkp.ini zu ändern) und verbinden sich mit einem privaten Raum auf dem Relay.', + 'Public relay ({addr})': 'Öffentliches Relay ({addr})', + 'Visitor': 'Besucher', + 'Co-op profile': 'Koop-Profil', + 'New': 'Neu', + 'New code': 'Neuer Code', + 'Private room code': 'Privater Raumcode', + 'Relay': 'Relay', + 'World version': 'Weltversion', + 'Group members': 'Gruppenmitglieder', + 'Add member': 'Mitglied hinzufügen', + 'Copy to singleplayer': 'In Einzelspieler kopieren', + 'Private co-op rooms never appear on the public room list. Co-op settings are passed for that launch only and never saved to pkp.ini.': 'Private Koop-Räume erscheinen nie in der öffentlichen Raumliste. Koop-Einstellungen gelten nur für den jeweiligen Start und werden nie in pkp.ini gespeichert.', + 'Starts a co-op save in its own folder with a private room on the relay.': 'Erstellt einen Koop-Spielstand in einem eigenen Ordner mit einem privaten Raum auf dem Relay.', + 'Next': 'Weiter', + 'Leave blank to make a new private room, or enter your group\'s room code.': 'Leer lassen für einen neuen privaten Raum, oder den Raumcode deiner Gruppe eingeben.', + 'Room code': 'Raumcode', + 'Co-op profile {name} added': 'Koop-Profil {name} hinzugefügt', + 'Copies {name}\'s save into a new co-op profile. Your singleplayer save stays untouched.': 'Kopiert den Spielstand von {name} in ein neues Koop-Profil. Dein Einzelspieler-Spielstand bleibt unverändert.', + 'Co-op profile name': 'Name des Koop-Profils', + 'Start co-op': 'Koop starten', + 'Copies {name}\'s co-op save into a new singleplayer profile.': 'Kopiert den Koop-Spielstand von {name} in ein neues Einzelspieler-Profil.', + 'Enter the 16-character room code shared by your group.': 'Gib den 16-stelligen Raumcode deiner Gruppe ein.', + 'Save': 'Speichern', + 'Room code updated': 'Raumcode aktualisiert', + 'New room code created': 'Neuer Raumcode erstellt', + 'Co-op relay': 'Koop-Relay', + 'Leave empty to use the public relay ({addr}), or enter a custom relay IPv4:port.': 'Leer lassen für das öffentliche Relay ({addr}), oder eine eigene Relay-Adresse IPv4:Port eingeben.', + 'Relay updated': 'Relay aktualisiert', + 'Member name': 'Name des Mitglieds', + 'Member added': 'Mitglied hinzugefügt', + 'Member removed': 'Mitglied entfernt', + 'World v{version}': 'Welt v{version}', + '{count} in group': '{count} in der Gruppe', }; diff --git a/launcher/src/i18n/es.js b/launcher/src/i18n/es.js index 7b2cca50..0e24f843 100644 --- a/launcher/src/i18n/es.js +++ b/launcher/src/i18n/es.js @@ -943,4 +943,62 @@ export default { 'You no longer show as online': 'Ya no apareces en línea', 'Online': 'En línea', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': 'El mismo interruptor está en Inicio y en los ajustes del propio juego, en la pestaña En línea.', + 'Play co-op': 'Jugar co-op', + 'This profile is a co-op save. Start it from Co-op instead, or switch to a singleplayer profile.': 'Este perfil es una partida co-op. Ábrelo desde Co-op o cambia a un perfil para un jugador.', + 'This profile is a co-op save. Start it from Co-op in the launcher instead, or switch to a singleplayer profile.': 'Este perfil es una partida co-op. Ábrelo desde Co-op en el launcher o cambia a un perfil para un jugador.', + 'This profile is a singleplayer save. Pick a co-op profile, or start co-op from a copy of it.': 'Este perfil es una partida para un jugador. Elige un perfil co-op o empieza un co-op a partir de una copia.', + 'This co-op profile has no valid account ID.': 'Este perfil co-op no tiene un ID de cuenta válido.', + 'The relay on this PC is off. Turn on Run a relay on this PC on the Link Play page, or clear the relay address to use the public relay.': 'El relay de esta PC está apagado. Activa Ejecutar un relay en esta PC en Link Play, o borra la dirección para usar el relay público.', + 'Cannot make a room code: {1}': 'No se pudo crear el código de sala: {1}', + 'Type a 16-character room code (XXXX-XXXX-XXXX-XXXX).': 'Escribe un código de sala de 16 caracteres (XXXX-XXXX-XXXX-XXXX).', + 'Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.': 'Escribe una dirección de relay como 203.0.113.5:47610, o déjalo vacío para el relay público.', + 'A member\'s network ID must be 32 hex digits.': 'El ID de red de un miembro debe tener 32 dígitos hexadecimales.', + 'A member\'s role must be host or visitor.': 'El rol de un miembro debe ser anfitrión o visitante.', + '{1} is already in the group.': '{1} ya está en el grupo.', + 'That profile has no save to copy yet.': 'Ese perfil todavía no tiene una partida para copiar.', + 'That save has a write the game did not finish. Start the game once on that profile, then try again.': 'Esa partida tiene una escritura que el juego no terminó. Inicia el juego una vez con ese perfil y vuelve a intentarlo.', + 'Pick a singleplayer profile to start co-op from.': 'Elige un perfil para un jugador desde el que empezar co-op.', + 'Cannot make an id for the profile.': 'No se pudo crear un ID para el perfil.', + 'That profile is already a singleplayer profile.': 'Ese perfil ya es un perfil para un jugador.', + 'That profile is not a co-op profile.': 'Ese perfil no es un perfil co-op.', + '{1} already holds a save.': '{1} ya tiene una partida.', + 'Co-op: {name}': 'Co-op: {name}', + 'New co-op profile': 'Nuevo perfil co-op', + 'Start coop from my singleplayer save': 'Empezar co-op desde mi partida de un jugador', + 'Co-op': 'Co-op', + 'Co-op saves': 'Partidas co-op', + 'Co-op saves use their own folder, apply co-op settings in the environment for that launch only (without touching pkp.ini), and connect to a private room on the relay.': 'Las partidas co-op usan su propia carpeta, aplican los ajustes co-op en el entorno solo para ese inicio (sin tocar pkp.ini) y se conectan a una sala privada en el relay.', + 'Public relay ({addr})': 'Relay público ({addr})', + 'Visitor': 'Visitante', + 'Co-op profile': 'Perfil co-op', + 'New': 'Nuevo', + 'New code': 'Nuevo código', + 'Private room code': 'Código de sala privada', + 'Relay': 'Relay', + 'World version': 'Versión del mundo', + 'Group members': 'Miembros del grupo', + 'Add member': 'Añadir miembro', + 'Copy to singleplayer': 'Copiar a un jugador', + 'Private co-op rooms never appear on the public room list. Co-op settings are passed for that launch only and never saved to pkp.ini.': 'Las salas co-op privadas nunca aparecen en la lista pública. Los ajustes co-op se pasan solo en ese inicio y nunca se guardan en pkp.ini.', + 'Starts a co-op save in its own folder with a private room on the relay.': 'Crea una partida co-op en su propia carpeta con una sala privada en el relay.', + 'Next': 'Siguiente', + 'Leave blank to make a new private room, or enter your group\'s room code.': 'Déjalo vacío para crear una sala privada nueva, o escribe el código de sala de tu grupo.', + 'Room code': 'Código de sala', + 'Co-op profile {name} added': 'Perfil co-op {name} añadido', + 'Copies {name}\'s save into a new co-op profile. Your singleplayer save stays untouched.': 'Copia la partida de {name} en un nuevo perfil co-op. Tu partida para un jugador no se toca.', + 'Co-op profile name': 'Nombre del perfil co-op', + 'Start co-op': 'Empezar co-op', + 'Copies {name}\'s co-op save into a new singleplayer profile.': 'Copia la partida co-op de {name} en un nuevo perfil para un jugador.', + 'Enter the 16-character room code shared by your group.': 'Escribe el código de sala de 16 caracteres que comparte tu grupo.', + 'Save': 'Guardar', + 'Room code updated': 'Código de sala actualizado', + 'New room code created': 'Nuevo código de sala creado', + 'Co-op relay': 'Relay co-op', + 'Leave empty to use the public relay ({addr}), or enter a custom relay IPv4:port.': 'Déjalo vacío para usar el relay público ({addr}), o escribe un relay propio IPv4:puerto.', + 'Relay updated': 'Relay actualizado', + 'Member name': 'Nombre del miembro', + 'Member added': 'Miembro añadido', + 'Member removed': 'Miembro eliminado', + 'World v{version}': 'Mundo v{version}', + '{count} in group': '{count} en el grupo', }; diff --git a/launcher/src/i18n/fr.js b/launcher/src/i18n/fr.js index 74a01d06..703fffd8 100644 --- a/launcher/src/i18n/fr.js +++ b/launcher/src/i18n/fr.js @@ -943,4 +943,62 @@ export default { 'You no longer show as online': 'Tu n\'apparais plus en ligne', 'Online': 'En ligne', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': 'Le même interrupteur se trouve sur l\'accueil et dans les paramètres du jeu, onglet En ligne.', + 'Play co-op': 'Jouer en coop', + 'This profile is a co-op save. Start it from Co-op instead, or switch to a singleplayer profile.': 'Ce profil est une sauvegarde coop. Lance-le depuis Coop ou passe à un profil solo.', + 'This profile is a co-op save. Start it from Co-op in the launcher instead, or switch to a singleplayer profile.': 'Ce profil est une sauvegarde coop. Lance-le depuis Coop dans le launcher ou passe à un profil solo.', + 'This profile is a singleplayer save. Pick a co-op profile, or start co-op from a copy of it.': 'Ce profil est une sauvegarde solo. Choisis un profil coop ou démarre une partie coop à partir d\'une copie.', + 'This co-op profile has no valid account ID.': 'Ce profil coop n\'a pas d\'identifiant de compte valide.', + 'The relay on this PC is off. Turn on Run a relay on this PC on the Link Play page, or clear the relay address to use the public relay.': 'Le relais sur ce PC est éteint. Active Exécuter un relais sur ce PC dans Link Play, ou vide l\'adresse pour utiliser le relais public.', + 'Cannot make a room code: {1}': 'Impossible de créer le code de salle : {1}', + 'Type a 16-character room code (XXXX-XXXX-XXXX-XXXX).': 'Saisis un code de salle à 16 caractères (XXXX-XXXX-XXXX-XXXX).', + 'Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.': 'Saisis une adresse de relais comme 203.0.113.5:47610, ou laisse vide pour le relais public.', + 'A member\'s network ID must be 32 hex digits.': 'L\'identifiant réseau d\'un membre doit contenir 32 chiffres hexadécimaux.', + 'A member\'s role must be host or visitor.': 'Le rôle d\'un membre doit être hôte ou visiteur.', + '{1} is already in the group.': '{1} est déjà dans le groupe.', + 'That profile has no save to copy yet.': 'Ce profil n\'a pas encore de sauvegarde à copier.', + 'That save has a write the game did not finish. Start the game once on that profile, then try again.': 'Cette sauvegarde contient une écriture inachevée. Lance le jeu une fois avec ce profil puis réessaie.', + 'Pick a singleplayer profile to start co-op from.': 'Choisis un profil solo à partir duquel démarrer la coop.', + 'Cannot make an id for the profile.': 'Impossible de créer un identifiant pour le profil.', + 'That profile is already a singleplayer profile.': 'Ce profil est déjà un profil solo.', + 'That profile is not a co-op profile.': 'Ce profil n\'est pas un profil coop.', + '{1} already holds a save.': '{1} contient déjà une sauvegarde.', + 'Co-op: {name}': 'Coop : {name}', + 'New co-op profile': 'Nouveau profil coop', + 'Start coop from my singleplayer save': 'Démarrer la coop depuis ma sauvegarde solo', + 'Co-op': 'Coop', + 'Co-op saves': 'Sauvegardes coop', + 'Co-op saves use their own folder, apply co-op settings in the environment for that launch only (without touching pkp.ini), and connect to a private room on the relay.': 'Les sauvegardes coop utilisent leur propre dossier, appliquent les réglages coop dans l\'environnement uniquement pour ce lancement (sans toucher à pkp.ini) et se connectent à une salle privée sur le relais.', + 'Public relay ({addr})': 'Relais public ({addr})', + 'Visitor': 'Visiteur', + 'Co-op profile': 'Profil coop', + 'New': 'Nouveau', + 'New code': 'Nouveau code', + 'Private room code': 'Code de salle privée', + 'Relay': 'Relais', + 'World version': 'Version du monde', + 'Group members': 'Membres du groupe', + 'Add member': 'Ajouter un membre', + 'Copy to singleplayer': 'Copier vers solo', + 'Private co-op rooms never appear on the public room list. Co-op settings are passed for that launch only and never saved to pkp.ini.': 'Les salles coop privées n\'apparaissent jamais dans la liste publique. Les réglages coop sont transmis uniquement au lancement et ne sont jamais enregistrés dans pkp.ini.', + 'Starts a co-op save in its own folder with a private room on the relay.': 'Crée une sauvegarde coop dans son propre dossier avec une salle privée sur le relais.', + 'Next': 'Suivant', + 'Leave blank to make a new private room, or enter your group\'s room code.': 'Laisse vide pour créer une nouvelle salle privée, ou saisis le code de salle de ton groupe.', + 'Room code': 'Code de salle', + 'Co-op profile {name} added': 'Profil coop {name} ajouté', + 'Copies {name}\'s save into a new co-op profile. Your singleplayer save stays untouched.': 'Copie la sauvegarde de {name} dans un nouveau profil coop. Ta sauvegarde solo reste intacte.', + 'Co-op profile name': 'Nom du profil coop', + 'Start co-op': 'Démarrer la coop', + 'Copies {name}\'s co-op save into a new singleplayer profile.': 'Copie la sauvegarde coop de {name} dans un nouveau profil solo.', + 'Enter the 16-character room code shared by your group.': 'Saisis le code de salle à 16 caractères partagé par ton groupe.', + 'Save': 'Enregistrer', + 'Room code updated': 'Code de salle mis à jour', + 'New room code created': 'Nouveau code de salle créé', + 'Co-op relay': 'Relais coop', + 'Leave empty to use the public relay ({addr}), or enter a custom relay IPv4:port.': 'Laisse vide pour utiliser le relais public ({addr}), ou saisis un relais personnalisé IPv4:port.', + 'Relay updated': 'Relais mis à jour', + 'Member name': 'Nom du membre', + 'Member added': 'Membre ajouté', + 'Member removed': 'Membre retiré', + 'World v{version}': 'Monde v{version}', + '{count} in group': '{count} dans le groupe', }; diff --git a/launcher/src/i18n/it.js b/launcher/src/i18n/it.js index 607dbbdc..982a0a4a 100644 --- a/launcher/src/i18n/it.js +++ b/launcher/src/i18n/it.js @@ -943,4 +943,62 @@ export default { 'You no longer show as online': 'Non risulti più online', 'Online': 'Online', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': 'Lo stesso interruttore è nella Home e nelle impostazioni del gioco, nella scheda Online.', + 'Play co-op': 'Gioca in co-op', + 'This profile is a co-op save. Start it from Co-op instead, or switch to a singleplayer profile.': 'Questo profilo è un salvataggio co-op. Avvialo da Co-op oppure passa a un profilo per giocatore singolo.', + 'This profile is a co-op save. Start it from Co-op in the launcher instead, or switch to a singleplayer profile.': 'Questo profilo è un salvataggio co-op. Avvialo da Co-op nel launcher oppure passa a un profilo per giocatore singolo.', + 'This profile is a singleplayer save. Pick a co-op profile, or start co-op from a copy of it.': 'Questo profilo è un salvataggio per giocatore singolo. Scegli un profilo co-op o avvia la co-op da una sua copia.', + 'This co-op profile has no valid account ID.': 'Questo profilo co-op non ha un ID account valido.', + 'The relay on this PC is off. Turn on Run a relay on this PC on the Link Play page, or clear the relay address to use the public relay.': 'Il relay su questo PC è spento. Attiva Esegui un relay su questo PC nella pagina Link Play, o svuota l\'indirizzo per usare il relay pubblico.', + 'Cannot make a room code: {1}': 'Impossibile creare il codice stanza: {1}', + 'Type a 16-character room code (XXXX-XXXX-XXXX-XXXX).': 'Inserisci un codice stanza di 16 caratteri (XXXX-XXXX-XXXX-XXXX).', + 'Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.': 'Inserisci un indirizzo relay come 203.0.113.5:47610, o lascia vuoto per il relay pubblico.', + 'A member\'s network ID must be 32 hex digits.': 'L\'ID di rete di un membro deve avere 32 cifre esadecimali.', + 'A member\'s role must be host or visitor.': 'Il ruolo di un membro deve essere host o visitatore.', + '{1} is already in the group.': '{1} è già nel gruppo.', + 'That profile has no save to copy yet.': 'Questo profilo non ha ancora un salvataggio da copiare.', + 'That save has a write the game did not finish. Start the game once on that profile, then try again.': 'Questo salvataggio ha una scrittura non completata. Avvia il gioco una volta con quel profilo e riprova.', + 'Pick a singleplayer profile to start co-op from.': 'Scegli un profilo giocatore singolo da cui avviare la co-op.', + 'Cannot make an id for the profile.': 'Impossibile creare un ID per il profilo.', + 'That profile is already a singleplayer profile.': 'Questo profilo è già per giocatore singolo.', + 'That profile is not a co-op profile.': 'Questo profilo non è un profilo co-op.', + '{1} already holds a save.': '{1} contiene già un salvataggio.', + 'Co-op: {name}': 'Co-op: {name}', + 'New co-op profile': 'Nuovo profilo co-op', + 'Start coop from my singleplayer save': 'Avvia co-op dal mio salvataggio giocatore singolo', + 'Co-op': 'Co-op', + 'Co-op saves': 'Salvataggi co-op', + 'Co-op saves use their own folder, apply co-op settings in the environment for that launch only (without touching pkp.ini), and connect to a private room on the relay.': 'I salvataggi co-op usano una propria cartella, applicano le impostazioni co-op nell\'ambiente solo per quell\'avvio (senza toccare pkp.ini) e si collegano a una stanza privata sul relay.', + 'Public relay ({addr})': 'Relay pubblico ({addr})', + 'Visitor': 'Visitatore', + 'Co-op profile': 'Profilo co-op', + 'New': 'Nuovo', + 'New code': 'Nuovo codice', + 'Private room code': 'Codice stanza privata', + 'Relay': 'Relay', + 'World version': 'Versione del mondo', + 'Group members': 'Membri del gruppo', + 'Add member': 'Aggiungi membro', + 'Copy to singleplayer': 'Copia in giocatore singolo', + 'Private co-op rooms never appear on the public room list. Co-op settings are passed for that launch only and never saved to pkp.ini.': 'Le stanze co-op private non compaiono mai nell\'elenco pubblico. Le impostazioni co-op vengono passate solo per quell\'avvio e mai salvate in pkp.ini.', + 'Starts a co-op save in its own folder with a private room on the relay.': 'Avvia un salvataggio co-op nella sua cartella con una stanza privata sul relay.', + 'Next': 'Avanti', + 'Leave blank to make a new private room, or enter your group\'s room code.': 'Lascia vuoto per creare una nuova stanza privata, o inserisci il codice stanza del tuo gruppo.', + 'Room code': 'Codice stanza', + 'Co-op profile {name} added': 'Profilo co-op {name} aggiunto', + 'Copies {name}\'s save into a new co-op profile. Your singleplayer save stays untouched.': 'Copia il salvataggio di {name} in un nuovo profilo co-op. Il salvataggio per giocatore singolo resta intatto.', + 'Co-op profile name': 'Nome profilo co-op', + 'Start co-op': 'Avvia co-op', + 'Copies {name}\'s co-op save into a new singleplayer profile.': 'Copia il salvataggio co-op di {name} in un nuovo profilo per giocatore singolo.', + 'Enter the 16-character room code shared by your group.': 'Inserisci il codice stanza di 16 caratteri condiviso dal tuo gruppo.', + 'Save': 'Salva', + 'Room code updated': 'Codice stanza aggiornato', + 'New room code created': 'Nuovo codice stanza creato', + 'Co-op relay': 'Relay co-op', + 'Leave empty to use the public relay ({addr}), or enter a custom relay IPv4:port.': 'Lascia vuoto per usare il relay pubblico ({addr}), o inserisci un relay personalizzato IPv4:porta.', + 'Relay updated': 'Relay aggiornato', + 'Member name': 'Nome membro', + 'Member added': 'Membro aggiunto', + 'Member removed': 'Membro rimosso', + 'World v{version}': 'Mondo v{version}', + '{count} in group': '{count} nel gruppo', }; diff --git a/launcher/src/i18n/ja.js b/launcher/src/i18n/ja.js index b5565301..1129fcdc 100644 --- a/launcher/src/i18n/ja.js +++ b/launcher/src/i18n/ja.js @@ -943,4 +943,62 @@ export default { 'You no longer show as online': 'オンラインとして表示されなくなりました', 'Online': 'オンライン', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': '同じスイッチがホームとゲーム内の設定の「Online」タブにあります。', + 'Play co-op': '協力プレイを開始', + 'This profile is a co-op save. Start it from Co-op instead, or switch to a singleplayer profile.': 'このプロフィールは協力プレイ用セーブです。Co-op から起動するか、シングルプレイ用プロフィールに切り替えてください。', + 'This profile is a co-op save. Start it from Co-op in the launcher instead, or switch to a singleplayer profile.': 'このプロフィールは協力プレイ用セーブです。ランチャーの Co-op から起動するか、シングルプレイ用プロフィールに切り替えてください。', + 'This profile is a singleplayer save. Pick a co-op profile, or start co-op from a copy of it.': 'このプロフィールはシングルプレイ用セーブです。協力プレイ用プロフィールを選ぶか、コピーから協力プレイを開始してください。', + 'This co-op profile has no valid account ID.': 'この協力プレイ用プロフィールには有効なアカウントIDがありません。', + 'The relay on this PC is off. Turn on Run a relay on this PC on the Link Play page, or clear the relay address to use the public relay.': 'このPCのリレーがオフです。Link Play ページで「このPCでリレーを実行」をオンにするか、リレーアドレスを空にして公開リレーを使用してください。', + 'Cannot make a room code: {1}': 'ルームコードを作成できません: {1}', + 'Type a 16-character room code (XXXX-XXXX-XXXX-XXXX).': '16文字のルームコードを入力してください (XXXX-XXXX-XXXX-XXXX)。', + 'Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.': '203.0.113.5:47610 のようなリレーアドレスを入力するか、公開リレーを使う場合は空のままにしてください。', + 'A member\'s network ID must be 32 hex digits.': 'メンバーのネットワークIDは32桁の16進数である必要があります。', + 'A member\'s role must be host or visitor.': 'メンバーの役割は host または visitor である必要があります。', + '{1} is already in the group.': '{1} はすでにグループにいます。', + 'That profile has no save to copy yet.': 'そのプロフィールにはまだコピーできるセーブがありません。', + 'That save has a write the game did not finish. Start the game once on that profile, then try again.': 'そのセーブには未完了の書き込みがあります。そのプロフィールで一度ゲームを起動してからやり直してください。', + 'Pick a singleplayer profile to start co-op from.': '協力プレイの元にするシングルプレイ用プロフィールを選んでください。', + 'Cannot make an id for the profile.': 'プロフィールのIDを作成できません。', + 'That profile is already a singleplayer profile.': 'そのプロフィールはすでにシングルプレイ用です。', + 'That profile is not a co-op profile.': 'そのプロフィールは協力プレイ用ではありません。', + '{1} already holds a save.': '{1} にはすでにセーブがあります。', + 'Co-op: {name}': 'Co-op: {name}', + 'New co-op profile': '新しい Co-op プロフィール', + 'Start coop from my singleplayer save': 'シングルプレイのセーブから Co-op を開始', + 'Co-op': 'Co-op', + 'Co-op saves': 'Co-op セーブ', + 'Co-op saves use their own folder, apply co-op settings in the environment for that launch only (without touching pkp.ini), and connect to a private room on the relay.': 'Co-op セーブは専用フォルダーを使い、起動時のみ環境変数で Co-op 設定を適用し(pkp.ini は変更しません)、リレー上のプライベートルームに接続します。', + 'Public relay ({addr})': '公開リレー ({addr})', + 'Visitor': 'ビジター', + 'Co-op profile': 'Co-op プロフィール', + 'New': '新規', + 'New code': '新しいコード', + 'Private room code': 'プライベートルームコード', + 'Relay': 'リレー', + 'World version': 'ワールドバージョン', + 'Group members': 'グループメンバー', + 'Add member': 'メンバーを追加', + 'Copy to singleplayer': 'シングルプレイにコピー', + 'Private co-op rooms never appear on the public room list. Co-op settings are passed for that launch only and never saved to pkp.ini.': 'プライベート Co-op ルームは公開ルーム一覧に表示されません。Co-op 設定はその起動時のみ渡され、pkp.ini には保存されません。', + 'Starts a co-op save in its own folder with a private room on the relay.': 'リレー上のプライベートルームと専用フォルダーで Co-op セーブを作成します。', + 'Next': '次へ', + 'Leave blank to make a new private room, or enter your group\'s room code.': '新しいプライベートルームを作る場合は空のままにし、参加する場合はグループのルームコードを入力してください。', + 'Room code': 'ルームコード', + 'Co-op profile {name} added': 'Co-op プロフィール「{name}」を追加しました', + 'Copies {name}\'s save into a new co-op profile. Your singleplayer save stays untouched.': '{name} のセーブを新しい Co-op プロフィールにコピーします。シングルプレイのセーブはそのまま残ります。', + 'Co-op profile name': 'Co-op プロフィール名', + 'Start co-op': 'Co-op を開始', + 'Copies {name}\'s co-op save into a new singleplayer profile.': '{name} の Co-op セーブを新しいシングルプレイ用プロフィールにコピーします。', + 'Enter the 16-character room code shared by your group.': 'グループで共有している16文字のルームコードを入力してください。', + 'Save': '保存', + 'Room code updated': 'ルームコードを更新しました', + 'New room code created': '新しいルームコードを作成しました', + 'Co-op relay': 'Co-op リレー', + 'Leave empty to use the public relay ({addr}), or enter a custom relay IPv4:port.': '公開リレー ({addr}) を使う場合は空にし、独自のリレーを使う場合は IPv4:port を入力してください。', + 'Relay updated': 'リレーを更新しました', + 'Member name': 'メンバー名', + 'Member added': 'メンバーを追加しました', + 'Member removed': 'メンバーを削除しました', + 'World v{version}': 'ワールド v{version}', + '{count} in group': '{count} 人', }; diff --git a/launcher/src/i18n/ko.js b/launcher/src/i18n/ko.js index 4fa7dc67..a7b4f38e 100644 --- a/launcher/src/i18n/ko.js +++ b/launcher/src/i18n/ko.js @@ -943,4 +943,62 @@ export default { 'You no longer show as online': '더 이상 온라인으로 표시되지 않습니다', 'Online': '온라인', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': '같은 스위치가 홈과 게임 자체 설정의 Online 탭에 있습니다.', + 'Play co-op': '협동 플레이 시작', + 'This profile is a co-op save. Start it from Co-op instead, or switch to a singleplayer profile.': '이 프로필은 협동 저장 데이터입니다. Co-op에서 시작하거나 싱글플레이 프로필로 전환하세요.', + 'This profile is a co-op save. Start it from Co-op in the launcher instead, or switch to a singleplayer profile.': '이 프로필은 협동 저장 데이터입니다. 런처의 Co-op에서 시작하거나 싱글플레이 프로필로 전환하세요.', + 'This profile is a singleplayer save. Pick a co-op profile, or start co-op from a copy of it.': '이 프로필은 싱글플레이 저장 데이터입니다. Co-op 프로필을 선택하거나 복사본으로 협동을 시작하세요.', + 'This co-op profile has no valid account ID.': '이 Co-op 프로필에 유효한 계정 ID가 없습니다.', + 'The relay on this PC is off. Turn on Run a relay on this PC on the Link Play page, or clear the relay address to use the public relay.': '이 PC의 릴레이가 꺼져 있습니다. Link Play 페이지에서 이 PC에서 릴레이 실행을 켜거나 주소를 비워 공개 릴레이를 사용하세요.', + 'Cannot make a room code: {1}': '방 코드를 만들 수 없습니다: {1}', + 'Type a 16-character room code (XXXX-XXXX-XXXX-XXXX).': '16자리 방 코드를 입력하세요 (XXXX-XXXX-XXXX-XXXX).', + 'Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.': '203.0.113.5:47610 같은 릴레이 주소를 입력하거나 공개 릴레이를 쓰려면 비워 두세요.', + 'A member\'s network ID must be 32 hex digits.': '멤버의 네트워크 ID는 32자리 16진수여야 합니다.', + 'A member\'s role must be host or visitor.': '멤버의 역할은 host 또는 visitor여야 합니다.', + '{1} is already in the group.': '{1}님은 이미 그룹에 있습니다.', + 'That profile has no save to copy yet.': '이 프로필에는 아직 복사할 저장 데이터가 없습니다.', + 'That save has a write the game did not finish. Start the game once on that profile, then try again.': '이 저장 데이터에 완료되지 않은 쓰기가 있습니다. 해당 프로필로 게임을 한 번 실행한 뒤 다시 시도하세요.', + 'Pick a singleplayer profile to start co-op from.': '협동을 시작할 싱글플레이 프로필을 선택하세요.', + 'Cannot make an id for the profile.': '프로필 ID를 만들 수 없습니다.', + 'That profile is already a singleplayer profile.': '이 프로필은 이미 싱글플레이 프로필입니다.', + 'That profile is not a co-op profile.': '이 프로필은 Co-op 프로필이 아닙니다.', + '{1} already holds a save.': '{1}에 이미 저장 데이터가 있습니다.', + 'Co-op: {name}': 'Co-op: {name}', + 'New co-op profile': '새 Co-op 프로필', + 'Start coop from my singleplayer save': '싱글플레이 저장 데이터로 Co-op 시작', + 'Co-op': 'Co-op', + 'Co-op saves': 'Co-op 저장 데이터', + 'Co-op saves use their own folder, apply co-op settings in the environment for that launch only (without touching pkp.ini), and connect to a private room on the relay.': 'Co-op 저장 데이터는 전용 폴더를 사용하며 실행 시에만 환경 변수로 Co-op 설정을 적용하고(pkp.ini는 건드리지 않음) 릴레이의 비공개 방에 연결합니다.', + 'Public relay ({addr})': '공개 릴레이 ({addr})', + 'Visitor': '방문자', + 'Co-op profile': 'Co-op 프로필', + 'New': '새로 만들기', + 'New code': '새 코드', + 'Private room code': '비공개 방 코드', + 'Relay': '릴레이', + 'World version': '월드 버전', + 'Group members': '그룹 멤버', + 'Add member': '멤버 추가', + 'Copy to singleplayer': '싱글플레이로 복사', + 'Private co-op rooms never appear on the public room list. Co-op settings are passed for that launch only and never saved to pkp.ini.': '비공개 Co-op 방은 공개 방 목록에 표시되지 않습니다. Co-op 설정은 해당 실행에만 전달되며 pkp.ini에 저장되지 않습니다.', + 'Starts a co-op save in its own folder with a private room on the relay.': '릴레이의 비공개 방과 전용 폴더로 새 Co-op 저장 데이터를 만듭니다.', + 'Next': '다음', + 'Leave blank to make a new private room, or enter your group\'s room code.': '새 비공개 방을 만들려면 비워 두고, 기존 그룹에 참여하려면 방 코드를 입력하세요.', + 'Room code': '방 코드', + 'Co-op profile {name} added': 'Co-op 프로필 {name} 추가됨', + 'Copies {name}\'s save into a new co-op profile. Your singleplayer save stays untouched.': '{name}의 저장 데이터를 새 Co-op 프로필로 복사합니다. 싱글플레이 저장 데이터는 그대로 유지됩니다.', + 'Co-op profile name': 'Co-op 프로필 이름', + 'Start co-op': 'Co-op 시작', + 'Copies {name}\'s co-op save into a new singleplayer profile.': '{name}의 Co-op 저장 데이터를 새 싱글플레이 프로필로 복사합니다.', + 'Enter the 16-character room code shared by your group.': '그룹에서 공유한 16자리 방 코드를 입력하세요.', + 'Save': '저장', + 'Room code updated': '방 코드가 업데이트되었습니다', + 'New room code created': '새 방 코드가 생성되었습니다', + 'Co-op relay': 'Co-op 릴레이', + 'Leave empty to use the public relay ({addr}), or enter a custom relay IPv4:port.': '공개 릴레이({addr})를 사용하려면 비워 두고, 직접 릴레이 IPv4:포트를 입력하세요.', + 'Relay updated': '릴레이가 업데이트되었습니다', + 'Member name': '멤버 이름', + 'Member added': '멤버가 추가되었습니다', + 'Member removed': '멤버가 제거되었습니다', + 'World v{version}': '월드 v{version}', + '{count} in group': '그룹 {count}명', }; diff --git a/launcher/src/i18n/pt-BR.js b/launcher/src/i18n/pt-BR.js index 0e4a856e..74a72780 100644 --- a/launcher/src/i18n/pt-BR.js +++ b/launcher/src/i18n/pt-BR.js @@ -941,4 +941,62 @@ export default { 'You no longer show as online': 'Você não aparece mais como online', 'Online': 'Online', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': 'O mesmo botão está no Início e nas configurações do próprio jogo, na aba Online.', + 'Play co-op': 'Jogar co-op', + 'This profile is a co-op save. Start it from Co-op instead, or switch to a singleplayer profile.': 'Este perfil é um save co-op. Inicie pelo Co-op ou troque para um perfil de um jogador.', + 'This profile is a co-op save. Start it from Co-op in the launcher instead, or switch to a singleplayer profile.': 'Este perfil é um save co-op. Inicie pelo Co-op no launcher ou troque para um perfil de um jogador.', + 'This profile is a singleplayer save. Pick a co-op profile, or start co-op from a copy of it.': 'Este perfil é um save de um jogador. Escolha um perfil co-op ou comece o co-op a partir de uma cópia.', + 'This co-op profile has no valid account ID.': 'Este perfil co-op não tem um ID de conta válido.', + 'The relay on this PC is off. Turn on Run a relay on this PC on the Link Play page, or clear the relay address to use the public relay.': 'O relay neste PC está desligado. Ative Executar um relay neste PC na página Link Play ou limpe o endereço para usar o relay público.', + 'Cannot make a room code: {1}': 'Não foi possível criar o código da sala: {1}', + 'Type a 16-character room code (XXXX-XXXX-XXXX-XXXX).': 'Digite um código de sala de 16 caracteres (XXXX-XXXX-XXXX-XXXX).', + 'Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.': 'Digite um endereço de relay como 203.0.113.5:47610 ou deixe vazio para o relay público.', + 'A member\'s network ID must be 32 hex digits.': 'O ID de rede de um membro deve ter 32 dígitos hexadecimaux.', + 'A member\'s role must be host or visitor.': 'O papel de um membro deve ser host ou visitor.', + '{1} is already in the group.': '{1} já está no grupo.', + 'That profile has no save to copy yet.': 'Este perfil ainda não tem um save para copiar.', + 'That save has a write the game did not finish. Start the game once on that profile, then try again.': 'Esse save tem uma gravação inacabada. Abra o jogo uma vez nesse perfil e tente novamente.', + 'Pick a singleplayer profile to start co-op from.': 'Escolha um perfil de um jogador para começar o co-op.', + 'Cannot make an id for the profile.': 'Não foi possível criar um ID para o perfil.', + 'That profile is already a singleplayer profile.': 'Esse perfil já é um perfil de um jogador.', + 'That profile is not a co-op profile.': 'Esse perfil não é um perfil co-op.', + '{1} already holds a save.': '{1} já contém um save.', + 'Co-op: {name}': 'Co-op: {name}', + 'New co-op profile': 'Novo perfil co-op', + 'Start coop from my singleplayer save': 'Começar co-op do meu save de um jogador', + 'Co-op': 'Co-op', + 'Co-op saves': 'Saves co-op', + 'Co-op saves use their own folder, apply co-op settings in the environment for that launch only (without touching pkp.ini), and connect to a private room on the relay.': 'Saves co-op usam uma pasta própria, aplicam as configurações co-op no ambiente apenas nessa execução (sem alterar pkp.ini) e conectam a uma sala privada no relay.', + 'Public relay ({addr})': 'Relay público ({addr})', + 'Visitor': 'Visitante', + 'Co-op profile': 'Perfil co-op', + 'New': 'Novo', + 'New code': 'Novo código', + 'Private room code': 'Código da sala privada', + 'Relay': 'Relay', + 'World version': 'Versão do mundo', + 'Group members': 'Membros do grupo', + 'Add member': 'Adicionar membro', + 'Copy to singleplayer': 'Copiar para um jogador', + 'Private co-op rooms never appear on the public room list. Co-op settings are passed for that launch only and never saved to pkp.ini.': 'Salas co-op privadas nunca aparecem na lista pública. As configurações co-op são enviadas só nessa execução e nunca salvas em pkp.ini.', + 'Starts a co-op save in its own folder with a private room on the relay.': 'Cria um save co-op em pasta própria com uma sala privada no relay.', + 'Next': 'Avançar', + 'Leave blank to make a new private room, or enter your group\'s room code.': 'Deixe em branco para criar uma nova sala privada ou digite o código da sala do seu grupo.', + 'Room code': 'Código da sala', + 'Co-op profile {name} added': 'Perfil co-op {name} adicionado', + 'Copies {name}\'s save into a new co-op profile. Your singleplayer save stays untouched.': 'Copia o save de {name} para um novo perfil co-op. Seu save de um jogador permanece intacto.', + 'Co-op profile name': 'Nome do perfil co-op', + 'Start co-op': 'Começar co-op', + 'Copies {name}\'s co-op save into a new singleplayer profile.': 'Copia o save co-op de {name} para um novo perfil de um jogador.', + 'Enter the 16-character room code shared by your group.': 'Digite o código de sala de 16 caracteres compartilhado pelo seu grupo.', + 'Save': 'Salvar', + 'Room code updated': 'Código da sala atualizado', + 'New room code created': 'Novo código de sala criado', + 'Co-op relay': 'Relay co-op', + 'Leave empty to use the public relay ({addr}), or enter a custom relay IPv4:port.': 'Deixe vazio para usar o relay público ({addr}) ou digite um relay IPv4:porta.', + 'Relay updated': 'Relay atualizado', + 'Member name': 'Nome do membro', + 'Member added': 'Membro adicionado', + 'Member removed': 'Membro removido', + 'World v{version}': 'Mundo v{version}', + '{count} in group': '{count} no grupo', }; diff --git a/launcher/src/i18n/zh-CN.js b/launcher/src/i18n/zh-CN.js index 07d16a3f..93118189 100644 --- a/launcher/src/i18n/zh-CN.js +++ b/launcher/src/i18n/zh-CN.js @@ -943,4 +943,62 @@ export default { 'You no longer show as online': '你不再显示为在线', 'Online': '在线', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': '同一个开关也在主页和游戏自身设置的 Online 标签页中。', + 'Play co-op': '开始联机合作', + 'This profile is a co-op save. Start it from Co-op instead, or switch to a singleplayer profile.': '该配置文件是合作存档。请从合作模式启动,或切换到单人配置文件。', + 'This profile is a co-op save. Start it from Co-op in the launcher instead, or switch to a singleplayer profile.': '该配置文件是合作存档。请在启动器中从合作模式启动,或切换到单人配置文件。', + 'This profile is a singleplayer save. Pick a co-op profile, or start co-op from a copy of it.': '该配置文件是单人存档。请选择一个合作配置文件,或从其副本开始合作。', + 'This co-op profile has no valid account ID.': '该合作配置文件没有有效的账户 ID。', + 'The relay on this PC is off. Turn on Run a relay on this PC on the Link Play page, or clear the relay address to use the public relay.': '本机中继未开启。请在 Link Play 页面开启“在此电脑运行中继”,或清空地址以使用公共中继。', + 'Cannot make a room code: {1}': '无法生成房间代码:{1}', + 'Type a 16-character room code (XXXX-XXXX-XXXX-XXXX).': '请输入 16 位房间代码 (XXXX-XXXX-XXXX-XXXX)。', + 'Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.': '请输入中继地址(例如 203.0.113.5:47610),或留空以使用公共中继。', + 'A member\'s network ID must be 32 hex digits.': '成员的网络 ID 必须是 32 位十六进制数字。', + 'A member\'s role must be host or visitor.': '成员角色必须是 host 或 visitor。', + '{1} is already in the group.': '{1} 已在群组中。', + 'That profile has no save to copy yet.': '该配置文件还没有可复制的存档。', + 'That save has a write the game did not finish. Start the game once on that profile, then try again.': '该存档存在未完成的写入。请先用该配置文件启动一次游戏,然后再试。', + 'Pick a singleplayer profile to start co-op from.': '请选择要从其开始合作的单人配置文件。', + 'Cannot make an id for the profile.': '无法为配置文件生成 ID。', + 'That profile is already a singleplayer profile.': '该配置文件已经是单人配置文件。', + 'That profile is not a co-op profile.': '该配置文件不是合作配置文件。', + '{1} already holds a save.': '{1} 中已有存档。', + 'Co-op: {name}': '合作:{name}', + 'New co-op profile': '新建合作配置文件', + 'Start coop from my singleplayer save': '从我的单人存档开始合作', + 'Co-op': '合作', + 'Co-op saves': '合作存档', + 'Co-op saves use their own folder, apply co-op settings in the environment for that launch only (without touching pkp.ini), and connect to a private room on the relay.': '合作存档使用独立文件夹,仅在本次启动时通过环境变量应用合作设置(不修改 pkp.ini),并连接到中继上的私密房间。', + 'Public relay ({addr})': '公共中继 ({addr})', + 'Visitor': '访客', + 'Co-op profile': '合作配置文件', + 'New': '新建', + 'New code': '新代码', + 'Private room code': '私密房间代码', + 'Relay': '中继', + 'World version': '世界版本', + 'Group members': '群组成员', + 'Add member': '添加成员', + 'Copy to singleplayer': '复制到单人模式', + 'Private co-op rooms never appear on the public room list. Co-op settings are passed for that launch only and never saved to pkp.ini.': '私密合作房间绝不会出现在公共房间列表中。合作设置仅在本次启动时传入,绝不写入 pkp.ini。', + 'Starts a co-op save in its own folder with a private room on the relay.': '在独立文件夹中创建合作存档,并使用中继上的私密房间。', + 'Next': '下一步', + 'Leave blank to make a new private room, or enter your group\'s room code.': '留空以创建新私密房间,或输入你们群组的房间代码。', + 'Room code': '房间代码', + 'Co-op profile {name} added': '已添加合作配置文件 {name}', + 'Copies {name}\'s save into a new co-op profile. Your singleplayer save stays untouched.': '将 {name} 的存档复制到新的合作配置文件中。你的单人存档不会被修改。', + 'Co-op profile name': '合作配置文件名称', + 'Start co-op': '开始合作', + 'Copies {name}\'s co-op save into a new singleplayer profile.': '将 {name} 的合作存档复制到新的单人配置文件中。', + 'Enter the 16-character room code shared by your group.': '请输入群组共享的 16 位房间代码。', + 'Save': '保存', + 'Room code updated': '房间代码已更新', + 'New room code created': '已生成新房间代码', + 'Co-op relay': '合作中继', + 'Leave empty to use the public relay ({addr}), or enter a custom relay IPv4:port.': '留空以使用公共中继 ({addr}),或输入自定义中继 IPv4:端口。', + 'Relay updated': '中继已更新', + 'Member name': '成员名称', + 'Member added': '已添加成员', + 'Member removed': '已移除成员', + 'World v{version}': '世界 v{version}', + '{count} in group': '群组 {count} 人', }; diff --git a/launcher/src/i18n/zh-TW.js b/launcher/src/i18n/zh-TW.js index 772f36c8..3c94d75e 100644 --- a/launcher/src/i18n/zh-TW.js +++ b/launcher/src/i18n/zh-TW.js @@ -943,4 +943,62 @@ export default { 'You no longer show as online': '你不再顯示為線上', 'Online': '線上', 'The same switch is on Home and in the game\'s own Settings, on the Online tab.': '同一個開關也在首頁和遊戲本身設定的 Online 分頁中。', + 'Play co-op': '開始合作遊玩', + 'This profile is a co-op save. Start it from Co-op instead, or switch to a singleplayer profile.': '此設定檔為合作存檔。請從合作模式啟動,或切換至單人設定檔。', + 'This profile is a co-op save. Start it from Co-op in the launcher instead, or switch to a singleplayer profile.': '此設定檔為合作存檔。請在啟動器中從合作模式啟動,或切換至單人設定檔。', + 'This profile is a singleplayer save. Pick a co-op profile, or start co-op from a copy of it.': '此設定檔為單人存檔。請選擇一個合作設定檔,或從其複本開始合作。', + 'This co-op profile has no valid account ID.': '此合作設定檔沒有有效的帳號 ID。', + 'The relay on this PC is off. Turn on Run a relay on this PC on the Link Play page, or clear the relay address to use the public relay.': '此電腦上的中繼已關閉。請在 Link Play 頁面開啟「在此電腦執行中繼」,或清除位址以使用公開中繼。', + 'Cannot make a room code: {1}': '無法建立房間代碼:{1}', + 'Type a 16-character room code (XXXX-XXXX-XXXX-XXXX).': '請輸入 16 字元房間代碼 (XXXX-XXXX-XXXX-XXXX)。', + 'Type a relay address like 203.0.113.5:47610, or leave it empty for the public relay.': '請輸入中繼位址(例如 203.0.113.5:47610),或留空以使用公開中繼。', + 'A member\'s network ID must be 32 hex digits.': '成員的網路 ID 必須為 32 位十六進位數字。', + 'A member\'s role must be host or visitor.': '成員角色必須為 host 或 visitor。', + '{1} is already in the group.': '{1} 已在群組中。', + 'That profile has no save to copy yet.': '此設定檔尚無可複製的存檔。', + 'That save has a write the game did not finish. Start the game once on that profile, then try again.': '此存檔有尚未完成的寫入。請先用該設定檔啟動一次遊戲,再試一次。', + 'Pick a singleplayer profile to start co-op from.': '請選擇要從其開始合作的單人設定檔。', + 'Cannot make an id for the profile.': '無法為設定檔建立 ID。', + 'That profile is already a singleplayer profile.': '此設定檔已經是單人設定檔。', + 'That profile is not a co-op profile.': '此設定檔不是合作設定檔。', + '{1} already holds a save.': '{1} 已有存檔。', + 'Co-op: {name}': '合作:{name}', + 'New co-op profile': '新增合作設定檔', + 'Start coop from my singleplayer save': '從我的單人存檔開始合作', + 'Co-op': '合作', + 'Co-op saves': '合作存檔', + 'Co-op saves use their own folder, apply co-op settings in the environment for that launch only (without touching pkp.ini), and connect to a private room on the relay.': '合作存檔使用獨立資料夾,僅在本次啟動時透過環境變數套用合作設定(不修改 pkp.ini),並連線到中繼上的私人房間。', + 'Public relay ({addr})': '公開中繼 ({addr})', + 'Visitor': '訪客', + 'Co-op profile': '合作設定檔', + 'New': '新增', + 'New code': '新代碼', + 'Private room code': '私人房間代碼', + 'Relay': '中繼', + 'World version': '世界版本', + 'Group members': '群組成員', + 'Add member': '新增成員', + 'Copy to singleplayer': '複製到單人模式', + 'Private co-op rooms never appear on the public room list. Co-op settings are passed for that launch only and never saved to pkp.ini.': '私人合作房間絕不會出現在公開房間清單中。合作設定僅在本次啟動時傳入,絕不寫入 pkp.ini。', + 'Starts a co-op save in its own folder with a private room on the relay.': '在獨立資料夾中建立合作存檔,並使用中繼上的私人房間。', + 'Next': '下一步', + 'Leave blank to make a new private room, or enter your group\'s room code.': '留空以建立新的私人房間,或輸入你們群組的房間代碼。', + 'Room code': '房間代碼', + 'Co-op profile {name} added': '已新增合作設定檔 {name}', + 'Copies {name}\'s save into a new co-op profile. Your singleplayer save stays untouched.': '將 {name} 的存檔複製到新的合作設定檔中。你的單人存檔不會被更動。', + 'Co-op profile name': '合作設定檔名稱', + 'Start co-op': '開始合作', + 'Copies {name}\'s co-op save into a new singleplayer profile.': '將 {name} 的合作存檔複製到新的單人設定檔中。', + 'Enter the 16-character room code shared by your group.': '請輸入群組共享的 16 字元房間代碼。', + 'Save': '儲存', + 'Room code updated': '房間代碼已更新', + 'New room code created': '已產生新房間代碼', + 'Co-op relay': '合作中繼', + 'Leave empty to use the public relay ({addr}), or enter a custom relay IPv4:port.': '留空以使用公開中繼 ({addr}),或輸入自訂中繼 IPv4:連接埠。', + 'Relay updated': '中繼已更新', + 'Member name': '成員名稱', + 'Member added': '已新增成員', + 'Member removed': '已移除成員', + 'World v{version}': '世界 v{version}', + '{count} in group': '群組 {count} 人', }; diff --git a/launcher/src/pages/home.js b/launcher/src/pages/home.js index 49ddb39c..cd9d77c8 100644 --- a/launcher/src/pages/home.js +++ b/launcher/src/pages/home.js @@ -168,7 +168,10 @@ export function render(el, ctx) { case 'cancel': return store.cancelUpdate(); case 'pause': return store.pauseSetup(); case 'stop-repack': return store.cancelRepack(); - case 'play-without-mods': return store.play({ withoutMods: true }); + case 'play-without-mods': { + const active = store.state.profiles?.profiles?.find((p) => p.id === store.state.profiles.active); + return active?.coop ? store.playCoop({ withoutMods: true }) : store.play({ withoutMods: true }); + } case 'dismiss': crashDismissed = true; return draw(store.state); @@ -208,7 +211,7 @@ export function render(el, ctx) { }).catch((e) => console.warn('read_settings', e)); // with more than one profile the player picks who plays here; the choice is the Settings > Saves list const profileSelect = (list, busy) => ``; + list.profiles.map((p) => ``).join('')}`; // the play time is the active profile's save's, as the game counted it; a save not played since that count began shows none const loadProfiles = () => Promise.all([api.profilesList(), api.profilesPlayTime().catch(() => ({}))]).then(([list, times]) => { profileChip = list.profiles.length > 1 ? profileSelect(list, ['starting', 'running', 'finishing'].includes(gamePhase(store.state.game))) : ''; @@ -229,6 +232,7 @@ export function render(el, ctx) { if (e.target.id !== 'profile-pick') return; try { await api.profileSelect({ id: e.target.value }); + await store.refreshProfiles(); } catch (err) { toast(errText(err), 'error'); } diff --git a/launcher/src/pages/linkplay-coop.js b/launcher/src/pages/linkplay-coop.js new file mode 100644 index 00000000..73150c59 --- /dev/null +++ b/launcher/src/pages/linkplay-coop.js @@ -0,0 +1,211 @@ +// Co-op profiles on the Link Play page: private room code, relay, group members, world version and co-op launch. +import { api } from '../api.js'; +import { num, t } from '../i18n.js'; +import { askText, errText, esc, group, icon, row, select, toast } from '../ui.js'; +import { store } from '../store.js'; +import { PUBLIC_RELAY } from '../linkplay-model.js'; +import { activeProfileOf, coopProfiles, relayProblem, roomCodeProblem, singleplayerProfiles } from '../coop-model.js'; + +export function createCoopSection(host, { copy, gameActive }) { + let profileStore = store.state.profiles; + let pickedId = ''; + + const currentCoop = () => { + const list = coopProfiles(profileStore); + if (!list.length) return null; + const picked = list.find((p) => p.id === pickedId); + if (picked) return picked; + const active = activeProfileOf(profileStore); + return active?.coop ? active : list[0]; + }; + + async function refresh() { + try { + profileStore = await api.profilesList(); + store.refreshProfiles(); + draw(); + } catch (e) { + console.warn('profiles_list', e); + } + } + + async function runUpdate(fn, done) { + try { + profileStore = await fn(); + await store.refreshProfiles(); + draw(); + if (done) toast(done, 'ok'); + } catch (e) { + toast(errText(e), 'error'); + } + } + + function draw() { + if (!host) return; + const busy = gameActive(store.state) || !!store.state.starting || !!store.state.task; + const list = coopProfiles(profileStore); + const spList = singleplayerProfiles(profileStore); + const cp = currentCoop(); + + if (!cp) { + const sp = spList[0]; + const actions = [ + ``, + ...(sp ? [``] : []), + ].join(''); + host.innerHTML = group(t('Co-op'), [ + row(t('Co-op saves'), `
${actions}
`), + ]) + ``; + return; + } + + pickedId = cp.id; + const coop = cp.coop; + const relayText = coop.relay ? coop.relay : t('Public relay ({addr})', { addr: PUBLIC_RELAY }); + const members = coop.members ?? []; + const memberRows = members.map((m, i) => row( + m.name, + `${esc(m.role === 'host' ? t('Host') : m.role === 'visitor' ? t('Visitor') : '')} + `, + )); + + const headerCtrl = `
+ ${list.length > 1 ? select('lp-coop-pick', list.map((p) => [p.id, p.name]), cp.id, { label: t('Co-op profile') }) : `${esc(cp.name)}`} + + +
`; + + const codeCtrl = `
+ ${esc(coop.room_code)} + + + +
`; + + const relayCtrl = `
+ ${esc(relayText)} + +
`; + + const spBtn = spList[0] + ? `` + : ''; + + const html = group(t('Co-op'), [ + row(t('Co-op profile'), headerCtrl), + row(t('Private room code'), codeCtrl), + row(t('Relay'), relayCtrl), + row(t('World version'), `v${esc(num(coop.world_version ?? 0))}`), + ...memberRows, + row(t('Group members'), `
+ + + ${spBtn} +
`), + ]) + ``; + + if (host.dataset.html !== html) { + host.innerHTML = html; + host.dataset.html = html; + } + } + + host.addEventListener('change', (e) => { + if (e.target.id !== 'lp-coop-pick') return; + pickedId = e.target.value; + draw(); + }); + + host.addEventListener('click', async (e) => { + const btn = e.target.closest('[data-coop]'); + if (!btn || btn.disabled) return; + const cp = currentCoop(); + switch (btn.dataset.coop) { + case 'play': + if (cp) store.playCoop({ id: cp.id }); + return; + case 'copy-code': + if (cp) copy(cp.coop.room_code); + return; + case 'new': { + const name = await askText({ title: t('New co-op profile'), body: t('Starts a co-op save in its own folder with a private room on the relay.'), label: t('Profile name'), ok: t('Next') }); + if (name === '') return toast(t('Type a name for the profile'), 'error'); + if (!name) return; + const code = await askText({ title: t('Private room code'), body: t('Leave blank to make a new private room, or enter your group\'s room code.'), label: t('Room code'), ok: t('Add'), max: 24 }); + if (code === null) return; + if (code && roomCodeProblem(code, { optional: true })) return toast(roomCodeProblem(code, { optional: true }), 'error'); + await runUpdate(async () => { + const s = await api.profileAddCoop({ name, roomCode: code || null, relay: null }); + pickedId = s.profiles[s.profiles.length - 1]?.id ?? ''; + return s; + }, t('Co-op profile {name} added', { name })); + return; + } + case 'from-sp': { + const sourceId = btn.dataset.id; + const sourceName = btn.dataset.name; + const name = await askText({ title: t('Start coop from my singleplayer save'), body: t('Copies {name}\'s save into a new co-op profile. Your singleplayer save stays untouched.', { name: sourceName }), label: t('Co-op profile name'), value: `${sourceName} Co-op`.slice(0, 24), ok: t('Next') }); + if (name === '') return toast(t('Type a name for the profile'), 'error'); + if (!name) return; + const code = await askText({ title: t('Private room code'), body: t('Leave blank to make a new private room, or enter your group\'s room code.'), label: t('Room code'), ok: t('Start co-op'), max: 24 }); + if (code === null) return; + if (code && roomCodeProblem(code, { optional: true })) return toast(roomCodeProblem(code, { optional: true }), 'error'); + await runUpdate(async () => { + const s = await api.profileStartCoopFrom({ sourceId, name, roomCode: code || null, relay: null }); + pickedId = s.profiles[s.profiles.length - 1]?.id ?? ''; + return s; + }, t('Co-op profile {name} added', { name })); + return; + } + case 'to-sp': { + if (!cp) return; + const name = await askText({ title: t('Copy to singleplayer'), body: t('Copies {name}\'s co-op save into a new singleplayer profile.', { name: cp.name }), label: t('Profile name'), ok: t('Copy') }); + if (name === '') return toast(t('Type a name for the profile'), 'error'); + if (!name) return; + await runUpdate(() => api.profileCopyToSingleplayer({ sourceId: cp.id, name }), t('Profile {name} added', { name })); + return; + } + case 'edit-code': { + if (!cp) return; + const code = await askText({ title: t('Private room code'), body: t('Enter the 16-character room code shared by your group.'), label: t('Room code'), value: cp.coop.room_code, ok: t('Save'), max: 24 }); + if (code === null) return; + const prob = roomCodeProblem(code); + if (prob) return toast(prob, 'error'); + await runUpdate(() => api.profileCoopUpdate({ id: cp.id, roomCode: code, relay: null, members: null }), t('Room code updated')); + return; + } + case 'new-code': + if (!cp) return; + await runUpdate(() => api.profileCoopUpdate({ id: cp.id, roomCode: '', relay: null, members: null }), t('New room code created')); + return; + case 'edit-relay': { + if (!cp) return; + const relay = await askText({ title: t('Co-op relay'), body: t('Leave empty to use the public relay ({addr}), or enter a custom relay IPv4:port.', { addr: PUBLIC_RELAY }), label: t('Relay address'), value: cp.coop.relay, ok: t('Save'), max: 32 }); + if (relay === null) return; + const prob = relayProblem(relay); + if (prob) return toast(prob, 'error'); + await runUpdate(() => api.profileCoopUpdate({ id: cp.id, roomCode: null, relay, members: null }), t('Relay updated')); + return; + } + case 'add-member': { + if (!cp) return; + const name = await askText({ title: t('Add member'), label: t('Member name'), ok: t('Add') }); + if (name === '') return toast(t('Type a name for the profile'), 'error'); + if (!name) return; + const members = [...(cp.coop.members ?? []), { name, net_uid: '', role: 'visitor' }]; + await runUpdate(() => api.profileCoopUpdate({ id: cp.id, roomCode: null, relay: null, members }), t('Member added')); + return; + } + case 'rm-member': { + if (!cp) return; + const idx = Number(btn.dataset.idx); + const members = (cp.coop.members ?? []).filter((_, i) => i !== idx); + await runUpdate(() => api.profileCoopUpdate({ id: cp.id, roomCode: null, relay: null, members }), t('Member removed')); + return; + } + } + }); + + refresh(); + return { draw, refresh }; +} diff --git a/launcher/src/pages/linkplay.js b/launcher/src/pages/linkplay.js index 213ea235..8d9d0824 100644 --- a/launcher/src/pages/linkplay.js +++ b/launcher/src/pages/linkplay.js @@ -12,6 +12,7 @@ import { HOST_PORT, RELAY_PORT, addrProblem, addressRows, applyEdits, editsFor, interactEdits, internetShare, pathParts, protocolEdits, readIni, relayPort, storyEdits, uiFrom, } from '../linkplay-model.js'; +import { createCoopSection } from './linkplay-coop.js'; const LS = 'pkp.linkplay'; const POLL_MS = 3000; // this PC's relay and its link count, while the own-relay Host view is on screen @@ -346,6 +347,7 @@ export async function render(el, ctx) {
+
`; el.addEventListener('input', (e) => { @@ -388,7 +390,12 @@ export async function render(el, ctx) { else if (t.dataset.act === 'switch') inOrder(async () => { await save(protocolEdits()); draw(); }); }); - ctx.on(() => drawChrome()); + const coopSection = createCoopSection(part('lp-coop'), { copy, gameActive }); + + ctx.on(() => { + drawChrome(); + coopSection.draw(); + }); const timer = setInterval(async () => { if (document.hidden || !isHost()) return; diff --git a/launcher/src/pages/settings.js b/launcher/src/pages/settings.js index 95120906..5e78b374 100644 --- a/launcher/src/pages/settings.js +++ b/launcher/src/pages/settings.js @@ -91,7 +91,10 @@ export async function render(el, ctx) { const active = h.env().gameBusy; const dlssEnded = hadDlss && !s.dlss; hadDlss = !!s.dlss; - if ((wasActive && !active) || dlssEnded) h.reload().catch((e) => console.error(e)); // the game writes its settings as it leaves + if ((wasActive && !active) || dlssEnded) { + h.reload().catch((e) => console.error(e)); // the game writes its settings as it leaves + modules.forEach((m) => m.reload?.()); + } else if (why !== 'setup' || st.section === 'game') h.draw(); wasActive = active; }); diff --git a/launcher/src/pages/settings/profiles.js b/launcher/src/pages/settings/profiles.js index ddd0906e..ab25b7e0 100644 --- a/launcher/src/pages/settings/profiles.js +++ b/launcher/src/pages/settings/profiles.js @@ -1,16 +1,29 @@ // Save profiles: add, switch, rename, remove. Each goes through changeProfiles: flush pending edits, run the command, reload the // settings (a profile has its own save folder), say what happened. import { api } from '../../api.js'; -import { num, t } from '../../i18n.js'; +import { t } from '../../i18n.js'; +import { store } from '../../store.js'; import { askText, confirm, errText, toast } from '../../ui.js'; export function createProfileActions(h) { const { st } = h; + function loadLists() { + api.profilesList().then((list) => { + st.profiles = list; + h.draw(); + }).catch((e) => console.warn('profiles_list', e)); + api.profilesPlayTime().then((times) => { + st.playTimes = times; + h.draw(); + }).catch((e) => console.warn('profiles_play_time', e)); + } + async function changeProfiles(command, args, done) { try { await h.flush(); st.profiles = await command(args); + await store.refreshProfiles(); await h.reload(); toast(done, 'ok'); } catch (e) { @@ -20,22 +33,35 @@ export function createProfileActions(h) { } return { - load() { - api.profilesList().then((list) => { - st.profiles = list; - h.draw(); - }).catch((e) => console.warn('profiles_list', e)); - api.profilesPlayTime().then((times) => { - st.playTimes = times; - h.draw(); - }).catch((e) => console.warn('profiles_play_time', e)); - }, + load: loadLists, + reload: loadLists, actions: { async 'profile-new'() { const name = await askText({ title: t('New profile'), body: t('It starts with an empty save. Your other saves are not touched.'), label: t('Profile name'), ok: t('Add') }); if (name === '') toast(t('Type a name for the profile'), 'error'); else if (name) await changeProfiles(api.profileAdd, { name }, t('Profile {name} added', { name })); }, + async 'profile-new-coop'() { + const name = await askText({ title: t('New co-op profile'), body: t('Starts a co-op save in its own folder with a private room on the relay.'), label: t('Profile name'), ok: t('Next') }); + if (name === '') return toast(t('Type a name for the profile'), 'error'); + if (!name) return; + const code = await askText({ title: t('Private room code'), body: t('Leave blank to make a new private room, or enter your group\'s room code.'), label: t('Room code'), ok: t('Add'), max: 24 }); + if (code === null) return; + await changeProfiles(api.profileAddCoop, { name, roomCode: code || null, relay: null }, t('Co-op profile {name} added', { name })); + }, + async 'profile-start-coop'(arg, sourceName) { + const name = await askText({ title: t('Start coop from my singleplayer save'), body: t('Copies {name}\'s save into a new co-op profile. Your singleplayer save stays untouched.', { name: sourceName }), label: t('Co-op profile name'), value: `${sourceName} Co-op`.slice(0, 24), ok: t('Next') }); + if (name === '') return toast(t('Type a name for the profile'), 'error'); + if (!name) return; + const code = await askText({ title: t('Private room code'), body: t('Leave blank to make a new private room, or enter your group\'s room code.'), label: t('Room code'), ok: t('Start co-op'), max: 24 }); + if (code === null) return; + await changeProfiles(api.profileStartCoopFrom, { sourceId: arg, name, roomCode: code || null, relay: null }, t('Co-op profile {name} added', { name })); + }, + async 'profile-copy-singleplayer'(arg, sourceName) { + const name = await askText({ title: t('Copy to singleplayer'), body: t('Copies {name}\'s co-op save into a new singleplayer profile.', { name: sourceName }), label: t('Profile name'), ok: t('Copy') }); + if (name === '') return toast(t('Type a name for the profile'), 'error'); + else if (name) await changeProfiles(api.profileCopyToSingleplayer, { sourceId: arg, name }, t('Profile {name} added', { name })); + }, 'profile-use': (arg, name) => changeProfiles(api.profileSelect, { id: arg }, t('Playing as {name}', { name })), async 'profile-rename'(arg, name) { const next = await askText({ title: t('Rename profile'), label: t('Profile name'), value: name, ok: t('Rename') }); diff --git a/launcher/src/settings-schema.js b/launcher/src/settings-schema.js index 164bbf55..63406cb6 100644 --- a/launcher/src/settings-schema.js +++ b/launcher/src/settings-schema.js @@ -539,11 +539,21 @@ export const SECTIONS = [ { expand: (env) => (env.profiles?.profiles ?? []).map((p) => { const on = p.id === env.profiles.active; + const coop = p.coop; return { id: `profile_${p.id}`, label: p.name, type: 'info', - value: [on ? t('Playing') : '', playTimeLine(env.playTimes, p.id)].filter(Boolean).join(' · '), + value: [ + on ? t('Playing') : '', + coop ? t('Co-op') : '', + coop ? t('World v{version}', { version: num(coop.world_version ?? 0) }) : '', + coop ? t('{count} in group', { count: num(coop.members?.length ?? 1) }) : '', + playTimeLine(env.playTimes, p.id), + ].filter(Boolean).join(' · '), actions: [ ...(on ? [] : [{ act: 'profile-use', arg: p.id, name: p.name, label: t('Use'), icon: 'user-check', disabled: env.gameBusy }]), + ...(coop + ? [{ act: 'profile-copy-singleplayer', arg: p.id, name: p.name, label: t('Copy to singleplayer'), icon: 'copy', disabled: env.gameBusy }] + : [{ act: 'profile-start-coop', arg: p.id, name: p.name, label: t('Start co-op'), icon: 'users', disabled: env.gameBusy }]), { act: 'profile-rename', arg: p.id, name: p.name, label: t('Rename'), icon: 'pencil', disabled: env.gameBusy }, ...(p.id === 'default' ? [] : [{ act: 'profile-remove', arg: p.id, name: p.name, label: t('Remove'), icon: 'trash-2', disabled: env.gameBusy || on }]), ], @@ -552,7 +562,10 @@ export const SECTIONS = [ }, { id: 'profile_new', label: t('New profile'), type: 'info', - actions: (env) => [{ act: 'profile-new', label: t('Add'), icon: 'plus', disabled: env.gameBusy }], + actions: (env) => [ + { act: 'profile-new', label: t('Add'), icon: 'plus', disabled: env.gameBusy }, + { act: 'profile-new-coop', label: t('New co-op profile'), icon: 'users', disabled: env.gameBusy }, + ], }, ], }, diff --git a/launcher/src/store.js b/launcher/src/store.js index c8991bee..a3fd92d4 100644 --- a/launcher/src/store.js +++ b/launcher/src/store.js @@ -71,6 +71,7 @@ export const store = { setup: null, // setup_status game: null, // game_status news: { releases: [], update: null }, + profiles: null, // profiles_list, loaded for Play / Play co-op routing task: null, // derived: { kind: 'setup'|'update'|'unpack'|'dlss', label, pct (null: unknown) } | null update: null, // last update-progress while an update runs updateError: null, @@ -95,7 +96,10 @@ export const store = { async start() { const on = (event, fn) => listen(event, (ev) => fn(ev.payload)).catch((e) => console.error(event, e)); await Promise.all([ - on('game-status', (p) => set({ game: p }, 'game')), + on('game-status', (p) => { + set({ game: p }, 'game'); + if (p?.state === 'exited') store.refreshProfiles(); + }), on('setup-status', onSetupEvent), on('update-progress', (p) => set({ update: p }, 'update')), on('dlss-progress', (p) => store.state.dlss && set({ dlss: p }, 'task')), @@ -183,16 +187,25 @@ export const store = { cancelRepack: () => api.cancelShaderStorage().catch((e) => toast(errText(e), 'error')), - /** Reloads launcher_state, setup_status and game_status. A failed part keeps its last value. */ + /** Reloads launcher_state, setup_status, game_status and profiles. A failed part keeps its last value. */ async refresh() { - const [app, setup, game] = await Promise.allSettled([api.launcherState(), api.setupStatus(), api.gameStatus()]); + const [app, setup, game, profiles] = await Promise.allSettled([api.launcherState(), api.setupStatus(), api.gameStatus(), api.profilesList()]); const patch = { loadError: app.status === 'rejected' ? errText(app.reason) : null }; if (app.status === 'fulfilled') patch.app = app.value; if (setup.status === 'fulfilled') patch.setup = setup.value; if (game.status === 'fulfilled') patch.game = game.value; + if (profiles.status === 'fulfilled') patch.profiles = profiles.value; set(patch, 'app'); }, + async refreshProfiles() { + try { + set({ profiles: await api.profilesList() }, 'app'); + } catch (e) { + console.warn('profiles_list', e); + } + }, + /** get_releases. refresh=false serves the cache, true asks GitHub. Silent on failure: patch notes are optional. */ async refreshNews(refresh = false) { try { @@ -248,6 +261,24 @@ export const store = { } }, + /** Launches a co-op profile with its co-op settings in the process environment only (nothing written to pkp.ini). */ + async playCoop({ id = null, withoutMods = false } = {}) { + if (store.state.starting) return; + await askOnlineOnce(); + set({ starting: true }, 'task'); + try { + const args = {}; + if (id) args.id = id; + if (withoutMods) args.withoutMods = withoutMods; + await api.playCoop(args); + } catch (e) { + toast(errText(e), 'error'); + store.refresh(); + } finally { + set({ starting: false }, 'task'); + } + }, + /** Downloads and applies the update; on success Rust restarts the launcher, so this only returns on failure. */ async installUpdate() { if (!canUpdate(store.state)) return; @@ -311,6 +342,7 @@ export const store = { case 'game-folder': return go('settings', { section: 'game' }); case 'setup': return store.startSetup(); case 'play': return store.play(); + case 'play-coop': return store.playCoop(); case 'refresh': return store.refresh(); } },