summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Core/Page.cs
blob: 09fa11e81cff2d921faa99efce5489abe705e047 (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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Platform;

namespace Xamarin.Forms
{
	[RenderWith(typeof(_PageRenderer))]
	public class Page : VisualElement, ILayout, IPageController, IElementConfiguration<Page>
	{
		public const string BusySetSignalName = "Xamarin.BusySet";

		public const string AlertSignalName = "Xamarin.SendAlert";

		public const string ActionSheetSignalName = "Xamarin.ShowActionSheet";

		internal static readonly BindableProperty IgnoresContainerAreaProperty = BindableProperty.Create("IgnoresContainerArea", typeof(bool), typeof(Page), false);

		public static readonly BindableProperty BackgroundImageProperty = BindableProperty.Create("BackgroundImage", typeof(string), typeof(Page), default(string));

		public static readonly BindableProperty IsBusyProperty = BindableProperty.Create("IsBusy", typeof(bool), typeof(Page), false, propertyChanged: (bo, o, n) => ((Page)bo).OnPageBusyChanged());

		public static readonly BindableProperty PaddingProperty = BindableProperty.Create("Padding", typeof(Thickness), typeof(Page), default(Thickness), propertyChanged: (bindable, old, newValue) =>
		{
			var layout = (Page)bindable;
			layout.UpdateChildrenLayout();
		});

		public static readonly BindableProperty TitleProperty = BindableProperty.Create("Title", typeof(string), typeof(Page), null);

		public static readonly BindableProperty IconProperty = BindableProperty.Create("Icon", typeof(FileImageSource), typeof(Page), default(FileImageSource));

		readonly Lazy<PlatformConfigurationRegistry<Page>> _platformConfigurationRegistry;

		bool _allocatedFlag;
		Rectangle _containerArea;

		bool _containerAreaSet;

		bool _hasAppeared;

		ReadOnlyCollection<Element> _logicalChildren;

		public Page()
		{
			var toolbarItems = new ObservableCollection<ToolbarItem>();
			toolbarItems.CollectionChanged += OnToolbarItemsCollectionChanged;
			ToolbarItems = toolbarItems;
			InternalChildren.CollectionChanged += InternalChildrenOnCollectionChanged;
			_platformConfigurationRegistry = new Lazy<PlatformConfigurationRegistry<Page>>(() => new PlatformConfigurationRegistry<Page>(this));
		}

		public string BackgroundImage
		{
			get { return (string)GetValue(BackgroundImageProperty); }
			set { SetValue(BackgroundImageProperty, value); }
		}

		public FileImageSource Icon
		{
			get { return (FileImageSource)GetValue(IconProperty); }
			set { SetValue(IconProperty, value); }
		}

		public bool IsBusy
		{
			get { return (bool)GetValue(IsBusyProperty); }
			set { SetValue(IsBusyProperty, value); }
		}

		public Thickness Padding
		{
			get { return (Thickness)GetValue(PaddingProperty); }
			set { SetValue(PaddingProperty, value); }
		}

		public string Title
		{
			get { return (string)GetValue(TitleProperty); }
			set { SetValue(TitleProperty, value); }
		}

		public IList<ToolbarItem> ToolbarItems { get; internal set; }

        [EditorBrowsable(EditorBrowsableState.Never)]
        public Rectangle ContainerArea
		{
			get { return _containerArea; }
			set
			{
				if (_containerArea == value)
					return;
				_containerAreaSet = true;
				_containerArea = value;
				ForceLayout();
			}
		}

        [EditorBrowsable(EditorBrowsableState.Never)]
        public bool IgnoresContainerArea
		{
			get { return (bool)GetValue(IgnoresContainerAreaProperty); }
			set { SetValue(IgnoresContainerAreaProperty, value); }
		}

        [EditorBrowsable(EditorBrowsableState.Never)]
        public ObservableCollection<Element> InternalChildren { get; } = new ObservableCollection<Element>();

		internal override ReadOnlyCollection<Element> LogicalChildrenInternal => 
			_logicalChildren ?? (_logicalChildren = new ReadOnlyCollection<Element>(InternalChildren));

		public event EventHandler LayoutChanged;

		public event EventHandler Appearing;

		public event EventHandler Disappearing;

		public Task<string> DisplayActionSheet(string title, string cancel, string destruction, params string[] buttons)
		{
			var args = new ActionSheetArguments(title, cancel, destruction, buttons);
			MessagingCenter.Send(this, ActionSheetSignalName, args);
			return args.Result.Task;
		}

		public Task DisplayAlert(string title, string message, string cancel)
		{
			return DisplayAlert(title, message, null, cancel);
		}

		public Task<bool> DisplayAlert(string title, string message, string accept, string cancel)
		{
			if (string.IsNullOrEmpty(cancel))
				throw new ArgumentNullException("cancel");

			var args = new AlertArguments(title, message, accept, cancel);
			MessagingCenter.Send(this, AlertSignalName, args);
			return args.Result.Task;
		}

		public void ForceLayout()
		{
			SizeAllocated(Width, Height);
		}

		public bool SendBackButtonPressed()
		{
			return OnBackButtonPressed();
		}

		protected virtual void LayoutChildren(double x, double y, double width, double height)
		{
			var area = new Rectangle(x, y, width, height);
			Rectangle originalArea = area;
			if (_containerAreaSet)
			{
				area = ContainerArea;
				area.X += Padding.Left;
				area.Y += Padding.Right;
				area.Width -= Padding.HorizontalThickness;
				area.Height -= Padding.VerticalThickness;
				area.Width = Math.Max(0, area.Width);
				area.Height = Math.Max(0, area.Height);
			}

			List<Element> elements = LogicalChildren.ToList();
			foreach (Element element in elements)
			{
				var child = element as VisualElement;
				if (child == null)
					continue;
				var page = child as Page;
				if (page != null && page.IgnoresContainerArea)
					Forms.Layout.LayoutChildIntoBoundingRegion(child, originalArea);
				else
					Forms.Layout.LayoutChildIntoBoundingRegion(child, area);
			}
		}

		protected virtual void OnAppearing()
		{
		}

		protected virtual bool OnBackButtonPressed()
		{
			var application = RealParent as Application;
			if (application == null || this == application.MainPage)
				return false;

			var canceled = false;
			EventHandler handler = (sender, args) => { canceled = true; };
			application.PopCanceled += handler;
			Navigation.PopModalAsync().ContinueWith(t => { throw t.Exception; }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());

			application.PopCanceled -= handler;
			return !canceled;
		}

		protected override void OnBindingContextChanged()
		{
			base.OnBindingContextChanged();
			foreach (ToolbarItem toolbarItem in ToolbarItems)
			{
				SetInheritedBindingContext(toolbarItem, BindingContext);
			}
		}

		protected virtual void OnChildMeasureInvalidated(object sender, EventArgs e)
		{
			InvalidationTrigger trigger = (e as InvalidationEventArgs)?.Trigger ?? InvalidationTrigger.Undefined;
			OnChildMeasureInvalidated((VisualElement)sender, trigger);
		}

		protected virtual void OnDisappearing()
		{
		}

		protected override void OnParentSet()
		{
			if (!Application.IsApplicationOrNull(RealParent) && !(RealParent is Page))
				throw new InvalidOperationException("Parent of a Page must also be a Page");
			base.OnParentSet();
		}

		protected override void OnSizeAllocated(double width, double height)
		{
			_allocatedFlag = true;
			base.OnSizeAllocated(width, height);
			UpdateChildrenLayout();
		}

		protected void UpdateChildrenLayout()
		{
			if (!ShouldLayoutChildren())
				return;

			var startingLayout = new List<Rectangle>(LogicalChildren.Count);
			foreach (VisualElement c in LogicalChildren)
			{
				startingLayout.Add(c.Bounds);
			}

			double x = Padding.Left;
			double y = Padding.Top;
			double w = Math.Max(0, Width - Padding.HorizontalThickness);
			double h = Math.Max(0, Height - Padding.VerticalThickness);

			LayoutChildren(x, y, w, h);

			for (var i = 0; i < LogicalChildren.Count; i++)
			{
				var c = (VisualElement)LogicalChildren[i];

				if (c.Bounds != startingLayout[i])
				{
					EventHandler handler = LayoutChanged;
					if (handler != null)
						handler(this, EventArgs.Empty);
					return;
				}
			}
		}

		internal virtual void OnChildMeasureInvalidated(VisualElement child, InvalidationTrigger trigger)
		{
			var container = this as IPageContainer<Page>;
			if (container != null)
			{
				Page page = container.CurrentPage;
				if (page != null && page.IsVisible && (!page.IsPlatformEnabled || !page.IsNativeStateConsistent))
					return;
			}
			else
			{
				for (var i = 0; i < LogicalChildren.Count; i++)
				{
					var v = LogicalChildren[i] as VisualElement;
					if (v != null && v.IsVisible && (!v.IsPlatformEnabled || !v.IsNativeStateConsistent))
						return;
				}
			}

			_allocatedFlag = false;
			InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
			if (!_allocatedFlag && Width >= 0 && Height >= 0)
			{
				SizeAllocated(Width, Height);
			}
		}

        [EditorBrowsable(EditorBrowsableState.Never)]
        public void SendAppearing()
		{
			if (_hasAppeared)
				return;

			_hasAppeared = true;

			if (IsBusy)
				MessagingCenter.Send(this, BusySetSignalName, true);

			OnAppearing();
			EventHandler handler = Appearing;
			if (handler != null)
				handler(this, EventArgs.Empty);

			var pageContainer = this as IPageContainer<Page>;
			pageContainer?.CurrentPage?.SendAppearing();
		}

        [EditorBrowsable(EditorBrowsableState.Never)]
        public void SendDisappearing()
		{
			if (!_hasAppeared)
				return;

			_hasAppeared = false;

			if (IsBusy)
				MessagingCenter.Send(this, BusySetSignalName, false);

			var pageContainer = this as IPageContainer<Page>;
			pageContainer?.CurrentPage?.SendDisappearing();

			OnDisappearing();
			EventHandler handler = Disappearing;
			if (handler != null)
				handler(this, EventArgs.Empty);
		}

		void InternalChildrenOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			if (e.OldItems != null)
			{
				foreach (VisualElement item in e.OldItems.OfType<VisualElement>())
					OnInternalRemoved(item);
			}

			if (e.NewItems != null)
			{
				foreach (VisualElement item in e.NewItems.OfType<VisualElement>())
					OnInternalAdded(item);
			}
		}

		void OnInternalAdded(VisualElement view)
		{
			view.MeasureInvalidated += OnChildMeasureInvalidated;

			OnChildAdded(view);
			InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
		}

		void OnInternalRemoved(VisualElement view)
		{
			view.MeasureInvalidated -= OnChildMeasureInvalidated;

			OnChildRemoved(view);
		}

		void OnPageBusyChanged()
		{
			if (!_hasAppeared)
				return;

			MessagingCenter.Send(this, BusySetSignalName, IsBusy);
		}

		void OnToolbarItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
		{
			if (args.Action != NotifyCollectionChangedAction.Add)
				return;
			foreach (IElement item in args.NewItems)
				item.Parent = this;
		}

		bool ShouldLayoutChildren()
		{
			if (!LogicalChildren.Any() || Width <= 0 || Height <= 0 || !IsNativeStateConsistent)
				return false;

			var container = this as IPageContainer<Page>;
			if (container?.CurrentPage != null)
			{
				if (InternalChildren.Contains(container.CurrentPage))
					return container.CurrentPage.IsPlatformEnabled && container.CurrentPage.IsNativeStateConsistent;
				return true;
			}

			var any = false;
			for (var i = 0; i < LogicalChildren.Count; i++)
			{
				var v = LogicalChildren[i] as VisualElement;
				if (v != null && (!v.IsPlatformEnabled || !v.IsNativeStateConsistent))
				{
					any = true;
					break;
				}
			}
			return !any;
		}

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