1
0
mirror of https://github.com/ppy/osu.git synced 2024-12-16 00:52:59 +08:00
osu-lazer/osu.Game/Skinning/SkinReloadableDrawable.cs

85 lines
2.8 KiB
C#
Raw Normal View History

// 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.
2018-04-13 17:19:50 +08:00
using System;
using osu.Framework.Allocation;
2020-11-06 21:11:49 +08:00
using osu.Framework.Graphics.Pooling;
2018-04-13 17:19:50 +08:00
namespace osu.Game.Skinning
{
/// <summary>
/// A drawable which has a callback when the skin changes.
/// </summary>
2020-11-06 21:11:49 +08:00
public abstract class SkinReloadableDrawable : PoolableDrawable
2018-04-13 17:19:50 +08:00
{
/// <summary>
/// Invoked when <see cref="CurrentSkin"/> has changed.
/// </summary>
public event Action OnSkinChanged;
/// <summary>
/// The current skin source.
/// </summary>
protected ISkinSource CurrentSkin { get; private set; }
2018-04-13 17:19:50 +08:00
private readonly Func<ISkinSource, bool> allowFallback;
/// <summary>
/// Whether fallback to default skin should be allowed if the custom skin is missing this resource.
/// </summary>
2020-11-19 18:51:09 +08:00
protected bool AllowDefaultFallback => allowFallback == null || allowFallback.Invoke(CurrentSkin);
2018-04-13 17:19:50 +08:00
/// <summary>
/// Create a new <see cref="SkinReloadableDrawable"/>
/// </summary>
/// <param name="allowFallback">A conditional to decide whether to allow fallback to the default implementation if a skinned element is not present.</param>
protected SkinReloadableDrawable(Func<ISkinSource, bool> allowFallback = null)
{
this.allowFallback = allowFallback;
}
[BackgroundDependencyLoader]
private void load(ISkinSource source)
{
CurrentSkin = source;
CurrentSkin.SourceChanged += onChange;
2018-04-13 17:19:50 +08:00
}
private void onChange() =>
// schedule required to avoid calls after disposed.
2019-07-29 17:35:22 +08:00
// note that this has the side-effect of components only performing a skin change when they are alive.
Scheduler.AddOnce(skinChanged);
2018-04-13 17:19:50 +08:00
protected override void LoadAsyncComplete()
{
base.LoadAsyncComplete();
skinChanged();
}
private void skinChanged()
{
2020-11-19 18:51:09 +08:00
SkinChanged(CurrentSkin, AllowDefaultFallback);
OnSkinChanged?.Invoke();
2018-04-13 17:19:50 +08:00
}
/// <summary>
/// Called when a change is made to the skin.
/// </summary>
/// <param name="skin">The new skin.</param>
/// <param name="allowFallback">Whether fallback to default skin should be allowed if the custom skin is missing this resource.</param>
protected virtual void SkinChanged(ISkinSource skin, bool allowFallback)
{
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (CurrentSkin != null)
CurrentSkin.SourceChanged -= onChange;
OnSkinChanged = null;
}
2018-04-13 17:19:50 +08:00
}
}