Neg_Utils/NEG/UI/Popup/PopupData.cs
2025-10-06 17:31:41 +02:00

79 lines
2.0 KiB
C#

using JetBrains.Annotations;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using NEG.Utils;
using NegUtils;
using NegUtils.NEG.UI;
namespace NEG.UI.Popup
{
public struct PopupDataHook
{
private uint version;
private PopupData data;
public bool IsValid => version == data.CurrentVersion;
public PopupDataHook(PopupData data)
{
this.data = data;
version = data.CurrentVersion;
}
public void Invalidate()
{
if (!IsValid)
return;
data.Dispose();
}
}
[PublicAPI]
public class PopupData : IPoolable
{
private static readonly Dictionary<Type, Action<PopupData>> ReturnDelegates = new();
/// <summary>
/// Is this data is still valid. If set to false, popup will not show.
/// </summary>
public bool IsValid { get; protected set; }
internal uint CurrentVersion { get; private set; }
internal void Dispose()
{
IsValid = false;
IPopupsHandler.Instance.RefreshPopups();
var type = GetType();
if (!ReturnDelegates.TryGetValue(GetType(), out var returnDelegate))
ReturnDelegates[type] = CreateReturnDelegate(type);
returnDelegate?.Invoke(this);
}
private static Action<PopupData> CreateReturnDelegate(Type type)
{
var returnMethod = typeof(NativePool<>)
.MakeGenericType(type)
.GetMethod(nameof(NativePool<PopupData>.Return), new[] { type });
return (Action<PopupData>)Delegate.CreateDelegate(
typeof(Action<PopupData>),
returnMethod);
}
public virtual void OnGet()
{
IsValid = true;
}
public virtual void OnRelease()
{
CurrentVersion++;
}
}
}