This repository has been archived by the owner on Nov 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 122
/
UrhoEventAdapter.cs
68 lines (61 loc) · 2.2 KB
/
UrhoEventAdapter.cs
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
using System;
using System.Collections.Generic;
namespace Urho
{
internal class UrhoEventAdapter<TEventArgs>
{
readonly Dictionary<IntPtr, List<Action<TEventArgs>>> managedSubscribersByObjects;
readonly Dictionary<IntPtr, Subscription> nativeSubscriptionsForObjects;
readonly Type objectType;
public UrhoEventAdapter(Type objectType)
{
this.objectType = objectType;
managedSubscribersByObjects = new Dictionary<IntPtr, List<Action<TEventArgs>>>(IntPtrEqualityComparer.Instance);
nativeSubscriptionsForObjects = new Dictionary<IntPtr, Subscription>(IntPtrEqualityComparer.Instance);
Runtime.KnownObjectDeleted += OnObjectDeleted;
}
void OnObjectDeleted(RefCounted refCounted, IntPtr handle)
{
if (refCounted.GetType() != objectType)
return;
managedSubscribersByObjects.Remove(handle);
nativeSubscriptionsForObjects.Remove(handle);
}
public void AddManagedSubscriber(IntPtr handle, Action<TEventArgs> action, Func<Action<TEventArgs>, Subscription> nativeSubscriber)
{
List<Action<TEventArgs>> listOfManagedSubscribers;
if (!managedSubscribersByObjects.TryGetValue(handle, out listOfManagedSubscribers))
{
listOfManagedSubscribers = new List<Action<TEventArgs>> { action };
managedSubscribersByObjects[handle] = listOfManagedSubscribers;
nativeSubscriptionsForObjects[handle] = nativeSubscriber(args =>
{
var count = listOfManagedSubscribers.Count;
for (int i = 0; i < count; i++)
{
if (i < listOfManagedSubscribers.Count)
listOfManagedSubscribers[i](args);
}
});
}
else
{
//this handle is already subscribed to the native event - don't call native subscription again - just add it to the list.
listOfManagedSubscribers.Add(action);
}
}
public void RemoveManagedSubscriber(IntPtr handle, Action<TEventArgs> action)
{
List<Action<TEventArgs>> listOfManagedSubscribers;
if (managedSubscribersByObjects.TryGetValue(handle, out listOfManagedSubscribers))
{
listOfManagedSubscribers.RemoveAll(a => a == action);
if (listOfManagedSubscribers.Count < 1)
{
managedSubscribersByObjects.Remove(handle);
nativeSubscriptionsForObjects[handle].Unsubscribe();
}
}
}
}
}