Merge pull request #1788 from ludovic111/feat/discord-presence
🤖 Agent: merged after verify passed; Rich Presence e2e 6/6 on macOS and Linux.
This commit is contained in:
@@ -393,16 +393,20 @@ impl Client {
|
||||
/// Where Discord listens: `discord-ipc-0..9` in the temporary folders (and Flatpak's and
|
||||
/// Snap's subfolders) on Linux and macOS, named pipes on Windows.
|
||||
fn sockets() -> Vec<PathBuf> {
|
||||
sockets_with(|key| std::env::var_os(key), cfg!(windows))
|
||||
}
|
||||
|
||||
fn sockets_with(var: impl Fn(&str) -> Option<std::ffi::OsString>, windows: bool) -> Vec<PathBuf> {
|
||||
let names = (0..10).map(|n| format!("discord-ipc-{n}"));
|
||||
if let Some(dir) = std::env::var_os(IPC_DIR_ENV) {
|
||||
if let Some(dir) = var(IPC_DIR_ENV) {
|
||||
return names.map(|n| PathBuf::from(&dir).join(n)).collect();
|
||||
}
|
||||
if cfg!(windows) {
|
||||
if windows {
|
||||
return names.map(|n| PathBuf::from(r"\\?\pipe\").join(n)).collect();
|
||||
}
|
||||
let mut dirs: Vec<PathBuf> = ["XDG_RUNTIME_DIR", "TMPDIR", "TMP", "TEMP"]
|
||||
.into_iter()
|
||||
.filter_map(std::env::var_os)
|
||||
.filter_map(&var)
|
||||
.map(PathBuf::from)
|
||||
.collect();
|
||||
dirs.push("/tmp".into());
|
||||
@@ -445,6 +449,57 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The folders a real Discord listens in: `$TMPDIR` on macOS, `$XDG_RUNTIME_DIR` on Linux (and its
|
||||
/// Flatpak and Snap subfolders), named pipes on Windows.
|
||||
#[test]
|
||||
fn sockets_cover_where_discord_listens() {
|
||||
let env = |pairs: &'static [(&'static str, &'static str)]| {
|
||||
move |key: &str| {
|
||||
pairs
|
||||
.iter()
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
}
|
||||
};
|
||||
let macos = sockets_with(env(&[("TMPDIR", "/var/folders/xy/abc/T/")]), false);
|
||||
assert_eq!(
|
||||
macos[0],
|
||||
PathBuf::from("/var/folders/xy/abc/T/discord-ipc-0")
|
||||
);
|
||||
assert!(macos.contains(&PathBuf::from("/var/folders/xy/abc/T/discord-ipc-9")));
|
||||
assert!(macos.contains(&PathBuf::from("/tmp/discord-ipc-0")));
|
||||
|
||||
let linux = sockets_with(
|
||||
env(&[("XDG_RUNTIME_DIR", "/run/user/1000"), ("TMPDIR", "/tmp")]),
|
||||
false,
|
||||
);
|
||||
assert_eq!(linux[0], PathBuf::from("/run/user/1000/discord-ipc-0"));
|
||||
for path in [
|
||||
"/run/user/1000/app/com.discordapp.Discord/discord-ipc-0",
|
||||
"/run/user/1000/snap.discord/discord-ipc-0",
|
||||
"/tmp/discord-ipc-0",
|
||||
] {
|
||||
assert!(linux.contains(&PathBuf::from(path)), "{path}");
|
||||
}
|
||||
assert_eq!(linux.len(), 2 * 3 * 10, "/tmp is listed once");
|
||||
|
||||
let bare = sockets_with(env(&[]), false);
|
||||
assert_eq!(bare[0], PathBuf::from("/tmp/discord-ipc-0"));
|
||||
|
||||
let windows = sockets_with(env(&[("TEMP", r"C:\Temp")]), true);
|
||||
assert_eq!(windows.len(), 10);
|
||||
// `Path::join` only uses `\` as the separator on Windows itself.
|
||||
#[cfg(windows)]
|
||||
assert_eq!(windows[0], PathBuf::from(r"\\?\pipe\discord-ipc-0"));
|
||||
|
||||
let fake = sockets_with(
|
||||
env(&[("HORIZON_DISCORD_IPC_DIR", "/tmp/hz"), ("TMPDIR", "/x")]),
|
||||
false,
|
||||
);
|
||||
assert_eq!(fake.len(), 10);
|
||||
assert_eq!(fake[0], PathBuf::from("/tmp/hz/discord-ipc-0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_round_trip() {
|
||||
let frame = encode(FRAME, &json!({"cmd": "SET_ACTIVITY"}));
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Horizon's optional extras (zoom, FPS counter, keystroke overlay): their
|
||||
//! settings, kept in `horizon-extras.txt` next to `options.txt` so that file
|
||||
//! stays exactly vanilla's, and the logic behind them. Every extra is off by
|
||||
//! default; see `docs/extras.md`.
|
||||
//! default; see `docs/extras.md`. Horizon's own switches outside the Extras page
|
||||
//! (No AI, Agent Control, Discord Rich Presence) are kept here too.
|
||||
use std::{collections::VecDeque, fs, path::Path};
|
||||
|
||||
pub const FILE: &str = "horizon-extras.txt";
|
||||
@@ -112,6 +113,8 @@ pub struct Extras {
|
||||
/// Agents may control the game the player starts: it opens its control socket for
|
||||
/// horizon-ctl and MCP clients (off by default; an agent's own launch always opens it).
|
||||
pub agent_control: bool,
|
||||
/// "Playing Horizon" on the player's Discord profile (`discord_presence`; on by default).
|
||||
pub discord_presence: bool,
|
||||
}
|
||||
impl Default for Extras {
|
||||
fn default() -> Self {
|
||||
@@ -142,6 +145,7 @@ impl Default for Extras {
|
||||
sort_key: "key.keyboard.unknown".into(),
|
||||
no_ai: false,
|
||||
agent_control: false,
|
||||
discord_presence: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -207,6 +211,7 @@ impl Extras {
|
||||
"sortKey" if value.starts_with("key.") => e.sort_key = value.to_owned(),
|
||||
horizon_core::no_ai::KEY => e.no_ai = flag(e.no_ai),
|
||||
"agentControl" => e.agent_control = flag(e.agent_control),
|
||||
"discordPresence" => e.discord_presence = flag(e.discord_presence),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -214,7 +219,7 @@ impl Extras {
|
||||
}
|
||||
pub fn serialize(&self) -> String {
|
||||
format!(
|
||||
"fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n{}:{}\nagentControl:{}\n",
|
||||
"fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n{}:{}\nagentControl:{}\ndiscordPresence:{}\n",
|
||||
bool_text(self.fullbright),
|
||||
bool_text(self.dynamic_lights),
|
||||
bool_text(self.zoom),
|
||||
@@ -246,6 +251,7 @@ impl Extras {
|
||||
horizon_core::no_ai::KEY,
|
||||
bool_text(self.no_ai),
|
||||
bool_text(self.agent_control),
|
||||
bool_text(self.discord_presence),
|
||||
)
|
||||
}
|
||||
/// Binds the extra key `name` (`ZOOM_KEY`, `SORT_KEY`); false for
|
||||
@@ -466,6 +472,8 @@ pub enum Item {
|
||||
/// Not on the Extras page: Horizon Settings shows No AI, its AI Agent page Agent Control.
|
||||
NoAi,
|
||||
AgentControl,
|
||||
/// On the Horizon Settings page.
|
||||
DiscordPresence,
|
||||
}
|
||||
/// The Extras page: headers and items.
|
||||
pub fn rows() -> Vec<Result<Item, &'static str>> {
|
||||
@@ -546,6 +554,7 @@ impl Item {
|
||||
Item::KeystrokesCps => "Clicks per second",
|
||||
Item::NoAi => "No AI",
|
||||
Item::AgentControl => "Agent Control",
|
||||
Item::DiscordPresence => "Discord Rich Presence",
|
||||
}
|
||||
}
|
||||
/// The switch this setting belongs to: it does nothing while that is off.
|
||||
@@ -559,7 +568,7 @@ impl Item {
|
||||
MouseTweaksWheel => MouseTweaks,
|
||||
SortKey => Sort,
|
||||
Fullbright | DynamicLights | Zoom | Minimap | Fps | Keystrokes | MouseTweaks | Sort
|
||||
| AutoReconnect | NoAi | AgentControl => {
|
||||
| AutoReconnect | NoAi | AgentControl | DiscordPresence => {
|
||||
return None;
|
||||
}
|
||||
})
|
||||
@@ -606,6 +615,9 @@ impl Item {
|
||||
Item::NoAi => {
|
||||
"Hides and turns off every AI feature: agent control, horizon-ctl and the MCP servers. The launcher's switch too."
|
||||
}
|
||||
Item::DiscordPresence => {
|
||||
"Shows Playing Horizon on your Discord profile while Discord runs: menus, single player or multiplayer, the dimension and the time played. Never a world's name or a server's address."
|
||||
}
|
||||
Item::AgentControl => {
|
||||
"Your own AI agent can play this game through horizon-ctl or an MCP client, on this computer only."
|
||||
}
|
||||
@@ -641,6 +653,7 @@ impl Item {
|
||||
Item::Sort => e.sort,
|
||||
Item::NoAi => e.no_ai,
|
||||
Item::AgentControl => e.agent_control,
|
||||
Item::DiscordPresence => e.discord_presence,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -698,6 +711,7 @@ impl Item {
|
||||
Item::MinimapZoom => e.minimap_zoom = next(&MINIMAP_ZOOMS, e.minimap_zoom, back),
|
||||
Item::NoAi => e.no_ai = !e.no_ai,
|
||||
Item::AgentControl => e.agent_control = !e.agent_control,
|
||||
Item::DiscordPresence => e.discord_presence = !e.discord_presence,
|
||||
Item::ZoomKey | Item::SortKey => {}
|
||||
}
|
||||
}
|
||||
@@ -721,6 +735,7 @@ mod tests {
|
||||
assert!(!d.fullbright && !d.dynamic_lights);
|
||||
assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect);
|
||||
assert!(!d.mouse_tweaks && !d.sort);
|
||||
assert!(d.discord_presence);
|
||||
assert_eq!(Extras::parse(""), d);
|
||||
assert_eq!(Extras::parse(&d.serialize()), d);
|
||||
let mut e = d.clone();
|
||||
@@ -746,6 +761,7 @@ mod tests {
|
||||
e.mouse_tweaks_wheel = false;
|
||||
e.sort = true;
|
||||
e.sort_key = "key.keyboard.r".into();
|
||||
e.discord_presence = false;
|
||||
assert_eq!(Extras::parse(&e.serialize()), e);
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ mod debug_keys;
|
||||
mod decorated_pot;
|
||||
mod dedicated;
|
||||
mod deflect;
|
||||
mod discord;
|
||||
mod dispense_fixture;
|
||||
mod dispenser;
|
||||
mod dragon;
|
||||
@@ -11425,6 +11426,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.track_toggle_screens();
|
||||
// For the "I'm playing" ping: an atomic, sent on when it changes.
|
||||
horizon_client::heartbeat::set_lan(self.is_published());
|
||||
self.update_discord_presence();
|
||||
let steps = self.clock.advance(elapsed);
|
||||
// The world ticking in the frame: once its ticks took a
|
||||
// tick's length, the rest are dropped (`FixedStep::tick_fits`).
|
||||
@@ -12896,6 +12898,7 @@ fn write_report(game: &Game<'_>) -> Result<()> {
|
||||
|
||||
fn run_event_loop(mut game: Game<'_>) -> Result<()> {
|
||||
EventLoop::new()?.run_app(&mut game)?;
|
||||
horizon_client::discord_presence::stop();
|
||||
write_report(&game)?;
|
||||
if let Some(e) = game.error.take() {
|
||||
return Err(e);
|
||||
@@ -13253,6 +13256,7 @@ fn run_loading(
|
||||
};
|
||||
let mut app = App::Loading(Box::new(loading));
|
||||
EventLoop::new()?.run_app(&mut app)?;
|
||||
horizon_client::discord_presence::stop();
|
||||
match app {
|
||||
App::Ready(mut game) => {
|
||||
write_report(&game)?;
|
||||
@@ -13303,6 +13307,14 @@ pub fn run() -> Result<()> {
|
||||
horizon_client::spans::enable(options.spikes.is_some());
|
||||
let vanilla_root = options.resources.clone();
|
||||
let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt"));
|
||||
// "Playing Horizon" on Discord: never for a server; an automated run only talks to a test's fake Discord.
|
||||
if options.dedicated.is_none() {
|
||||
let automated = options.benchmark.is_some()
|
||||
|| options.offscreen
|
||||
|| options.frames.is_some()
|
||||
|| options.world_frames.is_some();
|
||||
horizon_client::discord_presence::start(early_settings.extras.discord_presence, automated);
|
||||
}
|
||||
// Snapshots of derived tables live in the game folder, never beside the
|
||||
// shared resources.
|
||||
Behaviours::set_cache_dir(std::env::current_dir()?.join(".horizon-cache"));
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
//! What the player is doing, for Discord Rich Presence (`horizon_client::discord_presence`).
|
||||
use super::*;
|
||||
use horizon_client::discord_presence::{self as presence, Dimension, Play, Status};
|
||||
|
||||
impl Game<'_> {
|
||||
/// Each frame: only a change reaches the presence thread.
|
||||
pub(super) fn update_discord_presence(&self) {
|
||||
presence::set(self.discord_status());
|
||||
}
|
||||
fn discord_status(&self) -> Status {
|
||||
if !self.settings.extras.discord_presence {
|
||||
return Status::Off;
|
||||
}
|
||||
if self.title.is_some() {
|
||||
return Status::Menus;
|
||||
}
|
||||
let play = if let Some(host) = &self.lan {
|
||||
Play::Hosting {
|
||||
players: 1 + host.hub.guests.len(),
|
||||
}
|
||||
} else if let Some(server) = &self.integrated {
|
||||
match (server.published(), &self.remote) {
|
||||
(Some(_), Some(remote)) => Play::Hosting {
|
||||
players: remote.player_count(),
|
||||
},
|
||||
_ => Play::Singleplayer,
|
||||
}
|
||||
} else if self.remote.is_some() {
|
||||
Play::Multiplayer
|
||||
} else {
|
||||
Play::Singleplayer
|
||||
};
|
||||
Status::World {
|
||||
play,
|
||||
dimension: match self.dim {
|
||||
Dim::Overworld => Dimension::Overworld,
|
||||
Dim::Nether => Dimension::Nether,
|
||||
Dim::End => Dimension::End,
|
||||
},
|
||||
mode: self.mode,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5450,6 +5450,10 @@ impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_
|
||||
}
|
||||
|
||||
impl Remote {
|
||||
/// Players in the server's player list, this one included.
|
||||
pub(super) fn player_count(&self) -> usize {
|
||||
self.players.len()
|
||||
}
|
||||
/// The local player's profile UUID.
|
||||
pub(super) fn profile(&self) -> u128 {
|
||||
self.profile
|
||||
|
||||
@@ -1292,7 +1292,10 @@ impl OptionsUi {
|
||||
open("Graphics...", Page::Graphics),
|
||||
Some(open("Advanced Graphics...", Page::GraphicsAdvanced)),
|
||||
),
|
||||
Row::Buttons(open("Controller Settings...", Page::Controller), None),
|
||||
Row::Buttons(
|
||||
open("Controller Settings...", Page::Controller),
|
||||
Some(self.extra_button(s, crate::extras::Item::DiscordPresence)),
|
||||
),
|
||||
Row::Buttons(
|
||||
open("Extras...", Page::Extras),
|
||||
Some(open("Mods...", Page::Mods)),
|
||||
|
||||
@@ -208,6 +208,28 @@ p50/p95/p99/max frame times), plus CPU and GPU time per frame; [the graphics
|
||||
benchmark](graphics.md#benchmark) is built on it. Frame times include waits for
|
||||
presentation, so `bench` reports what is on screen.
|
||||
|
||||
### Discord Rich Presence
|
||||
|
||||
While Discord runs on the same computer, the player's Discord profile shows
|
||||
"Playing Horizon" and what they are doing: "In the menus", "Singleplayer",
|
||||
"Multiplayer" or "Hosting a world" (with the party size, of 8), the dimension
|
||||
("In the Nether") and the time since they entered the world. It never shows a
|
||||
world's name or a server's address. Horizon Settings has the switch
|
||||
(**Discord Rich Presence**, on by default; `discordPresence` in
|
||||
`horizon-extras.txt`), and `HORIZON_NO_DISCORD=1` turns it off for one run.
|
||||
|
||||
`crates/horizon-client/src/discord_presence.rs` speaks Discord's local IPC
|
||||
itself (the `discord-ipc-N` socket or named pipe, no SDK) from a thread of its
|
||||
own: the frame only hands it a status when it changes. It retries every 15 s
|
||||
while Discord isn't running and stays within Discord's 5 updates per 20 s.
|
||||
Dedicated servers never start it, and automated runs (offscreen, benchmarks)
|
||||
only talk to a fake Discord: `lab.game_env` sets `HORIZON_NO_DISCORD=1`, and
|
||||
`tools/discord_presence_e2e.py` points games at a fake server with
|
||||
`HORIZON_DISCORD_IPC_DIR` (title, world, Nether and quit on both single-player
|
||||
paths; a LAN host and guest; the switch; a Discord started after the game).
|
||||
`DISCORD_APP_ID` is Discord's "Horizon" application, whose `horizon` image is
|
||||
the large one; there are no game-mode images yet.
|
||||
|
||||
### Play on another of your machines
|
||||
|
||||
Horizon targets Linux on x86-64 with an NVIDIA GPU (Vulkan); macOS and Windows
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
#!/usr/bin/env python3
|
||||
"""End-to-end check of Discord Rich Presence: real games talk to a fake Discord.
|
||||
|
||||
Each game gets its own fake Discord IPC server (a Unix socket in a scratch folder, pointed to by
|
||||
HORIZON_DISCORD_IPC_DIR) that answers the handshake with READY and records every SET_ACTIVITY.
|
||||
The game goes title -> world -> Nether -> quit through horizon-ctl, and the activities must say
|
||||
"In the menus", "Singleplayer" in the Overworld, then the Nether, and be cleared on quit:
|
||||
|
||||
single single player on its server thread (the default)
|
||||
in-frame single player ticked in the window's frame (--in-frame)
|
||||
lan a host opens its world to LAN and a guest joins: the guest shows "Multiplayer",
|
||||
the host "Hosting a world" with a party of 2 of 8 (lan-in-frame: the host in-frame)
|
||||
setting off in horizon-extras.txt: nothing reaches Discord; the Horizon Settings switch
|
||||
turns it on (the activity appears) and off (it is cleared)
|
||||
late Discord starts after the game: found within the 15 s retry
|
||||
|
||||
python3 tools/discord_presence_e2e.py # all of them
|
||||
python3 tools/discord_presence_e2e.py --check lan --bin-dir target/fast
|
||||
|
||||
macOS and Linux (Discord's Windows pipes aren't faked here). Games render offscreen, have no audio
|
||||
and use scratch homes (lab.game_env). Needs the prepared resources in .local/horizon-client.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from . import lab
|
||||
except ImportError:
|
||||
import lab
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
HANDSHAKE, FRAME, CLOSE = 0, 1, 2
|
||||
|
||||
|
||||
class FakeDiscord:
|
||||
"""discord-ipc-0 in a scratch folder: READY on handshake, a reply to each command."""
|
||||
|
||||
def __init__(self):
|
||||
# Short: Unix socket paths are limited to ~100 bytes.
|
||||
self.dir = Path(tempfile.mkdtemp(prefix='hzdc-', dir='/tmp'))
|
||||
self.server = None
|
||||
self.activities = [] # (seconds since start, activity or None)
|
||||
self.handshakes = []
|
||||
self.started = time.time()
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def start(self):
|
||||
"""Discord starts: its socket appears."""
|
||||
self.server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.server.bind(str(self.dir / 'discord-ipc-0'))
|
||||
self.server.listen()
|
||||
threading.Thread(target=self.accept, daemon=True).start()
|
||||
|
||||
def accept(self):
|
||||
while True:
|
||||
try:
|
||||
conn, _ = self.server.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self.serve, args=(conn,), daemon=True).start()
|
||||
|
||||
def serve(self, conn):
|
||||
def read():
|
||||
header = conn.recv(8, socket.MSG_WAITALL)
|
||||
if len(header) < 8:
|
||||
raise EOFError
|
||||
op, length = struct.unpack('<II', header)
|
||||
return op, json.loads(conn.recv(length, socket.MSG_WAITALL) or b'null')
|
||||
|
||||
def send(op, payload):
|
||||
body = json.dumps(payload).encode()
|
||||
conn.sendall(struct.pack('<II', op, len(body)) + body)
|
||||
|
||||
try:
|
||||
while True:
|
||||
op, msg = read()
|
||||
if op == HANDSHAKE:
|
||||
with self.lock:
|
||||
self.handshakes.append(msg)
|
||||
send(FRAME, {'cmd': 'DISPATCH', 'evt': 'READY', 'data': {'v': 1}})
|
||||
elif op == FRAME and msg.get('cmd') == 'SET_ACTIVITY':
|
||||
with self.lock:
|
||||
self.activities.append((round(time.time() - self.started, 1), msg['args']['activity']))
|
||||
send(FRAME, {'cmd': 'SET_ACTIVITY', 'nonce': msg['nonce'], 'data': msg['args']['activity']})
|
||||
elif op == CLOSE:
|
||||
return
|
||||
except (EOFError, OSError, ValueError):
|
||||
pass
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def last(self):
|
||||
with self.lock:
|
||||
return self.activities[-1][1] if self.activities else 'nothing yet'
|
||||
|
||||
def wait(self, what, check, timeout=60):
|
||||
"""Waits until the latest activity passes `check` (Discord's limit can hold one back 20 s)."""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
if check(self.last()):
|
||||
print(f' ok: {what}: {json.dumps(self.last())}')
|
||||
return
|
||||
time.sleep(0.25)
|
||||
raise AssertionError(f'{what}: the last activity was {self.last()!r}; all: {self.activities}')
|
||||
|
||||
def close(self):
|
||||
if self.server:
|
||||
self.server.close()
|
||||
shutil.rmtree(self.dir, ignore_errors=True)
|
||||
|
||||
|
||||
def shows(details, state=None):
|
||||
return lambda a: isinstance(a, dict) and a.get('details') == details and (state is None or a.get('state') == state)
|
||||
|
||||
|
||||
class Game:
|
||||
"""One game started by horizon-ctl in a scratch home, with its own fake Discord."""
|
||||
|
||||
def __init__(self, bins, name, args=(), extras=None, discord_running=True):
|
||||
self.ctl = bins / 'horizon-ctl'
|
||||
self.home = Path(tempfile.mkdtemp(prefix=f'hzdp-{name}-'))
|
||||
if extras:
|
||||
(self.home / 'horizon-extras.txt').write_text(extras)
|
||||
self.socket = self.home / 'c.sock'
|
||||
self.discord = FakeDiscord()
|
||||
if discord_running:
|
||||
self.discord.start()
|
||||
extra = {'HORIZON_HOME': self.home, 'HORIZON_TELEMETRY_URL': 'off', 'HORIZON_DISCORD_IPC_DIR': self.discord.dir}
|
||||
self.env = lab.game_env(**extra)
|
||||
self.ctl_run('launch', '--offscreen', '--game', str(bins / 'horizon-client'), '--resources',
|
||||
str(lab.RESOURCES.resolve()), *args)
|
||||
|
||||
def ctl_run(self, *words, timeout=600):
|
||||
r = subprocess.run([str(self.ctl), '--socket', str(self.socket), *words], cwd=self.home, env=self.env,
|
||||
capture_output=True, text=True, timeout=timeout)
|
||||
out = r.stdout.strip().splitlines()
|
||||
reply = json.loads(out[-1]) if out else {'error': r.stderr.strip()}
|
||||
if r.returncode or 'error' in reply:
|
||||
raise AssertionError(f'horizon-ctl {" ".join(words)}: exit {r.returncode}: {reply}')
|
||||
return reply
|
||||
|
||||
def quit(self):
|
||||
try:
|
||||
self.ctl_run('quit', timeout=120)
|
||||
except Exception as e: # the reply can be lost as the game exits
|
||||
print(f' quit: {e}')
|
||||
|
||||
def close(self):
|
||||
self.discord.close()
|
||||
shutil.rmtree(self.home, ignore_errors=True)
|
||||
|
||||
|
||||
def single(bins, args=()):
|
||||
game = Game(bins, 'single', args=args)
|
||||
d = game.discord
|
||||
try:
|
||||
d.wait('title screen', shows('In the menus'))
|
||||
assert d.handshakes[0]['v'] == 1 and d.handshakes[0]['client_id'], d.handshakes
|
||||
game.ctl_run('open', 'Presence', '5', 'creative')
|
||||
game.ctl_run('wait-for', 'loaded', '--timeout', '300')
|
||||
d.wait('in the world', shows('Singleplayer', 'In the Overworld'))
|
||||
start = d.last()['timestamps']['start']
|
||||
assert abs(start - time.time()) < 120 and 'party' not in d.last(), d.last()
|
||||
game.ctl_run('command', 'execute in minecraft:the_nether run tp @s 0 80 0')
|
||||
d.wait('in the Nether', shows('Singleplayer', 'In the Nether'))
|
||||
assert d.last()['timestamps']['start'] == start, 'a dimension change restarted the clock'
|
||||
text = json.dumps(d.activities)
|
||||
assert 'Presence' not in text, f'the world name reached Discord: {text}'
|
||||
game.quit()
|
||||
d.wait('cleared on quit', lambda a: a is None)
|
||||
finally:
|
||||
game.close()
|
||||
|
||||
|
||||
def lan(bins, host_args=()):
|
||||
host = Game(bins, 'host', args=host_args)
|
||||
guest = None
|
||||
try:
|
||||
host.ctl_run('open', 'Hosted', '5', 'creative')
|
||||
host.ctl_run('wait-for', 'loaded', '--timeout', '300')
|
||||
port = lab.free_port()
|
||||
host.ctl_run('lan', 'open', str(port))
|
||||
host.discord.wait('host, alone', lambda a: shows('Hosting a world')(a) and a['party']['size'] == [1, 8])
|
||||
guest = Game(bins, 'guest')
|
||||
guest.discord.wait('guest title screen', shows('In the menus'))
|
||||
guest.ctl_run('connect', f'127.0.0.1:{port}', 'Guest')
|
||||
guest.ctl_run('wait-for', 'loaded', '--timeout', '300')
|
||||
guest.discord.wait('guest in the world', shows('Multiplayer', 'In the Overworld'))
|
||||
assert '127.0.0.1' not in json.dumps(guest.discord.activities), guest.discord.activities
|
||||
host.discord.wait('host with a guest', lambda a: shows('Hosting a world')(a) and a['party']['size'] == [2, 8])
|
||||
guest.quit()
|
||||
guest.discord.wait('guest cleared on quit', lambda a: a is None)
|
||||
host.quit()
|
||||
host.discord.wait('host cleared on quit', lambda a: a is None)
|
||||
finally:
|
||||
for g in (guest, host):
|
||||
if g:
|
||||
g.close()
|
||||
|
||||
|
||||
def setting(bins):
|
||||
"""Off in horizon-extras.txt: Discord never hears from the game. Turned on in Horizon Settings: the
|
||||
activity appears; off again: it is cleared."""
|
||||
game = Game(bins, 'setting', extras='discordPresence:false\n')
|
||||
d = game.discord
|
||||
try:
|
||||
game.ctl_run('wait-for', 'screen', 'title')
|
||||
time.sleep(3)
|
||||
assert not d.handshakes and not d.activities, (d.handshakes, d.activities)
|
||||
game.ctl_run('options', 'horizon')
|
||||
switch = next(w for w in game.ctl_run('ui')['widgets'] if w.get('label', '').startswith('Discord Rich'))
|
||||
assert switch['label'] == 'Discord Rich Presence: Off', switch
|
||||
game.ctl_run('click', switch['id'])
|
||||
d.wait('turned on', shows('In the menus'))
|
||||
game.ctl_run('click', switch['id'])
|
||||
d.wait('turned off', lambda a: a is None)
|
||||
assert 'discordPresence:false' in (game.home / 'horizon-extras.txt').read_text()
|
||||
print(' ok: saved off')
|
||||
game.quit()
|
||||
finally:
|
||||
game.close()
|
||||
|
||||
|
||||
def late(bins):
|
||||
"""Discord started after the game: it is found at the next retry (every 15 s)."""
|
||||
game = Game(bins, 'late', discord_running=False)
|
||||
try:
|
||||
game.ctl_run('wait-for', 'screen', 'title')
|
||||
time.sleep(2)
|
||||
game.discord.start()
|
||||
started = time.time()
|
||||
game.discord.wait('found Discord', shows('In the menus'), timeout=30)
|
||||
print(f' ok: after {time.time() - started:.1f} s')
|
||||
game.quit()
|
||||
finally:
|
||||
game.close()
|
||||
|
||||
|
||||
CHECKS = {'single': single, 'in-frame': lambda b: single(b, ['--in-frame']), 'lan': lan,
|
||||
'lan-in-frame': lambda b: lan(b, ['--in-frame']), 'setting': setting,
|
||||
'late': late}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument('--check', choices=[*CHECKS, 'all'], default='all')
|
||||
parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build with the fast profile)')
|
||||
args = parser.parse_args()
|
||||
if sys.platform == 'win32':
|
||||
sys.exit('the fake Discord is a Unix socket: macOS or Linux only')
|
||||
if args.bin_dir:
|
||||
bins = Path(args.bin_dir).resolve()
|
||||
else:
|
||||
subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bins'],
|
||||
cwd=ROOT, check=True)
|
||||
meta = json.loads(subprocess.run(['cargo', 'metadata', '--format-version', '1', '--no-deps'], cwd=ROOT,
|
||||
capture_output=True, text=True, check=True).stdout)
|
||||
bins = Path(meta['target_directory']) / 'fast'
|
||||
if not (lab.RESOURCES / 'horizon-resources.json').exists():
|
||||
sys.exit(f'no prepared resources in {lab.RESOURCES}')
|
||||
results = {}
|
||||
for name in CHECKS if args.check == 'all' else [args.check]:
|
||||
print(f'[{name}]')
|
||||
started = time.time()
|
||||
try:
|
||||
CHECKS[name](bins)
|
||||
results[name] = True
|
||||
print(f'[{name}] PASS in {time.time() - started:.0f} s')
|
||||
except (AssertionError, KeyError, StopIteration, subprocess.TimeoutExpired) as e:
|
||||
results[name] = False
|
||||
print(f'[{name}] FAIL: {e}')
|
||||
print(json.dumps(results))
|
||||
sys.exit(0 if all(results.values()) else 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user