summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Core/MessagingCenter.cs
blob: 5e60046d09f7ca8b957abb17b8788ef20d4dc1de (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;

namespace Xamarin.Forms
{
	public static class MessagingCenter
	{
		class Sender : Tuple<string, Type, Type>
		{
			public Sender(string message, Type senderType, Type argType) : base(message, senderType, argType)
			{
			}
		}

		delegate bool Filter(object sender);

		class MaybeWeakReference
		{
			WeakReference DelegateWeakReference { get; set; }
			object DelegateStrongReference { get; set; }

			readonly bool _isStrongReference;

			public MaybeWeakReference(object subscriber, object delegateSource)
			{
				if (subscriber.Equals(delegateSource))
				{
					// The target is the subscriber; we can use a weakreference
					DelegateWeakReference = new WeakReference(delegateSource);
					_isStrongReference = false;
				}
				else
				{
					DelegateStrongReference = delegateSource;
					_isStrongReference = true;
				}
			}

			public object Target => _isStrongReference ? DelegateStrongReference : DelegateWeakReference.Target;
			public bool IsAlive => _isStrongReference || DelegateWeakReference.IsAlive;
		}

		class Subscription : Tuple<WeakReference, MaybeWeakReference, MethodInfo, Filter>
		{
			public Subscription(object subscriber, object delegateSource, MethodInfo methodInfo, Filter filter)
				: base(new WeakReference(subscriber), new MaybeWeakReference(subscriber, delegateSource), methodInfo, filter)
			{
			}

			public WeakReference Subscriber => Item1;
			MaybeWeakReference DelegateSource => Item2;
			MethodInfo MethodInfo => Item3;
			Filter Filter => Item4;

			public void InvokeCallback(object sender, object args)
			{
				if (!Filter(sender))
				{
					return;
				}

				if (MethodInfo.IsStatic)
				{
					MethodInfo.Invoke(null, MethodInfo.GetParameters().Length == 1 ? new[] { sender } : new[] { sender, args });
					return;
				}

				var target = DelegateSource.Target;

				if (target == null)
				{
					return; // Collected 
				}

				MethodInfo.Invoke(target, MethodInfo.GetParameters().Length == 1 ? new[] { sender } : new[] { sender, args });
			}

			public bool CanBeRemoved()
			{
				return !Subscriber.IsAlive || !DelegateSource.IsAlive;
			}
		}

		static readonly Dictionary<Sender, List<Subscription>> s_subscriptions =
			new Dictionary<Sender, List<Subscription>>();

		public static void Send<TSender, TArgs>(TSender sender, string message, TArgs args) where TSender : class
		{
			if (sender == null)
				throw new ArgumentNullException(nameof(sender));
			InnerSend(message, typeof(TSender), typeof(TArgs), sender, args);
		}

		public static void Send<TSender>(TSender sender, string message) where TSender : class
		{
			if (sender == null)
				throw new ArgumentNullException(nameof(sender));
			InnerSend(message, typeof(TSender), null, sender, null);
		}

		public static void Subscribe<TSender, TArgs>(object subscriber, string message, Action<TSender, TArgs> callback, TSender source = null) where TSender : class
		{
			if (subscriber == null)
				throw new ArgumentNullException(nameof(subscriber));
			if (callback == null)
				throw new ArgumentNullException(nameof(callback));

			var target = callback.Target;

			Filter filter = sender =>
			{
				var send = (TSender)sender;
				return (source == null || send == source);
			};

			InnerSubscribe(subscriber, message, typeof(TSender), typeof(TArgs), target, callback.GetMethodInfo(), filter);
		}

		public static void Subscribe<TSender>(object subscriber, string message, Action<TSender> callback, TSender source = null) where TSender : class
		{
			if (subscriber == null)
				throw new ArgumentNullException(nameof(subscriber));
			if (callback == null)
				throw new ArgumentNullException(nameof(callback));

			var target = callback.Target;

			Filter filter = sender =>
			{
				var send = (TSender)sender;
				return (source == null || send == source);
			};

			InnerSubscribe(subscriber, message, typeof(TSender), null, target, callback.GetMethodInfo(), filter);
		}

		public static void Unsubscribe<TSender, TArgs>(object subscriber, string message) where TSender : class
		{
			InnerUnsubscribe(message, typeof(TSender), typeof(TArgs), subscriber);
		}

		public static void Unsubscribe<TSender>(object subscriber, string message) where TSender : class
		{
			InnerUnsubscribe(message, typeof(TSender), null, subscriber);
		}

		internal static void ClearSubscribers()
		{
			s_subscriptions.Clear();
		}

		static void InnerSend(string message, Type senderType, Type argType, object sender, object args)
		{
			if (message == null)
				throw new ArgumentNullException(nameof(message));
			var key = new Sender(message, senderType, argType);
			if (!s_subscriptions.ContainsKey(key))
				return;
			List<Subscription> subcriptions = s_subscriptions[key];
			if (subcriptions == null || !subcriptions.Any())
				return; // should not be reachable

			// ok so this code looks a bit funky but here is the gist of the problem. It is possible that in the course
			// of executing the callbacks for this message someone will subscribe/unsubscribe from the same message in
			// the callback. This would invalidate the enumerator. To work around this we make a copy. However if you unsubscribe 
			// from a message you can fairly reasonably expect that you will therefor not receive a call. To fix this we then
			// check that the item we are about to send the message to actually exists in the live list.
			List<Subscription> subscriptionsCopy = subcriptions.ToList();
			foreach (Subscription subscription in subscriptionsCopy)
			{
				if (subscription.Subscriber.Target != null && subcriptions.Contains(subscription))
				{
					subscription.InvokeCallback(sender, args);
				}
			}
		}

		static void InnerSubscribe(object subscriber, string message, Type senderType, Type argType, object target, MethodInfo methodInfo, Filter filter)
		{
			if (message == null)
				throw new ArgumentNullException(nameof(message));
			var key = new Sender(message, senderType, argType);
			var value = new Subscription(subscriber, target, methodInfo, filter);
			if (s_subscriptions.ContainsKey(key))
			{
				s_subscriptions[key].Add(value);
			}
			else
			{
				var list = new List<Subscription> { value };
				s_subscriptions[key] = list;
			}
		}

		static void InnerUnsubscribe(string message, Type senderType, Type argType, object subscriber)
		{
			if (subscriber == null)
				throw new ArgumentNullException(nameof(subscriber));
			if (message == null)
				throw new ArgumentNullException(nameof(message));

			var key = new Sender(message, senderType, argType);
			if (!s_subscriptions.ContainsKey(key))
				return;
			s_subscriptions[key].RemoveAll(sub => !sub.CanBeRemoved() || sub.Subscriber.Target == subscriber);
			if (!s_subscriptions[key].Any())
				s_subscriptions.Remove(key);
		}
	}
}