Dalamud/Dalamud/Interface/ImGuiNotification/Internal/IconSource/TextureWrapTaskIconSource.cs
2024-02-28 17:11:30 +09:00

71 lines
2.6 KiB
C#

using System.Numerics;
using System.Threading.Tasks;
using Dalamud.Interface.Internal;
using Dalamud.Plugin.Internal.Types;
using Dalamud.Utility;
using Serilog;
namespace Dalamud.Interface.ImGuiNotification.Internal.IconSource;
/// <summary>Represents the use of future <see cref="IDalamudTextureWrap"/> as the icon of a notification.</summary>
/// <remarks>If there was no texture loaded for any reason, the plugin icon will be displayed instead.</remarks>
internal class TextureWrapTaskIconSource : INotificationIconSource.IInternal
{
/// <summary>Gets the default materialized icon, for the purpose of displaying the plugin icon.</summary>
internal static readonly INotificationMaterializedIcon DefaultMaterializedIcon = new MaterializedIcon(null);
/// <summary>Initializes a new instance of the <see cref="TextureWrapTaskIconSource"/> class.</summary>
/// <param name="taskFunc">The function.</param>
public TextureWrapTaskIconSource(Func<Task<IDalamudTextureWrap?>?>? taskFunc) =>
this.TextureWrapTaskFunc = taskFunc;
/// <summary>Gets the function that returns a task resulting in a new instance of <see cref="IDalamudTextureWrap"/>.
/// </summary>
/// <remarks>Dalamud will take ownership of the result. Do not call <see cref="IDisposable.Dispose"/>.</remarks>
public Func<Task<IDalamudTextureWrap?>?>? TextureWrapTaskFunc { get; }
/// <inheritdoc/>
public INotificationIconSource Clone() => this;
/// <inheritdoc/>
public void Dispose()
{
}
/// <inheritdoc/>
public INotificationMaterializedIcon Materialize() =>
new MaterializedIcon(this.TextureWrapTaskFunc);
private sealed class MaterializedIcon : INotificationMaterializedIcon
{
private Task<IDalamudTextureWrap>? task;
public MaterializedIcon(Func<Task<IDalamudTextureWrap?>?>? taskFunc)
{
try
{
this.task = taskFunc?.Invoke();
}
catch (Exception e)
{
Log.Error(e, $"{nameof(TextureWrapTaskIconSource)}: failed to materialize the icon texture.");
this.task = null;
}
}
public void Dispose()
{
this.task?.ToContentDisposedTask(true);
this.task = null;
}
public void DrawIcon(Vector2 minCoord, Vector2 maxCoord, Vector4 color, LocalPlugin? initiatorPlugin) =>
NotificationUtilities.DrawTexture(
this.task?.IsCompletedSuccessfully is true ? this.task.Result : null,
minCoord,
maxCoord,
initiatorPlugin);
}
}