This repository has been archived by the owner on May 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
VisualElementRenderer.cs
524 lines (416 loc) · 14.4 KB
/
VisualElementRenderer.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
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Android.Content;
using Android.Content.Res;
using Android.Graphics;
using Android.Runtime;
using Android.Views;
using AndroidX.Core.View;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Platform.Android.FastRenderers;
using AView = Android.Views.View;
namespace Xamarin.Forms.Platform.Android
{
public abstract class VisualElementRenderer<TElement> : FormsViewGroup, IVisualElementRenderer, IDisposedState,
IEffectControlProvider where TElement : VisualElement
{
readonly List<EventHandler<VisualElementChangedEventArgs>> _elementChangedHandlers = new List<EventHandler<VisualElementChangedEventArgs>>();
VisualElementRendererFlags _flags = VisualElementRendererFlags.AutoPackage | VisualElementRendererFlags.AutoTrack;
string _defaultContentDescription;
bool? _defaultFocusable;
ImportantForAccessibility? _defaultImportantForAccessibility;
string _defaultHint;
bool _cascadeInputTransparent = true;
bool _defaultAutomationSet;
VisualElementPackager _packager;
PropertyChangedEventHandler _propertyChangeHandler;
GestureManager _gestureManager;
protected VisualElementRenderer(Context context) : base(context)
{
_gestureManager = new GestureManager(this);
}
protected VisualElementRenderer(IntPtr handle, JniHandleOwnership transfer)
: base(handle, transfer)
{
}
public override bool OnTouchEvent(MotionEvent e)
{
return _gestureManager.OnTouchEvent(e) || base.OnTouchEvent(e);
}
public override bool OnInterceptTouchEvent(MotionEvent ev)
{
if (!Enabled)
{
// If Enabled is false, prevent all the events from being dispatched to child Views
// and prevent them from being processed by this View as well
return true; // IOW, intercepted
}
return base.OnInterceptTouchEvent(ev);
}
public override bool DispatchTouchEvent(MotionEvent e)
{
if (Element == null || (InputTransparent && _cascadeInputTransparent))
{
// If the Element is InputTransparent, this ViewGroup will be marked InputTransparent
// If we're InputTransparent and our transparency should be applied to our child controls,
// we return false on all touch events without even bothering to send them to the child Views
return false; // IOW, not handled
}
return base.DispatchTouchEvent(e);
}
[Obsolete("This constructor is obsolete as of version 2.5. Please use VisualElementRenderer(Context) instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
protected VisualElementRenderer() : this(Forms.Context)
{
}
public TElement Element { get; private set; }
protected bool AutoPackage
{
get { return (_flags & VisualElementRendererFlags.AutoPackage) != 0; }
set
{
if (value)
_flags |= VisualElementRendererFlags.AutoPackage;
else
_flags &= ~VisualElementRendererFlags.AutoPackage;
}
}
protected bool AutoTrack
{
get { return (_flags & VisualElementRendererFlags.AutoTrack) != 0; }
set
{
if (value)
_flags |= VisualElementRendererFlags.AutoTrack;
else
_flags &= ~VisualElementRendererFlags.AutoTrack;
}
}
View View => Element as View;
void IEffectControlProvider.RegisterEffect(Effect effect)
{
var platformEffect = effect as PlatformEffect;
if (platformEffect != null)
OnRegisterEffect(platformEffect);
}
VisualElement IVisualElementRenderer.Element => Element;
event EventHandler<VisualElementChangedEventArgs> IVisualElementRenderer.ElementChanged
{
add { _elementChangedHandlers.Add(value); }
remove { _elementChangedHandlers.Remove(value); }
}
public virtual SizeRequest GetDesiredSize(int widthConstraint, int heightConstraint)
{
Measure(widthConstraint, heightConstraint);
return new SizeRequest(new Size(MeasuredWidth, MeasuredHeight), MinimumSize());
}
void IVisualElementRenderer.SetElement(VisualElement element)
{
if (!(element is TElement))
throw new ArgumentException("element is not of type " + typeof(TElement), nameof(element));
SetElement((TElement)element);
}
public VisualElementTracker Tracker { get; private set; }
public void UpdateLayout()
{
Performance.Start(out string reference);
Tracker?.UpdateLayout();
Performance.Stop(reference);
}
protected int TabIndex { get; set; } = 0;
protected bool TabStop { get; set; } = true;
protected void UpdateTabStop()
{
TabStop = Element.IsTabStop;
UpdateParentPageTraversalOrder();
}
protected void UpdateTabIndex()
{
TabIndex = Element.TabIndex;
UpdateParentPageTraversalOrder();
}
bool CheckCustomNextFocus(AView focused, FocusSearchDirection direction)
{
return direction == FocusSearchDirection.Forward && focused.NextFocusForwardId != NoId ||
direction == FocusSearchDirection.Down && focused.NextFocusDownId != NoId ||
direction == FocusSearchDirection.Left && focused.NextFocusLeftId != NoId ||
direction == FocusSearchDirection.Right && focused.NextFocusRightId != NoId ||
direction == FocusSearchDirection.Up && focused.NextFocusUpId != NoId;
}
public override AView FocusSearch(AView focused, [GeneratedEnum] FocusSearchDirection direction)
{
if (CheckCustomNextFocus(focused, direction))
return base.FocusSearch(focused, direction);
var element = Element as ITabStopElement;
int maxAttempts = 0;
var tabIndexes = element?.GetTabIndexesOnParentPage(out maxAttempts);
if (tabIndexes == null)
return base.FocusSearch(focused, direction);
// use OS default--there's no need for us to keep going if there's one or fewer tab indexes!
if (tabIndexes.Count <= 1)
return base.FocusSearch(focused, direction);
int tabIndex = element.TabIndex;
AView control = null;
int attempt = 0;
bool forwardDirection = !(
(direction & FocusSearchDirection.Backward) != 0 ||
(direction & FocusSearchDirection.Left) != 0 ||
(direction & FocusSearchDirection.Up) != 0);
do
{
element = element.FindNextElement(forwardDirection, tabIndexes, ref tabIndex);
var renderer = (element as VisualElement)?.GetRenderer();
control = (renderer as ITabStop)?.TabStop;
} while (!(control?.Focusable == true || ++attempt >= maxAttempts));
// when the user focuses on picker show a popup dialog
if (control is IPopupTrigger popupElement)
popupElement.ShowPopupOnFocus = true;
return control?.Focusable == true ? control : null;
}
public ViewGroup ViewGroup => this;
AView IVisualElementRenderer.View => this;
public event EventHandler<ElementChangedEventArgs<TElement>> ElementChanged;
public event EventHandler<PropertyChangedEventArgs> ElementPropertyChanged;
public void SetElement(TElement element)
{
TElement oldElement = Element;
Element = element ?? throw new ArgumentNullException(nameof(element));
Performance.Start(out string reference);
if (oldElement != null)
{
oldElement.PropertyChanged -= _propertyChangeHandler;
}
Color currentColor = oldElement?.BackgroundColor ?? Color.Default;
if (element.BackgroundColor != currentColor)
UpdateBackgroundColor();
if (element.Background != null)
UpdateBackground();
if (_propertyChangeHandler == null)
_propertyChangeHandler = OnElementPropertyChanged;
element.PropertyChanged += _propertyChangeHandler;
if (oldElement == null)
{
SoundEffectsEnabled = false;
}
OnElementChanged(new ElementChangedEventArgs<TElement>(oldElement, element));
if (AutoPackage && _packager == null)
SetPackager(new VisualElementPackager(this));
if (AutoTrack && Tracker == null)
SetTracker(new VisualElementTracker(this));
if (oldElement != null)
Tracker?.UpdateLayout();
if (element != null)
SendVisualElementInitialized(element, this);
EffectUtilities.RegisterEffectControlProvider(this, oldElement, element);
if (!string.IsNullOrEmpty(element.AutomationId))
SetAutomationId(element.AutomationId);
SetContentDescription();
SetFocusable();
UpdateInputTransparent();
UpdateInputTransparentInherited();
UpdateTabStop();
UpdateTabIndex();
Performance.Stop(reference);
}
/// <summary>
/// Determines whether the native control is disposed of when this renderer is disposed
/// Can be overridden in deriving classes
/// </summary>
protected virtual bool ManageNativeControlLifetime => true;
bool CheckFlagsForDisposed() => (_flags & VisualElementRendererFlags.Disposed) != 0;
bool IDisposedState.IsDisposed => CheckFlagsForDisposed();
protected override void Dispose(bool disposing)
{
if (CheckFlagsForDisposed())
return;
_flags |= VisualElementRendererFlags.Disposed;
if (disposing)
{
SetOnClickListener(null);
SetOnTouchListener(null);
EffectUtilities.UnregisterEffectControlProvider(this, Element);
if (Element != null)
{
Element.PropertyChanged -= _propertyChangeHandler;
}
if (Tracker != null)
{
Tracker.Dispose();
Tracker = null;
}
if (_packager != null)
{
_packager.Dispose();
_packager = null;
}
if (_gestureManager != null)
{
_gestureManager.Dispose();
_gestureManager = null;
}
if (ManageNativeControlLifetime)
{
while (ChildCount > 0)
{
AView child = GetChildAt(0);
child.RemoveFromParent();
child.Dispose();
}
}
if (Element != null)
{
if (Platform.GetRenderer(Element) == this)
Platform.SetRenderer(Element, null);
Element = null;
}
}
base.Dispose(disposing);
}
protected override void OnConfigurationChanged(Configuration newConfig)
{
base.OnConfigurationChanged(newConfig);
Invalidate();
}
protected virtual Size MinimumSize()
{
return new Size();
}
protected virtual void OnElementChanged(ElementChangedEventArgs<TElement> e)
{
var args = new VisualElementChangedEventArgs(e.OldElement, e.NewElement);
// The list of event handlers can be changed inside the handlers. (ex.: are used CompressedLayout)
// To avoid an exception, a copy of the handlers is called.
var handlers = _elementChangedHandlers.ToArray();
foreach (var handler in handlers)
handler(this, args);
ElementChanged?.Invoke(this, e);
ElevationHelper.SetElevation(this, e.NewElement);
}
protected virtual void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
UpdateBackgroundColor();
else if (e.PropertyName == VisualElement.BackgroundProperty.PropertyName)
UpdateBackground();
else if (e.PropertyName == AutomationProperties.HelpTextProperty.PropertyName)
SetContentDescription();
else if (e.PropertyName == AutomationProperties.NameProperty.PropertyName)
SetContentDescription();
else if (e.PropertyName == AutomationProperties.IsInAccessibleTreeProperty.PropertyName)
SetFocusable();
else if (e.PropertyName == VisualElement.InputTransparentProperty.PropertyName)
UpdateInputTransparent();
else if (e.PropertyName == Xamarin.Forms.Layout.CascadeInputTransparentProperty.PropertyName)
UpdateInputTransparentInherited();
else if (e.PropertyName == VisualElement.IsTabStopProperty.PropertyName)
UpdateTabStop();
else if (e.PropertyName == VisualElement.TabIndexProperty.PropertyName)
UpdateTabIndex();
else if (e.PropertyName == nameof(Element.Parent))
UpdateParentPageTraversalOrder();
ElementPropertyChanged?.Invoke(this, e);
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
if (Element == null)
return;
UpdateLayout(((IElementController)Element).LogicalChildren);
}
public override void Draw(Canvas canvas)
{
canvas.ClipShape(Context, Element);
base.Draw(canvas);
}
static void UpdateLayout(IEnumerable<Element> children)
{
foreach (Element element in children)
{
var visualElement = element as VisualElement;
if (visualElement == null)
continue;
IVisualElementRenderer renderer = Platform.GetRenderer(visualElement);
if (renderer == null && CompressedLayout.GetIsHeadless(visualElement))
UpdateLayout(visualElement.LogicalChildren);
renderer?.UpdateLayout();
}
}
void UpdateParentPageTraversalOrder()
{
IViewParent parentRenderer = Parent;
while (parentRenderer != null && !(parentRenderer is IOrderedTraversalController))
parentRenderer = parentRenderer.Parent;
if (parentRenderer is IOrderedTraversalController controller)
controller.UpdateTraversalOrder();
}
protected virtual void OnRegisterEffect(PlatformEffect effect)
{
effect.SetContainer(this);
}
void SetupAutomationDefaults()
{
if (!_defaultAutomationSet)
{
_defaultAutomationSet = true;
AutomationPropertiesProvider.SetupDefaults(this, ref _defaultContentDescription, ref _defaultHint);
}
}
protected virtual void SetAutomationId(string id)
{
SetupAutomationDefaults();
AutomationPropertiesProvider.SetAutomationId(this, Element, id);
}
protected virtual void SetContentDescription()
{
SetupAutomationDefaults();
AutomationPropertiesProvider.SetContentDescription(this, Element, _defaultContentDescription, _defaultHint);
}
protected virtual void SetFocusable()
=> AutomationPropertiesProvider.SetFocusable(this, Element, ref _defaultFocusable, ref _defaultImportantForAccessibility);
void UpdateInputTransparent()
{
InputTransparent = Element.InputTransparent;
}
void UpdateInputTransparentInherited()
{
var layout = Element as Layout;
if (layout == null)
{
return;
}
_cascadeInputTransparent = layout.CascadeInputTransparent;
}
protected void SetPackager(VisualElementPackager packager)
{
_packager = packager;
packager.Load();
}
protected void SetTracker(VisualElementTracker tracker)
{
Tracker = tracker;
}
protected virtual void UpdateBackgroundColor()
{
SetBackgroundColor(Element.BackgroundColor.ToAndroid());
}
protected virtual void UpdateBackground()
{
Brush background = Element.Background;
this.UpdateBackground(background);
}
internal virtual void SendVisualElementInitialized(VisualElement element, AView nativeView)
{
element.SendViewInitialized(nativeView);
}
void IVisualElementRenderer.SetLabelFor(int? id)
=> ViewCompat.SetLabelFor(this, id ?? ViewCompat.GetLabelFor(this));
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
if (Element is Layout layout)
{
layout.ResolveLayoutChanges();
}
base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}