summaryrefslogtreecommitdiff
path: root/src/SMAPI/Framework/Events/ManagedEventBase.cs
blob: 7e42d6139815bdcb8f07867b7de195337b06c6e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Collections.Generic;
using System.Linq;

namespace StardewModdingAPI.Framework.Events
{
    /// <summary>The base implementation for an event wrapper which intercepts and logs errors in handler code.</summary>
    internal abstract class ManagedEventBase<TEventHandler>
    {
        /*********
        ** Properties
        *********/
        /// <summary>A human-readable name for the event.</summary>
        private readonly string EventName;

        /// <summary>Writes messages to the log.</summary>
        private readonly IMonitor Monitor;

        /// <summary>The mod registry with which to identify mods.</summary>
        private readonly ModRegistry ModRegistry;

        /// <summary>The display names for the mods which added each delegate.</summary>
        private readonly IDictionary<TEventHandler, IModMetadata> SourceMods = new Dictionary<TEventHandler, IModMetadata>();

        /// <summary>The cached invocation list.</summary>
        protected TEventHandler[] CachedInvocationList { get; private set; }


        /*********
        ** Public methods
        *********/
        /// <summary>Get whether anything is listening to the event.</summary>
        public bool HasListeners()
        {
            return this.CachedInvocationList?.Length > 0;
        }

        /*********
        ** Protected methods
        *********/
        /// <summary>Construct an instance.</summary>
        /// <param name="eventName">A human-readable name for the event.</param>
        /// <param name="monitor">Writes messages to the log.</param>
        /// <param name="modRegistry">The mod registry with which to identify mods.</param>
        protected ManagedEventBase(string eventName, IMonitor monitor, ModRegistry modRegistry)
        {
            this.EventName = eventName;
            this.Monitor = monitor;
            this.ModRegistry = modRegistry;
        }

        /// <summary>Track an event handler.</summary>
        /// <param name="handler">The event handler.</param>
        /// <param name="invocationList">The updated event invocation list.</param>
        protected void AddTracking(TEventHandler handler, IEnumerable<TEventHandler> invocationList)
        {
            this.SourceMods[handler] = this.ModRegistry.GetFromStack();
            this.CachedInvocationList = invocationList?.ToArray() ?? new TEventHandler[0];
        }

        /// <summary>Remove tracking for an event handler.</summary>
        /// <param name="handler">The event handler.</param>
        /// <param name="invocationList">The updated event invocation list.</param>
        protected void RemoveTracking(TEventHandler handler, IEnumerable<TEventHandler> invocationList)
        {
            this.CachedInvocationList = invocationList?.ToArray() ?? new TEventHandler[0];
            if(!this.CachedInvocationList.Contains(handler)) // don't remove if there's still a reference to the removed handler (e.g. it was added twice and removed once)
                this.SourceMods.Remove(handler);
        }

        /// <summary>Log an exception from an event handler.</summary>
        /// <param name="handler">The event handler instance.</param>
        /// <param name="ex">The exception that was raised.</param>
        protected void LogError(TEventHandler handler, Exception ex)
        {
            if (this.SourceMods.TryGetValue(handler, out IModMetadata mod))
                mod.LogAsMod($"This mod failed in the {this.EventName} event. Technical details: \n{ex.GetLogSummary()}", LogLevel.Error);
            else
                this.Monitor.Log($"A mod failed in the {this.EventName} event. Technical details: \n{ex.GetLogSummary()}", LogLevel.Error);
        }
    }
}