Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions crates/core/src/battlenet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ pub use launch::{game_uid, game_uri, launch, launch_wrapped, resolve_game_uid, L
pub use readiness::{signs_in_by_itself, wait_until_ready, Readiness, SessionLog, UpdateState};
pub use registry::{apply_registry, registry_tweaks, RegValue};
pub use tweaks::{
account_tweaks, apply_tweaks, auto_update_tweak, configure, configure_accounts, default_tweaks, download_limit,
known_product_codes, product_tweaks, set_download_limit, toasts_tweak, window_state_tweaks, Tweak,
account_tweaks, apply_tweaks, auto_update_tweak, close_hides_window, configure, configure_accounts, default_tweaks,
download_limit, known_product_codes, product_tweaks, set_download_limit, toasts_tweak, window_state_tweaks, Tweak,
AUTOSTART_MINIMIZED_KEY, DOWNLOAD_LIMIT_KEY,
};
pub use window::{ClientWindows, WindowError};
Expand Down
8 changes: 8 additions & 0 deletions crates/core/src/battlenet/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,14 @@ fn a_background_client_hides_on_close() {
assert_eq!(config["User"]["Client"]["DisplayExitPrompt"], json!("false"));
}

#[test]
fn only_a_background_client_survives_its_window_being_closed() {
// A hand-off sends `WM_DELETE_WINDOW` to keep the window in the tray. Sent
// to a client without `HideOnClose`, that quits it mid-launch.
assert!(close_hides_window(true));
assert!(!close_hides_window(false));
}

#[test]
fn only_a_background_client_has_its_notifications_switched_off() {
let mut config = json!({ "User": { "Client": { "ToastsEnabled": "false" } } });
Expand Down
10 changes: 10 additions & 0 deletions crates/core/src/battlenet/tweaks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,16 @@ pub fn account_tweaks(background: bool) -> Vec<Tweak> {
tweaks
}

/// Whether closing the client's window puts it in the tray, under the
/// [`account_tweaks`] for `background`. Without `HideOnClose` the X button,
/// or a `WM_DELETE_WINDOW` sent for it, quits the client outright, and with
/// `DisplayExitPrompt` off there is no countdown to stop it.
pub fn close_hides_window(background: bool) -> bool {
account_tweaks(background)
.iter()
.any(|tweak| tweak.key() == "User.Client.HideOnClose" && tweak.value == json!("true"))
}

/// The settings checkbox "Launch Battle.net minimized to the system tray".
/// Read from `Battle.net.config` only: the same key in the per-account file
/// is ignored, and so is the Qt `WindowState` there (client 2.53.6, measured
Expand Down
13 changes: 10 additions & 3 deletions crates/core/src/preflight/games.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::paths::Layout;

/// How often the prefix is re-scanned while waiting for a handed-off game to
/// start. Slower than [`super::POLL`]: a cold client takes most of a minute.
const HANDOFF_POLL: Duration = Duration::from_millis(500);
pub const HANDOFF_POLL: Duration = Duration::from_millis(500);

/// Wine's own processes, in every prefix and nobody's game. The
/// before-snapshot catches most, but Wine starts services on demand too.
Expand Down Expand Up @@ -182,11 +182,10 @@ pub fn wait_for_game_start(
before: &[GameProcess],
appear_within: Duration,
) -> Option<GameProcess> {
let known: HashSet<u32> = before.iter().map(|p| p.pid).collect();
let deadline = Instant::now() + appear_within;

loop {
if let Some(found) = games_running(layout).into_iter().find(|p| !known.contains(&p.pid)) {
if let Some(found) = game_started(layout, before) {
return Some(found);
}
if Instant::now() >= deadline {
Expand All @@ -195,3 +194,11 @@ pub fn wait_for_game_start(
std::thread::sleep(HANDOFF_POLL);
}
}

/// One look for a game that is not in `before`: [`wait_for_game_start`]
/// without the wait, for a caller that sleeps between looks itself (the GUI,
/// whose async runtime can then drop the wait when the window closes).
pub fn game_started(layout: &Layout, before: &[GameProcess]) -> Option<GameProcess> {
let known: HashSet<u32> = before.iter().map(|p| p.pid).collect();
games_running(layout).into_iter().find(|p| !known.contains(&p.pid))
}
4 changes: 2 additions & 2 deletions crates/core/src/preflight/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ mod shutdown;
mod tests;

pub use games::{
client_pids, client_running, games_running, stop_game, wait_for_exit, wait_for_game_start,
GameProcess, Stopped,
client_pids, client_running, game_started, games_running, stop_game, wait_for_exit,
wait_for_game_start, GameProcess, Stopped, HANDOFF_POLL,
};
pub use gate::{served_by, DownloadGuard, NoDownloads, Preflight, Report, Timing};
pub use scan::{scan, PrefixProcess, ProcKind};
Expand Down
1 change: 1 addition & 0 deletions crates/launcher-gui/src/app/launch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,7 @@ impl Lightforge {
self.family_of(&code),
self.install_uid_of(&code),
self.config.battle_net_minimized,
self.config.battle_net_in_background,
),
Message::HandoffStarted,
)
Expand Down
113 changes: 86 additions & 27 deletions crates/launcher-gui/src/tasks/launch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,8 +290,11 @@ pub async fn launch_via_battle_net(
family: Option<String>,
install_uid: String,
minimized: bool,
background: bool,
) -> Result<Handoff, Problem> {
tokio::task::spawn_blocking(move || -> Result<_, Problem> {
let wait_layout = layout.clone();
let wait_code = code.clone();
let sent = tokio::task::spawn_blocking(move || -> Result<_, Problem> {
use lightforge_core::battlenet::{self, Launch, Readiness};
use lightforge_core::preflight;

Expand All @@ -317,13 +320,13 @@ pub async fn launch_via_battle_net(
== Readiness::NeedsAttention
{
// Left to the user, who is told where the client is.
return Ok(Handoff::NeedsAttention { minimized: minimize });
return Ok(Sent::Done(Handoff::NeedsAttention { minimized: minimize }));
}
}

// Closed meanwhile: sending now would start a cold client that drops it.
if !preflight::client_running(&layout) {
return Ok(Handoff::ClientClosed);
return Ok(Sent::Done(Handoff::ClientClosed));
}

// A game that just exited is still running to the client for a few
Expand All @@ -332,22 +335,28 @@ pub async fn launch_via_battle_net(
if let Some(log) = &session {
if log.pending_update(&install_uid) {
tracing::info!("Battle.net holds {install_uid} back for an update; not sending the launch");
return Ok(Handoff::NeedsUpdate);
return Ok(Sent::Done(Handoff::NeedsUpdate));
}
if !log.wait_until_closed(&install_uid, GAME_GONE_WITHIN) {
tracing::warn!("Battle.net still counts {install_uid} as running; sending the launch anyway");
}
}

// The client raises its window for the command until the game is up;
// one nobody could see before goes straight back to the tray.
let tray = match battlenet::ClientWindows::connect(preflight::client_pids(&layout)) {
Ok(windows) if windows.any_shown().is_ok_and(|shown| !shown) => Some(windows),
Ok(_) => None,
Err(e) => {
tracing::info!("Battle.net's window stays as the client leaves it: {}", chain(&e));
None
}
// one nobody could see before goes straight back to the tray. Only
// where closing hides it: otherwise the close is a quit, and the
// client exits with the launch still in flight (35 ms after
// `GameLaunching=1`, before the game's process exists).
let tray = match battlenet::close_hides_window(background) {
false => None,
true => match battlenet::ClientWindows::connect(preflight::client_pids(&layout)) {
Ok(windows) if windows.any_shown().is_ok_and(|shown| !shown) => Some(windows),
Ok(_) => None,
Err(e) => {
tracing::info!("Battle.net's window stays as the client leaves it: {}", chain(&e));
None
}
},
};

// Over IPC to the running client, with the family the panel resolved.
Expand All @@ -366,29 +375,79 @@ pub async fn launch_via_battle_net(
if session.as_ref().is_some_and(|log| !log.launch_taken(TAKEN_WITHIN)) {
if preflight::client_running(&layout) {
tracing::warn!("Battle.net hand-off for {}: the client did not take the launch", code.as_str());
return Ok(Handoff::Ignored);
return Ok(Sent::Done(Handoff::Ignored));
}
tracing::warn!("Battle.net hand-off for {}: the client closed instead", code.as_str());
return Ok(match session.is_some_and(|log| log.updated_itself()) {
return Ok(Sent::Done(match session.is_some_and(|log| log.updated_itself()) {
true => Handoff::ClientUpdated,
false => Handoff::ClientClosed,
});
}));
}

let handoff = match preflight::wait_for_game_start(&layout, &before, HANDOFF_TIMEOUT) {
Some(game) => Handoff::Playing(game),
None => Handoff::NothingStarted,
};
match &handoff {
Handoff::NothingStarted => {
tracing::warn!("Battle.net hand-off for {}: no game started within {HANDOFF_TIMEOUT:?}", code.as_str());
}
_ => tracing::info!("Battle.net hand-off for {}: game started", code.as_str()),
}
Ok(handoff)
Ok(Sent::Waiting(before))
})
.await
.map_err(|e| Problem::of(&e))?
.map_err(|e| Problem::of(&e))??;

match sent {
Sent::Done(handoff) => Ok(handoff),
Sent::Waiting(before) => wait_for_handoff(wait_layout, wait_code, before).await,
}
}

/// How far a hand-off got on the blocking side.
enum Sent {
/// It ended before the launch went out, or the client never took it.
Done(Handoff),
/// Sent and taken; these are the games that were already running.
Waiting(Vec<lightforge_core::preflight::GameProcess>),
}

/// Wait for the handed-off game, one blocking scan at a time.
///
/// Awaited, not slept on a blocking thread: the runtime waits for every
/// `spawn_blocking` task when it shuts down, so a window closed during a
/// three-minute wait stayed on screen, unresponsive, until the wait ran out.
/// A client that is gone with no new game ends the wait early: nothing is
/// left that could start one.
async fn wait_for_handoff(
layout: Layout,
code: ProductCode,
before: Vec<lightforge_core::preflight::GameProcess>,
) -> Result<Handoff, Problem> {
use lightforge_core::preflight;

let deadline = Instant::now() + HANDOFF_TIMEOUT;
// The client exits right after the game is up (`GameLaunchWindowBehavior: 2`):
// one look more after it is seen gone, so a game that won the race counts.
let mut client_gone = false;
loop {
let scan_layout = layout.clone();
let known = before.clone();
let (started, client_up) = tokio::task::spawn_blocking(move || {
(
preflight::game_started(&scan_layout, &known),
preflight::client_running(&scan_layout),
)
})
.await
.map_err(|e| Problem::of(&e))?;

if let Some(game) = started {
tracing::info!("Battle.net hand-off for {}: game started", code.as_str());
return Ok(Handoff::Playing(game));
}
if !client_up && client_gone {
tracing::warn!("Battle.net hand-off for {}: the client exited and no game started", code.as_str());
return Ok(Handoff::ClientClosed);
}
client_gone = !client_up;
if Instant::now() >= deadline {
tracing::warn!("Battle.net hand-off for {}: no game started within {HANDOFF_TIMEOUT:?}", code.as_str());
return Ok(Handoff::NothingStarted);
}
tokio::time::sleep(preflight::HANDOFF_POLL).await;
}
}

/// Open the client's install flow for a game, dialog and all.
Expand Down