2024-11-11 05:03:12 +01:00
|
|
|
using Ryujinx.Common.Logging;
|
2023-12-04 14:17:13 +01:00
|
|
|
using System;
|
2024-11-11 05:03:12 +01:00
|
|
|
using System.Globalization;
|
2019-12-21 20:52:31 +01:00
|
|
|
using System.Threading;
|
|
|
|
|
|
|
|
namespace Ryujinx.Common
|
|
|
|
{
|
|
|
|
public class ReactiveObject<T>
|
|
|
|
{
|
2024-11-11 05:03:12 +01:00
|
|
|
private readonly ReaderWriterLockSlim _rwLock = new();
|
2023-06-28 18:41:38 +02:00
|
|
|
private bool _isInitialized;
|
2020-01-05 17:35:55 +01:00
|
|
|
private T _value;
|
2019-12-21 20:52:31 +01:00
|
|
|
|
|
|
|
public event EventHandler<ReactiveEventArgs<T>> Event;
|
|
|
|
|
|
|
|
public T Value
|
|
|
|
{
|
|
|
|
get
|
|
|
|
{
|
2024-11-11 05:03:12 +01:00
|
|
|
_rwLock.EnterReadLock();
|
2019-12-21 20:52:31 +01:00
|
|
|
T value = _value;
|
2024-11-11 05:03:12 +01:00
|
|
|
_rwLock.ExitReadLock();
|
2019-12-21 20:52:31 +01:00
|
|
|
|
|
|
|
return value;
|
|
|
|
}
|
|
|
|
set
|
|
|
|
{
|
2024-11-11 05:03:12 +01:00
|
|
|
_rwLock.EnterWriteLock();
|
2019-12-21 20:52:31 +01:00
|
|
|
|
|
|
|
T oldValue = _value;
|
2020-01-05 17:35:55 +01:00
|
|
|
|
|
|
|
bool oldIsInitialized = _isInitialized;
|
|
|
|
|
|
|
|
_isInitialized = true;
|
2023-06-28 18:41:38 +02:00
|
|
|
_value = value;
|
2019-12-21 20:52:31 +01:00
|
|
|
|
2024-11-11 05:03:12 +01:00
|
|
|
_rwLock.ExitWriteLock();
|
2019-12-21 20:52:31 +01:00
|
|
|
|
2022-04-15 12:58:27 +02:00
|
|
|
if (!oldIsInitialized || oldValue == null || !oldValue.Equals(_value))
|
2019-12-21 20:52:31 +01:00
|
|
|
{
|
|
|
|
Event?.Invoke(this, new ReactiveEventArgs<T>(oldValue, value));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-11-11 05:03:12 +01:00
|
|
|
|
|
|
|
public void LogChangesToValue(string valueName, LogClass logClass = LogClass.Configuration)
|
|
|
|
=> Event += (_, e) => ReactiveObjectHelper.LogValueChange(logClass, e, valueName);
|
2019-12-21 20:52:31 +01:00
|
|
|
|
2024-10-24 21:14:12 +02:00
|
|
|
public static implicit operator T(ReactiveObject<T> obj) => obj.Value;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static class ReactiveObjectHelper
|
|
|
|
{
|
2024-11-11 05:03:12 +01:00
|
|
|
public static void LogValueChange<T>(LogClass logClass, ReactiveEventArgs<T> eventArgs, string valueName)
|
|
|
|
{
|
|
|
|
string message = string.Create(CultureInfo.InvariantCulture, $"{valueName} set to: {eventArgs.NewValue}");
|
|
|
|
|
|
|
|
Logger.Info?.Print(logClass, message);
|
|
|
|
}
|
|
|
|
|
2024-10-24 21:14:12 +02:00
|
|
|
public static void Toggle(this ReactiveObject<bool> rBoolean) => rBoolean.Value = !rBoolean.Value;
|
2019-12-21 20:52:31 +01:00
|
|
|
}
|
|
|
|
|
2024-10-12 00:56:59 +02:00
|
|
|
public class ReactiveEventArgs<T>(T oldValue, T newValue)
|
2019-12-21 20:52:31 +01:00
|
|
|
{
|
2024-10-12 00:56:59 +02:00
|
|
|
public T OldValue { get; } = oldValue;
|
|
|
|
public T NewValue { get; } = newValue;
|
2019-12-21 20:52:31 +01:00
|
|
|
}
|
|
|
|
}
|