summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Platform.Tizen/Renderers/VisualElementRenderer.cs
blob: d5de949bb530abfa471a055011a1fb902431a236 (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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using ElmSharp;
using ESize = ElmSharp.Size;
using ERect = ElmSharp.Rect;
using EFocusDirection = ElmSharp.FocusDirection;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Platform.Tizen.Native;
using Specific = Xamarin.Forms.PlatformConfiguration.TizenSpecific.VisualElement;
using XFocusDirection = Xamarin.Forms.PlatformConfiguration.TizenSpecific.FocusDirection;

namespace Xamarin.Forms.Platform.Tizen
{
	/// <summary>
	/// Base class for rendering of a Xamarin element.
	/// </summary>
	public abstract class VisualElementRenderer<TElement> : IVisualElementRenderer, IEffectControlProvider where TElement : VisualElement
	{
		/// <summary>
		/// Holds registered element changed handlers.
		/// </summary>
		readonly List<EventHandler<VisualElementChangedEventArgs>> _elementChangedHandlers = new List<EventHandler<VisualElementChangedEventArgs>>();

		/// <summary>
		/// Flags which control status of renderer.
		/// </summary>
		VisualElementRendererFlags _flags = VisualElementRendererFlags.None;

		/// <summary>
		/// Holds the native view.
		/// </summary>
		EvasObject _view;

		Dictionary<string, Action<bool>> _propertyHandlersWithInit = new Dictionary<string, Action<bool>>();

		Dictionary<string, Action> _propertyHandlers = new Dictionary<string, Action>();

		HashSet<string> _batchedProperties = new HashSet<string>();

		bool _movedCallbackEnabled = false;
		/// <summary>
		/// Default constructor.
		/// </summary>
		protected VisualElementRenderer()
		{
			RegisterPropertyHandler(VisualElement.IsVisibleProperty, UpdateIsVisible);
			RegisterPropertyHandler(VisualElement.OpacityProperty, UpdateOpacity);
			RegisterPropertyHandler(VisualElement.IsEnabledProperty, UpdateIsEnabled);
			RegisterPropertyHandler(VisualElement.InputTransparentProperty, UpdateInputTransparent);
			RegisterPropertyHandler(VisualElement.BackgroundColorProperty, UpdateBackgroundColor);

			// Use TizenSpecific APIs only if available
			if (TizenPlatformServices.AppDomain.IsTizenSpecificAvailable)
			{
				RegisterPropertyHandler("ThemeStyle", UpdateThemeStyle);
				RegisterPropertyHandler("IsFocusAllowed", UpdateFocusAllowed);
				RegisterPropertyHandler("NextFocusDirection", UpdateFocusDirection);
				RegisterPropertyHandler("NextFocusUpView", UpdateFocusUpView);
				RegisterPropertyHandler("NextFocusDownView", UpdateFocusDownView);
				RegisterPropertyHandler("NextFocusLeftView", UpdateFocusLeftView);
				RegisterPropertyHandler("NextFocusRightView", UpdateFocusRightView);
				RegisterPropertyHandler("NextFocusBackView", UpdateFocusBackView);
				RegisterPropertyHandler("NextFocusForwardView", UpdateFocusForwardView);
				RegisterPropertyHandler("ToolTip", UpdateToolTip);
			}

			RegisterPropertyHandler(VisualElement.AnchorXProperty, ApplyTransformation);
			RegisterPropertyHandler(VisualElement.AnchorYProperty, ApplyTransformation);
			RegisterPropertyHandler(VisualElement.ScaleProperty, ApplyTransformation);
			RegisterPropertyHandler(VisualElement.RotationProperty, ApplyTransformation);
			RegisterPropertyHandler(VisualElement.RotationXProperty, ApplyTransformation);
			RegisterPropertyHandler(VisualElement.RotationYProperty, ApplyTransformation);
			RegisterPropertyHandler(VisualElement.TranslationXProperty, ApplyTransformation);
			RegisterPropertyHandler(VisualElement.TranslationYProperty, ApplyTransformation);
		}

		~VisualElementRenderer()
		{
			Dispose(false);
		}

		event EventHandler<VisualElementChangedEventArgs> ElementChanged
		{
			add
			{
				_elementChangedHandlers.Add(value);
			}
			remove
			{
				_elementChangedHandlers.Remove(value);
			}
		}

		/// <summary>
		/// Gets the Xamarin element associated with this renderer.
		/// </summary>
		public TElement Element
		{
			get;
			private set;
		}

		VisualElement IVisualElementRenderer.Element
		{
			get
			{
				return Element;
			}
		}

		public EvasObject NativeView
		{
			get
			{
				return _view;
			}
		}

		protected bool IsDisposed => _flags.HasFlag(VisualElementRendererFlags.Disposed);

		/// <summary>
		/// Releases all resource used by the <see cref="Xamarin.Forms.Platform.Tizen.VisualElementRenderer"/> object.
		/// </summary>
		/// <remarks>Call <see cref="Dispose"/> when you are finished using the
		/// <see cref="Xamarin.Forms.Platform.Tizen.VisualElementRenderer"/>. The <see cref="Dispose"/> method
		/// leaves the <see cref="Xamarin.Forms.Platform.Tizen.VisualElementRenderer"/> in an unusable state.
		/// After calling <see cref="Dispose"/>, you must release all references to the
		/// <see cref="Xamarin.Forms.Platform.Tizen.VisualElementRenderer"/> so the garbage collector can reclaim
		/// the memory that the <see cref="Xamarin.Forms.Platform.Tizen.VisualElementRenderer"/> was occupying.</remarks>
		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		public SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
		{
			if (null == NativeView)
			{
				return new SizeRequest(new Size(0, 0));
			}
			else
			{
				int availableWidth = Forms.ConvertToScaledPixel(widthConstraint);
				int availableHeight = Forms.ConvertToScaledPixel(heightConstraint);

				if (availableWidth < 0)
					availableWidth = int.MaxValue;
				if (availableHeight < 0)
					availableHeight = int.MaxValue;

				Size measured;
				var nativeViewMeasurable = NativeView as Native.IMeasurable;
				if (nativeViewMeasurable != null)
				{
					measured = nativeViewMeasurable.Measure(availableWidth, availableHeight).ToDP();
				}
				else
				{
					measured = Measure(availableWidth, availableHeight).ToDP();
				}

				return new SizeRequest(measured, MinimumSize());
			}
		}

		/// <summary>
		/// Sets the element associated with this renderer.
		/// </summary>
		public void SetElement(TElement newElement)
		{
			if (newElement == null)
			{
				throw new ArgumentNullException("newElement");
			}

			TElement oldElement = Element;

			Element = newElement;

			if (oldElement != null)
			{
				Platform.SetRenderer(oldElement, null);
			}

			// send notification
			OnElementChanged(new ElementChangedEventArgs<TElement>(oldElement, newElement));

			// add children
			var logicalChildren = (newElement as IElementController).LogicalChildren;
			foreach (Element child in logicalChildren)
			{
				AddChild(child);
			}

			// store renderer for the new element
			Platform.SetRenderer(newElement, this);

			OnElementReady();
		}

		void IVisualElementRenderer.UpdateLayout()
		{
			UpdateLayout();
		}

		void IVisualElementRenderer.SetElement(VisualElement element)
		{
			TElement tElement = element as TElement;
			if (tElement == null)
			{
				throw new ArgumentException("Element is not of type " + typeof(TElement), "Element");
			}
			SetElement(tElement);
		}

		/// <summary>
		/// Registers the effect with the element by establishing the parent-child relations needed for rendering on the specific platform.
		/// </summary>
		/// <param name="effect">The effect to register.</param>
		void IEffectControlProvider.RegisterEffect(Effect effect)
		{
			RegisterEffect(effect);
		}

		/// <summary>
		/// Registers the effect with the element by establishing the parent-child relations needed for rendering on the specific platform.
		/// </summary>
		/// <param name="effect">The effect to register.</param>
		protected void RegisterEffect(Effect effect)
		{
			var platformEffect = effect as PlatformEffect;
			if (platformEffect != null)
			{
				OnRegisterEffect(platformEffect);
			}
		}

		protected virtual void UpdateLayout()
		{
			if (null != NativeView)
			{
				UpdateNativeGeometry();
			}
		}

		/// <summary>
		/// Disposes of underlying resources.
		/// </summary>
		/// <param name="disposing">True if the memory release was requested on demand.</param>
		protected virtual void Dispose(bool disposing)
		{
			if (IsDisposed)
			{
				return;
			}

			_flags |= VisualElementRendererFlags.Disposed;

			if (disposing)
			{
				if (Element != null)
				{
					Element.PropertyChanged -= OnElementPropertyChanged;
					Element.BatchCommitted -= OnBatchCommitted;

					Element.ChildAdded -= OnChildAdded;
					Element.ChildRemoved -= OnChildRemoved;
					Element.ChildrenReordered -= OnChildrenReordered;

					Element.FocusChangeRequested -= OnFocusChangeRequested;

					var logicalChildren = (Element as IElementController).LogicalChildren;
					foreach (var child in logicalChildren)
					{
						Platform.GetRenderer(child)?.Dispose();
					}

					if (Platform.GetRenderer(Element) == this)
					{
						Platform.SetRenderer(Element, null);
					}

					// Reset Element geometry, to re-calculate when Renderer was re-attached
					Element.Layout(new Rectangle(0, 0, -1, -1));

					Element = default(TElement);
				}

				if (NativeView != null)
				{
					NativeView.Deleted -= NativeViewDeleted;
					NativeView.Unrealize();
					SetNativeView(null);
				}
			}
		}

		/// <summary>
		/// Notification that the associated element has changed.
		/// </summary>
		/// <param name="e">Event parameters.</param>
		protected virtual void OnElementChanged(ElementChangedEventArgs<TElement> e)
		{
			if (null != e.OldElement)
			{
				e.OldElement.PropertyChanged -= OnElementPropertyChanged;
				e.OldElement.BatchCommitted -= OnBatchCommitted;

				e.OldElement.ChildAdded -= OnChildAdded;
				e.OldElement.ChildRemoved -= OnChildRemoved;
				e.OldElement.ChildrenReordered -= OnChildrenReordered;

				e.OldElement.FocusChangeRequested -= OnFocusChangeRequested;

				var controller = e.OldElement as IElementController;
				if (controller != null && controller.EffectControlProvider == this)
				{
					controller.EffectControlProvider = null;
				}
			}

			if (null != e.NewElement)
			{
				e.NewElement.PropertyChanged += OnElementPropertyChanged;
				e.NewElement.BatchCommitted += OnBatchCommitted;

				e.NewElement.ChildAdded += OnChildAdded;
				e.NewElement.ChildRemoved += OnChildRemoved;
				e.NewElement.ChildrenReordered += OnChildrenReordered;

				e.NewElement.FocusChangeRequested += OnFocusChangeRequested;

				(NativeView as IBatchable)?.BatchBegin();
				UpdateAllProperties(true);
				(NativeView as IBatchable)?.BatchCommit();

				var controller = e.NewElement as IElementController;
				if (controller != null)
				{
					controller.EffectControlProvider = this;
				}
			}

			// TODO: handle the event
		}

		/// <summary>
		/// Notification that the property of the associated element has changed.
		/// </summary>
		/// <param name="sender">Object which sent the notification.</param>
		/// <param name="e">Event parameters.</param>
		protected virtual void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			if (Element.Batched)
			{
				if (e.PropertyName == VisualElement.XProperty.PropertyName ||
					e.PropertyName == VisualElement.YProperty.PropertyName ||
					e.PropertyName == VisualElement.WidthProperty.PropertyName ||
					e.PropertyName == VisualElement.HeightProperty.PropertyName)
				{
					_flags |= VisualElementRendererFlags.NeedsLayout;
				}
				else if (e.PropertyName == VisualElement.TranslationXProperty.PropertyName ||
						e.PropertyName == VisualElement.TranslationYProperty.PropertyName ||
						e.PropertyName == VisualElement.RotationProperty.PropertyName ||
						e.PropertyName == VisualElement.RotationXProperty.PropertyName ||
						e.PropertyName == VisualElement.RotationYProperty.PropertyName ||
						e.PropertyName == VisualElement.ScaleProperty.PropertyName ||
						e.PropertyName == VisualElement.AnchorXProperty.PropertyName ||
						e.PropertyName == VisualElement.AnchorYProperty.PropertyName)
				{
					_flags |= VisualElementRendererFlags.NeedsTransformation;
				}
				else
				{
					_batchedProperties.Add(e.PropertyName);
				}
				return;
			}

			Action<bool> init;
			if (_propertyHandlersWithInit.TryGetValue(e.PropertyName, out init))
			{
				init(false);
			}
			else
			{
				Action handler;
				if (_propertyHandlers.TryGetValue(e.PropertyName, out handler))
				{
					handler();
				}
			}
		}

		/// <summary>
		/// Updates the attached event handlers, sets the native control.
		/// </summary>
		protected void SetNativeControl(EvasObject control)
		{
			if (NativeView != null)
			{
				if (_movedCallbackEnabled)
				{
					NativeView.Moved -= OnMoved;
				}
				NativeView.Deleted -= NativeViewDeleted;
			}

			Widget widget = NativeView as Widget;
			if (widget != null)
			{
				widget.Focused -= OnFocused;
				widget.Unfocused -= OnUnfocused;
			}

			SetNativeView(control);

			if (NativeView != null)
			{
				NativeView.Deleted += NativeViewDeleted;
				if (_movedCallbackEnabled)
				{
					NativeView.Moved += OnMoved;
				}
			}

			widget = NativeView as Widget;
			if (widget != null)
			{
				widget.Focused += OnFocused;
				widget.Unfocused += OnUnfocused;
			}
		}

		void UpdateNativeGeometry()
		{
			var updatedGeometry = new Rectangle(ComputeAbsolutePoint(Element), new Size(Element.Width, Element.Height)).ToPixel();

			if (NativeView.Geometry != updatedGeometry)
			{
				NativeView.Geometry = updatedGeometry;
				ApplyTransformation();
			}
		}

		void NativeViewDeleted(object sender, EventArgs e)
		{
			Dispose();
		}

		void OnBatchCommitted(object sender, EventArg<VisualElement> e)
		{
			if (_flags.HasFlag(VisualElementRendererFlags.NeedsLayout))
			{
				UpdateLayout();
				// UpdateLayout already updates transformation, clear NeedsTranformation flag then
				_flags &= ~VisualElementRendererFlags.NeedsTransformation;

				_flags ^= VisualElementRendererFlags.NeedsLayout;
			}
			if (_flags.HasFlag(VisualElementRendererFlags.NeedsTransformation))
			{
				ApplyTransformation();
				_flags ^= VisualElementRendererFlags.NeedsTransformation;
			}

			foreach (string property in _batchedProperties)
			{
				OnElementPropertyChanged(this, new PropertyChangedEventArgs(property));
			}
			_batchedProperties.Clear();
		}

		/// <summary>
		/// Registers a handler which is executed when specified property changes.
		/// </summary>
		/// <param name="property">Handled property.</param>
		/// <param name="handler">Action to be executed when property changes.</param>
		protected void RegisterPropertyHandler(BindableProperty property, Action<bool> handler)
		{
			RegisterPropertyHandler(property.PropertyName, handler);
		}

		/// <summary>
		/// Registers a handler which is executed when specified property changes.
		/// </summary>
		/// <param name="name">Name of the handled property.</param>
		/// <param name="handler">Action to be executed when property changes.</param>
		protected void RegisterPropertyHandler(string name, Action<bool> handler)
		{
			_propertyHandlersWithInit.Add(name, handler);
		}

		/// <summary>
		/// Registers a handler which is executed when specified property changes.
		/// </summary>
		/// <param name="property">Handled property.</param>
		/// <param name="handler">Action to be executed when property changes.</param>
		protected void RegisterPropertyHandler(BindableProperty property, Action handler)
		{
			RegisterPropertyHandler(property.PropertyName, handler);
		}

		/// <summary>
		/// Registers a handler which is executed when specified property changes.
		/// </summary>
		/// <param name="name">Name of the handled property.</param>
		/// <param name="handler">Action to be executed when property changes.</param>
		protected void RegisterPropertyHandler(string name, Action handler)
		{
			_propertyHandlers.Add(name, handler);
		}

		/// <summary>
		/// Updates all registered properties.
		/// </summary>
		/// <param name="initialization">If set to <c>true</c> the method is called for an uninitialized object.</param>
		protected void UpdateAllProperties(bool initialization)
		{
			foreach (var action in _propertyHandlersWithInit.Values.Distinct())
			{
				action(initialization);
			}

			foreach (var action in _propertyHandlers.Values.Distinct())
			{
				action();
			}
		}

		/// <summary>
		/// Called when Element has been set and its native counterpart
		/// is properly initialized.
		/// </summary>
		protected virtual void OnElementReady()
		{
		}

		protected void DoLayout(Native.LayoutEventArgs e)
		{
			Element.Layout(e.Geometry.ToDP());
		}

		protected virtual Size MinimumSize()
		{
			return new ESize(NativeView.MinimumWidth, NativeView.MinimumHeight).ToDP();
		}

		/// <summary>
		/// Calculates how much space this element should take, given how much room there is.
		/// </summary>
		/// <returns>a desired dimensions of the element</returns>
		protected virtual ESize Measure(int availableWidth, int availableHeight)
		{
			return new ESize(NativeView.MinimumWidth, NativeView.MinimumHeight);
		}

		protected virtual void UpdateBackgroundColor(bool initialize)
		{
			if (initialize && Element.BackgroundColor.IsDefault)
				return;

			if (NativeView is Widget)
			{
				(NativeView as Widget).BackgroundColor = Element.BackgroundColor.ToNative();
			}
			else
			{
				Log.Warn("{0} uses {1} which does not support background color", this, NativeView);
			}
		}

		protected virtual void UpdateOpacity(bool initialize)
		{
			if (initialize && Element.Opacity == 1d)
				return;

			if (NativeView is Widget)
			{
				(NativeView as Widget).Opacity = (int)(Element.Opacity * 255.0);
			}
			else
			{
				Log.Warn("{0} uses {1} which does not support opacity", this, NativeView);
			}
		}

		static double ComputeAbsoluteX(VisualElement e)
		{
			return e.X + ((e.RealParent is VisualElement) && !(e.RealParent is ListView) ? Forms.ConvertToScaledDP(Platform.GetRenderer(e.RealParent).NativeView.Geometry.X) : 0.0);
		}

		static double ComputeAbsoluteY(VisualElement e)
		{
			return e.Y + ((e.RealParent is VisualElement) && !(e.RealParent is ListView) ? Forms.ConvertToScaledDP(Platform.GetRenderer(e.RealParent).NativeView.Geometry.Y) : 0.0);
		}

		static Point ComputeAbsolutePoint(VisualElement e)
		{
			return new Point(ComputeAbsoluteX(e), ComputeAbsoluteY(e));
		}

		/// <summary>
		/// Handles focus events.
		/// </summary>
		void OnFocused(object sender, EventArgs e)
		{
			if (null != Element)
			{
				Element.SetValue(VisualElement.IsFocusedPropertyKey, true);
			}
		}

		/// <summary>
		/// Handles unfocus events.
		/// </summary>
		void OnUnfocused(object sender, EventArgs e)
		{
			if (null != Element)
			{
				Element.SetValue(VisualElement.IsFocusedPropertyKey, false);
			}
		}

		/// <summary>
		/// Sets the native control, updates the control's properties.
		/// </summary>
		void SetNativeView(EvasObject control)
		{
			_view = control;
		}

		/// <summary>
		/// Adds a new child if it's derived from the VisualElement class. Otherwise this method does nothing.
		/// </summary>
		/// <param name="child">Child to be added.</param>
		void AddChild(Element child)
		{
			VisualElement vElement = child as VisualElement;
			if (vElement != null)
			{
				var childRenderer = Platform.GetOrCreateRenderer(vElement);

				// if the native view can have children, attach the new child
				if (NativeView is Native.IContainable<EvasObject>)
				{
					(NativeView as Native.IContainable<EvasObject>).Children.Add(childRenderer.NativeView);
				}
			}
		}

		void RemoveChild(VisualElement view)
		{
			var renderer = Platform.GetRenderer(view);
			var containerObject = NativeView as Native.IContainable<EvasObject>;
			if (containerObject != null)
			{
				containerObject.Children.Remove(renderer.NativeView);
			}

			renderer.Dispose();
		}

		void OnChildAdded(object sender, ElementEventArgs e)
		{
			var view = e.Element as VisualElement;
			if (view != null)
			{
				AddChild(view);
			}

			// changing the order makes sense only in case of Layouts
			if (Element is Layout)
			{
				IElementController controller = Element as IElementController;
				if (controller.LogicalChildren[controller.LogicalChildren.Count - 1] != view)
				{
					EnsureChildOrder();
				}
			}
		}

		void OnChildRemoved(object sender, ElementEventArgs e)
		{
			var view = e.Element as VisualElement;
			if (view != null)
			{
				RemoveChild(view);
			}
		}

		void OnChildrenReordered(object sender, EventArgs e)
		{
			EnsureChildOrder();
			Layout layout = Element as Layout;
			if (layout != null)
			{
				layout.InvalidateMeasureNonVirtual(InvalidationTrigger.MeasureChanged);
				layout.ForceLayout();
			}
		}

		void OnFocusChangeRequested(object sender, VisualElement.FocusRequestArgs e)
		{
			Widget widget = NativeView as Widget;
			if (widget == null)
			{
				Log.Warn("{0} is not a widget, it cannot receive focus", NativeView);
				return;
			}

			widget.SetFocus(e.Focus);
			e.Result = true;
		}

		/// <summary>
		/// On register the effect
		/// </summary>
		/// <param name="effect">The effect to register.</param>
		void OnRegisterEffect(PlatformEffect effect)
		{
			effect.SetContainer(Element.Parent == null ? null : Platform.GetRenderer(Element.Parent)?.NativeView);
			effect.SetControl(NativeView);
		}

		void OnMoved(object sender, EventArgs e)
		{
			ApplyTransformation();
		}

		void EnsureChildOrder()
		{
			var logicalChildren = (Element as IElementController).LogicalChildren;
			for (var i = logicalChildren.Count - 1; i >= 0; --i)
			{
				var element = logicalChildren[i] as VisualElement;
				if (element != null)
				{
					Platform.GetRenderer(element).NativeView?.Lower();
				}
			}
		}

		void UpdateIsVisible()
		{
			if (null != NativeView)
			{
				if (Element.IsVisible)
				{
					NativeView.Show();
				}
				else
				{
					NativeView.Hide();
				}
			}
		}

		/// <summary>
		/// Updates the IsEnabled property.
		/// </summary>
		void UpdateIsEnabled(bool initialize)
		{
			if (initialize && Element.IsEnabled)
				return;

			var widget = NativeView as Widget;
			if (widget != null)
			{
				widget.IsEnabled = Element.IsEnabled;
			}
		}

		/// <summary>
		/// Updates the InputTransparent property.
		/// </summary>
		void UpdateInputTransparent(bool initialize)
		{
			if (initialize && Element.InputTransparent == default(bool))
				return;

			NativeView.PassEvents = Element.InputTransparent;
		}

		protected virtual void UpdateThemeStyle()
		{
		}

		void UpdateFocusAllowed(bool initialize)
		{
			if (!initialize)
			{
				var widget = NativeView as Widget;
				if (widget != null && Specific.IsFocusAllowed(Element).HasValue)
				{
					widget.AllowFocus((bool)Specific.IsFocusAllowed(Element));
				}
				else
				{
					Log.Warn("{0} uses {1} which does not support Focus management", this, NativeView);
				}
			}
		}

		void UpdateFocusDirection(bool initialize)
		{
			var direction = Specific.GetNextFocusDirection(Element);
			if (!initialize && direction != XFocusDirection.None)
			{
				var widget = NativeView as Widget;
				if (widget != null)
				{
					widget.FocusNext(ConvertToNativeFocusDirection(direction));
				}
				else
				{
					Log.Warn("{0} uses {1} which does not support Focus management", this, NativeView);
				}
			}
		}

		void UpdateToolTip(bool initialize)
		{
			var tooltip = Specific.GetToolTip(Element);
			if (tooltip != null)
			{
				NativeView.SetTooltipText(tooltip);
			}
			else if (!initialize)
			{
				NativeView.UnsetTooltip();
			}
		}

		void SetNextFocusViewInternal(string direction)
		{
			var widget = NativeView as Widget;
			if (widget != null)
			{
				EvasObject nativeControl;
				switch (direction)
				{
					case XFocusDirection.Back:
						nativeControl = Platform.GetRenderer(Specific.GetNextFocusBackView(Element))?.NativeView;
						break;
					case XFocusDirection.Forward:
						nativeControl = Platform.GetRenderer(Specific.GetNextFocusForwardView(Element))?.NativeView;
						break;
					case XFocusDirection.Up:
						nativeControl = Platform.GetRenderer(Specific.GetNextFocusUpView(Element))?.NativeView;
						break;
					case XFocusDirection.Down:
						nativeControl = Platform.GetRenderer(Specific.GetNextFocusDownView(Element))?.NativeView;
						break;
					case XFocusDirection.Right:
						nativeControl = Platform.GetRenderer(Specific.GetNextFocusRightView(Element))?.NativeView;
						break;
					case XFocusDirection.Left:
						nativeControl = Platform.GetRenderer(Specific.GetNextFocusLeftView(Element))?.NativeView;
						break;
					default:
						nativeControl = null;
						break;
				}
				if (nativeControl != null)
				{
					widget.SetNextFocusObject(nativeControl, ConvertToNativeFocusDirection(direction));
				}
			}
			else
			{
				Log.Warn("{0} uses {1} which does not support Focus management", this, NativeView);
			}
		}

		void UpdateFocusUpView(bool initialize)
		{
			if (!initialize && Specific.GetNextFocusUpView(Element) != null)
			{
				SetNextFocusViewInternal(XFocusDirection.Up);
			}
		}

		void UpdateFocusDownView(bool initialize)
		{
			if (!initialize && Specific.GetNextFocusDownView(Element) != null)
			{
				SetNextFocusViewInternal(XFocusDirection.Down);
			}
		}

		void UpdateFocusLeftView(bool initialize)
		{
			if (!initialize && Specific.GetNextFocusLeftView(Element) != null)
			{
				SetNextFocusViewInternal(XFocusDirection.Left);
			}
		}

		void UpdateFocusRightView(bool initialize)
		{
			if (!initialize && Specific.GetNextFocusRightView(Element) != null)
			{
				SetNextFocusViewInternal(XFocusDirection.Right);
			}
		}

		void UpdateFocusBackView(bool initialize)
		{
			if (!initialize && Specific.GetNextFocusBackView(Element) != null)
			{
				SetNextFocusViewInternal(XFocusDirection.Back);
			}
		}

		void UpdateFocusForwardView(bool initialize)
		{
			if (!initialize && Specific.GetNextFocusForwardView(Element) != null)
			{
				SetNextFocusViewInternal(XFocusDirection.Forward);
			}
		}

		void ApplyRotation(EvasMap map, ERect geometry, ref bool changed)
		{
			var rotationX = Element.RotationX;
			var rotationY = Element.RotationY;
			var rotationZ = Element.Rotation;
			var anchorX = Element.AnchorX;
			var anchorY = Element.AnchorY;

			// apply rotations
			if (rotationX != 0 || rotationY != 0 || rotationZ != 0)
			{
				map.Rotate3D(rotationX, rotationY, rotationZ, (int)(geometry.X + geometry.Width * anchorX),
															  (int)(geometry.Y + geometry.Height * anchorY), 0);
				changed = true;
			}
		}

		void ApplyScale(EvasMap map, ERect geometry, ref bool changed)
		{
			var scale = Element.Scale;

			// apply scale factor
			if (scale != 1.0)
			{
				map.Zoom(scale, scale,
					geometry.X + (int)(geometry.Width * Element.AnchorX),
					geometry.Y + (int)(geometry.Height * Element.AnchorY));
				changed = true;
			}
		}

		void ApplyTranslation(EvasMap map, ERect geometry, ref bool changed)
		{
			var shiftX = Forms.ConvertToScaledPixel(Element.TranslationX);
			var shiftY = Forms.ConvertToScaledPixel(Element.TranslationY);

			// apply translation, i.e. move/shift the object a little
			if (shiftX != 0 || shiftY != 0)
			{
				if (changed)
				{
					// special care is taken to apply the translation last
					Point3D p;
					for (int i = 0; i < 4; i++)
					{
						p = map.GetPointCoordinate(i);
						p.X += shiftX;
						p.Y += shiftY;
						map.SetPointCoordinate(i, p);
					}
				}
				else
				{
					// in case when we only need translation, then construct the map in a simpler way
					geometry.X += shiftX;
					geometry.Y += shiftY;
					map.PopulatePoints(geometry, 0);

					changed = true;
				}
			}
		}

		protected virtual void ApplyTransformation()
		{
			if (null == NativeView)
			{
				Log.Error("Trying to apply transformation to the non-existent native control");
				return;
			}

			// prepare the EFL effect structure
			ERect geometry = NativeView.Geometry;
			EvasMap map = new EvasMap(4);
			map.PopulatePoints(geometry, 0);

			bool changed = false;
			ApplyRotation(map, geometry, ref changed);
			ApplyScale(map, geometry, ref changed);
			ApplyTranslation(map, geometry, ref changed);

			NativeView.IsMapEnabled = changed;
			if (changed)
			{
				NativeView.EvasMap = map;
				if (!_movedCallbackEnabled)
				{
					_movedCallbackEnabled = true;
					NativeView.Moved += OnMoved;
				}
			}
			else
			{
				if (_movedCallbackEnabled)
				{
					_movedCallbackEnabled = false;
					NativeView.Moved -= OnMoved;
				}
			}
		}
		EFocusDirection ConvertToNativeFocusDirection(string direction) {
			if (direction == XFocusDirection.Back) return EFocusDirection.Previous;
			if (direction == XFocusDirection.Forward) return EFocusDirection.Next;
			if (direction == XFocusDirection.Up) return EFocusDirection.Up;
			if (direction == XFocusDirection.Down) return EFocusDirection.Down;
			if (direction == XFocusDirection.Right) return EFocusDirection.Right;
			if (direction == XFocusDirection.Left) return EFocusDirection.Left;

			return EFocusDirection.Next;
		}
	}
}