1
0
mirror of https://github.com/ppy/osu.git synced 2025-01-28 03:22:54 +08:00

Merge branch 'master' into use-ReadableKeyCombinationProvider

This commit is contained in:
Dean Herbert 2021-11-08 18:15:49 +09:00
commit 3183b20e2f
38 changed files with 723 additions and 395 deletions

View File

@ -408,8 +408,8 @@ namespace osu.Game.Tests.Beatmaps.IO
var manager = osu.Dependencies.Get<BeatmapManager>(); var manager = osu.Dependencies.Get<BeatmapManager>();
// ReSharper disable once AccessToModifiedClosure // ReSharper disable once AccessToModifiedClosure
manager.ItemUpdated.BindValueChanged(_ => Interlocked.Increment(ref itemAddRemoveFireCount)); manager.ItemUpdated += _ => Interlocked.Increment(ref itemAddRemoveFireCount);
manager.ItemRemoved.BindValueChanged(_ => Interlocked.Increment(ref itemAddRemoveFireCount)); manager.ItemRemoved += _ => Interlocked.Increment(ref itemAddRemoveFireCount);
var imported = await LoadOszIntoOsu(osu); var imported = await LoadOszIntoOsu(osu);

View File

@ -31,22 +31,51 @@ namespace osu.Game.Tests.Visual.Beatmaps
normal.HasVideo = true; normal.HasVideo = true;
normal.HasStoryboard = true; normal.HasStoryboard = true;
var withStatistics = CreateAPIBeatmapSet(Ruleset.Value);
withStatistics.Title = withStatistics.TitleUnicode = "play favourite stats";
withStatistics.Status = BeatmapSetOnlineStatus.Approved;
withStatistics.FavouriteCount = 284_239;
withStatistics.PlayCount = 999_001;
withStatistics.Ranked = DateTimeOffset.Now.AddDays(-45);
withStatistics.HypeStatus = new BeatmapSetHypeStatus
{
Current = 34,
Required = 5
};
withStatistics.NominationStatus = new BeatmapSetNominationStatus
{
Current = 1,
Required = 2
};
var undownloadable = getUndownloadableBeatmapSet(); var undownloadable = getUndownloadableBeatmapSet();
undownloadable.LastUpdated = DateTimeOffset.Now.AddYears(-1);
var someDifficulties = getManyDifficultiesBeatmapSet(11); var someDifficulties = getManyDifficultiesBeatmapSet(11);
someDifficulties.Title = someDifficulties.TitleUnicode = "favourited";
someDifficulties.Title = someDifficulties.TitleUnicode = "some difficulties"; someDifficulties.Title = someDifficulties.TitleUnicode = "some difficulties";
someDifficulties.Status = BeatmapSetOnlineStatus.Qualified; someDifficulties.Status = BeatmapSetOnlineStatus.Qualified;
someDifficulties.HasFavourited = true;
someDifficulties.FavouriteCount = 1;
someDifficulties.NominationStatus = new BeatmapSetNominationStatus
{
Current = 2,
Required = 2
};
var manyDifficulties = getManyDifficultiesBeatmapSet(100); var manyDifficulties = getManyDifficultiesBeatmapSet(100);
manyDifficulties.Status = BeatmapSetOnlineStatus.Pending; manyDifficulties.Status = BeatmapSetOnlineStatus.Pending;
var explicitMap = CreateAPIBeatmapSet(Ruleset.Value); var explicitMap = CreateAPIBeatmapSet(Ruleset.Value);
explicitMap.Title = someDifficulties.TitleUnicode = "explicit beatmap";
explicitMap.HasExplicitContent = true; explicitMap.HasExplicitContent = true;
var featuredMap = CreateAPIBeatmapSet(Ruleset.Value); var featuredMap = CreateAPIBeatmapSet(Ruleset.Value);
featuredMap.Title = someDifficulties.TitleUnicode = "featured artist beatmap";
featuredMap.TrackId = 1; featuredMap.TrackId = 1;
var explicitFeaturedMap = CreateAPIBeatmapSet(Ruleset.Value); var explicitFeaturedMap = CreateAPIBeatmapSet(Ruleset.Value);
explicitFeaturedMap.Title = someDifficulties.TitleUnicode = "explicit featured artist";
explicitFeaturedMap.HasExplicitContent = true; explicitFeaturedMap.HasExplicitContent = true;
explicitFeaturedMap.TrackId = 2; explicitFeaturedMap.TrackId = 2;
@ -59,6 +88,7 @@ namespace osu.Game.Tests.Visual.Beatmaps
testCases = new[] testCases = new[]
{ {
normal, normal,
withStatistics,
undownloadable, undownloadable,
someDifficulties, someDifficulties,
manyDifficulties, manyDifficulties,

View File

@ -10,6 +10,7 @@ using osu.Game.Scoring;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Bindables; using osu.Framework.Bindables;
using osu.Framework.Testing; using osu.Framework.Testing;
using osu.Game.Database;
using osu.Game.Graphics.UserInterface; using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets; using osu.Game.Rulesets;
using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu;
@ -113,6 +114,36 @@ namespace osu.Game.Tests.Visual.Gameplay
AddAssert("button is not enabled", () => !downloadButton.ChildrenOfType<DownloadButton>().First().Enabled.Value); AddAssert("button is not enabled", () => !downloadButton.ChildrenOfType<DownloadButton>().First().Enabled.Value);
} }
[Resolved]
private ScoreManager scoreManager { get; set; }
[Test]
public void TestScoreImportThenDelete()
{
ILive<ScoreInfo> imported = null;
AddStep("create button without replay", () =>
{
Child = downloadButton = new TestReplayDownloadButton(getScoreInfo(false))
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
};
});
AddUntilStep("wait for load", () => downloadButton.IsLoaded);
AddUntilStep("state is not downloaded", () => downloadButton.State.Value == DownloadState.NotDownloaded);
AddStep("import score", () => imported = scoreManager.Import(getScoreInfo(true)).Result);
AddUntilStep("state is available", () => downloadButton.State.Value == DownloadState.LocallyAvailable);
AddStep("delete score", () => scoreManager.Delete(imported.Value));
AddUntilStep("state is not downloaded", () => downloadButton.State.Value == DownloadState.NotDownloaded);
}
[Test] [Test]
public void CreateButtonWithNoScore() public void CreateButtonWithNoScore()
{ {

View File

@ -45,10 +45,10 @@ namespace osu.Game.Tests.Visual.Online
AddStep("import soleily", () => beatmaps.Import(TestResources.GetQuickTestBeatmapForImport())); AddStep("import soleily", () => beatmaps.Import(TestResources.GetQuickTestBeatmapForImport()));
AddUntilStep("wait for beatmap import", () => beatmaps.GetAllUsableBeatmapSets().Any(b => b.OnlineBeatmapSetID == 241526)); AddUntilStep("wait for beatmap import", () => beatmaps.GetAllUsableBeatmapSets().Any(b => b.OnlineBeatmapSetID == 241526));
AddAssert("button state downloaded", () => downloadButton.DownloadState == DownloadState.LocallyAvailable); AddUntilStep("button state downloaded", () => downloadButton.DownloadState == DownloadState.LocallyAvailable);
createButtonWithBeatmap(createSoleily()); createButtonWithBeatmap(createSoleily());
AddAssert("button state downloaded", () => downloadButton.DownloadState == DownloadState.LocallyAvailable); AddUntilStep("button state downloaded", () => downloadButton.DownloadState == DownloadState.LocallyAvailable);
ensureSoleilyRemoved(); ensureSoleilyRemoved();
AddAssert("button state not downloaded", () => downloadButton.DownloadState == DownloadState.NotDownloaded); AddAssert("button state not downloaded", () => downloadButton.DownloadState == DownloadState.NotDownloaded);
} }

View File

@ -10,7 +10,6 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using JetBrains.Annotations; using JetBrains.Annotations;
using osu.Framework.Audio; using osu.Framework.Audio;
using osu.Framework.Bindables;
using osu.Framework.IO.Stores; using osu.Framework.IO.Stores;
using osu.Framework.Platform; using osu.Framework.Platform;
using osu.Framework.Testing; using osu.Framework.Testing;
@ -101,12 +100,20 @@ namespace osu.Game.Beatmaps
/// <summary> /// <summary>
/// Fired when a single difficulty has been hidden. /// Fired when a single difficulty has been hidden.
/// </summary> /// </summary>
public IBindable<WeakReference<BeatmapInfo>> BeatmapHidden => beatmapModelManager.BeatmapHidden; public event Action<BeatmapInfo> BeatmapHidden
{
add => beatmapModelManager.BeatmapHidden += value;
remove => beatmapModelManager.BeatmapHidden -= value;
}
/// <summary> /// <summary>
/// Fired when a single difficulty has been restored. /// Fired when a single difficulty has been restored.
/// </summary> /// </summary>
public IBindable<WeakReference<BeatmapInfo>> BeatmapRestored => beatmapModelManager.BeatmapRestored; public event Action<BeatmapInfo> BeatmapRestored
{
add => beatmapModelManager.BeatmapRestored += value;
remove => beatmapModelManager.BeatmapRestored -= value;
}
/// <summary> /// <summary>
/// Saves an <see cref="IBeatmap"/> file against a given <see cref="BeatmapInfo"/>. /// Saves an <see cref="IBeatmap"/> file against a given <see cref="BeatmapInfo"/>.
@ -198,9 +205,17 @@ namespace osu.Game.Beatmaps
return beatmapModelManager.IsAvailableLocally(model); return beatmapModelManager.IsAvailableLocally(model);
} }
public IBindable<WeakReference<BeatmapSetInfo>> ItemUpdated => beatmapModelManager.ItemUpdated; public event Action<BeatmapSetInfo> ItemUpdated
{
add => beatmapModelManager.ItemUpdated += value;
remove => beatmapModelManager.ItemUpdated -= value;
}
public IBindable<WeakReference<BeatmapSetInfo>> ItemRemoved => beatmapModelManager.ItemRemoved; public event Action<BeatmapSetInfo> ItemRemoved
{
add => beatmapModelManager.ItemRemoved += value;
remove => beatmapModelManager.ItemRemoved -= value;
}
public Task ImportFromStableAsync(StableStorage stableStorage) public Task ImportFromStableAsync(StableStorage stableStorage)
{ {
@ -246,9 +261,17 @@ namespace osu.Game.Beatmaps
#region Implementation of IModelDownloader<BeatmapSetInfo> #region Implementation of IModelDownloader<BeatmapSetInfo>
public IBindable<WeakReference<ArchiveDownloadRequest<IBeatmapSetInfo>>> DownloadBegan => beatmapModelDownloader.DownloadBegan; public event Action<ArchiveDownloadRequest<IBeatmapSetInfo>> DownloadBegan
{
add => beatmapModelDownloader.DownloadBegan += value;
remove => beatmapModelDownloader.DownloadBegan -= value;
}
public IBindable<WeakReference<ArchiveDownloadRequest<IBeatmapSetInfo>>> DownloadFailed => beatmapModelDownloader.DownloadFailed; public event Action<ArchiveDownloadRequest<IBeatmapSetInfo>> DownloadFailed
{
add => beatmapModelDownloader.DownloadFailed += value;
remove => beatmapModelDownloader.DownloadFailed -= value;
}
public bool Download(IBeatmapSetInfo model, bool minimiseDownloadSize = false) => public bool Download(IBeatmapSetInfo model, bool minimiseDownloadSize = false) =>
beatmapModelDownloader.Download(model, minimiseDownloadSize); beatmapModelDownloader.Download(model, minimiseDownloadSize);

View File

@ -11,7 +11,6 @@ using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using osu.Framework.Audio.Track; using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
using osu.Framework.Extensions; using osu.Framework.Extensions;
using osu.Framework.Graphics.Textures; using osu.Framework.Graphics.Textures;
using osu.Framework.Logging; using osu.Framework.Logging;
@ -37,14 +36,12 @@ namespace osu.Game.Beatmaps
/// <summary> /// <summary>
/// Fired when a single difficulty has been hidden. /// Fired when a single difficulty has been hidden.
/// </summary> /// </summary>
public IBindable<WeakReference<BeatmapInfo>> BeatmapHidden => beatmapHidden; public event Action<BeatmapInfo> BeatmapHidden;
private readonly Bindable<WeakReference<BeatmapInfo>> beatmapHidden = new Bindable<WeakReference<BeatmapInfo>>();
/// <summary> /// <summary>
/// Fired when a single difficulty has been restored. /// Fired when a single difficulty has been restored.
/// </summary> /// </summary>
public IBindable<WeakReference<BeatmapInfo>> BeatmapRestored => beatmapRestored; public event Action<BeatmapInfo> BeatmapRestored;
/// <summary> /// <summary>
/// An online lookup queue component which handles populating online beatmap metadata. /// An online lookup queue component which handles populating online beatmap metadata.
@ -56,8 +53,6 @@ namespace osu.Game.Beatmaps
/// </summary> /// </summary>
public IWorkingBeatmapCache WorkingBeatmapCache { private get; set; } public IWorkingBeatmapCache WorkingBeatmapCache { private get; set; }
private readonly Bindable<WeakReference<BeatmapInfo>> beatmapRestored = new Bindable<WeakReference<BeatmapInfo>>();
public override IEnumerable<string> HandledExtensions => new[] { ".osz" }; public override IEnumerable<string> HandledExtensions => new[] { ".osz" };
protected override string[] HashableFileTypes => new[] { ".osu" }; protected override string[] HashableFileTypes => new[] { ".osu" };
@ -75,8 +70,8 @@ namespace osu.Game.Beatmaps
this.rulesets = rulesets; this.rulesets = rulesets;
beatmaps = (BeatmapStore)ModelStore; beatmaps = (BeatmapStore)ModelStore;
beatmaps.BeatmapHidden += b => beatmapHidden.Value = new WeakReference<BeatmapInfo>(b); beatmaps.BeatmapHidden += b => BeatmapHidden?.Invoke(b);
beatmaps.BeatmapRestored += b => beatmapRestored.Value = new WeakReference<BeatmapInfo>(b); beatmaps.BeatmapRestored += b => BeatmapRestored?.Invoke(b);
beatmaps.ItemRemoved += b => WorkingBeatmapCache?.Invalidate(b); beatmaps.ItemRemoved += b => WorkingBeatmapCache?.Invalidate(b);
beatmaps.ItemUpdated += obj => WorkingBeatmapCache?.Invalidate(obj); beatmaps.ItemUpdated += obj => WorkingBeatmapCache?.Invalidate(obj);
} }

View File

@ -0,0 +1,25 @@
// 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.
using Newtonsoft.Json;
namespace osu.Game.Beatmaps
{
/// <summary>
/// Contains information about the current hype status of a beatmap set.
/// </summary>
public class BeatmapSetHypeStatus
{
/// <summary>
/// The current number of hypes that the set has received.
/// </summary>
[JsonProperty(@"current")]
public int Current { get; set; }
/// <summary>
/// The number of hypes required so that the set is eligible for nomination.
/// </summary>
[JsonProperty(@"required")]
public int Required { get; set; }
}
}

View File

@ -0,0 +1,25 @@
// 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.
using Newtonsoft.Json;
namespace osu.Game.Beatmaps
{
/// <summary>
/// Contains information about the current nomination status of a beatmap set.
/// </summary>
public class BeatmapSetNominationStatus
{
/// <summary>
/// The current number of nominations that the set has received.
/// </summary>
[JsonProperty(@"current")]
public int Current { get; set; }
/// <summary>
/// The number of nominations required so that the map is eligible for qualification.
/// </summary>
[JsonProperty(@"required")]
public int Required { get; set; }
}
}

View File

@ -1,6 +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.
using System.Collections.Generic;
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;
@ -8,6 +9,7 @@ using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Events; using osu.Framework.Input.Events;
using osu.Framework.Localisation; using osu.Framework.Localisation;
using osu.Game.Beatmaps.Drawables.Cards.Statistics;
using osu.Game.Graphics; using osu.Game.Graphics;
using osu.Game.Graphics.Containers; using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites; using osu.Game.Graphics.Sprites;
@ -40,6 +42,7 @@ namespace osu.Game.Beatmaps.Drawables.Cards
private GridContainer titleContainer; private GridContainer titleContainer;
private GridContainer artistContainer; private GridContainer artistContainer;
private FillFlowContainer<BeatmapCardStatistic> statisticsContainer;
[Resolved] [Resolved]
private OverlayColourProvider colourProvider { get; set; } private OverlayColourProvider colourProvider { get; set; }
@ -176,6 +179,15 @@ namespace osu.Game.Beatmaps.Drawables.Cards
d.AddText("mapped by ", t => t.Colour = colourProvider.Content2); d.AddText("mapped by ", t => t.Colour = colourProvider.Content2);
d.AddUserLink(beatmapSet.Author); d.AddUserLink(beatmapSet.Author);
}), }),
statisticsContainer = new FillFlowContainer<BeatmapCardStatistic>
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(10, 0),
Alpha = 0,
ChildrenEnumerable = createStatistics()
}
} }
}, },
new FillFlowContainer new FillFlowContainer
@ -265,6 +277,24 @@ namespace osu.Game.Beatmaps.Drawables.Cards
return BeatmapsetsStrings.ShowDetailsByArtist(romanisableArtist); return BeatmapsetsStrings.ShowDetailsByArtist(romanisableArtist);
} }
private IEnumerable<BeatmapCardStatistic> createStatistics()
{
if (beatmapSet.HypeStatus != null)
yield return new HypesStatistic(beatmapSet.HypeStatus);
// web does not show nominations unless hypes are also present.
// see: https://github.com/ppy/osu-web/blob/8ed7d071fd1d3eaa7e43cf0e4ff55ca2fef9c07c/resources/assets/lib/beatmapset-panel.tsx#L443
if (beatmapSet.HypeStatus != null && beatmapSet.NominationStatus != null)
yield return new NominationsStatistic(beatmapSet.NominationStatus);
yield return new FavouritesStatistic(beatmapSet);
yield return new PlayCountStatistic(beatmapSet);
var dateStatistic = BeatmapCardDateStatistic.CreateFor(beatmapSet);
if (dateStatistic != null)
yield return dateStatistic;
}
private void updateState() private void updateState()
{ {
float targetWidth = width - height; float targetWidth = width - height;
@ -275,6 +305,7 @@ namespace osu.Game.Beatmaps.Drawables.Cards
mainContentBackground.Dimmed.Value = IsHovered; mainContentBackground.Dimmed.Value = IsHovered;
leftCover.FadeColour(IsHovered ? OsuColour.Gray(0.2f) : Color4.White, TRANSITION_DURATION, Easing.OutQuint); leftCover.FadeColour(IsHovered ? OsuColour.Gray(0.2f) : Color4.White, TRANSITION_DURATION, Easing.OutQuint);
statisticsContainer.FadeTo(IsHovered ? 1 : 0, TRANSITION_DURATION, Easing.OutQuint);
} }
} }
} }

View File

@ -0,0 +1,55 @@
// 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.
#nullable enable
using System;
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
namespace osu.Game.Beatmaps.Drawables.Cards.Statistics
{
public class BeatmapCardDateStatistic : BeatmapCardStatistic
{
private readonly DateTimeOffset dateTime;
private BeatmapCardDateStatistic(DateTimeOffset dateTime)
{
this.dateTime = dateTime;
Icon = FontAwesome.Regular.CheckCircle;
Text = dateTime.ToLocalisableString(@"d MMM yyyy");
}
public override object TooltipContent => dateTime;
public override ITooltip GetCustomTooltip() => new DateTooltip();
public static BeatmapCardDateStatistic? CreateFor(IBeatmapSetOnlineInfo beatmapSetInfo)
{
var displayDate = displayDateFor(beatmapSetInfo);
if (displayDate == null)
return null;
return new BeatmapCardDateStatistic(displayDate.Value);
}
private static DateTimeOffset? displayDateFor(IBeatmapSetOnlineInfo beatmapSetInfo)
{
// reference: https://github.com/ppy/osu-web/blob/ef432c11719fd1207bec5f9194b04f0033bdf02c/resources/assets/lib/beatmapset-panel.tsx#L36-L44
switch (beatmapSetInfo.Status)
{
case BeatmapSetOnlineStatus.Ranked:
case BeatmapSetOnlineStatus.Approved:
case BeatmapSetOnlineStatus.Loved:
case BeatmapSetOnlineStatus.Qualified:
return beatmapSetInfo.Ranked;
default:
return beatmapSetInfo.LastUpdated;
}
}
}
}

View File

@ -0,0 +1,80 @@
// 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.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Overlays;
using osuTK;
namespace osu.Game.Beatmaps.Drawables.Cards.Statistics
{
/// <summary>
/// A single statistic shown on a beatmap card.
/// </summary>
public abstract class BeatmapCardStatistic : CompositeDrawable, IHasTooltip, IHasCustomTooltip
{
protected IconUsage Icon
{
get => spriteIcon.Icon;
set => spriteIcon.Icon = value;
}
protected LocalisableString Text
{
get => spriteText.Text;
set => spriteText.Text = value;
}
public LocalisableString TooltipText { get; protected set; }
private readonly SpriteIcon spriteIcon;
private readonly OsuSpriteText spriteText;
protected BeatmapCardStatistic()
{
AutoSizeAxes = Axes.Both;
InternalChild = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(5, 0),
Children = new Drawable[]
{
spriteIcon = new SpriteIcon
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Size = new Vector2(10),
Margin = new MarginPadding { Top = 1 }
},
spriteText = new OsuSpriteText
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Font = OsuFont.Default.With(size: 14)
}
}
};
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
spriteIcon.Colour = colourProvider.Content2;
}
#region Tooltip implementation
public virtual ITooltip GetCustomTooltip() => null;
public virtual object TooltipContent => null;
#endregion
}
}

View File

@ -0,0 +1,23 @@
// 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.
using Humanizer;
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Graphics.Sprites;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Beatmaps.Drawables.Cards.Statistics
{
/// <summary>
/// Shows the number of favourites that a beatmap set has received.
/// </summary>
public class FavouritesStatistic : BeatmapCardStatistic
{
public FavouritesStatistic(IBeatmapSetOnlineInfo onlineInfo)
{
Icon = onlineInfo.HasFavourited ? FontAwesome.Solid.Heart : FontAwesome.Regular.Heart;
Text = onlineInfo.FavouriteCount.ToMetric(decimals: 1);
TooltipText = BeatmapsStrings.PanelFavourites(onlineInfo.FavouriteCount.ToLocalisableString(@"N0"));
}
}
}

View File

@ -0,0 +1,22 @@
// 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.
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Graphics.Sprites;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Beatmaps.Drawables.Cards.Statistics
{
/// <summary>
/// Shows the number of current hypes that a map has received, as well as the number of hypes required for nomination.
/// </summary>
public class HypesStatistic : BeatmapCardStatistic
{
public HypesStatistic(BeatmapSetHypeStatus hypeStatus)
{
Icon = FontAwesome.Solid.Bullhorn;
Text = hypeStatus.Current.ToLocalisableString();
TooltipText = BeatmapsStrings.HypeRequiredText(hypeStatus.Current.ToLocalisableString(), hypeStatus.Required.ToLocalisableString());
}
}
}

View File

@ -0,0 +1,22 @@
// 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.
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Graphics.Sprites;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Beatmaps.Drawables.Cards.Statistics
{
/// <summary>
/// Shows the number of current nominations that a map has received, as well as the number of nominations required for qualification.
/// </summary>
public class NominationsStatistic : BeatmapCardStatistic
{
public NominationsStatistic(BeatmapSetNominationStatus nominationStatus)
{
Icon = FontAwesome.Solid.ThumbsUp;
Text = nominationStatus.Current.ToLocalisableString();
TooltipText = BeatmapsStrings.NominationsRequiredText(nominationStatus.Current.ToLocalisableString(), nominationStatus.Required.ToLocalisableString());
}
}
}

View File

@ -0,0 +1,23 @@
// 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.
using Humanizer;
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Graphics.Sprites;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Beatmaps.Drawables.Cards.Statistics
{
/// <summary>
/// Shows the number of times the given beatmap set has been played.
/// </summary>
public class PlayCountStatistic : BeatmapCardStatistic
{
public PlayCountStatistic(IBeatmapSetOnlineInfo onlineInfo)
{
Icon = FontAwesome.Regular.PlayCircle;
Text = onlineInfo.PlayCount.ToMetric(decimals: 1);
TooltipText = BeatmapsStrings.PanelPlaycount(onlineInfo.PlayCount.ToLocalisableString(@"N0"));
}
}
}

View File

@ -102,5 +102,19 @@ namespace osu.Game.Beatmaps
/// Total vote counts of user ratings on a scale of 0..10 where 0 is unused (probably will be fixed at API?). /// Total vote counts of user ratings on a scale of 0..10 where 0 is unused (probably will be fixed at API?).
/// </summary> /// </summary>
int[]? Ratings { get; } int[]? Ratings { get; }
/// <summary>
/// Contains the current hype status of the beatmap set.
/// Non-null only for <see cref="BeatmapSetOnlineStatus.WIP"/>, <see cref="BeatmapSetOnlineStatus.Pending"/>, and <see cref="BeatmapSetOnlineStatus.Qualified"/> sets.
/// </summary>
/// <remarks>
/// See: https://github.com/ppy/osu-web/blob/93930cd02cfbd49724929912597c727c9fbadcd1/app/Models/Beatmapset.php#L155
/// </remarks>
BeatmapSetHypeStatus? HypeStatus { get; }
/// <summary>
/// Contains the current nomination status of the beatmap set.
/// </summary>
BeatmapSetNominationStatus? NominationStatus { get; }
} }
} }

View File

@ -10,7 +10,6 @@ using System.Threading.Tasks;
using Humanizer; using Humanizer;
using JetBrains.Annotations; using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using osu.Framework.Bindables;
using osu.Framework.Extensions; using osu.Framework.Extensions;
using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Logging; using osu.Framework.Logging;
@ -63,17 +62,13 @@ namespace osu.Game.Database
/// Fired when a new or updated <typeparamref name="TModel"/> becomes available in the database. /// Fired when a new or updated <typeparamref name="TModel"/> becomes available in the database.
/// This is not guaranteed to run on the update thread. /// This is not guaranteed to run on the update thread.
/// </summary> /// </summary>
public IBindable<WeakReference<TModel>> ItemUpdated => itemUpdated; public event Action<TModel> ItemUpdated;
private readonly Bindable<WeakReference<TModel>> itemUpdated = new Bindable<WeakReference<TModel>>();
/// <summary> /// <summary>
/// Fired when a <typeparamref name="TModel"/> is removed from the database. /// Fired when a <typeparamref name="TModel"/> is removed from the database.
/// This is not guaranteed to run on the update thread. /// This is not guaranteed to run on the update thread.
/// </summary> /// </summary>
public IBindable<WeakReference<TModel>> ItemRemoved => itemRemoved; public event Action<TModel> ItemRemoved;
private readonly Bindable<WeakReference<TModel>> itemRemoved = new Bindable<WeakReference<TModel>>();
public virtual IEnumerable<string> HandledExtensions => new[] { @".zip" }; public virtual IEnumerable<string> HandledExtensions => new[] { @".zip" };
@ -93,8 +88,8 @@ namespace osu.Game.Database
ContextFactory = contextFactory; ContextFactory = contextFactory;
ModelStore = modelStore; ModelStore = modelStore;
ModelStore.ItemUpdated += item => handleEvent(() => itemUpdated.Value = new WeakReference<TModel>(item)); ModelStore.ItemUpdated += item => handleEvent(() => ItemUpdated?.Invoke(item));
ModelStore.ItemRemoved += item => handleEvent(() => itemRemoved.Value = new WeakReference<TModel>(item)); ModelStore.ItemRemoved += item => handleEvent(() => ItemRemoved?.Invoke(item));
exportStorage = storage.GetStorageForDirectory(@"exports"); exportStorage = storage.GetStorageForDirectory(@"exports");

View File

@ -3,7 +3,6 @@
using System; using System;
using osu.Game.Online.API; using osu.Game.Online.API;
using osu.Framework.Bindables;
namespace osu.Game.Database namespace osu.Game.Database
{ {
@ -18,13 +17,13 @@ namespace osu.Game.Database
/// Fired when a <typeparamref name="T"/> download begins. /// Fired when a <typeparamref name="T"/> download begins.
/// This is NOT run on the update thread and should be scheduled. /// This is NOT run on the update thread and should be scheduled.
/// </summary> /// </summary>
IBindable<WeakReference<ArchiveDownloadRequest<T>>> DownloadBegan { get; } event Action<ArchiveDownloadRequest<T>> DownloadBegan;
/// <summary> /// <summary>
/// Fired when a <typeparamref name="T"/> download is interrupted, either due to user cancellation or failure. /// Fired when a <typeparamref name="T"/> download is interrupted, either due to user cancellation or failure.
/// This is NOT run on the update thread and should be scheduled. /// This is NOT run on the update thread and should be scheduled.
/// </summary> /// </summary>
IBindable<WeakReference<ArchiveDownloadRequest<T>>> DownloadFailed { get; } event Action<ArchiveDownloadRequest<T>> DownloadFailed;
/// <summary> /// <summary>
/// Begin a download for the requested <typeparamref name="T"/>. /// Begin a download for the requested <typeparamref name="T"/>.

View File

@ -5,7 +5,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
using osu.Framework.Bindables;
using osu.Game.IO; using osu.Game.IO;
namespace osu.Game.Database namespace osu.Game.Database
@ -18,16 +17,14 @@ namespace osu.Game.Database
where TModel : class where TModel : class
{ {
/// <summary> /// <summary>
/// A bindable which contains a weak reference to the last item that was updated. /// Fired when an item is updated.
/// This is not thread-safe and should be scheduled locally if consumed from a drawable component.
/// </summary> /// </summary>
IBindable<WeakReference<TModel>> ItemUpdated { get; } event Action<TModel> ItemUpdated;
/// <summary> /// <summary>
/// A bindable which contains a weak reference to the last item that was removed. /// Fired when an item is removed.
/// This is not thread-safe and should be scheduled locally if consumed from a drawable component.
/// </summary> /// </summary>
IBindable<WeakReference<TModel>> ItemRemoved { get; } event Action<TModel> ItemRemoved;
/// <summary> /// <summary>
/// This is a temporary method and will likely be replaced by a full-fledged (and more correctly placed) migration process in the future. /// This is a temporary method and will likely be replaced by a full-fledged (and more correctly placed) migration process in the future.

View File

@ -6,7 +6,6 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Humanizer; using Humanizer;
using osu.Framework.Bindables;
using osu.Framework.Logging; using osu.Framework.Logging;
using osu.Framework.Platform; using osu.Framework.Platform;
using osu.Game.Online.API; using osu.Game.Online.API;
@ -20,13 +19,9 @@ namespace osu.Game.Database
{ {
public Action<Notification> PostNotification { protected get; set; } public Action<Notification> PostNotification { protected get; set; }
public IBindable<WeakReference<ArchiveDownloadRequest<T>>> DownloadBegan => downloadBegan; public event Action<ArchiveDownloadRequest<T>> DownloadBegan;
private readonly Bindable<WeakReference<ArchiveDownloadRequest<T>>> downloadBegan = new Bindable<WeakReference<ArchiveDownloadRequest<T>>>(); public event Action<ArchiveDownloadRequest<T>> DownloadFailed;
public IBindable<WeakReference<ArchiveDownloadRequest<T>>> DownloadFailed => downloadFailed;
private readonly Bindable<WeakReference<ArchiveDownloadRequest<T>>> downloadFailed = new Bindable<WeakReference<ArchiveDownloadRequest<T>>>();
private readonly IModelImporter<TModel> importer; private readonly IModelImporter<TModel> importer;
private readonly IAPIProvider api; private readonly IAPIProvider api;
@ -73,7 +68,7 @@ namespace osu.Game.Database
// for now a failed import will be marked as a failed download for simplicity. // for now a failed import will be marked as a failed download for simplicity.
if (!imported.Any()) if (!imported.Any())
downloadFailed.Value = new WeakReference<ArchiveDownloadRequest<T>>(request); DownloadFailed?.Invoke(request);
CurrentDownloads.Remove(request); CurrentDownloads.Remove(request);
}, TaskCreationOptions.LongRunning); }, TaskCreationOptions.LongRunning);
@ -92,14 +87,14 @@ namespace osu.Game.Database
api.PerformAsync(request); api.PerformAsync(request);
downloadBegan.Value = new WeakReference<ArchiveDownloadRequest<T>>(request); DownloadBegan?.Invoke(request);
return true; return true;
void triggerFailure(Exception error) void triggerFailure(Exception error)
{ {
CurrentDownloads.Remove(request); CurrentDownloads.Remove(request);
downloadFailed.Value = new WeakReference<ArchiveDownloadRequest<T>>(request); DownloadFailed?.Invoke(request);
notification.State = ProgressNotificationState.Cancelled; notification.State = ProgressNotificationState.Cancelled;

View File

@ -46,7 +46,7 @@ namespace osu.Game.Graphics.Containers
AddText(text[previousLinkEnd..link.Index]); AddText(text[previousLinkEnd..link.Index]);
string displayText = text.Substring(link.Index, link.Length); string displayText = text.Substring(link.Index, link.Length);
string linkArgument = link.Argument; object linkArgument = link.Argument;
string tooltip = displayText == link.Url ? null : link.Url; string tooltip = displayText == link.Url ? null : link.Url;
AddLink(displayText, link.Action, linkArgument, tooltip); AddLink(displayText, link.Action, linkArgument, tooltip);
@ -62,16 +62,16 @@ namespace osu.Game.Graphics.Containers
public void AddLink(LocalisableString text, Action action, string tooltipText = null, Action<SpriteText> creationParameters = null) public void AddLink(LocalisableString text, Action action, string tooltipText = null, Action<SpriteText> creationParameters = null)
=> createLink(CreateChunkFor(text, true, CreateSpriteText, creationParameters), new LinkDetails(LinkAction.Custom, string.Empty), tooltipText, action); => createLink(CreateChunkFor(text, true, CreateSpriteText, creationParameters), new LinkDetails(LinkAction.Custom, string.Empty), tooltipText, action);
public void AddLink(LocalisableString text, LinkAction action, string argument, string tooltipText = null, Action<SpriteText> creationParameters = null) public void AddLink(LocalisableString text, LinkAction action, object argument, string tooltipText = null, Action<SpriteText> creationParameters = null)
=> createLink(CreateChunkFor(text, true, CreateSpriteText, creationParameters), new LinkDetails(action, argument), tooltipText); => createLink(CreateChunkFor(text, true, CreateSpriteText, creationParameters), new LinkDetails(action, argument), tooltipText);
public void AddLink(IEnumerable<SpriteText> text, LinkAction action, string linkArgument, string tooltipText = null) public void AddLink(IEnumerable<SpriteText> text, LinkAction action, object linkArgument, string tooltipText = null)
{ {
createLink(new TextPartManual(text), new LinkDetails(action, linkArgument), tooltipText); createLink(new TextPartManual(text), new LinkDetails(action, linkArgument), tooltipText);
} }
public void AddUserLink(IUser user, Action<SpriteText> creationParameters = null) public void AddUserLink(IUser user, Action<SpriteText> creationParameters = null)
=> createLink(CreateChunkFor(user.Username, true, CreateSpriteText, creationParameters), new LinkDetails(LinkAction.OpenUserProfile, user.OnlineID.ToString()), "view profile"); => createLink(CreateChunkFor(user.Username, true, CreateSpriteText, creationParameters), new LinkDetails(LinkAction.OpenUserProfile, user), "view profile");
private void createLink(ITextPart textPart, LinkDetails link, LocalisableString tooltipText, Action action = null) private void createLink(ITextPart textPart, LinkDetails link, LocalisableString tooltipText, Action action = null)
{ {
@ -83,7 +83,7 @@ namespace osu.Game.Graphics.Containers
game.HandleLink(link); game.HandleLink(link);
// fallback to handle cases where OsuGame is not available, ie. tournament client. // fallback to handle cases where OsuGame is not available, ie. tournament client.
else if (link.Action == LinkAction.External) else if (link.Action == LinkAction.External)
host.OpenUrlExternally(link.Argument); host.OpenUrlExternally(link.Argument.ToString());
}; };
AddPart(new TextLink(textPart, tooltipText, onClickAction)); AddPart(new TextLink(textPart, tooltipText, onClickAction));

View File

@ -61,6 +61,12 @@ namespace osu.Game.Online.API.Requests.Responses
[JsonProperty(@"track_id")] [JsonProperty(@"track_id")]
public int? TrackId { get; set; } public int? TrackId { get; set; }
[JsonProperty(@"hype")]
public BeatmapSetHypeStatus? HypeStatus { get; set; }
[JsonProperty(@"nominations_summary")]
public BeatmapSetNominationStatus? NominationStatus { get; set; }
public string Title { get; set; } = string.Empty; public string Title { get; set; } = string.Empty;
[JsonProperty("title_unicode")] [JsonProperty("title_unicode")]

View File

@ -3,7 +3,6 @@
using System; using System;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Beatmaps; using osu.Game.Beatmaps;
using osu.Game.Online.API; using osu.Game.Online.API;
@ -23,11 +22,6 @@ namespace osu.Game.Online
{ {
} }
private IBindable<WeakReference<BeatmapSetInfo>>? managerUpdated;
private IBindable<WeakReference<BeatmapSetInfo>>? managerRemoved;
private IBindable<WeakReference<ArchiveDownloadRequest<IBeatmapSetInfo>>>? managerDownloadBegan;
private IBindable<WeakReference<ArchiveDownloadRequest<IBeatmapSetInfo>>>? managerDownloadFailed;
[BackgroundDependencyLoader(true)] [BackgroundDependencyLoader(true)]
private void load() private void load()
{ {
@ -42,39 +36,23 @@ namespace osu.Game.Online
else else
attachDownload(Manager.GetExistingDownload(beatmapSetInfo)); attachDownload(Manager.GetExistingDownload(beatmapSetInfo));
managerDownloadBegan = Manager.DownloadBegan.GetBoundCopy(); Manager.DownloadBegan += downloadBegan;
managerDownloadBegan.BindValueChanged(downloadBegan); Manager.DownloadFailed += downloadFailed;
managerDownloadFailed = Manager.DownloadFailed.GetBoundCopy(); Manager.ItemUpdated += itemUpdated;
managerDownloadFailed.BindValueChanged(downloadFailed); Manager.ItemRemoved += itemRemoved;
managerUpdated = Manager.ItemUpdated.GetBoundCopy();
managerUpdated.BindValueChanged(itemUpdated);
managerRemoved = Manager.ItemRemoved.GetBoundCopy();
managerRemoved.BindValueChanged(itemRemoved);
} }
private void downloadBegan(ValueChangedEvent<WeakReference<ArchiveDownloadRequest<IBeatmapSetInfo>>> weakRequest) private void downloadBegan(ArchiveDownloadRequest<IBeatmapSetInfo> request) => Schedule(() =>
{ {
if (weakRequest.NewValue.TryGetTarget(out var request)) if (checkEquality(request.Model, TrackedItem))
{ attachDownload(request);
Schedule(() => });
{
if (checkEquality(request.Model, TrackedItem))
attachDownload(request);
});
}
}
private void downloadFailed(ValueChangedEvent<WeakReference<ArchiveDownloadRequest<IBeatmapSetInfo>>> weakRequest) private void downloadFailed(ArchiveDownloadRequest<IBeatmapSetInfo> request) => Schedule(() =>
{ {
if (weakRequest.NewValue.TryGetTarget(out var request)) if (checkEquality(request.Model, TrackedItem))
{ attachDownload(null);
Schedule(() => });
{
if (checkEquality(request.Model, TrackedItem))
attachDownload(null);
});
}
}
private void attachDownload(ArchiveDownloadRequest<IBeatmapSetInfo>? request) private void attachDownload(ArchiveDownloadRequest<IBeatmapSetInfo>? request)
{ {
@ -116,29 +94,17 @@ namespace osu.Game.Online
private void onRequestFailure(Exception e) => Schedule(() => attachDownload(null)); private void onRequestFailure(Exception e) => Schedule(() => attachDownload(null));
private void itemUpdated(ValueChangedEvent<WeakReference<BeatmapSetInfo>> weakItem) private void itemUpdated(BeatmapSetInfo item) => Schedule(() =>
{ {
if (weakItem.NewValue.TryGetTarget(out var item)) if (checkEquality(item, TrackedItem))
{ UpdateState(DownloadState.LocallyAvailable);
Schedule(() => });
{
if (checkEquality(item, TrackedItem))
UpdateState(DownloadState.LocallyAvailable);
});
}
}
private void itemRemoved(ValueChangedEvent<WeakReference<BeatmapSetInfo>> weakItem) private void itemRemoved(BeatmapSetInfo item) => Schedule(() =>
{ {
if (weakItem.NewValue.TryGetTarget(out var item)) if (checkEquality(item, TrackedItem))
{ UpdateState(DownloadState.NotDownloaded);
Schedule(() => });
{
if (checkEquality(item, TrackedItem))
UpdateState(DownloadState.NotDownloaded);
});
}
}
private bool checkEquality(IBeatmapSetInfo x, IBeatmapSetInfo y) => x.OnlineID == y.OnlineID; private bool checkEquality(IBeatmapSetInfo x, IBeatmapSetInfo y) => x.OnlineID == y.OnlineID;
@ -148,6 +114,14 @@ namespace osu.Game.Online
{ {
base.Dispose(isDisposing); base.Dispose(isDisposing);
attachDownload(null); attachDownload(null);
if (Manager != null)
{
Manager.DownloadBegan -= downloadBegan;
Manager.DownloadFailed -= downloadFailed;
Manager.ItemUpdated -= itemUpdated;
Manager.ItemRemoved -= itemRemoved;
}
} }
#endregion #endregion

View File

@ -320,9 +320,9 @@ namespace osu.Game.Online.Chat
{ {
public readonly LinkAction Action; public readonly LinkAction Action;
public readonly string Argument; public readonly object Argument;
public LinkDetails(LinkAction action, string argument) public LinkDetails(LinkAction action, object argument)
{ {
Action = action; Action = action;
Argument = argument; Argument = argument;
@ -351,9 +351,9 @@ namespace osu.Game.Online.Chat
public int Index; public int Index;
public int Length; public int Length;
public LinkAction Action; public LinkAction Action;
public string Argument; public object Argument;
public Link(string url, int startIndex, int length, LinkAction action, string argument) public Link(string url, int startIndex, int length, LinkAction action, object argument)
{ {
Url = url; Url = url;
Index = startIndex; Index = startIndex;

View File

@ -3,7 +3,6 @@
using System; using System;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Online.API; using osu.Game.Online.API;
using osu.Game.Scoring; using osu.Game.Scoring;
@ -23,11 +22,6 @@ namespace osu.Game.Online
{ {
} }
private IBindable<WeakReference<ScoreInfo>>? managerUpdated;
private IBindable<WeakReference<ScoreInfo>>? managerRemoved;
private IBindable<WeakReference<ArchiveDownloadRequest<IScoreInfo>>>? managerDownloadBegan;
private IBindable<WeakReference<ArchiveDownloadRequest<IScoreInfo>>>? managerDownloadFailed;
[BackgroundDependencyLoader(true)] [BackgroundDependencyLoader(true)]
private void load() private void load()
{ {
@ -46,39 +40,23 @@ namespace osu.Game.Online
else else
attachDownload(Manager.GetExistingDownload(scoreInfo)); attachDownload(Manager.GetExistingDownload(scoreInfo));
managerDownloadBegan = Manager.DownloadBegan.GetBoundCopy(); Manager.DownloadBegan += downloadBegan;
managerDownloadBegan.BindValueChanged(downloadBegan); Manager.DownloadFailed += downloadFailed;
managerDownloadFailed = Manager.DownloadFailed.GetBoundCopy(); Manager.ItemUpdated += itemUpdated;
managerDownloadFailed.BindValueChanged(downloadFailed); Manager.ItemRemoved += itemRemoved;
managerUpdated = Manager.ItemUpdated.GetBoundCopy();
managerUpdated.BindValueChanged(itemUpdated);
managerRemoved = Manager.ItemRemoved.GetBoundCopy();
managerRemoved.BindValueChanged(itemRemoved);
} }
private void downloadBegan(ValueChangedEvent<WeakReference<ArchiveDownloadRequest<IScoreInfo>>> weakRequest) private void downloadBegan(ArchiveDownloadRequest<IScoreInfo> request) => Schedule(() =>
{ {
if (weakRequest.NewValue.TryGetTarget(out var request)) if (checkEquality(request.Model, TrackedItem))
{ attachDownload(request);
Schedule(() => });
{
if (checkEquality(request.Model, TrackedItem))
attachDownload(request);
});
}
}
private void downloadFailed(ValueChangedEvent<WeakReference<ArchiveDownloadRequest<IScoreInfo>>> weakRequest) private void downloadFailed(ArchiveDownloadRequest<IScoreInfo> request) => Schedule(() =>
{ {
if (weakRequest.NewValue.TryGetTarget(out var request)) if (checkEquality(request.Model, TrackedItem))
{ attachDownload(null);
Schedule(() => });
{
if (checkEquality(request.Model, TrackedItem))
attachDownload(null);
});
}
}
private void attachDownload(ArchiveDownloadRequest<IScoreInfo>? request) private void attachDownload(ArchiveDownloadRequest<IScoreInfo>? request)
{ {
@ -120,29 +98,17 @@ namespace osu.Game.Online
private void onRequestFailure(Exception e) => Schedule(() => attachDownload(null)); private void onRequestFailure(Exception e) => Schedule(() => attachDownload(null));
private void itemUpdated(ValueChangedEvent<WeakReference<ScoreInfo>> weakItem) private void itemUpdated(ScoreInfo item) => Schedule(() =>
{ {
if (weakItem.NewValue.TryGetTarget(out var item)) if (checkEquality(item, TrackedItem))
{ UpdateState(DownloadState.LocallyAvailable);
Schedule(() => });
{
if (checkEquality(item, TrackedItem))
UpdateState(DownloadState.LocallyAvailable);
});
}
}
private void itemRemoved(ValueChangedEvent<WeakReference<ScoreInfo>> weakItem) private void itemRemoved(ScoreInfo item) => Schedule(() =>
{ {
if (weakItem.NewValue.TryGetTarget(out var item)) if (checkEquality(item, TrackedItem))
{ UpdateState(DownloadState.NotDownloaded);
Schedule(() => });
{
if (checkEquality(item, TrackedItem))
UpdateState(DownloadState.NotDownloaded);
});
}
}
private bool checkEquality(IScoreInfo x, IScoreInfo y) => x.OnlineID == y.OnlineID; private bool checkEquality(IScoreInfo x, IScoreInfo y) => x.OnlineID == y.OnlineID;
@ -152,6 +118,14 @@ namespace osu.Game.Online
{ {
base.Dispose(isDisposing); base.Dispose(isDisposing);
attachDownload(null); attachDownload(null);
if (Manager != null)
{
Manager.DownloadBegan -= downloadBegan;
Manager.DownloadFailed -= downloadFailed;
Manager.ItemUpdated -= itemUpdated;
Manager.ItemRemoved -= itemRemoved;
}
} }
#endregion #endregion

View File

@ -289,25 +289,27 @@ namespace osu.Game
/// <param name="link">The link to load.</param> /// <param name="link">The link to load.</param>
public void HandleLink(LinkDetails link) => Schedule(() => public void HandleLink(LinkDetails link) => Schedule(() =>
{ {
string argString = link.Argument.ToString();
switch (link.Action) switch (link.Action)
{ {
case LinkAction.OpenBeatmap: case LinkAction.OpenBeatmap:
// TODO: proper query params handling // TODO: proper query params handling
if (int.TryParse(link.Argument.Contains('?') ? link.Argument.Split('?')[0] : link.Argument, out int beatmapId)) if (int.TryParse(argString.Contains('?') ? argString.Split('?')[0] : argString, out int beatmapId))
ShowBeatmap(beatmapId); ShowBeatmap(beatmapId);
break; break;
case LinkAction.OpenBeatmapSet: case LinkAction.OpenBeatmapSet:
if (int.TryParse(link.Argument, out int setId)) if (int.TryParse(argString, out int setId))
ShowBeatmapSet(setId); ShowBeatmapSet(setId);
break; break;
case LinkAction.OpenChannel: case LinkAction.OpenChannel:
ShowChannel(link.Argument); ShowChannel(argString);
break; break;
case LinkAction.SearchBeatmapSet: case LinkAction.SearchBeatmapSet:
SearchBeatmapSet(link.Argument); SearchBeatmapSet(argString);
break; break;
case LinkAction.OpenEditorTimestamp: case LinkAction.OpenEditorTimestamp:
@ -321,26 +323,31 @@ namespace osu.Game
break; break;
case LinkAction.External: case LinkAction.External:
OpenUrlExternally(link.Argument); OpenUrlExternally(argString);
break; break;
case LinkAction.OpenUserProfile: case LinkAction.OpenUserProfile:
ShowUser(int.TryParse(link.Argument, out int userId) if (!(link.Argument is IUser user))
? new APIUser { Id = userId } {
: new APIUser { Username = link.Argument }); user = int.TryParse(argString, out int userId)
? new APIUser { Id = userId }
: new APIUser { Username = argString };
}
ShowUser(user);
break; break;
case LinkAction.OpenWiki: case LinkAction.OpenWiki:
ShowWiki(link.Argument); ShowWiki(argString);
break; break;
case LinkAction.OpenChangelog: case LinkAction.OpenChangelog:
if (string.IsNullOrEmpty(link.Argument)) if (string.IsNullOrEmpty(argString))
ShowChangelogListing(); ShowChangelogListing();
else else
{ {
string[] changelogArgs = link.Argument.Split("/"); string[] changelogArgs = argString.Split("/");
ShowChangelogBuild(changelogArgs[0], changelogArgs[1]); ShowChangelogBuild(changelogArgs[0], changelogArgs[1]);
} }

View File

@ -40,6 +40,7 @@ using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Mods;
using osu.Game.Scoring; using osu.Game.Scoring;
using osu.Game.Skinning; using osu.Game.Skinning;
using osu.Game.Stores;
using osu.Game.Utils; using osu.Game.Utils;
using RuntimeInfo = osu.Framework.RuntimeInfo; using RuntimeInfo = osu.Framework.RuntimeInfo;
@ -160,6 +161,8 @@ namespace osu.Game
private readonly BindableNumber<double> globalTrackVolumeAdjust = new BindableNumber<double>(GLOBAL_TRACK_VOLUME_ADJUST); private readonly BindableNumber<double> globalTrackVolumeAdjust = new BindableNumber<double>(GLOBAL_TRACK_VOLUME_ADJUST);
private RealmRulesetStore realmRulesetStore;
public OsuGameBase() public OsuGameBase()
{ {
UseDevelopmentServer = DebugUtils.IsDebugBuild; UseDevelopmentServer = DebugUtils.IsDebugBuild;
@ -206,17 +209,11 @@ namespace osu.Game
dependencies.CacheAs<ISkinSource>(SkinManager); dependencies.CacheAs<ISkinSource>(SkinManager);
// needs to be done here rather than inside SkinManager to ensure thread safety of CurrentSkinInfo. // needs to be done here rather than inside SkinManager to ensure thread safety of CurrentSkinInfo.
SkinManager.ItemRemoved.BindValueChanged(weakRemovedInfo => SkinManager.ItemRemoved += item => Schedule(() =>
{ {
if (weakRemovedInfo.NewValue.TryGetTarget(out var removedInfo)) // check the removed skin is not the current user choice. if it is, switch back to default.
{ if (item.ID == SkinManager.CurrentSkinInfo.Value.ID)
Schedule(() => SkinManager.CurrentSkinInfo.Value = SkinInfo.Default;
{
// check the removed skin is not the current user choice. if it is, switch back to default.
if (removedInfo.ID == SkinManager.CurrentSkinInfo.Value.ID)
SkinManager.CurrentSkinInfo.Value = SkinInfo.Default;
});
}
}); });
EndpointConfiguration endpoints = UseDevelopmentServer ? (EndpointConfiguration)new DevelopmentEndpointConfiguration() : new ProductionEndpointConfiguration(); EndpointConfiguration endpoints = UseDevelopmentServer ? (EndpointConfiguration)new DevelopmentEndpointConfiguration() : new ProductionEndpointConfiguration();
@ -237,6 +234,11 @@ namespace osu.Game
dependencies.Cache(ScoreManager = new ScoreManager(RulesetStore, () => BeatmapManager, Storage, API, contextFactory, Scheduler, Host, () => difficultyCache, LocalConfig)); dependencies.Cache(ScoreManager = new ScoreManager(RulesetStore, () => BeatmapManager, Storage, API, contextFactory, Scheduler, Host, () => difficultyCache, LocalConfig));
dependencies.Cache(BeatmapManager = new BeatmapManager(Storage, contextFactory, RulesetStore, API, Audio, Resources, Host, defaultBeatmap, performOnlineLookups: true)); dependencies.Cache(BeatmapManager = new BeatmapManager(Storage, contextFactory, RulesetStore, API, Audio, Resources, Host, defaultBeatmap, performOnlineLookups: true));
// the following realm components are not actively used yet, but initialised and kept up to date for initial testing.
realmRulesetStore = new RealmRulesetStore(realmFactory, Storage);
dependencies.Cache(realmRulesetStore);
// this should likely be moved to ArchiveModelManager when another case appears where it is necessary // this should likely be moved to ArchiveModelManager when another case appears where it is necessary
// to have inter-dependent model managers. this could be obtained with an IHasForeign<T> interface to // to have inter-dependent model managers. this could be obtained with an IHasForeign<T> interface to
// allow lookups to be done on the child (ScoreManager in this case) to perform the cascading delete. // allow lookups to be done on the child (ScoreManager in this case) to perform the cascading delete.
@ -246,17 +248,8 @@ namespace osu.Game
return ScoreManager.QueryScores(s => beatmapIds.Contains(s.BeatmapInfo.ID)).ToList(); return ScoreManager.QueryScores(s => beatmapIds.Contains(s.BeatmapInfo.ID)).ToList();
} }
BeatmapManager.ItemRemoved.BindValueChanged(i => BeatmapManager.ItemRemoved += item => ScoreManager.Delete(getBeatmapScores(item), true);
{ BeatmapManager.ItemUpdated += item => ScoreManager.Undelete(getBeatmapScores(item), true);
if (i.NewValue.TryGetTarget(out var item))
ScoreManager.Delete(getBeatmapScores(item), true);
});
BeatmapManager.ItemUpdated.BindValueChanged(i =>
{
if (i.NewValue.TryGetTarget(out var item))
ScoreManager.Undelete(getBeatmapScores(item), true);
});
dependencies.Cache(difficultyCache = new BeatmapDifficultyCache()); dependencies.Cache(difficultyCache = new BeatmapDifficultyCache());
AddInternal(difficultyCache); AddInternal(difficultyCache);
@ -527,6 +520,8 @@ namespace osu.Game
LocalConfig?.Dispose(); LocalConfig?.Dispose();
contextFactory?.FlushConnections(); contextFactory?.FlushConnections();
realmRulesetStore?.Dispose();
realmFactory?.Dispose(); realmFactory?.Dispose();
} }
} }

View File

@ -209,7 +209,7 @@ namespace osu.Game.Overlays.Chat
username.Text = $@"{message.Sender.Username}" + (senderHasBackground || message.IsAction ? "" : ":"); username.Text = $@"{message.Sender.Username}" + (senderHasBackground || message.IsAction ? "" : ":");
// remove non-existent channels from the link list // remove non-existent channels from the link list
message.Links.RemoveAll(link => link.Action == LinkAction.OpenChannel && chatManager?.AvailableChannels.Any(c => c.Name == link.Argument) != true); message.Links.RemoveAll(link => link.Action == LinkAction.OpenChannel && chatManager?.AvailableChannels.Any(c => c.Name == link.Argument.ToString()) != true);
ContentFlow.Clear(); ContentFlow.Clear();
ContentFlow.AddLinks(message.DisplayContent, message.Links); ContentFlow.AddLinks(message.DisplayContent, message.Links);

View File

@ -65,16 +65,11 @@ namespace osu.Game.Overlays
[NotNull] [NotNull]
public DrawableTrack CurrentTrack { get; private set; } = new DrawableTrack(new TrackVirtual(1000)); public DrawableTrack CurrentTrack { get; private set; } = new DrawableTrack(new TrackVirtual(1000));
private IBindable<WeakReference<BeatmapSetInfo>> managerUpdated;
private IBindable<WeakReference<BeatmapSetInfo>> managerRemoved;
[BackgroundDependencyLoader] [BackgroundDependencyLoader]
private void load() private void load()
{ {
managerUpdated = beatmaps.ItemUpdated.GetBoundCopy(); beatmaps.ItemUpdated += beatmapUpdated;
managerUpdated.BindValueChanged(beatmapUpdated); beatmaps.ItemRemoved += beatmapRemoved;
managerRemoved = beatmaps.ItemRemoved.GetBoundCopy();
managerRemoved.BindValueChanged(beatmapRemoved);
beatmapSets.AddRange(beatmaps.GetAllUsableBeatmapSets(IncludedDetails.Minimal, true).OrderBy(_ => RNG.Next())); beatmapSets.AddRange(beatmaps.GetAllUsableBeatmapSets(IncludedDetails.Minimal, true).OrderBy(_ => RNG.Next()));
@ -110,28 +105,13 @@ namespace osu.Game.Overlays
/// </summary> /// </summary>
public bool TrackLoaded => CurrentTrack.TrackLoaded; public bool TrackLoaded => CurrentTrack.TrackLoaded;
private void beatmapUpdated(ValueChangedEvent<WeakReference<BeatmapSetInfo>> weakSet) private void beatmapUpdated(BeatmapSetInfo set) => Schedule(() =>
{ {
if (weakSet.NewValue.TryGetTarget(out var set)) beatmapSets.Remove(set);
{ beatmapSets.Add(set);
Schedule(() => });
{
beatmapSets.Remove(set);
beatmapSets.Add(set);
});
}
}
private void beatmapRemoved(ValueChangedEvent<WeakReference<BeatmapSetInfo>> weakSet) private void beatmapRemoved(BeatmapSetInfo set) => Schedule(() => beatmapSets.RemoveAll(s => s.ID == set.ID));
{
if (weakSet.NewValue.TryGetTarget(out var set))
{
Schedule(() =>
{
beatmapSets.RemoveAll(s => s.ID == set.ID);
});
}
}
private ScheduledDelegate seekDelegate; private ScheduledDelegate seekDelegate;
@ -437,6 +417,17 @@ namespace osu.Game.Overlays
mod.ApplyToTrack(CurrentTrack); mod.ApplyToTrack(CurrentTrack);
} }
} }
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (beatmaps != null)
{
beatmaps.ItemUpdated -= beatmapUpdated;
beatmaps.ItemRemoved -= beatmapRemoved;
}
}
} }
public enum TrackChangeDirection public enum TrackChangeDirection

View File

@ -216,7 +216,7 @@ namespace osu.Game.Overlays.Profile.Sections.Recent
private void addBeatmapsetLink() private void addBeatmapsetLink()
=> content.AddLink(activity.Beatmapset?.Title, LinkAction.OpenBeatmapSet, getLinkArgument(activity.Beatmapset?.Url), creationParameters: t => t.Font = getLinkFont()); => content.AddLink(activity.Beatmapset?.Title, LinkAction.OpenBeatmapSet, getLinkArgument(activity.Beatmapset?.Url), creationParameters: t => t.Font = getLinkFont());
private string getLinkArgument(string url) => MessageFormatter.GetLinkDetails($"{api.APIEndpointUrl}{url}").Argument; private string getLinkArgument(string url) => MessageFormatter.GetLinkDetails($"{api.APIEndpointUrl}{url}").Argument.ToString();
private FontUsage getLinkFont(FontWeight fontWeight = FontWeight.Regular) private FontUsage getLinkFont(FontWeight fontWeight = FontWeight.Regular)
=> OsuFont.GetFont(size: font_size, weight: fontWeight, italics: true); => OsuFont.GetFont(size: font_size, weight: fontWeight, italics: true);

View File

@ -56,9 +56,6 @@ namespace osu.Game.Overlays.Settings.Sections
[Resolved] [Resolved]
private SkinManager skins { get; set; } private SkinManager skins { get; set; }
private IBindable<WeakReference<SkinInfo>> managerUpdated;
private IBindable<WeakReference<SkinInfo>> managerRemoved;
[BackgroundDependencyLoader(permitNulls: true)] [BackgroundDependencyLoader(permitNulls: true)]
private void load(OsuConfigManager config, [CanBeNull] SkinEditorOverlay skinEditor) private void load(OsuConfigManager config, [CanBeNull] SkinEditorOverlay skinEditor)
{ {
@ -76,11 +73,8 @@ namespace osu.Game.Overlays.Settings.Sections
new ExportSkinButton(), new ExportSkinButton(),
}; };
managerUpdated = skins.ItemUpdated.GetBoundCopy(); skins.ItemUpdated += itemUpdated;
managerUpdated.BindValueChanged(itemUpdated); skins.ItemRemoved += itemRemoved;
managerRemoved = skins.ItemRemoved.GetBoundCopy();
managerRemoved.BindValueChanged(itemRemoved);
config.BindWith(OsuSetting.Skin, configBindable); config.BindWith(OsuSetting.Skin, configBindable);
@ -129,11 +123,7 @@ namespace osu.Game.Overlays.Settings.Sections
skinDropdown.Items = skinItems; skinDropdown.Items = skinItems;
} }
private void itemUpdated(ValueChangedEvent<WeakReference<SkinInfo>> weakItem) private void itemUpdated(SkinInfo item) => Schedule(() => addItem(item));
{
if (weakItem.NewValue.TryGetTarget(out var item))
Schedule(() => addItem(item));
}
private void addItem(SkinInfo item) private void addItem(SkinInfo item)
{ {
@ -142,11 +132,7 @@ namespace osu.Game.Overlays.Settings.Sections
skinDropdown.Items = newDropdownItems; skinDropdown.Items = newDropdownItems;
} }
private void itemRemoved(ValueChangedEvent<WeakReference<SkinInfo>> weakItem) private void itemRemoved(SkinInfo item) => Schedule(() => skinDropdown.Items = skinDropdown.Items.Where(i => i.ID != item.ID).ToArray());
{
if (weakItem.NewValue.TryGetTarget(out var item))
Schedule(() => skinDropdown.Items = skinDropdown.Items.Where(i => i.ID != item.ID).ToArray());
}
private void sortUserSkins(List<SkinInfo> skinsList) private void sortUserSkins(List<SkinInfo> skinsList)
{ {
@ -155,6 +141,17 @@ namespace osu.Game.Overlays.Settings.Sections
Comparer<SkinInfo>.Create((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase))); Comparer<SkinInfo>.Create((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)));
} }
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (skins != null)
{
skins.ItemUpdated -= itemUpdated;
skins.ItemRemoved -= itemRemoved;
}
}
private class SkinSettingsDropdown : SettingsDropdown<SkinInfo> private class SkinSettingsDropdown : SettingsDropdown<SkinInfo>
{ {
protected override OsuDropdown<SkinInfo> CreateDropdown() => new SkinDropdownControl(); protected override OsuDropdown<SkinInfo> CreateDropdown() => new SkinDropdownControl();

View File

@ -246,9 +246,17 @@ namespace osu.Game.Scoring
#region Implementation of IModelManager<ScoreInfo> #region Implementation of IModelManager<ScoreInfo>
public IBindable<WeakReference<ScoreInfo>> ItemUpdated => scoreModelManager.ItemUpdated; public event Action<ScoreInfo> ItemUpdated
{
add => scoreModelManager.ItemUpdated += value;
remove => scoreModelManager.ItemUpdated -= value;
}
public IBindable<WeakReference<ScoreInfo>> ItemRemoved => scoreModelManager.ItemRemoved; public event Action<ScoreInfo> ItemRemoved
{
add => scoreModelManager.ItemRemoved += value;
remove => scoreModelManager.ItemRemoved -= value;
}
public Task ImportFromStableAsync(StableStorage stableStorage) public Task ImportFromStableAsync(StableStorage stableStorage)
{ {
@ -348,11 +356,19 @@ namespace osu.Game.Scoring
#endregion #endregion
#region Implementation of IModelDownloader<ScoreInfo> #region Implementation of IModelDownloader<IScoreInfo>
public IBindable<WeakReference<ArchiveDownloadRequest<IScoreInfo>>> DownloadBegan => scoreModelDownloader.DownloadBegan; public event Action<ArchiveDownloadRequest<IScoreInfo>> DownloadBegan
{
add => scoreModelDownloader.DownloadBegan += value;
remove => scoreModelDownloader.DownloadBegan -= value;
}
public IBindable<WeakReference<ArchiveDownloadRequest<IScoreInfo>>> DownloadFailed => scoreModelDownloader.DownloadFailed; public event Action<ArchiveDownloadRequest<IScoreInfo>> DownloadFailed
{
add => scoreModelDownloader.DownloadFailed += value;
remove => scoreModelDownloader.DownloadFailed -= value;
}
public bool Download(IScoreInfo model, bool minimiseDownloadSize) => public bool Download(IScoreInfo model, bool minimiseDownloadSize) =>
scoreModelDownloader.Download(model, minimiseDownloadSize); scoreModelDownloader.Download(model, minimiseDownloadSize);

View File

@ -62,8 +62,6 @@ namespace osu.Game.Screens.OnlinePlay.Match
[Resolved(canBeNull: true)] [Resolved(canBeNull: true)]
protected OnlinePlayScreen ParentScreen { get; private set; } protected OnlinePlayScreen ParentScreen { get; private set; }
private IBindable<WeakReference<BeatmapSetInfo>> managerUpdated;
[Cached] [Cached]
private OnlinePlayBeatmapAvailabilityTracker beatmapAvailabilityTracker { get; set; } private OnlinePlayBeatmapAvailabilityTracker beatmapAvailabilityTracker { get; set; }
@ -246,8 +244,7 @@ namespace osu.Game.Screens.OnlinePlay.Match
SelectedItem.BindValueChanged(_ => Scheduler.AddOnce(selectedItemChanged)); SelectedItem.BindValueChanged(_ => Scheduler.AddOnce(selectedItemChanged));
managerUpdated = beatmapManager.ItemUpdated.GetBoundCopy(); beatmapManager.ItemUpdated += beatmapUpdated;
managerUpdated.BindValueChanged(beatmapUpdated);
UserMods.BindValueChanged(_ => Scheduler.AddOnce(UpdateMods)); UserMods.BindValueChanged(_ => Scheduler.AddOnce(UpdateMods));
} }
@ -362,7 +359,7 @@ namespace osu.Game.Screens.OnlinePlay.Match
} }
} }
private void beatmapUpdated(ValueChangedEvent<WeakReference<BeatmapSetInfo>> weakSet) => Schedule(updateWorkingBeatmap); private void beatmapUpdated(BeatmapSetInfo set) => Schedule(updateWorkingBeatmap);
private void updateWorkingBeatmap() private void updateWorkingBeatmap()
{ {
@ -431,6 +428,14 @@ namespace osu.Game.Screens.OnlinePlay.Match
/// <param name="room">The room to change the settings of.</param> /// <param name="room">The room to change the settings of.</param>
protected abstract RoomSettingsOverlay CreateRoomSettingsOverlay(Room room); protected abstract RoomSettingsOverlay CreateRoomSettingsOverlay(Room room);
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (beatmapManager != null)
beatmapManager.ItemUpdated -= beatmapUpdated;
}
public class UserModSelectButton : PurpleTriangleButton public class UserModSelectButton : PurpleTriangleButton
{ {
} }

View File

@ -143,11 +143,6 @@ namespace osu.Game.Screens.Select
private CarouselRoot root; private CarouselRoot root;
private IBindable<WeakReference<BeatmapSetInfo>> itemUpdated;
private IBindable<WeakReference<BeatmapSetInfo>> itemRemoved;
private IBindable<WeakReference<BeatmapInfo>> itemHidden;
private IBindable<WeakReference<BeatmapInfo>> itemRestored;
private readonly DrawablePool<DrawableCarouselBeatmapSet> setPool = new DrawablePool<DrawableCarouselBeatmapSet>(100); private readonly DrawablePool<DrawableCarouselBeatmapSet> setPool = new DrawablePool<DrawableCarouselBeatmapSet>(100);
public BeatmapCarousel() public BeatmapCarousel()
@ -179,14 +174,10 @@ namespace osu.Game.Screens.Select
RightClickScrollingEnabled.ValueChanged += enabled => Scroll.RightMouseScrollbar = enabled.NewValue; RightClickScrollingEnabled.ValueChanged += enabled => Scroll.RightMouseScrollbar = enabled.NewValue;
RightClickScrollingEnabled.TriggerChange(); RightClickScrollingEnabled.TriggerChange();
itemUpdated = beatmaps.ItemUpdated.GetBoundCopy(); beatmaps.ItemUpdated += beatmapUpdated;
itemUpdated.BindValueChanged(beatmapUpdated); beatmaps.ItemRemoved += beatmapRemoved;
itemRemoved = beatmaps.ItemRemoved.GetBoundCopy(); beatmaps.BeatmapHidden += beatmapHidden;
itemRemoved.BindValueChanged(beatmapRemoved); beatmaps.BeatmapRestored += beatmapRestored;
itemHidden = beatmaps.BeatmapHidden.GetBoundCopy();
itemHidden.BindValueChanged(beatmapHidden);
itemRestored = beatmaps.BeatmapRestored.GetBoundCopy();
itemRestored.BindValueChanged(beatmapRestored);
if (!beatmapSets.Any()) if (!beatmapSets.Any())
loadBeatmapSets(GetLoadableBeatmaps()); loadBeatmapSets(GetLoadableBeatmaps());
@ -675,29 +666,10 @@ namespace osu.Game.Screens.Select
return (firstIndex, lastIndex); return (firstIndex, lastIndex);
} }
private void beatmapRemoved(ValueChangedEvent<WeakReference<BeatmapSetInfo>> weakItem) private void beatmapRemoved(BeatmapSetInfo item) => RemoveBeatmapSet(item);
{ private void beatmapUpdated(BeatmapSetInfo item) => UpdateBeatmapSet(item);
if (weakItem.NewValue.TryGetTarget(out var item)) private void beatmapRestored(BeatmapInfo b) => UpdateBeatmapSet(beatmaps.QueryBeatmapSet(s => s.ID == b.BeatmapSetInfoID));
RemoveBeatmapSet(item); private void beatmapHidden(BeatmapInfo b) => UpdateBeatmapSet(beatmaps.QueryBeatmapSet(s => s.ID == b.BeatmapSetInfoID));
}
private void beatmapUpdated(ValueChangedEvent<WeakReference<BeatmapSetInfo>> weakItem)
{
if (weakItem.NewValue.TryGetTarget(out var item))
UpdateBeatmapSet(item);
}
private void beatmapRestored(ValueChangedEvent<WeakReference<BeatmapInfo>> weakItem)
{
if (weakItem.NewValue.TryGetTarget(out var b))
UpdateBeatmapSet(beatmaps.QueryBeatmapSet(s => s.ID == b.BeatmapSetInfoID));
}
private void beatmapHidden(ValueChangedEvent<WeakReference<BeatmapInfo>> weakItem)
{
if (weakItem.NewValue.TryGetTarget(out var b))
UpdateBeatmapSet(beatmaps.QueryBeatmapSet(s => s.ID == b.BeatmapSetInfoID));
}
private CarouselBeatmapSet createCarouselSet(BeatmapSetInfo beatmapSet) private CarouselBeatmapSet createCarouselSet(BeatmapSetInfo beatmapSet)
{ {
@ -956,5 +928,18 @@ namespace osu.Game.Screens.Select
return base.OnDragStart(e); return base.OnDragStart(e);
} }
} }
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (beatmaps != null)
{
beatmaps.ItemUpdated -= beatmapUpdated;
beatmaps.ItemRemoved -= beatmapRemoved;
beatmaps.BeatmapHidden -= beatmapHidden;
beatmaps.BeatmapRestored -= beatmapRestored;
}
}
} }
} }

View File

@ -1,7 +1,6 @@
// 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.
using System;
using System.Linq; using System.Linq;
using osu.Framework.Allocation; using osu.Framework.Allocation;
using osu.Framework.Bindables; using osu.Framework.Bindables;
@ -28,9 +27,6 @@ namespace osu.Game.Screens.Select.Carousel
[Resolved] [Resolved]
private IAPIProvider api { get; set; } private IAPIProvider api { get; set; }
private IBindable<WeakReference<ScoreInfo>> itemUpdated;
private IBindable<WeakReference<ScoreInfo>> itemRemoved;
public TopLocalRank(BeatmapInfo beatmapInfo) public TopLocalRank(BeatmapInfo beatmapInfo)
: base(null) : base(null)
{ {
@ -40,24 +36,18 @@ namespace osu.Game.Screens.Select.Carousel
[BackgroundDependencyLoader] [BackgroundDependencyLoader]
private void load() private void load()
{ {
itemUpdated = scores.ItemUpdated.GetBoundCopy(); scores.ItemUpdated += scoreChanged;
itemUpdated.BindValueChanged(scoreChanged); scores.ItemRemoved += scoreChanged;
itemRemoved = scores.ItemRemoved.GetBoundCopy();
itemRemoved.BindValueChanged(scoreChanged);
ruleset.ValueChanged += _ => fetchAndLoadTopScore(); ruleset.ValueChanged += _ => fetchAndLoadTopScore();
fetchAndLoadTopScore(); fetchAndLoadTopScore();
} }
private void scoreChanged(ValueChangedEvent<WeakReference<ScoreInfo>> weakScore) private void scoreChanged(ScoreInfo score)
{ {
if (weakScore.NewValue.TryGetTarget(out var score)) if (score.BeatmapInfoID == beatmapInfo.ID)
{ fetchAndLoadTopScore();
if (score.BeatmapInfoID == beatmapInfo.ID)
fetchAndLoadTopScore();
}
} }
private ScheduledDelegate scheduledRankUpdate; private ScheduledDelegate scheduledRankUpdate;
@ -86,5 +76,16 @@ namespace osu.Game.Screens.Select.Carousel
.OrderByDescending(s => s.TotalScore) .OrderByDescending(s => s.TotalScore)
.FirstOrDefault(); .FirstOrDefault();
} }
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (scores != null)
{
scores.ItemUpdated -= scoreChanged;
scores.ItemRemoved -= scoreChanged;
}
}
} }
} }

View File

@ -44,10 +44,6 @@ namespace osu.Game.Screens.Select.Leaderboards
private bool filterMods; private bool filterMods;
private IBindable<WeakReference<ScoreInfo>> itemRemoved;
private IBindable<WeakReference<ScoreInfo>> itemAdded;
/// <summary> /// <summary>
/// Whether to apply the game's currently selected mods as a filter when retrieving scores. /// Whether to apply the game's currently selected mods as a filter when retrieving scores.
/// </summary> /// </summary>
@ -90,11 +86,8 @@ namespace osu.Game.Screens.Select.Leaderboards
UpdateScores(); UpdateScores();
}; };
itemRemoved = scoreManager.ItemRemoved.GetBoundCopy(); scoreManager.ItemRemoved += scoreStoreChanged;
itemRemoved.BindValueChanged(onScoreRemoved); scoreManager.ItemUpdated += scoreStoreChanged;
itemAdded = scoreManager.ItemUpdated.GetBoundCopy();
itemAdded.BindValueChanged(onScoreAdded);
} }
protected override void Reset() protected override void Reset()
@ -103,22 +96,13 @@ namespace osu.Game.Screens.Select.Leaderboards
TopScore = null; TopScore = null;
} }
private void onScoreRemoved(ValueChangedEvent<WeakReference<ScoreInfo>> score) => private void scoreStoreChanged(ScoreInfo score)
scoreStoreChanged(score);
private void onScoreAdded(ValueChangedEvent<WeakReference<ScoreInfo>> score) =>
scoreStoreChanged(score);
private void scoreStoreChanged(ValueChangedEvent<WeakReference<ScoreInfo>> score)
{ {
if (Scope != BeatmapLeaderboardScope.Local) if (Scope != BeatmapLeaderboardScope.Local)
return; return;
if (score.NewValue.TryGetTarget(out var scoreInfo)) if (BeatmapInfo?.ID != score.BeatmapInfoID)
{ return;
if (BeatmapInfo?.ID != scoreInfo.BeatmapInfoID)
return;
}
RefreshScores(); RefreshScores();
} }
@ -215,5 +199,16 @@ namespace osu.Game.Screens.Select.Leaderboards
{ {
Action = () => ScoreSelected?.Invoke(model) Action = () => ScoreSelected?.Invoke(model)
}; };
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (scoreManager != null)
{
scoreManager.ItemRemoved -= scoreStoreChanged;
scoreManager.ItemUpdated -= scoreStoreChanged;
}
}
} }
} }

View File

@ -1,7 +1,6 @@
// 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.
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
@ -45,8 +44,6 @@ namespace osu.Game.Screens.Spectate
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 IBindable<WeakReference<BeatmapSetInfo>> managerUpdated;
/// <summary> /// <summary>
/// Creates a new <see cref="SpectatorScreen"/>. /// Creates a new <see cref="SpectatorScreen"/>.
/// </summary> /// </summary>
@ -73,20 +70,16 @@ namespace osu.Game.Screens.Spectate
playingUserStates.BindTo(spectatorClient.PlayingUserStates); playingUserStates.BindTo(spectatorClient.PlayingUserStates);
playingUserStates.BindCollectionChanged(onPlayingUserStatesChanged, true); playingUserStates.BindCollectionChanged(onPlayingUserStatesChanged, true);
managerUpdated = beatmaps.ItemUpdated.GetBoundCopy(); beatmaps.ItemUpdated += beatmapUpdated;
managerUpdated.BindValueChanged(beatmapUpdated);
foreach ((int id, var _) in userMap) foreach ((int id, var _) in userMap)
spectatorClient.WatchUser(id); spectatorClient.WatchUser(id);
})); }));
} }
private void beatmapUpdated(ValueChangedEvent<WeakReference<BeatmapSetInfo>> e) private void beatmapUpdated(BeatmapSetInfo beatmapSet)
{ {
if (!e.NewValue.TryGetTarget(out var beatmapSet)) foreach ((int userId, _) in userMap)
return;
foreach ((int userId, var _) in userMap)
{ {
if (!playingUserStates.TryGetValue(userId, out var userState)) if (!playingUserStates.TryGetValue(userId, out var userState))
continue; continue;
@ -223,7 +216,8 @@ namespace osu.Game.Screens.Spectate
spectatorClient.StopWatchingUser(userId); spectatorClient.StopWatchingUser(userId);
} }
managerUpdated?.UnbindAll(); if (beatmaps != null)
beatmaps.ItemUpdated -= beatmapUpdated;
} }
} }
} }

View File

@ -102,75 +102,78 @@ namespace osu.Game.Stores
private void addMissingRulesets() private void addMissingRulesets()
{ {
realmFactory.Context.Write(realm => using (var context = realmFactory.CreateContext())
{ {
var rulesets = realm.All<RealmRuleset>(); context.Write(realm =>
List<Ruleset> instances = loadedAssemblies.Values
.Select(r => Activator.CreateInstance(r) as Ruleset)
.Where(r => r != null)
.Select(r => r.AsNonNull())
.ToList();
// add all legacy rulesets first to ensure they have exclusive choice of primary key.
foreach (var r in instances.Where(r => r is ILegacyRuleset))
{ {
if (realm.All<RealmRuleset>().FirstOrDefault(rr => rr.OnlineID == r.RulesetInfo.ID) == null) var rulesets = realm.All<RealmRuleset>();
realm.Add(new RealmRuleset(r.RulesetInfo.ShortName, r.RulesetInfo.Name, r.RulesetInfo.InstantiationInfo, r.RulesetInfo.ID));
}
// add any other rulesets which have assemblies present but are not yet in the database. List<Ruleset> instances = loadedAssemblies.Values
foreach (var r in instances.Where(r => !(r is ILegacyRuleset))) .Select(r => Activator.CreateInstance(r) as Ruleset)
{ .Where(r => r != null)
if (rulesets.FirstOrDefault(ri => ri.InstantiationInfo.Equals(r.RulesetInfo.InstantiationInfo, StringComparison.Ordinal)) == null) .Select(r => r.AsNonNull())
.ToList();
// add all legacy rulesets first to ensure they have exclusive choice of primary key.
foreach (var r in instances.Where(r => r is ILegacyRuleset))
{ {
var existingSameShortName = rulesets.FirstOrDefault(ri => ri.ShortName == r.RulesetInfo.ShortName); if (realm.All<RealmRuleset>().FirstOrDefault(rr => rr.OnlineID == r.RulesetInfo.ID) == null)
if (existingSameShortName != null)
{
// even if a matching InstantiationInfo was not found, there may be an existing ruleset with the same ShortName.
// this generally means the user or ruleset provider has renamed their dll but the underlying ruleset is *likely* the same one.
// in such cases, update the instantiation info of the existing entry to point to the new one.
existingSameShortName.InstantiationInfo = r.RulesetInfo.InstantiationInfo;
}
else
realm.Add(new RealmRuleset(r.RulesetInfo.ShortName, r.RulesetInfo.Name, r.RulesetInfo.InstantiationInfo, r.RulesetInfo.ID)); realm.Add(new RealmRuleset(r.RulesetInfo.ShortName, r.RulesetInfo.Name, r.RulesetInfo.InstantiationInfo, r.RulesetInfo.ID));
} }
}
List<RealmRuleset> detachedRulesets = new List<RealmRuleset>(); // add any other rulesets which have assemblies present but are not yet in the database.
foreach (var r in instances.Where(r => !(r is ILegacyRuleset)))
// perform a consistency check and detach final rulesets from realm for cross-thread runtime usage.
foreach (var r in rulesets)
{
try
{ {
var type = Type.GetType(r.InstantiationInfo); if (rulesets.FirstOrDefault(ri => ri.InstantiationInfo.Equals(r.RulesetInfo.InstantiationInfo, StringComparison.Ordinal)) == null)
{
var existingSameShortName = rulesets.FirstOrDefault(ri => ri.ShortName == r.RulesetInfo.ShortName);
if (type == null) if (existingSameShortName != null)
throw new InvalidOperationException(@"Type resolution failure."); {
// even if a matching InstantiationInfo was not found, there may be an existing ruleset with the same ShortName.
var rInstance = (Activator.CreateInstance(type) as Ruleset)?.RulesetInfo; // this generally means the user or ruleset provider has renamed their dll but the underlying ruleset is *likely* the same one.
// in such cases, update the instantiation info of the existing entry to point to the new one.
if (rInstance == null) existingSameShortName.InstantiationInfo = r.RulesetInfo.InstantiationInfo;
throw new InvalidOperationException(@"Instantiation failure."); }
else
r.Name = rInstance.Name; realm.Add(new RealmRuleset(r.RulesetInfo.ShortName, r.RulesetInfo.Name, r.RulesetInfo.InstantiationInfo, r.RulesetInfo.ID));
r.ShortName = rInstance.ShortName; }
r.InstantiationInfo = rInstance.InstantiationInfo;
r.Available = true;
detachedRulesets.Add(r.Clone());
} }
catch (Exception ex)
List<RealmRuleset> detachedRulesets = new List<RealmRuleset>();
// perform a consistency check and detach final rulesets from realm for cross-thread runtime usage.
foreach (var r in rulesets)
{ {
r.Available = false; try
Logger.Log($"Could not load ruleset {r}: {ex.Message}"); {
} var type = Type.GetType(r.InstantiationInfo);
}
availableRulesets.AddRange(detachedRulesets); if (type == null)
}); throw new InvalidOperationException(@"Type resolution failure.");
var rInstance = (Activator.CreateInstance(type) as Ruleset)?.RulesetInfo;
if (rInstance == null)
throw new InvalidOperationException(@"Instantiation failure.");
r.Name = rInstance.Name;
r.ShortName = rInstance.ShortName;
r.InstantiationInfo = rInstance.InstantiationInfo;
r.Available = true;
detachedRulesets.Add(r.Clone());
}
catch (Exception ex)
{
r.Available = false;
Logger.Log($"Could not load ruleset {r}: {ex.Message}");
}
}
availableRulesets.AddRange(detachedRulesets);
});
}
} }
private void loadFromAppDomain() private void loadFromAppDomain()