Merge pull request #2597 from ludovic111/feat/launcher-play-time
🤖 Agent: launcher-features-1 — item 5 (play time per instance); base retargeted to main after #2596 merged, merges cleanly, CI green.
This commit is contained in:
+5
-3
@@ -78,9 +78,11 @@ The opening, then Play ([clip](docs/opening.webm)):
|
||||
data folder, so renaming moves nothing. Every instance follows the launcher's data collection
|
||||
answer and No AI. In the window, **+** beside Instances makes one, the sidebar lists them by
|
||||
group (click one to play it), and Home's Instance row has Edit (name, group, icon), Copy and
|
||||
Open folder. Each instance plays the launcher's version, which follows updates, unless the Play
|
||||
page's version picker keeps it on another installed one (to keep an old world on the version
|
||||
it was made with); picking the version marked "follows updates" lets it follow again.
|
||||
Open folder. The Instance row shows its play time and when it was last played: every run started
|
||||
from the window or `horizon-launcher play` adds to it (`instance list` shows it too). Each
|
||||
instance plays the launcher's version, which follows updates, unless the Play page's version
|
||||
picker keeps it on another installed one (to keep an old world on the version it was made
|
||||
with); picking the version marked "follows updates" lets it follow again.
|
||||
- **Worlds**: Home lists the selected instance's worlds (picture, mode, version, last played,
|
||||
size). **Back up** zips one into the instance's `backups/` as the game's Make Backup does
|
||||
(`<date>_<time>_<folder>.zip`); **Copy** puts "<name> (1)" beside it; **Delete** moves it to the
|
||||
|
||||
+13
-3
@@ -740,7 +740,12 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
|
||||
cmd.arg("--creative");
|
||||
}
|
||||
cmd.args(arg);
|
||||
attached(cmd)?
|
||||
let started = std::time::Instant::now();
|
||||
let played = attached(cmd);
|
||||
if let Err(e) = instances::record_play(&instance.id, started.elapsed()) {
|
||||
eprintln!("Play time not saved: {e}");
|
||||
}
|
||||
played?
|
||||
}
|
||||
Cmd::Server {
|
||||
dir,
|
||||
@@ -1470,7 +1475,8 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> {
|
||||
serde_json::json!({
|
||||
"id": i.id, "name": i.name, "kind": format!("{:?}", i.kind).to_lowercase(),
|
||||
"home": i.home, "icon": i.icon, "group": i.group, "selected": selected,
|
||||
"version": i.version,
|
||||
"version": i.version, "played_secs": i.played.as_secs(),
|
||||
"last_played_ms": i.last_played.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_millis() as u64),
|
||||
})
|
||||
};
|
||||
let line = |i: &instances::Instance, selected: bool| {
|
||||
@@ -1485,8 +1491,12 @@ fn instance(action: InstanceCmd, as_json: bool) -> Result<(), String> {
|
||||
.as_ref()
|
||||
.map(|v| format!(" {v}"))
|
||||
.unwrap_or_default();
|
||||
let played = match i.last_played {
|
||||
Some(_) => format!(" {} played", instances::play_time(i.played)),
|
||||
None => String::new(),
|
||||
};
|
||||
println!(
|
||||
"{mark} {} ({}){pinned}{group}\n {}",
|
||||
"{mark} {} ({}){pinned}{group}{played}\n {}",
|
||||
i.name,
|
||||
i.id,
|
||||
i.home.display()
|
||||
|
||||
@@ -14,6 +14,7 @@ use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
/// The default instance's id: the game's home itself.
|
||||
pub const DEFAULT: &str = "horizon";
|
||||
@@ -90,6 +91,16 @@ pub struct Meta {
|
||||
/// launcher's own version, which follows updates.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub version: Option<String>,
|
||||
/// Seconds played in it, every run started by the launcher (the window or `play`) added up.
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub played_secs: u64,
|
||||
/// When its last run ended, in seconds since 1970.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_played: Option<u64>,
|
||||
}
|
||||
|
||||
fn is_zero(n: &u64) -> bool {
|
||||
*n == 0
|
||||
}
|
||||
|
||||
/// `instances.json`: each instance's choices, by id.
|
||||
@@ -127,6 +138,8 @@ pub struct Instance {
|
||||
pub group: Option<String>,
|
||||
/// Its pinned Horizon version, if any (`Meta::version`).
|
||||
pub version: Option<String>,
|
||||
pub played: Duration,
|
||||
pub last_played: Option<SystemTime>,
|
||||
}
|
||||
|
||||
impl Instance {
|
||||
@@ -196,6 +209,10 @@ fn list_in(game_home: &Path, data: &Path) -> Vec<Instance> {
|
||||
icon: meta.icon,
|
||||
group: meta.group,
|
||||
version: meta.version,
|
||||
played: Duration::from_secs(meta.played_secs),
|
||||
last_played: meta
|
||||
.last_played
|
||||
.map(|s| UNIX_EPOCH + Duration::from_secs(s)),
|
||||
id,
|
||||
kind,
|
||||
work,
|
||||
@@ -397,6 +414,36 @@ fn edit_in(
|
||||
find_in(&list_in(game_home, data), &instance.id)
|
||||
}
|
||||
|
||||
/// Adds a finished run of the game to the instance's play time (by id: a renamed instance keeps
|
||||
/// it).
|
||||
pub fn record_play(id: &str, played: Duration) -> Result<(), String> {
|
||||
record_play_in(&backend::data_dir(), id, played, SystemTime::now())
|
||||
}
|
||||
|
||||
fn record_play_in(
|
||||
data: &Path,
|
||||
id: &str,
|
||||
played: Duration,
|
||||
ended: SystemTime,
|
||||
) -> Result<(), String> {
|
||||
let mut store = Store::load(data);
|
||||
let meta = store.instances.entry(id.to_string()).or_default();
|
||||
meta.played_secs = meta.played_secs.saturating_add(played.as_secs());
|
||||
meta.last_played = ended.duration_since(UNIX_EPOCH).ok().map(|d| d.as_secs());
|
||||
store.save(data)
|
||||
}
|
||||
|
||||
/// "12 min", "3 h 05 min", "140 h": the play time as players read it.
|
||||
pub fn play_time(played: Duration) -> String {
|
||||
let minutes = played.as_secs() / 60;
|
||||
match (minutes / 60, minutes % 60) {
|
||||
(0, 0) => "under a minute".into(),
|
||||
(0, m) => format!("{m} min"),
|
||||
(h, m) if h < 100 => format!("{h} h {m:02} min"),
|
||||
(h, _) => format!("{h} h"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns the game's command into this instance: its own game folder, and a pack's mods. The
|
||||
/// player's answers that hold everywhere follow it in: data collection and No AI as the
|
||||
/// launcher has them, and options.txt and the offline name when it has none yet.
|
||||
|
||||
@@ -224,3 +224,37 @@ fn an_instance_keeps_its_own_version_until_it_follows_updates_again() {
|
||||
assert_eq!(follows.version, None);
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_time_adds_up_per_instance_and_survives_a_rename() {
|
||||
let root = scratch("play-time");
|
||||
let (home, data) = (root.join("home"), root.join("data"));
|
||||
fs::create_dir_all(home.join(OWN).join("skyblock")).unwrap();
|
||||
let ended = UNIX_EPOCH + Duration::from_secs(1_800_000_000);
|
||||
record_play_in(&data, "skyblock", Duration::from_secs(25 * 60 + 10), ended).unwrap();
|
||||
edit_in(&home, &data, "skyblock", |m| m.name = Some("Sky".into())).unwrap();
|
||||
let later = ended + Duration::from_secs(3600);
|
||||
record_play_in(&data, "skyblock", Duration::from_secs(40 * 60), later).unwrap();
|
||||
let all = list_in(&home, &data);
|
||||
let sky = find_in(&all, "Sky").unwrap();
|
||||
assert_eq!(sky.played, Duration::from_secs(65 * 60 + 10));
|
||||
assert_eq!(sky.last_played, Some(later));
|
||||
let default = find_in(&all, DEFAULT).unwrap();
|
||||
assert_eq!(
|
||||
(default.played, default.last_played),
|
||||
(Duration::ZERO, None)
|
||||
);
|
||||
// Never played: nothing written for it.
|
||||
let text = fs::read_to_string(data.join(FILE)).unwrap();
|
||||
assert!(!text.contains("horizon"), "{text}");
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_time_reads_as_minutes_then_hours() {
|
||||
let t = |s| play_time(Duration::from_secs(s));
|
||||
assert_eq!(t(59), "under a minute");
|
||||
assert_eq!(t(12 * 60 + 59), "12 min");
|
||||
assert_eq!(t(3 * 3600 + 5 * 60), "3 h 05 min");
|
||||
assert_eq!(t(140 * 3600 + 7 * 60), "140 h");
|
||||
}
|
||||
|
||||
@@ -584,13 +584,37 @@ impl Launcher {
|
||||
Some(index_row(
|
||||
n,
|
||||
"Instance",
|
||||
Some(div().child(instance.name.clone()).into_any_element()),
|
||||
Some(
|
||||
div()
|
||||
.flex()
|
||||
.items_baseline()
|
||||
.gap(px(10.))
|
||||
.child(instance.name.clone())
|
||||
.child(
|
||||
text(theme::CAPTION)
|
||||
.text_color(t.muted)
|
||||
.child(played_line(&instance)),
|
||||
)
|
||||
.into_any_element(),
|
||||
),
|
||||
Some(actions.into_any_element()),
|
||||
&t,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// "3 h 05 min in total · last played today", or "Not played yet".
|
||||
fn played_line(instance: &Instance) -> String {
|
||||
match instance.last_played {
|
||||
Some(when) => format!(
|
||||
"{} in total · last played {}",
|
||||
instances::play_time(instance.played),
|
||||
worlds_page::ago(when)
|
||||
),
|
||||
None => "Not played yet".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first letter or digit of a name, for an icon without a picture.
|
||||
fn initial(name: &str) -> String {
|
||||
name.chars()
|
||||
|
||||
+25
-4
@@ -189,6 +189,8 @@ struct Launcher {
|
||||
joining: Option<String>,
|
||||
/// Where the next start goes at once: `--world <folder>` or `--server <address>`.
|
||||
quick_play: Option<(&'static str, String)>,
|
||||
/// The instance the running game plays and when it started: its play time grows on exit.
|
||||
client_run: Option<(String, Instant)>,
|
||||
/// Settings' Game arguments field: the line, whether it has focus, and its focus handle.
|
||||
args_input: String,
|
||||
args_focused: bool,
|
||||
@@ -369,6 +371,7 @@ impl Launcher {
|
||||
friend_focus: cx.focus_handle(),
|
||||
joining: None,
|
||||
quick_play: None,
|
||||
client_run: None,
|
||||
collection: collection::Collection::load(),
|
||||
agents: agents_page::AgentsUi::default(),
|
||||
playing: None,
|
||||
@@ -552,11 +555,20 @@ impl Launcher {
|
||||
}
|
||||
self.accounts = Accounts::load();
|
||||
// A pack's Play button plays that pack; Play plays the selected instance.
|
||||
let profile = match self.starting_pack.take() {
|
||||
let (profile, run) = match self.starting_pack.take() {
|
||||
Some(work) => {
|
||||
horizon_launcher::modpacks::apply_profile(&mut cmd, &work)
|
||||
let id = instances::list()
|
||||
.into_iter()
|
||||
.find(|i| i.work == work)
|
||||
.map(|i| i.id);
|
||||
let applied =
|
||||
horizon_launcher::modpacks::apply_profile(&mut cmd, &work);
|
||||
(applied, id)
|
||||
}
|
||||
None => {
|
||||
let instance = instances::selected();
|
||||
(instances::apply(&mut cmd, &instance), Some(instance.id))
|
||||
}
|
||||
None => instances::apply(&mut cmd, &instances::selected()),
|
||||
};
|
||||
if let Err(e) = profile {
|
||||
self.client_error = Some(e);
|
||||
@@ -573,7 +585,10 @@ impl Launcher {
|
||||
backend::append_game_args(&mut cmd);
|
||||
self.client_home = cmd.get_current_dir().map(|d| d.to_path_buf());
|
||||
match backend::spawn(Job::Client, cmd, self.tx.clone()) {
|
||||
Ok(r) => self.client = Some(r),
|
||||
Ok(r) => {
|
||||
self.client = Some(r);
|
||||
self.client_run = run.map(|id| (id, Instant::now()));
|
||||
}
|
||||
Err(e) => self.client_error = Some(e),
|
||||
}
|
||||
}
|
||||
@@ -693,6 +708,12 @@ impl Launcher {
|
||||
// The game saved: last played, sizes and pictures changed.
|
||||
self.worlds.stale();
|
||||
self.multiplayer.stale();
|
||||
if let Some((id, started)) = self.client_run.take() {
|
||||
if let Err(e) = instances::record_play(&id, started.elapsed()) {
|
||||
eprintln!("Play time not saved: {e}");
|
||||
}
|
||||
self.reload_instances();
|
||||
}
|
||||
// The run's own game folder: an instance's or a pack's keeps its reports.
|
||||
let home = self.client_home.clone().unwrap_or_else(backend::game_home);
|
||||
let report = self
|
||||
|
||||
@@ -28,7 +28,7 @@ impl Worlds {
|
||||
}
|
||||
|
||||
/// "today", "yesterday", "3 days ago", else the date.
|
||||
fn ago(when: std::time::SystemTime) -> String {
|
||||
pub(super) fn ago(when: std::time::SystemTime) -> String {
|
||||
let when: chrono::DateTime<chrono::Local> = when.into();
|
||||
let days = (chrono::Local::now().date_naive() - when.date_naive()).num_days();
|
||||
match days {
|
||||
|
||||
Reference in New Issue
Block a user