1
0
mirror of https://github.com/ppy/osu.git synced 2025-01-26 21:13:20 +08:00

Merge pull request #25565 from peppy/fix-spectator-quit-2

Fix spectator mode not showing when a spectated user quits correctly
This commit is contained in:
Bartłomiej Dach 2023-11-27 12:14:17 +09:00 committed by GitHub
commit 884b614987
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 79 additions and 74 deletions

View File

@ -43,7 +43,7 @@ namespace osu.Game.Tests.Visual.Gameplay
private TestSpectatorClient spectatorClient => dependenciesScreen.SpectatorClient; private TestSpectatorClient spectatorClient => dependenciesScreen.SpectatorClient;
private DependenciesScreen dependenciesScreen; private DependenciesScreen dependenciesScreen;
private SoloSpectator spectatorScreen; private SoloSpectatorScreen spectatorScreen;
private BeatmapSetInfo importedBeatmap; private BeatmapSetInfo importedBeatmap;
private int importedBeatmapId; private int importedBeatmapId;
@ -100,19 +100,18 @@ namespace osu.Game.Tests.Visual.Gameplay
start(); start();
AddUntilStep("wait for player loader", () => (Stack.CurrentScreen as PlayerLoader)?.IsLoaded == true); AddUntilStep("wait for player loader", () => this.ChildrenOfType<PlayerLoader>().SingleOrDefault()?.IsLoaded == true);
AddUntilStep("queue send frames on player load", () => AddUntilStep("queue send frames on player load", () =>
{ {
var loadingPlayer = (Stack.CurrentScreen as PlayerLoader)?.CurrentPlayer; var loadingPlayer = this.ChildrenOfType<PlayerLoader>().SingleOrDefault()?.CurrentPlayer;
if (loadingPlayer == null) if (loadingPlayer == null)
return false; return false;
loadingPlayer.OnLoadComplete += _ => loadingPlayer.OnLoadComplete += _ =>
{
spectatorClient.SendFramesFromUser(streamingUser.Id, 10, gameplay_start); spectatorClient.SendFramesFromUser(streamingUser.Id, 10, gameplay_start);
};
return true; return true;
}); });
@ -127,7 +126,7 @@ namespace osu.Game.Tests.Visual.Gameplay
{ {
loadSpectatingScreen(); loadSpectatingScreen();
AddAssert("screen hasn't changed", () => Stack.CurrentScreen is SoloSpectator); AddAssert("screen hasn't changed", () => Stack.CurrentScreen is SoloSpectatorScreen);
start(); start();
waitForPlayer(); waitForPlayer();
@ -255,7 +254,7 @@ namespace osu.Game.Tests.Visual.Gameplay
start(-1234); start(-1234);
sendFrames(); sendFrames();
AddAssert("screen didn't change", () => Stack.CurrentScreen is SoloSpectator); AddAssert("screen didn't change", () => Stack.CurrentScreen is SoloSpectatorScreen);
} }
[Test] [Test]
@ -333,6 +332,8 @@ namespace osu.Game.Tests.Visual.Gameplay
AddStep("send quit", () => spectatorClient.SendEndPlay(streamingUser.Id)); AddStep("send quit", () => spectatorClient.SendEndPlay(streamingUser.Id));
AddUntilStep("state is quit", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Quit); AddUntilStep("state is quit", () => spectatorClient.WatchedUserStates[streamingUser.Id].State == SpectatedUserState.Quit);
AddAssert("wait for player exit", () => Stack.CurrentScreen is SoloSpectatorScreen);
start(); start();
sendFrames(); sendFrames();
waitForPlayer(); waitForPlayer();
@ -360,12 +361,12 @@ namespace osu.Game.Tests.Visual.Gameplay
private OsuFramedReplayInputHandler replayHandler => private OsuFramedReplayInputHandler replayHandler =>
(OsuFramedReplayInputHandler)Stack.ChildrenOfType<OsuInputManager>().First().ReplayInputHandler; (OsuFramedReplayInputHandler)Stack.ChildrenOfType<OsuInputManager>().First().ReplayInputHandler;
private Player player => Stack.CurrentScreen as Player; private Player player => this.ChildrenOfType<Player>().Single();
private double currentFrameStableTime private double currentFrameStableTime
=> player.ChildrenOfType<FrameStabilityContainer>().First().CurrentTime; => player.ChildrenOfType<FrameStabilityContainer>().First().CurrentTime;
private void waitForPlayer() => AddUntilStep("wait for player", () => (Stack.CurrentScreen as Player)?.IsLoaded == true); private void waitForPlayer() => AddUntilStep("wait for player", () => this.ChildrenOfType<Player>().SingleOrDefault()?.IsLoaded == true);
private void start(int? beatmapId = null) => AddStep("start play", () => spectatorClient.SendStartPlay(streamingUser.Id, beatmapId ?? importedBeatmapId)); private void start(int? beatmapId = null) => AddStep("start play", () => spectatorClient.SendStartPlay(streamingUser.Id, beatmapId ?? importedBeatmapId));
@ -381,7 +382,7 @@ namespace osu.Game.Tests.Visual.Gameplay
private void loadSpectatingScreen() private void loadSpectatingScreen()
{ {
AddStep("load spectator", () => LoadScreen(spectatorScreen = new SoloSpectator(streamingUser))); AddStep("load spectator", () => LoadScreen(spectatorScreen = new SoloSpectatorScreen(streamingUser)));
AddUntilStep("wait for screen load", () => spectatorScreen.LoadState == LoadState.Loaded); AddUntilStep("wait for screen load", () => spectatorScreen.LoadState == LoadState.Loaded);
} }

View File

@ -48,7 +48,7 @@ namespace osu.Game.Online.Spectator
/// <summary> /// <summary>
/// Whether the local user is playing. /// Whether the local user is playing.
/// </summary> /// </summary>
protected internal bool IsPlaying { get; private set; } private bool isPlaying { get; set; }
/// <summary> /// <summary>
/// Called whenever new frames arrive from the server. /// Called whenever new frames arrive from the server.
@ -58,17 +58,17 @@ namespace osu.Game.Online.Spectator
/// <summary> /// <summary>
/// Called whenever a user starts a play session, or immediately if the user is being watched and currently in a play session. /// Called whenever a user starts a play session, or immediately if the user is being watched and currently in a play session.
/// </summary> /// </summary>
public virtual event Action<int, SpectatorState>? OnUserBeganPlaying; public event Action<int, SpectatorState>? OnUserBeganPlaying;
/// <summary> /// <summary>
/// Called whenever a user finishes a play session. /// Called whenever a user finishes a play session.
/// </summary> /// </summary>
public virtual event Action<int, SpectatorState>? OnUserFinishedPlaying; public event Action<int, SpectatorState>? OnUserFinishedPlaying;
/// <summary> /// <summary>
/// Called whenever a user-submitted score has been fully processed. /// Called whenever a user-submitted score has been fully processed.
/// </summary> /// </summary>
public virtual event Action<int, long>? OnUserScoreProcessed; public event Action<int, long>? OnUserScoreProcessed;
/// <summary> /// <summary>
/// A dictionary containing all users currently being watched, with the number of watching components for each user. /// A dictionary containing all users currently being watched, with the number of watching components for each user.
@ -114,7 +114,7 @@ namespace osu.Game.Online.Spectator
} }
// re-send state in case it wasn't received // re-send state in case it wasn't received
if (IsPlaying) if (isPlaying)
// TODO: this is likely sent out of order after a reconnect scenario. needs further consideration. // TODO: this is likely sent out of order after a reconnect scenario. needs further consideration.
BeginPlayingInternal(currentScoreToken, currentState); BeginPlayingInternal(currentScoreToken, currentState);
} }
@ -179,10 +179,10 @@ namespace osu.Game.Online.Spectator
// This schedule is only here to match the one below in `EndPlaying`. // This schedule is only here to match the one below in `EndPlaying`.
Schedule(() => Schedule(() =>
{ {
if (IsPlaying) if (isPlaying)
throw new InvalidOperationException($"Cannot invoke {nameof(BeginPlaying)} when already playing"); throw new InvalidOperationException($"Cannot invoke {nameof(BeginPlaying)} when already playing");
IsPlaying = true; isPlaying = true;
// transfer state at point of beginning play // transfer state at point of beginning play
currentState.BeatmapID = score.ScoreInfo.BeatmapInfo!.OnlineID; currentState.BeatmapID = score.ScoreInfo.BeatmapInfo!.OnlineID;
@ -202,7 +202,7 @@ namespace osu.Game.Online.Spectator
public void HandleFrame(ReplayFrame frame) => Schedule(() => public void HandleFrame(ReplayFrame frame) => Schedule(() =>
{ {
if (!IsPlaying) if (!isPlaying)
{ {
Logger.Log($"Frames arrived at {nameof(SpectatorClient)} outside of gameplay scope and will be ignored."); Logger.Log($"Frames arrived at {nameof(SpectatorClient)} outside of gameplay scope and will be ignored.");
return; return;
@ -224,7 +224,7 @@ namespace osu.Game.Online.Spectator
// We probably need to find a better way to handle this... // We probably need to find a better way to handle this...
Schedule(() => Schedule(() =>
{ {
if (!IsPlaying) if (!isPlaying)
return; return;
// Disposal can take some time, leading to EndPlaying potentially being called after a future play session. // Disposal can take some time, leading to EndPlaying potentially being called after a future play session.
@ -235,7 +235,7 @@ namespace osu.Game.Online.Spectator
if (pendingFrames.Count > 0) if (pendingFrames.Count > 0)
purgePendingFrames(); purgePendingFrames();
IsPlaying = false; isPlaying = false;
currentBeatmap = null; currentBeatmap = null;
if (state.HasPassed) if (state.HasPassed)

View File

@ -212,7 +212,7 @@ namespace osu.Game.Overlays.Dashboard
Text = "Spectate", Text = "Spectate",
Anchor = Anchor.TopCentre, Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre, Origin = Anchor.TopCentre,
Action = () => performer?.PerformFromScreen(s => s.Push(new SoloSpectator(User))), Action = () => performer?.PerformFromScreen(s => s.Push(new SoloSpectatorScreen(User))),
Enabled = { Value = User.Id != api.LocalUser.Value.Id } Enabled = { Value = User.Id != api.LocalUser.Value.Id }
} }
} }

View File

@ -228,7 +228,7 @@ namespace osu.Game.Screens.OnlinePlay.Multiplayer.Spectate
{ {
} }
protected override void StartGameplay(int userId, SpectatorGameplayState spectatorGameplayState) protected override void StartGameplay(int userId, SpectatorGameplayState spectatorGameplayState) => Schedule(() =>
{ {
var playerArea = instances.Single(i => i.UserId == userId); var playerArea = instances.Single(i => i.UserId == userId);
@ -242,9 +242,9 @@ namespace osu.Game.Screens.OnlinePlay.Multiplayer.Spectate
return; return;
playerArea.LoadScore(spectatorGameplayState.Score); playerArea.LoadScore(spectatorGameplayState.Score);
} });
protected override void QuitGameplay(int userId) protected override void QuitGameplay(int userId) => Schedule(() =>
{ {
RemoveUser(userId); RemoveUser(userId);
@ -252,7 +252,7 @@ namespace osu.Game.Screens.OnlinePlay.Multiplayer.Spectate
instance.FadeColour(colours.Gray4, 400, Easing.OutQuint); instance.FadeColour(colours.Gray4, 400, Easing.OutQuint);
syncManager.RemoveManagedClock(instance.SpectatorPlayerClock); syncManager.RemoveManagedClock(instance.SpectatorPlayerClock);
} });
public override bool OnBackButton() public override bool OnBackButton()
{ {

View File

@ -1,10 +1,7 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text. // See the LICENCE file in the repository root for full licence text.
#nullable disable
using System.Diagnostics; using System.Diagnostics;
using JetBrains.Annotations;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers;
@ -33,41 +30,40 @@ using osuTK;
namespace osu.Game.Screens.Play namespace osu.Game.Screens.Play
{ {
[Cached(typeof(IPreviewTrackOwner))] [Cached(typeof(IPreviewTrackOwner))]
public partial class SoloSpectator : SpectatorScreen, IPreviewTrackOwner public partial class SoloSpectatorScreen : SpectatorScreen, IPreviewTrackOwner
{ {
[NotNull] [Resolved]
private readonly APIUser targetUser; private IAPIProvider api { get; set; } = null!;
[Resolved] [Resolved]
private IAPIProvider api { get; set; } private PreviewTrackManager previewTrackManager { get; set; } = null!;
[Resolved] [Resolved]
private PreviewTrackManager previewTrackManager { get; set; } private BeatmapManager beatmaps { get; set; } = null!;
[Resolved] [Resolved]
private BeatmapManager beatmaps { get; set; } private BeatmapModelDownloader beatmapDownloader { get; set; } = null!;
[Resolved]
private BeatmapModelDownloader beatmapDownloader { get; set; }
[Cached] [Cached]
private OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple); private OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple);
private Container beatmapPanelContainer; private Container beatmapPanelContainer = null!;
private RoundedButton watchButton; private RoundedButton watchButton = null!;
private SettingsCheckbox automaticDownload; private SettingsCheckbox automaticDownload = null!;
private readonly APIUser targetUser;
/// <summary> /// <summary>
/// The player's immediate online gameplay state. /// The player's immediate online gameplay state.
/// This doesn't always reflect the gameplay state being watched. /// This doesn't always reflect the gameplay state being watched.
/// </summary> /// </summary>
private SpectatorGameplayState immediateSpectatorGameplayState; private SpectatorGameplayState? immediateSpectatorGameplayState;
private GetBeatmapSetRequest onlineBeatmapRequest; private GetBeatmapSetRequest? onlineBeatmapRequest;
private APIBeatmapSet beatmapSet; private APIBeatmapSet? beatmapSet;
public SoloSpectator([NotNull] APIUser targetUser) public SoloSpectatorScreen(APIUser targetUser)
: base(targetUser.Id) : base(targetUser.Id)
{ {
this.targetUser = targetUser; this.targetUser = targetUser;
@ -168,27 +164,33 @@ namespace osu.Game.Screens.Play
automaticDownload.Current.BindValueChanged(_ => checkForAutomaticDownload()); automaticDownload.Current.BindValueChanged(_ => checkForAutomaticDownload());
} }
protected override void OnNewPlayingUserState(int userId, SpectatorState spectatorState) protected override void OnNewPlayingUserState(int userId, SpectatorState spectatorState) => Schedule(() =>
{ {
clearDisplay(); clearDisplay();
showBeatmapPanel(spectatorState); showBeatmapPanel(spectatorState);
} });
protected override void StartGameplay(int userId, SpectatorGameplayState spectatorGameplayState) protected override void StartGameplay(int userId, SpectatorGameplayState spectatorGameplayState) => Schedule(() =>
{ {
immediateSpectatorGameplayState = spectatorGameplayState; immediateSpectatorGameplayState = spectatorGameplayState;
watchButton.Enabled.Value = true; watchButton.Enabled.Value = true;
scheduleStart(spectatorGameplayState); scheduleStart(spectatorGameplayState);
} });
protected override void QuitGameplay(int userId) protected override void QuitGameplay(int userId)
{
// Importantly, don't schedule this call, as a child screen may be present (and will cause the schedule to not be run as expected).
this.MakeCurrent();
Schedule(() =>
{ {
scheduledStart?.Cancel(); scheduledStart?.Cancel();
immediateSpectatorGameplayState = null; immediateSpectatorGameplayState = null;
watchButton.Enabled.Value = false; watchButton.Enabled.Value = false;
clearDisplay(); clearDisplay();
});
} }
private void clearDisplay() private void clearDisplay()
@ -199,10 +201,12 @@ namespace osu.Game.Screens.Play
previewTrackManager.StopAnyPlaying(this); previewTrackManager.StopAnyPlaying(this);
} }
private ScheduledDelegate scheduledStart; private ScheduledDelegate? scheduledStart;
private void scheduleStart(SpectatorGameplayState spectatorGameplayState) private void scheduleStart(SpectatorGameplayState? spectatorGameplayState)
{ {
Debug.Assert(spectatorGameplayState != null);
// This function may be called multiple times in quick succession once the screen becomes current again. // This function may be called multiple times in quick succession once the screen becomes current again.
scheduledStart?.Cancel(); scheduledStart?.Cancel();
scheduledStart = Schedule(() => scheduledStart = Schedule(() =>

View File

@ -1,13 +1,10 @@
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text. // See the LICENCE file in the repository root for full licence text.
#nullable disable
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Bindables; using osu.Framework.Bindables;
using osu.Framework.Extensions; using osu.Framework.Extensions;
@ -33,22 +30,27 @@ namespace osu.Game.Screens.Spectate
private readonly List<int> users = new List<int>(); private readonly List<int> users = new List<int>();
[Resolved] [Resolved]
private BeatmapManager beatmaps { get; set; } private BeatmapManager beatmaps { get; set; } = null!;
[Resolved] [Resolved]
private RulesetStore rulesets { get; set; } private RulesetStore rulesets { get; set; } = null!;
[Resolved] [Resolved]
private SpectatorClient spectatorClient { get; set; } private SpectatorClient spectatorClient { get; set; } = null!;
[Resolved] [Resolved]
private UserLookupCache userLookupCache { get; set; } private UserLookupCache userLookupCache { get; set; } = null!;
[Resolved]
private RealmAccess realm { get; set; } = null!;
private readonly IBindableDictionary<int, SpectatorState> userStates = new BindableDictionary<int, SpectatorState>(); private readonly IBindableDictionary<int, SpectatorState> userStates = new BindableDictionary<int, SpectatorState>();
private readonly Dictionary<int, APIUser> userMap = new Dictionary<int, APIUser>(); private readonly Dictionary<int, APIUser> userMap = new Dictionary<int, APIUser>();
private readonly Dictionary<int, SpectatorGameplayState> gameplayStates = new Dictionary<int, SpectatorGameplayState>(); private readonly Dictionary<int, SpectatorGameplayState> gameplayStates = new Dictionary<int, SpectatorGameplayState>();
private IDisposable? realmSubscription;
/// <summary> /// <summary>
/// Creates a new <see cref="SpectatorScreen"/>. /// Creates a new <see cref="SpectatorScreen"/>.
/// </summary> /// </summary>
@ -58,11 +60,6 @@ namespace osu.Game.Screens.Spectate
this.users.AddRange(users); this.users.AddRange(users);
} }
[Resolved]
private RealmAccess realm { get; set; }
private IDisposable realmSubscription;
protected override void LoadComplete() protected override void LoadComplete()
{ {
base.LoadComplete(); base.LoadComplete();
@ -90,7 +87,7 @@ namespace osu.Game.Screens.Spectate
})); }));
} }
private void beatmapsChanged(IRealmCollection<BeatmapSetInfo> items, ChangeSet changes) private void beatmapsChanged(IRealmCollection<BeatmapSetInfo> items, ChangeSet? changes)
{ {
if (changes?.InsertedIndices == null) return; if (changes?.InsertedIndices == null) return;
@ -109,7 +106,7 @@ namespace osu.Game.Screens.Spectate
} }
} }
private void onUserStatesChanged(object sender, NotifyDictionaryChangedEventArgs<int, SpectatorState> e) private void onUserStatesChanged(object? sender, NotifyDictionaryChangedEventArgs<int, SpectatorState> e)
{ {
switch (e.Action) switch (e.Action)
{ {
@ -132,7 +129,7 @@ namespace osu.Game.Screens.Spectate
switch (newState.State) switch (newState.State)
{ {
case SpectatedUserState.Playing: case SpectatedUserState.Playing:
Schedule(() => OnNewPlayingUserState(userId, newState)); OnNewPlayingUserState(userId, newState);
startGameplay(userId); startGameplay(userId);
break; break;
@ -176,7 +173,7 @@ namespace osu.Game.Screens.Spectate
var gameplayState = new SpectatorGameplayState(score, resolvedRuleset, beatmaps.GetWorkingBeatmap(resolvedBeatmap)); var gameplayState = new SpectatorGameplayState(score, resolvedRuleset, beatmaps.GetWorkingBeatmap(resolvedBeatmap));
gameplayStates[userId] = gameplayState; gameplayStates[userId] = gameplayState;
Schedule(() => StartGameplay(userId, gameplayState)); StartGameplay(userId, gameplayState);
} }
/// <summary> /// <summary>
@ -199,25 +196,28 @@ namespace osu.Game.Screens.Spectate
markReceivedAllFrames(userId); markReceivedAllFrames(userId);
gameplayStates.Remove(userId); gameplayStates.Remove(userId);
Schedule(() => QuitGameplay(userId)); QuitGameplay(userId);
} }
/// <summary> /// <summary>
/// Invoked when a spectated user's state has changed to a new state indicating the player is currently playing. /// Invoked when a spectated user's state has changed to a new state indicating the player is currently playing.
/// Thread safety is not guaranteed should be scheduled as required.
/// </summary> /// </summary>
/// <param name="userId">The user whose state has changed.</param> /// <param name="userId">The user whose state has changed.</param>
/// <param name="spectatorState">The new state.</param> /// <param name="spectatorState">The new state.</param>
protected abstract void OnNewPlayingUserState(int userId, [NotNull] SpectatorState spectatorState); protected abstract void OnNewPlayingUserState(int userId, SpectatorState spectatorState);
/// <summary> /// <summary>
/// Starts gameplay for a user. /// Starts gameplay for a user.
/// Thread safety is not guaranteed should be scheduled as required.
/// </summary> /// </summary>
/// <param name="userId">The user to start gameplay for.</param> /// <param name="userId">The user to start gameplay for.</param>
/// <param name="spectatorGameplayState">The gameplay state.</param> /// <param name="spectatorGameplayState">The gameplay state.</param>
protected abstract void StartGameplay(int userId, [NotNull] SpectatorGameplayState spectatorGameplayState); protected abstract void StartGameplay(int userId, SpectatorGameplayState spectatorGameplayState);
/// <summary> /// <summary>
/// Quits gameplay for a user. /// Quits gameplay for a user.
/// Thread safety is not guaranteed should be scheduled as required.
/// </summary> /// </summary>
/// <param name="userId">The user to quit gameplay for.</param> /// <param name="userId">The user to quit gameplay for.</param>
protected abstract void QuitGameplay(int userId); protected abstract void QuitGameplay(int userId);
@ -243,7 +243,7 @@ namespace osu.Game.Screens.Spectate
{ {
base.Dispose(isDisposing); base.Dispose(isDisposing);
if (spectatorClient != null) if (spectatorClient.IsNotNull())
{ {
foreach ((int userId, var _) in userMap) foreach ((int userId, var _) in userMap)
spectatorClient.StopWatchingUser(userId); spectatorClient.StopWatchingUser(userId);