summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Core/Application.cs
blob: b084b52a87167130837a0d3791929a3ba37c8777 (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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.ComponentModel;
using System.Threading.Tasks;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Platform;

namespace Xamarin.Forms
{
	public class Application : Element, IResourcesProvider, IApplicationController, IElementConfiguration<Application>
	{
		static Application s_current;
		Task<IDictionary<string, object>> _propertiesTask;
		readonly Lazy<PlatformConfigurationRegistry<Application>> _platformConfigurationRegistry;

		IAppIndexingProvider _appIndexProvider;

		ReadOnlyCollection<Element> _logicalChildren;

		Page _mainPage;

		ResourceDictionary _resources;
		static SemaphoreSlim SaveSemaphore = new SemaphoreSlim(1, 1);

		protected Application()
		{
			var f = false;
			if (f)
				Loader.Load();
			NavigationProxy = new NavigationImpl(this);
			SetCurrentApplication(this);

			SystemResources = DependencyService.Get<ISystemResourcesProvider>().GetSystemResources();
			SystemResources.ValuesChanged += OnParentResourcesChanged;
			_platformConfigurationRegistry = new Lazy<PlatformConfigurationRegistry<Application>>(() => new PlatformConfigurationRegistry<Application>(this));
		}

		public IAppLinks AppLinks
		{
			get
			{
				if (_appIndexProvider == null)
					throw new ArgumentException("No IAppIndexingProvider was provided");
				if (_appIndexProvider.AppLinks == null)
					throw new ArgumentException("No AppLinks implementation was found, if in Android make sure you installed the Xamarin.Forms.AppLinks");
				return _appIndexProvider.AppLinks;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public static void SetCurrentApplication(Application value) => Current = value;

		public static Application Current
		{
			get { return s_current; }
			set 
			{
				if (s_current == value)
					return;
				if (value == null)
					s_current = null; //Allow to reset current for unittesting
				s_current = value;
			}
		}

		public Page MainPage
		{
			get { return _mainPage; }
			set
			{
				if (value == null)
					throw new ArgumentNullException("value");

				if (_mainPage == value)
					return;

				OnPropertyChanging();
				if (_mainPage != null)
				{
					InternalChildren.Remove(_mainPage);
					_mainPage.Parent = null;
				}

				_mainPage = value;

				if (_mainPage != null)
				{
					_mainPage.Parent = this;
					_mainPage.NavigationProxy.Inner = NavigationProxy;
					InternalChildren.Add(_mainPage);
				}
				OnPropertyChanged();
			}
		}

		public IDictionary<string, object> Properties
		{
			get
			{
				if (_propertiesTask == null)
				{
					_propertiesTask = GetPropertiesAsync();
				}

				return _propertiesTask.Result;
			}
		}

		internal override ReadOnlyCollection<Element> LogicalChildrenInternal
		{
			get { return _logicalChildren ?? (_logicalChildren = new ReadOnlyCollection<Element>(InternalChildren)); }
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public NavigationProxy NavigationProxy { get; }

		[EditorBrowsable(EditorBrowsableState.Never)]
		public int PanGestureId { get; set; }

		internal IResourceDictionary SystemResources { get; }

		ObservableCollection<Element> InternalChildren { get; } = new ObservableCollection<Element>();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public void SetAppIndexingProvider(IAppIndexingProvider provider)
		{
			_appIndexProvider = provider;
		}

		public ResourceDictionary Resources
		{
			get { return _resources; }
			set
			{
				if (_resources == value)
					return;
				OnPropertyChanging();
				if (_resources != null)
					((IResourceDictionary)_resources).ValuesChanged -= OnResourcesChanged;
				_resources = value;
				OnResourcesChanged(value);
				if (_resources != null)
					((IResourceDictionary)_resources).ValuesChanged += OnResourcesChanged;
				OnPropertyChanged();
			}
		}

		public event EventHandler<ModalPoppedEventArgs> ModalPopped;

		public event EventHandler<ModalPoppingEventArgs> ModalPopping;

		public event EventHandler<ModalPushedEventArgs> ModalPushed;

		public event EventHandler<ModalPushingEventArgs> ModalPushing;

		public async Task SavePropertiesAsync()
		{
			if (Device.IsInvokeRequired)
				Device.BeginInvokeOnMainThread(async () => await SetPropertiesAsync());
			else
				await SetPropertiesAsync();
		}

		public IPlatformElementConfiguration<T, Application> On<T>() where T : IConfigPlatform
		{
			return _platformConfigurationRegistry.Value.On<T>();
		}

		protected virtual void OnAppLinkRequestReceived(Uri uri)
		{
		}

		protected override void OnParentSet()
		{
			throw new InvalidOperationException("Setting a Parent on Application is invalid.");
		}

		protected virtual void OnResume()
		{
		}

		protected virtual void OnSleep()
		{
		}

		protected virtual void OnStart()
		{
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public static void ClearCurrent()
		{
			s_current = null;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public static bool IsApplicationOrNull(Element element)
		{
			return element == null || element is Application;
		}

		internal override void OnParentResourcesChanged(IEnumerable<KeyValuePair<string, object>> values)
		{
			if (Resources == null || Resources.Count == 0)
			{
				base.OnParentResourcesChanged(values);
				return;
			}

			var innerKeys = new HashSet<string>();
			var changedResources = new List<KeyValuePair<string, object>>();
			foreach (KeyValuePair<string, object> c in Resources)
				innerKeys.Add(c.Key);
			foreach (KeyValuePair<string, object> value in values)
			{
				if (innerKeys.Add(value.Key))
					changedResources.Add(value);
			}
			OnResourcesChanged(changedResources);
		}

		internal event EventHandler PopCanceled;

		[EditorBrowsable(EditorBrowsableState.Never)]
		public void SendOnAppLinkRequestReceived(Uri uri)
		{
			OnAppLinkRequestReceived(uri);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public void SendResume()
		{
			s_current = this;
			OnResume();
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public Task SendSleepAsync()
		{
			OnSleep();
			return SavePropertiesAsync();
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public void SendStart()
		{
			OnStart();
		}

		async Task<IDictionary<string, object>> GetPropertiesAsync()
		{
			var deserializer = DependencyService.Get<IDeserializer>();
			if (deserializer == null)
			{
				Log.Warning("Startup", "No IDeserialzier was found registered");
				return new Dictionary<string, object>(4);
			}

			IDictionary<string, object> properties = await deserializer.DeserializePropertiesAsync().ConfigureAwait(false);
			if (properties == null)
				properties = new Dictionary<string, object>(4);

			return properties;
		}

		void OnModalPopped(Page modalPage)
		{
			EventHandler<ModalPoppedEventArgs> handler = ModalPopped;
			if (handler != null)
				handler(this, new ModalPoppedEventArgs(modalPage));
		}

		bool OnModalPopping(Page modalPage)
		{
			EventHandler<ModalPoppingEventArgs> handler = ModalPopping;
			var args = new ModalPoppingEventArgs(modalPage);
			if (handler != null)
				handler(this, args);
			return args.Cancel;
		}

		void OnModalPushed(Page modalPage)
		{
			EventHandler<ModalPushedEventArgs> handler = ModalPushed;
			if (handler != null)
				handler(this, new ModalPushedEventArgs(modalPage));
		}

		void OnModalPushing(Page modalPage)
		{
			EventHandler<ModalPushingEventArgs> handler = ModalPushing;
			if (handler != null)
				handler(this, new ModalPushingEventArgs(modalPage));
		}

		void OnPopCanceled()
		{
			EventHandler handler = PopCanceled;
			if (handler != null)
				handler(this, EventArgs.Empty);
		}

		async Task SetPropertiesAsync()
		{
			await SaveSemaphore.WaitAsync();
            try
            {
                await DependencyService.Get<IDeserializer>().SerializePropertiesAsync(Properties);
            }
            finally
            {
                SaveSemaphore.Release();
            }

		}

		class NavigationImpl : NavigationProxy
		{
			readonly Application _owner;

			public NavigationImpl(Application owner)
			{
				_owner = owner;
			}

			protected override async Task<Page> OnPopModal(bool animated)
			{
				Page modal = ModalStack[ModalStack.Count - 1];
				if (_owner.OnModalPopping(modal))
				{
					_owner.OnPopCanceled();
					return null;
				}
				Page result = await base.OnPopModal(animated);
				result.Parent = null;
				_owner.OnModalPopped(result);
				return result;
			}

			protected override async Task OnPushModal(Page modal, bool animated)
			{
				_owner.OnModalPushing(modal);

				modal.Parent = _owner;

				if (modal.NavigationProxy.ModalStack.Count == 0)
				{
					modal.NavigationProxy.Inner = this;
					await base.OnPushModal(modal, animated);
				}
				else
				{
					await base.OnPushModal(modal, animated);
					modal.NavigationProxy.Inner = this;
				}

				_owner.OnModalPushed(modal);
			}
		}
	}
}