// // SingleHook.cs // // Copyright (c) František Boháček. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using NosSmooth.Extensions.SharedBinding.EventArgs; using NosSmooth.LocalBinding.Hooks; using Remora.Results; namespace NosSmooth.Extensions.SharedBinding.Hooks; /// /// A hook for a single instance of NosSmooth sharing with the rest of application. /// /// The function delegate. /// A wrapper function that abstracts the call to original function. May get the neccessary object to call the function and accept only relevant arguments. /// The event args used in case of a call. public class SingleHook : INostaleHook where TFunction : Delegate where TWrapperFunction : Delegate where TEventArgs : System.EventArgs { private readonly INostaleHook _underlyingHook; /// /// Initializes a new instance of the class. /// /// The underlying hook. public SingleHook(INostaleHook underlyingHook) { _underlyingHook = underlyingHook; } /// /// Called upon Enable or Disable. /// public event EventHandler? StateChanged; /// public string Name => _underlyingHook.Name; /// public bool IsEnabled { get; private set; } /// public Result Enable() { if (!IsEnabled) { IsEnabled = true; StateChanged?.Invoke(this, new HookStateEventArgs(true)); _underlyingHook.Called += FireCalled; } return Result.FromSuccess(); } /// public Result Disable() { if (IsEnabled) { IsEnabled = true; StateChanged?.Invoke(this, new HookStateEventArgs(false)); _underlyingHook.Called -= FireCalled; } return Result.FromSuccess(); } private void FireCalled(object? owner, TEventArgs eventArgs) { Called?.Invoke(this, eventArgs); } /// public TWrapperFunction WrapperFunction => _underlyingHook.WrapperFunction; /// public TFunction OriginalFunction => _underlyingHook.OriginalFunction; /// public event EventHandler? Called; }