com.alicizax.unity.framework/Runtime/UI/Manager/UIModule.Cache.cs

87 lines
2.5 KiB
C#

using System;
using System.Collections.Generic;
using AlicizaX;
namespace AlicizaX.UI.Runtime
{
internal sealed partial class UIModule
{
private readonly struct CacheEntry
{
public readonly UIMetadata Metadata;
public readonly int TimerId;
public CacheEntry(UIMetadata metadata, int timerId)
{
Metadata = metadata;
TimerId = timerId;
}
}
private readonly Dictionary<RuntimeTypeHandle, CacheEntry> m_CacheWindow = new();
private void CacheWindow(UIMetadata uiMetadata, bool force)
{
if (uiMetadata?.View?.Holder == null)
{
Log.Error("Cannot cache null UI metadata or holder");
return;
}
if (force || uiMetadata.MetaInfo.CacheTime == 0)
{
uiMetadata.Dispose();
return;
}
RemoveFromCache(uiMetadata.MetaInfo.RuntimeTypeHandle);
int timerId = -1;
uiMetadata.View.Holder.transform.SetParent(UICacheLayer);
if (uiMetadata.MetaInfo.CacheTime > 0)
{
timerId = _timerModule.AddTimer(
OnTimerDisposeWindow,
uiMetadata.MetaInfo.CacheTime,
isLoop: false,
isUnscaled: true,
uiMetadata
);
if (timerId <= 0)
{
Log.Warning($"Failed to create cache timer for {uiMetadata.UILogicType.Name}");
}
}
uiMetadata.InCache = true;
m_CacheWindow.Add(uiMetadata.MetaInfo.RuntimeTypeHandle, new CacheEntry(uiMetadata, timerId));
}
private void OnTimerDisposeWindow(object[] args)
{
if (args == null || args.Length == 0) return;
UIMetadata meta = args[0] as UIMetadata;
if (meta != null)
{
meta.Dispose();
RemoveFromCache(meta.MetaInfo.RuntimeTypeHandle);
}
}
private void RemoveFromCache(RuntimeTypeHandle typeHandle)
{
if (m_CacheWindow.TryGetValue(typeHandle, out var entry))
{
m_CacheWindow.Remove(typeHandle);
entry.Metadata.InCache = false;
if (entry.TimerId > 0)
{
_timerModule.RemoveTimer(entry.TimerId);
}
}
}
}
}