diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 35de188f9..842a3c3c2 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -116,7 +116,7 @@ MCP: `account_sign_out`, needs `confirm: true`. ## `horizon-launcher account select` -Play as this account. +Play as this account, or as one of your offline names. horizon-launcher account select @@ -126,12 +126,24 @@ MCP: `account_select`. ## `horizon-launcher account offline` -Play offline, without an account. +Play offline, without an account: as NAME (kept to switch back to; 3 to 16 letters, digits or _), or as the name the game made up. - horizon-launcher account offline + horizon-launcher account offline [NAME] + +- `NAME` MCP: `account_offline`. +## `horizon-launcher account forget-offline` + +Forget one of your offline names. + + horizon-launcher account forget-offline + +- `NAME` + +MCP: `account_forget_offline`. + ## `horizon-launcher settings` Show the launcher's settings, or set one (the Settings page): selected-version TAG, minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions on|off, opening-animation on|off, proxy http://host:port ("default" removes it), while-playing stay|minimize|hide (what the window does while the game runs). diff --git a/launcher/README.md b/launcher/README.md index 104285c5a..93115c479 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -122,6 +122,13 @@ The opening, then Play ([clip](docs/opening.webm)): (`horizon_launcher::shortcut`). **Remove shortcut** moves it to the trash; it is found by the instance id inside it, so a rename doesn't lose it. `horizon-launcher instance shortcut [instance] [--remove]`; `HORIZON_LAUNCHER_DESKTOP` points it at another folder. +- **Accounts and quick switch**: the top bar's account chip opens a menu of everyone who can play: + each signed-in Microsoft account, the offline names the player keeps, and the name the game + made up (`horizon-player.txt`). Picking one plays as it from the next Play. Settings > Account + adds offline names (3 to 16 letters, digits or `_`; the game gets `--name`) and forgets them; + the Console's Share log takes them out of the log too. `horizon-launcher account offline + [NAME]`, `account select ` (an account or an offline name), `account forget-offline + `. - **Console**: Home's Console shows the game's output of this run as it comes: a search (every word, any case), Follow to keep the newest line in view, Copy, and Open logs folder. Warnings and errors stand out. **Share log…** uploads the log to [mclo.gs](https://mclo.gs), a paste diff --git a/launcher/src/account.rs b/launcher/src/account.rs index 1416424ce..f402fe5ce 100644 --- a/launcher/src/account.rs +++ b/launcher/src/account.rs @@ -638,6 +638,30 @@ pub struct Accounts { pub accounts: Vec, /// The UUID of the account the game starts with; none plays offline. pub selected: Option, + /// Offline names the player keeps, to switch between (`--name`): no account, no skin. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub offline: Vec, + /// The offline name that plays when no account is selected; none: the name the game made up + /// (`horizon-player.txt`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub offline_selected: Option, +} + +/// Who plays, as the quick switch lists them. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Player { + /// A Microsoft account, by UUID. + Microsoft(String), + /// An offline name. + Offline(String), + /// Offline as the name the game made up. + GameName, +} + +/// Whether `name` can be an offline name: 3 to 16 letters, digits or `_`, as account names are. +pub fn valid_offline_name(name: &str) -> bool { + (3..=16).contains(&name.chars().count()) + && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') } impl Accounts { @@ -687,6 +711,77 @@ impl Accounts { } Ok(()) } + /// Who plays now. + pub fn player(&self) -> Player { + match (self.selected(), &self.offline_selected) { + (Some(a), _) => Player::Microsoft(a.uuid.clone()), + (None, Some(name)) => Player::Offline(name.clone()), + (None, None) => Player::GameName, + } + } + + /// Plays as `who`: an account, an offline name (kept), or the game's own name. + pub fn play_as(&mut self, who: Player) -> Result<(), String> { + match who { + Player::Microsoft(uuid) => { + if !self.accounts.iter().any(|a| a.uuid == uuid) { + return Err("That account isn't signed in.".into()); + } + self.selected = Some(uuid); + } + Player::Offline(name) => { + let name = self.add_offline(&name)?; + self.selected = None; + self.offline_selected = Some(name); + } + Player::GameName => { + self.selected = None; + self.offline_selected = None; + } + } + Ok(()) + } + + /// Keeps an offline name (once, in any case); returns it as kept. + pub fn add_offline(&mut self, name: &str) -> Result { + let name = name.trim(); + if !valid_offline_name(name) { + return Err(format!( + "{name}: an offline name is 3 to 16 letters, digits or _" + )); + } + if let Some(kept) = self.offline.iter().find(|n| n.eq_ignore_ascii_case(name)) { + return Ok(kept.clone()); + } + self.offline.push(name.to_string()); + Ok(name.to_string()) + } + + /// Forgets an offline name; if it was playing, the game's own name plays. + pub fn remove_offline(&mut self, name: &str) -> Result<(), String> { + let before = self.offline.len(); + self.offline.retain(|n| !n.eq_ignore_ascii_case(name)); + if self.offline.len() == before { + return Err(format!("No offline name {name}.")); + } + if self + .offline_selected + .as_ref() + .is_some_and(|n| n.eq_ignore_ascii_case(name)) + { + self.offline_selected = None; + } + Ok(()) + } + + /// The game's `--name` for this run: the offline name, when one plays. + pub fn name_arg(&self) -> Option<&str> { + match self.selected() { + Some(_) => None, + None => self.offline_selected.as_deref(), + } + } + /// Sign out: the secrets leave the keychain, the account the list. pub fn remove(&mut self, store: &dyn SecretStore, uuid: &str) -> Result<(), String> { store.delete(uuid)?; diff --git a/launcher/src/account/tests.rs b/launcher/src/account/tests.rs index 5aea5dd12..ec3766c7e 100644 --- a/launcher/src/account/tests.rs +++ b/launcher/src/account/tests.rs @@ -423,3 +423,43 @@ fn client_id_is_configuration() { ); std::env::remove_var("HORIZON_MSA_CLIENT_ID"); } + +#[test] +fn offline_names_switch_with_accounts() { + let mut a = Accounts { + accounts: vec![Account { + uuid: "abc".into(), + name: "Ludo".into(), + skin: None, + cape: None, + }], + selected: Some("abc".into()), + ..Accounts::default() + }; + assert_eq!(a.player(), Player::Microsoft("abc".into())); + assert_eq!(a.name_arg(), None); + a.play_as(Player::Offline("Builder_1".into())).unwrap(); + assert_eq!(a.player(), Player::Offline("Builder_1".into())); + assert_eq!(a.name_arg(), Some("Builder_1")); + // Kept once, as first written, whatever the case. + a.play_as(Player::Offline("builder_1".into())).unwrap(); + assert_eq!(a.offline, ["Builder_1"]); + assert_eq!(a.name_arg(), Some("Builder_1")); + assert!(a.add_offline("no spaces").is_err()); + assert!(a.add_offline("ab").is_err()); + assert!(a.add_offline("seventeen_letters").is_err()); + a.play_as(Player::Microsoft("abc".into())).unwrap(); + assert_eq!(a.name_arg(), None, "an account plays with its own name"); + assert!(a.play_as(Player::Microsoft("zzz".into())).is_err()); + a.play_as(Player::Offline("Builder_1".into())).unwrap(); + a.remove_offline("BUILDER_1").unwrap(); + assert_eq!(a.player(), Player::GameName); + assert!(a.remove_offline("Builder_1").is_err()); + // An accounts.json from before offline names reads as it was, and writes nothing new. + let old: Accounts = serde_json::from_str(r#"{"accounts":[],"selected":null}"#).unwrap(); + assert_eq!(old.player(), Player::GameName); + assert_eq!( + serde_json::to_string(&old).unwrap(), + r#"{"accounts":[],"selected":null}"# + ); +} diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index e88144fe3..8153c7968 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -86,10 +86,13 @@ enum AccountCmd { /// Its name or UUID who: String, }, - /// Play as this account + /// Play as this account, or as one of your offline names Select { who: String }, - /// Play offline, without an account - Offline, + /// Play offline, without an account: as NAME (kept to switch back to; 3 to 16 letters, + /// digits or _), or as the name the game made up + Offline { name: Option }, + /// Forget one of your offline names + ForgetOffline { name: String }, } #[derive(Subcommand)] @@ -960,6 +963,9 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { } cmd.args(arg); let started = std::time::Instant::now(); + if let Some(name) = Accounts::load().name_arg() { + cmd.arg("--name").arg(name); + } let played = attached(horizon_launcher::launch::wrap(cmd, &instance.launch)); if let Err(e) = instances::record_play(&instance.id, started.elapsed()) { eprintln!("Play time not saved: {e}"); @@ -1245,9 +1251,13 @@ fn account_command(action: AccountCmd, as_json: bool) -> Result<(), String> { "name": a.name, "uuid": a.uuid, "selected": accounts.selected.as_ref() == Some(&a.uuid), })).collect::>(), + "offline": accounts.offline.iter().map(|n| serde_json::json!({ + "name": n, + "selected": accounts.player() == account::Player::Offline(n.clone()), + })).collect::>(), "sign_in_configured": account::client_id().is_some(), })); - } else if accounts.accounts.is_empty() { + } else if accounts.accounts.is_empty() && accounts.offline.is_empty() { println!("No Microsoft account signed in: the game plays offline."); } else { for a in &accounts.accounts { @@ -1258,8 +1268,14 @@ fn account_command(action: AccountCmd, as_json: bool) -> Result<(), String> { }; println!("{mark} {} {}", a.name, a.uuid); } - if accounts.selected().is_none() { - println!("Playing offline (`account select NAME` to play as one)."); + for n in &accounts.offline { + let on = accounts.player() == account::Player::Offline(n.clone()); + println!("{} {n} offline", if on { "*" } else { " " }); + } + if accounts.player() == account::Player::GameName { + println!( + "Playing offline as the game's own name (`account select NAME` to switch)." + ); } } } @@ -1287,15 +1303,39 @@ fn account_command(action: AccountCmd, as_json: bool) -> Result<(), String> { println!("Signed out {}.", a.name); } AccountCmd::Select { who } => { - let a = find(&accounts, &who)?; - accounts.selected = Some(a.uuid); + let offline = accounts + .offline + .iter() + .find(|n| n.eq_ignore_ascii_case(&who)) + .cloned(); + let (player, name) = match (accounts.find(&who).cloned(), offline) { + (Some(a), _) => (account::Player::Microsoft(a.uuid), a.name), + (None, Some(n)) => ( + account::Player::Offline(n.clone()), + format!("{n} (offline)"), + ), + (None, None) => return Err(find(&accounts, &who).unwrap_err()), + }; + accounts.play_as(player)?; accounts.save()?; - println!("The game plays as {}.", a.name); + println!("The game plays as {name}."); } - AccountCmd::Offline => { - accounts.selected = None; + AccountCmd::Offline { name } => { + let player = match name { + Some(n) => account::Player::Offline(n), + None => account::Player::GameName, + }; + accounts.play_as(player)?; accounts.save()?; - println!("The game plays offline."); + match accounts.name_arg() { + Some(n) => println!("The game plays offline as {n}."), + None => println!("The game plays offline, as the name it made up."), + } + } + AccountCmd::ForgetOffline { name } => { + accounts.remove_offline(&name)?; + accounts.save()?; + println!("Forgot the offline name {name}."); } } Ok(()) diff --git a/launcher/src/game_log.rs b/launcher/src/game_log.rs index a9c787544..1d671f27e 100644 --- a/launcher/src/game_log.rs +++ b/launcher/src/game_log.rs @@ -29,14 +29,12 @@ pub fn matches(line: &str, search: &str) -> bool { .all(|w| line.contains(&w.to_lowercase())) } -/// The names to take out of a log: the account names, the offline player name kept in each -/// game folder (`horizon-player.txt`), and the computer's user name. +/// The names to take out of a log: the account names and offline names, the offline player +/// name kept in each game folder (`horizon-player.txt`), and the computer's user name. pub fn names(homes: &[&Path]) -> Vec { - let mut names: Vec = crate::account::Accounts::load() - .accounts - .into_iter() - .map(|a| a.name) - .collect(); + let accounts = crate::account::Accounts::load(); + let mut names: Vec = accounts.accounts.into_iter().map(|a| a.name).collect(); + names.extend(accounts.offline); for home in homes { if let Ok(name) = std::fs::read_to_string(home.join("horizon-player.txt")) { names.push(name.trim().to_string()); diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 90475305b..1496dbe59 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -32,6 +32,7 @@ mod screenshots_page; mod scrollbar; mod servers_page; mod shortcut_page; +mod switch_page; mod theme; mod titlebar; mod while_playing; @@ -164,6 +165,8 @@ struct Launcher { install_error: Option<(String, String)>, confirm_remove: Option, picker_open: bool, + /// The top bar's quick switch of who plays (`switch_page.rs`). + account_menu: bool, settings: Settings, /// The Discord, sponsor and website links: built in until links.json on main has been read. links: backend::Links, @@ -362,6 +365,7 @@ impl Launcher { install_error: None, confirm_remove: None, picker_open: false, + account_menu: false, args_input: settings.game_args.clone(), args_focused: false, args_focus: cx.focus_handle(), @@ -467,6 +471,7 @@ impl Launcher { } } self.picker_open = false; + self.account_menu = false; } fn check_updates(&mut self) { @@ -583,6 +588,10 @@ impl Launcher { Err(e) => self.client_error = Some(format!("Playing offline: {e}")), } self.accounts = Accounts::load(); + // An offline name the player picked (the quick switch). + if let Some(name) = self.accounts.name_arg() { + cmd.arg("--name").arg(name); + } // A pack's Play button plays that pack; Play plays the selected instance. let (profile, run) = match self.starting_pack.take() { Some(work) => { @@ -1557,14 +1566,9 @@ impl Launcher { })); nav = nav.child(keyboard(track_hover(item, id), &t)); } - // Only a signed-in account says "Microsoft account"; otherwise the name the game made up. - let (name, how) = match self.accounts.selected() { - Some(a) => (a.name.clone(), "Microsoft account"), - None => ( - self.offline_name.clone().unwrap_or_else(|| "Player".into()), - "Offline", - ), - }; + // Only a signed-in account says "Microsoft account"; otherwise an offline name, or the + // one the game made up. + let (name, how) = self.who_plays(); let account = keyboard(div().id("account"), &t) .relative() .flex() @@ -1603,9 +1607,13 @@ impl Launcher { .child(text(theme::CAPTION).text_color(t.muted).child(how)), ) .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.go(Page::Settings); + this.account_menu = !this.account_menu; cx.notify(); })); + let account = div() + .relative() + .child(account) + .children(self.account_menu(cx)); let settings_open = self.page == Page::Settings; let settings = keyboard(div().id("nav-Settings"), &t) .relative() @@ -2626,6 +2634,7 @@ impl Launcher { let mono = |s: String| div().font_family(theme::MONO).child(s).into_any_element(); let plain = |s: &str| div().child(s.to_string()).into_any_element(); let (accounts, n) = self.account_rows(cx); + let (offline, n) = self.offline_rows(n, cx); let appearance = segments( "appearance", &[ @@ -2666,6 +2675,7 @@ impl Launcher { .flex_col() .child(group("Account", "user").mt_0()) .child(accounts) + .child(offline) .child(group("Updates", "reload")) .child(index_row( n + 1, diff --git a/launcher/src/servers_page.rs b/launcher/src/servers_page.rs index ae33e6cc0..e3ed4f441 100644 --- a/launcher/src/servers_page.rs +++ b/launcher/src/servers_page.rs @@ -44,10 +44,12 @@ pub(super) enum Field { PreLaunch, Wrapper, LaunchEnv, + /// Settings' new offline name (`switch_page.rs`). + OfflineName, } impl Field { - const ALL: [Field; 17] = [ + const ALL: [Field; 18] = [ Field::Name, Field::Seed, Field::Players, @@ -65,6 +67,7 @@ impl Field { Field::PreLaunch, Field::Wrapper, Field::LaunchEnv, + Field::OfflineName, ]; } @@ -1043,6 +1046,7 @@ impl Launcher { Field::Email => self.invite_friend(), Field::InstanceName | Field::InstanceGroup | Field::ConsoleSearch => {} Field::PreLaunch | Field::Wrapper | Field::LaunchEnv => self.save_launch(), + Field::OfflineName => self.offline_name_enter(), Field::ServerName | Field::ServerAddress => self.add_server(), } } diff --git a/launcher/src/switch_page.rs b/launcher/src/switch_page.rs new file mode 100644 index 000000000..3b6bdac14 --- /dev/null +++ b/launcher/src/switch_page.rs @@ -0,0 +1,231 @@ +//! Who plays: the top bar's quick switch (a menu under the account chip) and Settings' offline +//! names (`horizon_launcher::account::Accounts::offline`). +use super::servers_page::Field; +use super::*; +use horizon_launcher::account::Player; + +impl Launcher { + /// The chip's two lines: the name that plays, and how. + pub(super) fn who_plays(&self) -> (String, &'static str) { + match self.accounts.player() { + Player::Microsoft(_) => ( + self.accounts + .selected() + .map_or_else(String::new, |a| a.name.clone()), + "Microsoft account", + ), + Player::Offline(name) => (name, "Offline"), + Player::GameName => ( + self.offline_name.clone().unwrap_or_else(|| "Player".into()), + "Offline", + ), + } + } + + pub(super) fn play_as(&mut self, who: Player) { + let mut accounts = Accounts::load(); + let done = accounts.play_as(who).and_then(|()| accounts.save()); + match done { + Ok(()) => self.accounts = accounts, + Err(e) => self.sign_in_state = Some(SignInState::Done(Err(e))), + } + self.account_menu = false; + } + + /// Everyone the player can play as, with how each signs in. + fn players(&self) -> Vec<(Player, String, &'static str)> { + let mut out: Vec<_> = self + .accounts + .accounts + .iter() + .map(|a| { + ( + Player::Microsoft(a.uuid.clone()), + a.name.clone(), + "Microsoft", + ) + }) + .collect(); + out.extend( + self.accounts + .offline + .iter() + .map(|n| (Player::Offline(n.clone()), n.clone(), "Offline")), + ); + out.push(( + Player::GameName, + self.offline_name.clone().unwrap_or_else(|| "Player".into()), + "Offline, the game's name", + )); + out + } + + /// The menu under the account chip, while open. + pub(super) fn account_menu(&self, cx: &mut Context) -> Option { + if !self.account_menu { + return None; + } + let t = self.theme; + let now = self.accounts.player(); + let mut menu = div() + .id("account-menu") + .absolute() + .top(px(46.)) + .right_0() + .w(px(280.)) + .p(px(6.)) + .border_2() + .border_color(t.outline) + .bg(t.surface) + .flex() + .flex_col() + .occlude(); + for (i, (who, name, how)) in self.players().into_iter().enumerate() { + let chosen = who == now; + menu = menu.child( + div() + .id(SharedString::from(format!("account-pick-{i}"))) + .flex() + .items_center() + .justify_between() + .gap(px(8.)) + .h(px(46.)) + .px(px(10.)) + .rounded(px(theme::RADIUS)) + .cursor_pointer() + .hover(move |s| s.bg(t.plate_soft)) + .child( + div() + .flex() + .flex_col() + .min_w_0() + .child(text(theme::LABEL).truncate().text_color(t.ink).child(name)) + .child(text(theme::CAPTION).text_color(t.muted).child(how)), + ) + .when(chosen, |d| { + d.child(div().size(px(6.)).rounded_full().bg(t.accent)) + }) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.play_as(who.clone()); + cx.notify(); + })), + ); + } + menu = menu.child(div().my(px(6.)).h(px(1.)).bg(t.rule)).child( + div() + .id("account-manage") + .flex() + .items_center() + .h(px(32.)) + .px(px(10.)) + .rounded(px(theme::RADIUS)) + .text_size(px(theme::LABEL.px)) + .text_color(t.muted) + .cursor_pointer() + .hover(move |s| s.bg(t.plate_soft).text_color(t.ink)) + .child("Manage accounts") + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.account_menu = false; + this.go(Page::Settings); + cx.notify(); + })), + ); + Some(gpui::deferred(menu).with_priority(1)) + } + + fn add_offline_name(&mut self) { + let name = self.servers.value(Field::OfflineName).trim().to_string(); + if name.is_empty() { + return; + } + self.play_as(Player::Offline(name)); + if !matches!(self.sign_in_state, Some(SignInState::Done(Err(_)))) { + self.servers.text(Field::OfflineName).clear(); + } + } + + /// Enter in the offline name field. + pub(super) fn offline_name_enter(&mut self) { + self.add_offline_name(); + } + + /// Settings' rows for the offline names, after the Microsoft accounts: each with Play as + /// and Forget, then a field to add one. + pub(super) fn offline_rows(&mut self, mut n: usize, cx: &mut Context) -> (Div, usize) { + let t = self.theme; + let mut rows = div().flex().flex_col(); + let now = self.accounts.player(); + for (i, name) in self.accounts.offline.clone().into_iter().enumerate() { + let plays = now == Player::Offline(name.clone()); + let mut actions = div().flex().gap(px(4.)); + if !plays { + let who = Player::Offline(name.clone()); + actions = actions.child( + button(format!("offline-play-{i}"), "Play as", Kind::Secondary, &t).on_click( + cx.listener(move |this, _: &ClickEvent, _, cx| { + this.play_as(who.clone()); + cx.notify(); + }), + ), + ); + } + let forget = name.clone(); + actions = actions.child( + button(format!("offline-forget-{i}"), "Forget", Kind::Ghost, &t).on_click( + cx.listener(move |this, _: &ClickEvent, _, cx| { + let mut accounts = Accounts::load(); + if accounts.remove_offline(&forget).is_ok() && accounts.save().is_ok() { + this.accounts = accounts; + } + cx.notify(); + }), + ), + ); + n += 1; + rows = rows.child(index_row( + n, + name, + Some( + div() + .child(if plays { + "Offline name · plays" + } else { + "Offline name" + }) + .into_any_element(), + ), + Some(actions.into_any_element()), + &t, + )); + } + n += 1; + let add = div() + .flex() + .items_center() + .gap(px(8.)) + .child(self.field(Field::OfflineName, "A name, 3 to 16 letters", 220., cx)) + .child( + button("offline-add", "Add", Kind::Secondary, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.add_offline_name(); + cx.notify(); + }, + )), + ); + rows = rows.child(index_row( + n, + "Offline name", + Some( + div() + .child( + "Play offline under another name, and switch from the top bar. Offline \ + names have no skin, and online servers don't take them.", + ) + .into_any_element(), + ), + Some(add.into_any_element()), + &t, + )); + (rows, n) + } +}