Merge pull request #10579 from peppy/api-access-state-changed-bindable

Remove IOnlineComponent and change existing components to use bindable flow
This commit is contained in:
Dan Balasescu 2020-10-22 15:36:32 +09:00 committed by GitHub
commit 27c69f6526
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 143 additions and 231 deletions

View File

@ -3,14 +3,13 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using osu.Framework.Graphics.Containers;
using osu.Game.Overlays.Dashboard.Friends;
using osu.Framework.Graphics;
using osu.Game.Users;
using osu.Game.Overlays;
using osu.Framework.Allocation;
using NUnit.Framework; using NUnit.Framework;
using osu.Game.Online.API; using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Overlays;
using osu.Game.Overlays.Dashboard.Friends;
using osu.Game.Users;
namespace osu.Game.Tests.Visual.Online namespace osu.Game.Tests.Visual.Online
{ {
@ -36,7 +35,7 @@ namespace osu.Game.Tests.Visual.Online
[Test] [Test]
public void TestOffline() public void TestOffline()
{ {
AddStep("Populate", () => display.Users = getUsers()); AddStep("Populate with offline test users", () => display.Users = getUsers());
} }
[Test] [Test]
@ -80,14 +79,7 @@ namespace osu.Game.Tests.Visual.Online
private class TestFriendDisplay : FriendDisplay private class TestFriendDisplay : FriendDisplay
{ {
public void Fetch() public void Fetch() => PerformFetch();
{
base.APIStateChanged(API, APIState.Online);
}
public override void APIStateChanged(IAPIProvider api, APIState state)
{
}
} }
} }
} }

View File

@ -32,7 +32,7 @@ namespace osu.Game.Tests.Visual.Online
[Test] [Test]
public void TestOnlineStateVisibility() public void TestOnlineStateVisibility()
{ {
AddStep("set status to online", () => ((DummyAPIAccess)API).State = APIState.Online); AddStep("set status to online", () => ((DummyAPIAccess)API).SetState(APIState.Online));
AddUntilStep("children are visible", () => onlineView.ViewTarget.IsPresent); AddUntilStep("children are visible", () => onlineView.ViewTarget.IsPresent);
AddUntilStep("loading animation is not visible", () => !onlineView.LoadingSpinner.IsPresent); AddUntilStep("loading animation is not visible", () => !onlineView.LoadingSpinner.IsPresent);
@ -41,7 +41,7 @@ namespace osu.Game.Tests.Visual.Online
[Test] [Test]
public void TestOfflineStateVisibility() public void TestOfflineStateVisibility()
{ {
AddStep("set status to offline", () => ((DummyAPIAccess)API).State = APIState.Offline); AddStep("set status to offline", () => ((DummyAPIAccess)API).SetState(APIState.Offline));
AddUntilStep("children are not visible", () => !onlineView.ViewTarget.IsPresent); AddUntilStep("children are not visible", () => !onlineView.ViewTarget.IsPresent);
AddUntilStep("loading animation is not visible", () => !onlineView.LoadingSpinner.IsPresent); AddUntilStep("loading animation is not visible", () => !onlineView.LoadingSpinner.IsPresent);
@ -50,7 +50,7 @@ namespace osu.Game.Tests.Visual.Online
[Test] [Test]
public void TestConnectingStateVisibility() public void TestConnectingStateVisibility()
{ {
AddStep("set status to connecting", () => ((DummyAPIAccess)API).State = APIState.Connecting); AddStep("set status to connecting", () => ((DummyAPIAccess)API).SetState(APIState.Connecting));
AddUntilStep("children are not visible", () => !onlineView.ViewTarget.IsPresent); AddUntilStep("children are not visible", () => !onlineView.ViewTarget.IsPresent);
AddUntilStep("loading animation is visible", () => onlineView.LoadingSpinner.IsPresent); AddUntilStep("loading animation is visible", () => onlineView.LoadingSpinner.IsPresent);
@ -59,7 +59,7 @@ namespace osu.Game.Tests.Visual.Online
[Test] [Test]
public void TestFailingStateVisibility() public void TestFailingStateVisibility()
{ {
AddStep("set status to failing", () => ((DummyAPIAccess)API).State = APIState.Failing); AddStep("set status to failing", () => ((DummyAPIAccess)API).SetState(APIState.Failing));
AddUntilStep("children are not visible", () => !onlineView.ViewTarget.IsPresent); AddUntilStep("children are not visible", () => !onlineView.ViewTarget.IsPresent);
AddUntilStep("loading animation is visible", () => onlineView.LoadingSpinner.IsPresent); AddUntilStep("loading animation is visible", () => onlineView.LoadingSpinner.IsPresent);

View File

@ -63,7 +63,7 @@ namespace osu.Game.Beatmaps
if (checkLocalCache(set, beatmap)) if (checkLocalCache(set, beatmap))
return; return;
if (api?.State != APIState.Online) if (api?.State.Value != APIState.Online)
return; return;
var req = new GetBeatmapRequest(beatmap); var req = new GetBeatmapRequest(beatmap);

View File

@ -78,26 +78,8 @@ namespace osu.Game.Online.API
private void onTokenChanged(ValueChangedEvent<OAuthToken> e) => config.Set(OsuSetting.Token, config.Get<bool>(OsuSetting.SavePassword) ? authentication.TokenString : string.Empty); private void onTokenChanged(ValueChangedEvent<OAuthToken> e) => config.Set(OsuSetting.Token, config.Get<bool>(OsuSetting.SavePassword) ? authentication.TokenString : string.Empty);
private readonly List<IOnlineComponent> components = new List<IOnlineComponent>();
internal new void Schedule(Action action) => base.Schedule(action); internal new void Schedule(Action action) => base.Schedule(action);
/// <summary>
/// Register a component to receive API events.
/// Fires <see cref="IOnlineComponent.APIStateChanged"/> once immediately to ensure a correct state.
/// </summary>
/// <param name="component"></param>
public void Register(IOnlineComponent component)
{
Schedule(() => components.Add(component));
component.APIStateChanged(this, state);
}
public void Unregister(IOnlineComponent component)
{
Schedule(() => components.Remove(component));
}
public string AccessToken => authentication.RequestAccessToken(); public string AccessToken => authentication.RequestAccessToken();
/// <summary> /// <summary>
@ -109,7 +91,7 @@ namespace osu.Game.Online.API
{ {
while (!cancellationToken.IsCancellationRequested) while (!cancellationToken.IsCancellationRequested)
{ {
switch (State) switch (State.Value)
{ {
case APIState.Failing: case APIState.Failing:
//todo: replace this with a ping request. //todo: replace this with a ping request.
@ -131,12 +113,12 @@ namespace osu.Game.Online.API
// work to restore a connection... // work to restore a connection...
if (!HasLogin) if (!HasLogin)
{ {
State = APIState.Offline; state.Value = APIState.Offline;
Thread.Sleep(50); Thread.Sleep(50);
continue; continue;
} }
State = APIState.Connecting; state.Value = APIState.Connecting;
// save the username at this point, if the user requested for it to be. // save the username at this point, if the user requested for it to be.
config.Set(OsuSetting.Username, config.Get<bool>(OsuSetting.SaveUsername) ? ProvidedUsername : string.Empty); config.Set(OsuSetting.Username, config.Get<bool>(OsuSetting.SaveUsername) ? ProvidedUsername : string.Empty);
@ -162,20 +144,20 @@ namespace osu.Game.Online.API
failureCount = 0; failureCount = 0;
//we're connected! //we're connected!
State = APIState.Online; state.Value = APIState.Online;
}; };
if (!handleRequest(userReq)) if (!handleRequest(userReq))
{ {
if (State == APIState.Connecting) if (State.Value == APIState.Connecting)
State = APIState.Failing; state.Value = APIState.Failing;
continue; continue;
} }
// The Success callback event is fired on the main thread, so we should wait for that to run before proceeding. // The Success callback event is fired on the main thread, so we should wait for that to run before proceeding.
// Without this, we will end up circulating this Connecting loop multiple times and queueing up many web requests // Without this, we will end up circulating this Connecting loop multiple times and queueing up many web requests
// before actually going online. // before actually going online.
while (State > APIState.Offline && State < APIState.Online) while (State.Value > APIState.Offline && State.Value < APIState.Online)
Thread.Sleep(500); Thread.Sleep(500);
break; break;
@ -224,7 +206,7 @@ namespace osu.Game.Online.API
public void Login(string username, string password) public void Login(string username, string password)
{ {
Debug.Assert(State == APIState.Offline); Debug.Assert(State.Value == APIState.Offline);
ProvidedUsername = username; ProvidedUsername = username;
this.password = password; this.password = password;
@ -232,7 +214,7 @@ namespace osu.Game.Online.API
public RegistrationRequest.RegistrationRequestErrors CreateAccount(string email, string username, string password) public RegistrationRequest.RegistrationRequestErrors CreateAccount(string email, string username, string password)
{ {
Debug.Assert(State == APIState.Offline); Debug.Assert(State.Value == APIState.Offline);
var req = new RegistrationRequest var req = new RegistrationRequest
{ {
@ -276,7 +258,7 @@ namespace osu.Game.Online.API
req.Perform(this); req.Perform(this);
// we could still be in initialisation, at which point we don't want to say we're Online yet. // we could still be in initialisation, at which point we don't want to say we're Online yet.
if (IsLoggedIn) State = APIState.Online; if (IsLoggedIn) state.Value = APIState.Online;
failureCount = 0; failureCount = 0;
return true; return true;
@ -293,27 +275,12 @@ namespace osu.Game.Online.API
} }
} }
private APIState state; private readonly Bindable<APIState> state = new Bindable<APIState>();
public APIState State /// <summary>
{ /// The current connectivity state of the API.
get => state; /// </summary>
private set public IBindable<APIState> State => state;
{
if (state == value)
return;
APIState oldState = state;
state = value;
log.Add($@"We just went {state}!");
Schedule(() =>
{
components.ForEach(c => c.APIStateChanged(this, state));
OnStateChange?.Invoke(oldState, state);
});
}
}
private bool handleWebException(WebException we) private bool handleWebException(WebException we)
{ {
@ -343,9 +310,9 @@ namespace osu.Game.Online.API
// we might try again at an api level. // we might try again at an api level.
return false; return false;
if (State == APIState.Online) if (State.Value == APIState.Online)
{ {
State = APIState.Failing; state.Value = APIState.Failing;
flushQueue(); flushQueue();
} }
@ -362,10 +329,6 @@ namespace osu.Game.Online.API
lock (queue) queue.Enqueue(request); lock (queue) queue.Enqueue(request);
} }
public event StateChangeDelegate OnStateChange;
public delegate void StateChangeDelegate(APIState oldState, APIState newState);
private void flushQueue(bool failOldRequests = true) private void flushQueue(bool failOldRequests = true)
{ {
lock (queue) lock (queue)
@ -392,7 +355,7 @@ namespace osu.Game.Online.API
// Scheduled prior to state change such that the state changed event is invoked with the correct user present // Scheduled prior to state change such that the state changed event is invoked with the correct user present
Schedule(() => LocalUser.Value = createGuestUser()); Schedule(() => LocalUser.Value = createGuestUser());
State = APIState.Offline; state.Value = APIState.Offline;
} }
private static User createGuestUser() => new GuestUser(); private static User createGuestUser() => new GuestUser();

View File

@ -2,7 +2,6 @@
// See the LICENCE file in the repository root for full licence text. // See the LICENCE file in the repository root for full licence text.
using System; using System;
using System.Collections.Generic;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using osu.Framework.Bindables; using osu.Framework.Bindables;
@ -21,34 +20,23 @@ namespace osu.Game.Online.API
public Bindable<UserActivity> Activity { get; } = new Bindable<UserActivity>(); public Bindable<UserActivity> Activity { get; } = new Bindable<UserActivity>();
public bool IsLoggedIn => State == APIState.Online; public bool IsLoggedIn => State.Value == APIState.Online;
public string ProvidedUsername => LocalUser.Value.Username; public string ProvidedUsername => LocalUser.Value.Username;
public string Endpoint => "http://localhost"; public string Endpoint => "http://localhost";
private APIState state = APIState.Online;
private readonly List<IOnlineComponent> components = new List<IOnlineComponent>();
/// <summary> /// <summary>
/// Provide handling logic for an arbitrary API request. /// Provide handling logic for an arbitrary API request.
/// </summary> /// </summary>
public Action<APIRequest> HandleRequest; public Action<APIRequest> HandleRequest;
public APIState State private readonly Bindable<APIState> state = new Bindable<APIState>(APIState.Online);
{
get => state;
set
{
if (state == value)
return;
state = value; /// <summary>
/// The current connectivity state of the API.
Scheduler.Add(() => components.ForEach(c => c.APIStateChanged(this, value))); /// </summary>
} public IBindable<APIState> State => state;
}
public DummyAPIAccess() public DummyAPIAccess()
{ {
@ -72,17 +60,6 @@ namespace osu.Game.Online.API
return Task.CompletedTask; return Task.CompletedTask;
} }
public void Register(IOnlineComponent component)
{
Scheduler.Add(delegate { components.Add(component); });
component.APIStateChanged(this, state);
}
public void Unregister(IOnlineComponent component)
{
Scheduler.Add(delegate { components.Remove(component); });
}
public void Login(string username, string password) public void Login(string username, string password)
{ {
LocalUser.Value = new User LocalUser.Value = new User
@ -91,13 +68,13 @@ namespace osu.Game.Online.API
Id = 1001, Id = 1001,
}; };
State = APIState.Online; state.Value = APIState.Online;
} }
public void Logout() public void Logout()
{ {
LocalUser.Value = new GuestUser(); LocalUser.Value = new GuestUser();
State = APIState.Offline; state.Value = APIState.Offline;
} }
public RegistrationRequest.RegistrationRequestErrors CreateAccount(string email, string username, string password) public RegistrationRequest.RegistrationRequestErrors CreateAccount(string email, string username, string password)
@ -105,5 +82,7 @@ namespace osu.Game.Online.API
Thread.Sleep(200); Thread.Sleep(200);
return null; return null;
} }
public void SetState(APIState newState) => state.Value = newState;
} }
} }

View File

@ -11,11 +11,13 @@ namespace osu.Game.Online.API
{ {
/// <summary> /// <summary>
/// The local user. /// The local user.
/// This is not thread-safe and should be scheduled locally if consumed from a drawable component.
/// </summary> /// </summary>
Bindable<User> LocalUser { get; } Bindable<User> LocalUser { get; }
/// <summary> /// <summary>
/// The current user's activity. /// The current user's activity.
/// This is not thread-safe and should be scheduled locally if consumed from a drawable component.
/// </summary> /// </summary>
Bindable<UserActivity> Activity { get; } Bindable<UserActivity> Activity { get; }
@ -35,7 +37,11 @@ namespace osu.Game.Online.API
/// </summary> /// </summary>
string Endpoint { get; } string Endpoint { get; }
APIState State { get; } /// <summary>
/// The current connection state of the API.
/// This is not thread-safe and should be scheduled locally if consumed from a drawable component.
/// </summary>
IBindable<APIState> State { get; }
/// <summary> /// <summary>
/// Queue a new request. /// Queue a new request.
@ -61,18 +67,6 @@ namespace osu.Game.Online.API
/// <param name="request">The request to perform.</param> /// <param name="request">The request to perform.</param>
Task PerformAsync(APIRequest request); Task PerformAsync(APIRequest request);
/// <summary>
/// Register a component to receive state changes.
/// </summary>
/// <param name="component">The component to register.</param>
void Register(IOnlineComponent component);
/// <summary>
/// Unregisters a component to receive state changes.
/// </summary>
/// <param name="component">The component to unregister.</param>
void Unregister(IOnlineComponent component);
/// <summary> /// <summary>
/// Attempt to login using the provided credentials. This is a non-blocking operation. /// Attempt to login using the provided credentials. This is a non-blocking operation.
/// </summary> /// </summary>

View File

@ -1,10 +0,0 @@
// 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.
namespace osu.Game.Online.API
{
public interface IOnlineComponent
{
void APIStateChanged(IAPIProvider api, APIState state);
}
}

View File

@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.Colour;
@ -22,7 +23,7 @@ using osuTK.Graphics;
namespace osu.Game.Online.Leaderboards namespace osu.Game.Online.Leaderboards
{ {
public abstract class Leaderboard<TScope, TScoreInfo> : Container, IOnlineComponent public abstract class Leaderboard<TScope, TScoreInfo> : Container
{ {
private const double fade_duration = 300; private const double fade_duration = 300;
@ -242,16 +243,13 @@ namespace osu.Game.Online.Leaderboards
private ScheduledDelegate pendingUpdateScores; private ScheduledDelegate pendingUpdateScores;
private readonly IBindable<APIState> apiState = new Bindable<APIState>();
[BackgroundDependencyLoader] [BackgroundDependencyLoader]
private void load() private void load()
{ {
api?.Register(this); apiState.BindTo(api.State);
} apiState.BindValueChanged(onlineStateChanged, true);
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
api?.Unregister(this);
} }
public void RefreshScores() => UpdateScores(); public void RefreshScores() => UpdateScores();
@ -260,9 +258,9 @@ namespace osu.Game.Online.Leaderboards
protected abstract bool IsOnlineScope { get; } protected abstract bool IsOnlineScope { get; }
public void APIStateChanged(IAPIProvider api, APIState state) private void onlineStateChanged(ValueChangedEvent<APIState> state) => Schedule(() =>
{ {
switch (state) switch (state.NewValue)
{ {
case APIState.Online: case APIState.Online:
case APIState.Offline: case APIState.Offline:
@ -271,7 +269,7 @@ namespace osu.Game.Online.Leaderboards
break; break;
} }
} });
protected void UpdateScores() protected void UpdateScores()
{ {

View File

@ -2,6 +2,7 @@
// See the LICENCE file in the repository root for full licence text. // See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface; using osu.Game.Graphics.UserInterface;
@ -14,7 +15,7 @@ namespace osu.Game.Online
/// A <see cref="Container"/> for displaying online content which require a local user to be logged in. /// A <see cref="Container"/> for displaying online content which require a local user to be logged in.
/// Shows its children only when the local user is logged in and supports displaying a placeholder if not. /// Shows its children only when the local user is logged in and supports displaying a placeholder if not.
/// </summary> /// </summary>
public abstract class OnlineViewContainer : Container, IOnlineComponent public abstract class OnlineViewContainer : Container
{ {
protected LoadingSpinner LoadingSpinner { get; private set; } protected LoadingSpinner LoadingSpinner { get; private set; }
@ -34,8 +35,10 @@ namespace osu.Game.Online
this.placeholderMessage = placeholderMessage; this.placeholderMessage = placeholderMessage;
} }
private readonly IBindable<APIState> apiState = new Bindable<APIState>();
[BackgroundDependencyLoader] [BackgroundDependencyLoader]
private void load() private void load(IAPIProvider api)
{ {
InternalChildren = new Drawable[] InternalChildren = new Drawable[]
{ {
@ -46,18 +49,14 @@ namespace osu.Game.Online
Alpha = 0, Alpha = 0,
} }
}; };
apiState.BindTo(api.State);
apiState.BindValueChanged(onlineStateChanged, true);
} }
protected override void LoadComplete() private void onlineStateChanged(ValueChangedEvent<APIState> state) => Schedule(() =>
{ {
base.LoadComplete(); switch (state.NewValue)
API.Register(this);
}
public virtual void APIStateChanged(IAPIProvider api, APIState state)
{
switch (state)
{ {
case APIState.Offline: case APIState.Offline:
PopContentOut(Content); PopContentOut(Content);
@ -79,7 +78,7 @@ namespace osu.Game.Online
placeholder.FadeOut(transform_duration / 2, Easing.OutQuint); placeholder.FadeOut(transform_duration / 2, Easing.OutQuint);
break; break;
} }
} });
/// <summary> /// <summary>
/// Applies a transform to the online content to make it hidden. /// Applies a transform to the online content to make it hidden.
@ -90,11 +89,5 @@ namespace osu.Game.Online
/// Applies a transform to the online content to make it visible. /// Applies a transform to the online content to make it visible.
/// </summary> /// </summary>
protected virtual void PopContentIn(Drawable content) => content.FadeIn(transform_duration, Easing.OutQuint); protected virtual void PopContentIn(Drawable content) => content.FadeIn(transform_duration, Easing.OutQuint);
protected override void Dispose(bool isDisposing)
{
API?.Unregister(this);
base.Dispose(isDisposing);
}
} }
} }

View File

@ -2,6 +2,7 @@
// See the LICENCE file in the repository root for full licence text. // See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers;
@ -17,7 +18,7 @@ using osuTK.Graphics;
namespace osu.Game.Overlays namespace osu.Game.Overlays
{ {
public class AccountCreationOverlay : OsuFocusedOverlayContainer, IOnlineComponent public class AccountCreationOverlay : OsuFocusedOverlayContainer
{ {
private const float transition_time = 400; private const float transition_time = 400;
@ -30,10 +31,13 @@ namespace osu.Game.Overlays
Origin = Anchor.Centre; Origin = Anchor.Centre;
} }
private readonly IBindable<APIState> apiState = new Bindable<APIState>();
[BackgroundDependencyLoader] [BackgroundDependencyLoader]
private void load(OsuColour colours, IAPIProvider api) private void load(OsuColour colours, IAPIProvider api)
{ {
api.Register(this); apiState.BindTo(api.State);
apiState.BindValueChanged(apiStateChanged, true);
Children = new Drawable[] Children = new Drawable[]
{ {
@ -97,9 +101,9 @@ namespace osu.Game.Overlays
this.FadeOut(100); this.FadeOut(100);
} }
public void APIStateChanged(IAPIProvider api, APIState state) private void apiStateChanged(ValueChangedEvent<APIState> state) => Schedule(() =>
{ {
switch (state) switch (state.NewValue)
{ {
case APIState.Offline: case APIState.Offline:
case APIState.Failing: case APIState.Failing:
@ -112,6 +116,6 @@ namespace osu.Game.Overlays
Hide(); Hide();
break; break;
} }
} });
} }
} }

View File

@ -33,9 +33,14 @@ namespace osu.Game.Overlays
{ {
} }
private readonly IBindable<APIState> apiState = new Bindable<APIState>();
[BackgroundDependencyLoader] [BackgroundDependencyLoader]
private void load() private void load(IAPIProvider api)
{ {
apiState.BindTo(api.State);
apiState.BindValueChanged(onlineStateChanged, true);
Children = new Drawable[] Children = new Drawable[]
{ {
new Box new Box
@ -130,13 +135,13 @@ namespace osu.Game.Overlays
} }
} }
public override void APIStateChanged(IAPIProvider api, APIState state) private void onlineStateChanged(ValueChangedEvent<APIState> state) => Schedule(() =>
{ {
if (State.Value == Visibility.Hidden) if (State.Value == Visibility.Hidden)
return; return;
Header.Current.TriggerChange(); Header.Current.TriggerChange();
} });
protected override void Dispose(bool isDisposing) protected override void Dispose(bool isDisposing)
{ {

View File

@ -12,7 +12,7 @@ using osuTK.Graphics;
namespace osu.Game.Overlays namespace osu.Game.Overlays
{ {
public abstract class FullscreenOverlay<T> : WaveOverlayContainer, IOnlineComponent, INamedOverlayComponent public abstract class FullscreenOverlay<T> : WaveOverlayContainer, INamedOverlayComponent
where T : OverlayHeader where T : OverlayHeader
{ {
public virtual string IconTexture => Header?.Title.IconTexture ?? string.Empty; public virtual string IconTexture => Header?.Title.IconTexture ?? string.Empty;
@ -86,21 +86,5 @@ namespace osu.Game.Overlays
protected virtual void PopOutComplete() protected virtual void PopOutComplete()
{ {
} }
protected override void LoadComplete()
{
base.LoadComplete();
API.Register(this);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
API?.Unregister(this);
}
public virtual void APIStateChanged(IAPIProvider api, APIState state)
{
}
} }
} }

View File

@ -2,6 +2,7 @@
// See the LICENCE file in the repository root for full licence text. // See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers;
using osu.Game.Online.API; using osu.Game.Online.API;
@ -15,7 +16,7 @@ namespace osu.Game.Overlays
/// Automatically performs a data fetch on load. /// Automatically performs a data fetch on load.
/// </remarks> /// </remarks>
/// <typeparam name="T">The type of the API response.</typeparam> /// <typeparam name="T">The type of the API response.</typeparam>
public abstract class OverlayView<T> : CompositeDrawable, IOnlineComponent public abstract class OverlayView<T> : CompositeDrawable
where T : class where T : class
{ {
[Resolved] [Resolved]
@ -29,10 +30,13 @@ namespace osu.Game.Overlays
AutoSizeAxes = Axes.Y; AutoSizeAxes = Axes.Y;
} }
protected override void LoadComplete() private readonly IBindable<APIState> apiState = new Bindable<APIState>();
[BackgroundDependencyLoader]
private void load()
{ {
base.LoadComplete(); apiState.BindTo(API.State);
API.Register(this); apiState.BindValueChanged(onlineStateChanged, true);
} }
/// <summary> /// <summary>
@ -59,20 +63,19 @@ namespace osu.Game.Overlays
API.Queue(request); API.Queue(request);
} }
public virtual void APIStateChanged(IAPIProvider api, APIState state) private void onlineStateChanged(ValueChangedEvent<APIState> state) => Schedule(() =>
{ {
switch (state) switch (state.NewValue)
{ {
case APIState.Online: case APIState.Online:
PerformFetch(); PerformFetch();
break; break;
} }
} });
protected override void Dispose(bool isDisposing) protected override void Dispose(bool isDisposing)
{ {
request?.Cancel(); request?.Cancel();
API?.Unregister(this);
base.Dispose(isDisposing); base.Dispose(isDisposing);
} }
} }

View File

@ -13,6 +13,7 @@ using osu.Game.Online.API;
using osuTK; using osuTK;
using osu.Game.Users; using osu.Game.Users;
using System.ComponentModel; using System.ComponentModel;
using osu.Framework.Bindables;
using osu.Game.Graphics; using osu.Game.Graphics;
using osuTK.Graphics; using osuTK.Graphics;
using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Extensions.Color4Extensions;
@ -25,7 +26,7 @@ using Container = osu.Framework.Graphics.Containers.Container;
namespace osu.Game.Overlays.Settings.Sections.General namespace osu.Game.Overlays.Settings.Sections.General
{ {
public class LoginSettings : FillFlowContainer, IOnlineComponent public class LoginSettings : FillFlowContainer
{ {
private bool bounding = true; private bool bounding = true;
private LoginForm form; private LoginForm form;
@ -41,6 +42,11 @@ namespace osu.Game.Overlays.Settings.Sections.General
/// </summary> /// </summary>
public Action RequestHide; public Action RequestHide;
private readonly IBindable<APIState> apiState = new Bindable<APIState>();
[Resolved]
private IAPIProvider api { get; set; }
public override RectangleF BoundingBox => bounding ? base.BoundingBox : RectangleF.Empty; public override RectangleF BoundingBox => bounding ? base.BoundingBox : RectangleF.Empty;
public bool Bounding public bool Bounding
@ -61,17 +67,18 @@ namespace osu.Game.Overlays.Settings.Sections.General
Spacing = new Vector2(0f, 5f); Spacing = new Vector2(0f, 5f);
} }
[BackgroundDependencyLoader(permitNulls: true)] [BackgroundDependencyLoader]
private void load(IAPIProvider api) private void load()
{ {
api?.Register(this); apiState.BindTo(api.State);
apiState.BindValueChanged(onlineStateChanged, true);
} }
public void APIStateChanged(IAPIProvider api, APIState state) => Schedule(() => private void onlineStateChanged(ValueChangedEvent<APIState> state) => Schedule(() =>
{ {
form = null; form = null;
switch (state) switch (state.NewValue)
{ {
case APIState.Offline: case APIState.Offline:
Children = new Drawable[] Children = new Drawable[]
@ -107,7 +114,7 @@ namespace osu.Game.Overlays.Settings.Sections.General
Origin = Anchor.TopCentre, Origin = Anchor.TopCentre,
TextAnchor = Anchor.TopCentre, TextAnchor = Anchor.TopCentre,
AutoSizeAxes = Axes.Both, AutoSizeAxes = Axes.Both,
Text = state == APIState.Failing ? "Connection is failing, will attempt to reconnect... " : "Attempting to connect... ", Text = state.NewValue == APIState.Failing ? "Connection is failing, will attempt to reconnect... " : "Attempting to connect... ",
Margin = new MarginPadding { Top = 10, Bottom = 10 }, Margin = new MarginPadding { Top = 10, Bottom = 10 },
}, },
}; };

View File

@ -2,6 +2,7 @@
// See the LICENCE file in the repository root for full licence text. // See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics; using osu.Framework.Graphics;
using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Effects;
@ -14,10 +15,15 @@ using osuTK.Graphics;
namespace osu.Game.Overlays.Toolbar namespace osu.Game.Overlays.Toolbar
{ {
public class ToolbarUserButton : ToolbarOverlayToggleButton, IOnlineComponent public class ToolbarUserButton : ToolbarOverlayToggleButton
{ {
private readonly UpdateableAvatar avatar; private readonly UpdateableAvatar avatar;
[Resolved]
private IAPIProvider api { get; set; }
private readonly IBindable<APIState> apiState = new Bindable<APIState>();
public ToolbarUserButton() public ToolbarUserButton()
{ {
AutoSizeAxes = Axes.X; AutoSizeAxes = Axes.X;
@ -44,16 +50,17 @@ namespace osu.Game.Overlays.Toolbar
} }
[BackgroundDependencyLoader(true)] [BackgroundDependencyLoader(true)]
private void load(IAPIProvider api, LoginOverlay login) private void load(LoginOverlay login)
{ {
api.Register(this); apiState.BindTo(api.State);
apiState.BindValueChanged(onlineStateChanged, true);
StateContainer = login; StateContainer = login;
} }
public void APIStateChanged(IAPIProvider api, APIState state) private void onlineStateChanged(ValueChangedEvent<APIState> state) => Schedule(() =>
{ {
switch (state) switch (state.NewValue)
{ {
default: default:
Text = @"Guest"; Text = @"Guest";
@ -65,6 +72,6 @@ namespace osu.Game.Overlays.Toolbar
avatar.User = api.LocalUser.Value; avatar.User = api.LocalUser.Value;
break; break;
} }
} });
} }
} }

View File

@ -29,7 +29,7 @@ using osuTK;
namespace osu.Game.Screens.Multi namespace osu.Game.Screens.Multi
{ {
[Cached] [Cached]
public class Multiplayer : OsuScreen, IOnlineComponent public class Multiplayer : OsuScreen
{ {
public override bool CursorVisible => (screenStack.CurrentScreen as IMultiplayerSubScreen)?.CursorVisible ?? true; public override bool CursorVisible => (screenStack.CurrentScreen as IMultiplayerSubScreen)?.CursorVisible ?? true;
@ -146,15 +146,24 @@ namespace osu.Game.Screens.Multi
screenStack.ScreenExited += screenExited; screenStack.ScreenExited += screenExited;
} }
private readonly IBindable<APIState> apiState = new Bindable<APIState>();
[BackgroundDependencyLoader(true)] [BackgroundDependencyLoader(true)]
private void load(IdleTracker idleTracker) private void load(IdleTracker idleTracker)
{ {
api.Register(this); apiState.BindTo(api.State);
apiState.BindValueChanged(onlineStateChanged, true);
if (idleTracker != null) if (idleTracker != null)
isIdle.BindTo(idleTracker.IsIdle); isIdle.BindTo(idleTracker.IsIdle);
} }
private void onlineStateChanged(ValueChangedEvent<APIState> state) => Schedule(() =>
{
if (state.NewValue != APIState.Online)
Schedule(forcefullyExit);
});
protected override void LoadComplete() protected override void LoadComplete()
{ {
base.LoadComplete(); base.LoadComplete();
@ -199,12 +208,6 @@ namespace osu.Game.Screens.Multi
Logger.Log($"Polling adjusted (listing: {roomManager.TimeBetweenListingPolls}, selection: {roomManager.TimeBetweenSelectionPolls})"); Logger.Log($"Polling adjusted (listing: {roomManager.TimeBetweenListingPolls}, selection: {roomManager.TimeBetweenSelectionPolls})");
} }
public void APIStateChanged(IAPIProvider api, APIState state)
{
if (state != APIState.Online)
Schedule(forcefullyExit);
}
private void forcefullyExit() private void forcefullyExit()
{ {
// This is temporary since we don't currently have a way to force screens to be exited // This is temporary since we don't currently have a way to force screens to be exited
@ -371,12 +374,6 @@ namespace osu.Game.Screens.Multi
} }
} }
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
api?.Unregister(this);
}
private class MultiplayerWaveContainer : WaveContainer private class MultiplayerWaveContainer : WaveContainer
{ {
protected override bool StartHidden => true; protected override bool StartHidden => true;

View File

@ -15,7 +15,7 @@ using osu.Game.Rulesets;
namespace osu.Game.Screens.Select namespace osu.Game.Screens.Select
{ {
public class DifficultyRecommender : Component, IOnlineComponent public class DifficultyRecommender : Component
{ {
[Resolved] [Resolved]
private IAPIProvider api { get; set; } private IAPIProvider api { get; set; }
@ -28,10 +28,13 @@ namespace osu.Game.Screens.Select
private readonly Dictionary<RulesetInfo, double> recommendedStarDifficulty = new Dictionary<RulesetInfo, double>(); private readonly Dictionary<RulesetInfo, double> recommendedStarDifficulty = new Dictionary<RulesetInfo, double>();
private readonly IBindable<APIState> apiState = new Bindable<APIState>();
[BackgroundDependencyLoader] [BackgroundDependencyLoader]
private void load() private void load()
{ {
api.Register(this); apiState.BindTo(api.State);
apiState.BindValueChanged(onlineStateChanged, true);
} }
/// <summary> /// <summary>
@ -72,21 +75,14 @@ namespace osu.Game.Screens.Select
}); });
} }
public void APIStateChanged(IAPIProvider api, APIState state) private void onlineStateChanged(ValueChangedEvent<APIState> state) => Schedule(() =>
{ {
switch (state) switch (state.NewValue)
{ {
case APIState.Online: case APIState.Online:
calculateRecommendedDifficulties(); calculateRecommendedDifficulties();
break; break;
} }
} });
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
api?.Unregister(this);
}
} }
} }