-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
MvxLayoutInflater.cs
513 lines (428 loc) · 19.1 KB
/
MvxLayoutInflater.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MS-PL license.
// See the LICENSE file in the project root for more information.
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Java.Interop;
using Java.Lang;
using Java.Lang.Reflect;
using Microsoft.Extensions.Logging;
using MvvmCross.Logging;
using MvvmCross.Platforms.Android.Binding.Binders;
using MvvmCross.Platforms.Android.Binding.BindingContext;
using Boolean = Java.Lang.Boolean;
using Exception = Java.Lang.Exception;
using Object = Java.Lang.Object;
namespace MvvmCross.Platforms.Android.Binding.Views
{
#nullable enable
/// <summary>
/// Custom LayoutInflater responsible for inflating views and hooking up bindings
/// Typically this is attached to MvxActivity and co via our MvxContextWrapper.
///
/// Potential order of view creation is the following (HC+):
/// 1. IFactory2.OnCreateView
/// 2. IFactory.OnCreateView
/// 3. PrivateFactory.OnCreateView
/// 4. OnCreateView(parent, name, attrs)
/// 5. OnCreateView(name, attrs)
/// 6. CreateView (sadly final)
///
/// We intercept these calls and wrap any IFactory/IFactory2 with our own factory
/// that binds when the view is returned.
///
/// Heavily based on Calligraphy's CalligraphyLayoutInflater
/// See: https://github.com/chrisjenx/Calligraphy/blob/master/calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyLayoutInflater.java" />
/// </summary>
[Register("mvvmcross.platforms.android.binding.views.MvxLayoutInflater")]
public class MvxLayoutInflater : LayoutInflater
{
public class MvxBindingVisitor
{
private static readonly Boolean TheTruth = Boolean.True!;
public IMvxLayoutInflaterHolderFactory? Factory { get; set; }
public View? OnViewCreated(View? view, Context? context, IAttributeSet? attrs)
{
if (Factory != null && view != null && view.GetTag(Resource.Id.MvvmCrossTagId) != TheTruth)
{
// Bind here.
view = Factory.BindCreatedView(view, context, attrs);
view.SetTag(Resource.Id.MvvmCrossTagId, TheTruth);
}
return view;
}
}
public static bool Debug { get; set; }
private const string Tag = "MvxLayoutInflater";
private static readonly string[] ClassPrefixList = {
"android.widget.",
"android.webkit.",
"android.app."
};
private readonly MvxBindingVisitor _bindingVisitor;
private IMvxAndroidViewFactory? _androidViewFactory;
private IMvxLayoutInflaterHolderFactoryFactory? _layoutInflaterHolderFactoryFactory;
private Field? _constructorArgs;
private bool _setPrivateFactory;
public MvxLayoutInflater(Context context)
: base(context)
{
_bindingVisitor = new MvxBindingVisitor();
SetupLayoutFactories(false);
}
public MvxLayoutInflater(LayoutInflater original, Context? newContext, MvxBindingVisitor? bindingVisitor, bool cloned)
: base(original, newContext)
{
_bindingVisitor = bindingVisitor ?? new MvxBindingVisitor();
SetupLayoutFactories(cloned);
}
[Preserve(Conditional = true)]
public MvxLayoutInflater(IntPtr handle, JniHandleOwnership transfer)
: base(handle, transfer)
{
_bindingVisitor = new MvxBindingVisitor();
SetupLayoutFactories(false);
}
public override LayoutInflater CloneInContext(Context? newContext)
{
return new MvxLayoutInflater(this, newContext, _bindingVisitor, true);
}
// We can't call this. See: https://bugzilla.xamarin.com/show_bug.cgi?id=30843
//public override View Inflate(XmlReader parser, ViewGroup root, bool attachToRoot)
//{
// SetPrivateFactoryInternal();
// return base.Inflate(parser, root, attachToRoot);
//}
// Calligraphy doesn't override this one...
public override View? Inflate(int resource, ViewGroup? root, bool attachToRoot)
{
// Make sure our private factory is set since LayoutInflater > Honeycomb
// uses a private factory.
SetPrivateFactoryInternal();
// Save the old factory in case we are recursing because of an MvxAdapter etc.
IMvxLayoutInflaterHolderFactory? originalFactory = _bindingVisitor.Factory;
try
{
IMvxLayoutInflaterHolderFactory? factory = null;
// Get the current binding context
var currentBindingContext = MvxAndroidBindingContextHelpers.Current();
if (currentBindingContext != null)
{
factory = FactoryFactory?.Create(currentBindingContext.DataContext);
// Set the current factory used to generate bindings
if (factory != null)
_bindingVisitor.Factory = factory;
}
// Inflate the resource
var view = base.Inflate(resource, root, attachToRoot);
// Register bindings with clear key
if (currentBindingContext != null)
{
if (factory != null)
currentBindingContext.RegisterBindingsWithClearKey(view, factory.CreatedBindings);
}
return view;
}
finally
{
_bindingVisitor.Factory = originalFactory;
}
}
protected override View? OnCreateView(View? parent, string? name, IAttributeSet? attrs)
{
if (Debug)
MvxLogHost.GetLog<MvxLayoutInflater>()?.Log(LogLevel.Trace, "{Tag} - ... OnCreateView 3 ... {Name}", Tag, name);
return _bindingVisitor.OnViewCreated(
base.OnCreateView(parent, name, attrs),
Context,
attrs);
}
protected override View? OnCreateView(string? name, IAttributeSet? attrs)
{
if (Debug)
MvxLogHost.GetLog<MvxLayoutInflater>()?.Log(LogLevel.Trace, "{Tag} - ... OnCreateView 2 ... {Name}", Tag, name);
View? view = null;
if (name != null && Context != null && attrs != null)
view = AndroidViewFactory?.CreateView(null, name, Context, attrs);
view ??= PhoneLayoutInflaterOnCreateView(name, attrs) ?? base.OnCreateView(name, attrs);
return _bindingVisitor.OnViewCreated(view, Context, attrs);
}
public override View? OnCreateView(Context viewContext, View? parent, string name, IAttributeSet? attrs)
{
if (Debug)
MvxLogHost.GetLog<MvxLayoutInflater>()?.Log(LogLevel.Trace, "{Tag} - ... OnCreateView 4 ... {Name}", Tag, name);
return _bindingVisitor.OnViewCreated(
base.OnCreateView(viewContext, parent, name, attrs),
viewContext,
attrs);
}
// Mimic PhoneLayoutInflater's OnCreateView.
private View? PhoneLayoutInflaterOnCreateView(string? name, IAttributeSet? attrs)
{
if (Debug)
MvxLogHost.GetLog<MvxLayoutInflater>()?.Log(LogLevel.Trace, "{Tag} - ... PhoneLayoutInflaterOnCreateView ... {Name}", Tag, name);
foreach (var prefix in ClassPrefixList)
{
try
{
return CreateView(name, prefix, attrs);
}
catch (ClassNotFoundException)
{
// ignore
}
}
return null;
}
// Note: setFactory/setFactory2 are implemented with export
// because there's a bug in the generator that doesn't
// mark the Factory/Factory2 setters as virtual.
// See: https://bugzilla.xamarin.com/show_bug.cgi?id=30764
[Export]
public void setFactory(IFactory factory)
{
// Wrap the incoming factory if we need to.
if (!(factory is MvxLayoutInflaterCompat.FactoryWrapper))
{
Factory = new MvxLayoutInflaterCompat.FactoryWrapper(new DelegateFactory1(factory, _bindingVisitor));
return;
}
Factory = factory;
}
[Export]
public void setFactory2(IFactory2 factory2)
{
// Wrap the incoming factory if we need to.
if (!(factory2 is MvxLayoutInflaterCompat.FactoryWrapper2))
{
Factory2 = new MvxLayoutInflaterCompat.FactoryWrapper2(new DelegateFactory2(factory2, _bindingVisitor));
return;
}
Factory2 = factory2;
}
private void SetupLayoutFactories(bool cloned)
{
if (cloned)
return;
// Check for FactoryWrapper2 may be too loose
if (Factory2 != null && !(Factory2 is MvxLayoutInflaterCompat.FactoryWrapper2))
{
MvxLayoutInflaterCompat.SetFactory(this, new DelegateFactory2(Factory2, _bindingVisitor));
}
}
private void SetPrivateFactoryInternal()
{
if (_setPrivateFactory)
return;
if (!(Context is IFactory2))
{
_setPrivateFactory = true;
return;
}
try
{
Class layoutInflaterClass = Class.FromType(typeof(LayoutInflater));
Method setPrivateFactoryMethod = layoutInflaterClass.GetMethod("setPrivateFactory", Class.FromType(typeof(IFactory2)));
setPrivateFactoryMethod.Accessible = true;
setPrivateFactoryMethod.Invoke(this,
new PrivateFactoryWrapper2((IFactory2)Context, this, _bindingVisitor));
}
catch (Exception ex)
{
MvxLogHost.GetLog<MvxLayoutInflater>()?.Log(LogLevel.Warning, ex, "Cannot invoke LayoutInflater.setPrivateFactory");
}
_setPrivateFactory = true;
}
internal View? CreateCustomViewInternal(View? parent, View? view, string name, Context viewContext,
IAttributeSet attrs)
{
if (Debug)
MvxLogHost.GetLog<MvxLayoutInflater>()?.Log(LogLevel.Trace, "{Tag} - ... CreateCustomViewInternal ... {Name}", Tag, name);
if (view == null &&
!string.IsNullOrWhiteSpace(name) &&
name.IndexOf('.', StringComparison.InvariantCulture) > -1)
{
// Attempt to inflate with MvvmCross unless we're trying to inflate an internal views
// since we don't resolve those.
if (!name.StartsWith("com.android.internal.", StringComparison.InvariantCulture))
{
view = AndroidViewFactory?.CreateView(parent, name, viewContext, attrs);
}
if (view == null)
{
var (constructorArgsArr, lastContext) = GetConstructorArgs(viewContext);
try
{
view = CreateViewCompat(viewContext, name, attrs);
}
catch (ClassNotFoundException)
{
// ignore
}
finally
{
RestoreConstructorArgs(constructorArgsArr, lastContext);
}
}
}
return view;
}
private (Object[]? constructorArgs, Object? lastContext) GetConstructorArgs(Context viewContext)
{
if (Build.VERSION.SdkInt > BuildVersionCodes.P)
{
return (null, null);
}
if (_constructorArgs == null)
{
Class layoutInflaterClass = Class.FromType(typeof(LayoutInflater));
_constructorArgs = layoutInflaterClass.GetDeclaredField("mConstructorArgs");
_constructorArgs.Accessible = true;
}
var constructorArgsArr = (Object[]?)_constructorArgs!.Get(this);
var lastContext = constructorArgsArr?[0];
// The LayoutInflater actually finds out the correct context to use. We just need to set
// it on the mConstructor for the internal method.
// Set the constructor args up for the createView, not sure why we can't pass these in.
if (constructorArgsArr != null)
{
constructorArgsArr[0] = viewContext;
_constructorArgs.Set(this, constructorArgsArr);
}
return (constructorArgsArr, lastContext);
}
private void RestoreConstructorArgs(Object[]? constructorArgsArr, Object? lastContext)
{
if (Build.VERSION.SdkInt > BuildVersionCodes.P || constructorArgsArr == null || lastContext == null)
return;
constructorArgsArr[0] = lastContext;
_constructorArgs?.Set(this, constructorArgsArr);
}
private View? CreateViewCompat(Context viewContext, string name, IAttributeSet attrs) =>
Build.VERSION.SdkInt > BuildVersionCodes.P ?
CreateView(viewContext, name, null, attrs) :
CreateView(name, null, attrs);
protected IMvxAndroidViewFactory? AndroidViewFactory
{
get
{
if (_androidViewFactory != null)
return _androidViewFactory;
if (Mvx.IoCProvider == null)
{
// if IoCProvider is null, Log instance will probably be null too
MvxLogHost.GetLog<MvxLayoutInflater>()?.Log(LogLevel.Trace, "{Tag} - ... AndroidViewFactory IoCProvider is null!", Tag);
return null;
}
if (Mvx.IoCProvider?.TryResolve(out IMvxAndroidViewFactory viewFactory) == true)
{
_androidViewFactory = viewFactory;
}
return _androidViewFactory;
}
}
protected IMvxLayoutInflaterHolderFactoryFactory? FactoryFactory
{
get
{
if (_layoutInflaterHolderFactoryFactory != null)
return _layoutInflaterHolderFactoryFactory;
if (Mvx.IoCProvider == null)
{
// if IoCProvider is null, Log instance will probably be null too
MvxLogHost.GetLog<MvxLayoutInflater>()?.Log(LogLevel.Error, "{Tag} - ... FactoryFactory IoCProvider is null!", Tag);
return null;
}
if (Mvx.IoCProvider?.TryResolve(out IMvxLayoutInflaterHolderFactoryFactory factoryFactory) == true)
{
_layoutInflaterHolderFactoryFactory = factoryFactory;
}
return _layoutInflaterHolderFactoryFactory;
}
}
private sealed class DelegateFactory2 : IMvxLayoutInflaterFactory
{
private const string DelegateFactory2Tag = "DelegateFactory2";
private readonly IFactory2 _factory;
private readonly MvxBindingVisitor _factoryPlaceholder;
public DelegateFactory2(IFactory2 factoryToWrap, MvxBindingVisitor binder)
{
_factory = factoryToWrap;
_factoryPlaceholder = binder;
}
public View? OnCreateView(View? parent, string name, Context context, IAttributeSet attrs)
{
if (Debug)
MvxLogHost.GetLog<MvxLayoutInflater>()?.Log(LogLevel.Trace, "{Tag} - ... OnCreateView ... {Name}", DelegateFactory2Tag, name);
return _factoryPlaceholder.OnViewCreated(
_factory.OnCreateView(parent, name, context, attrs),
context, attrs);
}
}
private sealed class DelegateFactory1 : IMvxLayoutInflaterFactory
{
private const string DelegateFactory1Tag = "DelegateFactory1";
private readonly IFactory _factory;
private readonly MvxBindingVisitor _factoryPlaceholder;
public DelegateFactory1(IFactory factoryToWrap, MvxBindingVisitor bindingVisitor)
{
_factory = factoryToWrap;
_factoryPlaceholder = bindingVisitor;
}
public View? OnCreateView(View? parent, string name, Context context, IAttributeSet attrs)
{
if (Debug)
MvxLogHost.GetLog<MvxLayoutInflater>()?.Log(LogLevel.Trace, "{Tag} - ... OnCreateView ... {Name}", DelegateFactory1Tag, name);
return _factoryPlaceholder.OnViewCreated(
_factory.OnCreateView(name, context, attrs),
context, attrs);
}
}
private sealed class PrivateFactoryWrapper2 : Object, IFactory2
{
private const string PrivateFactoryWrapper2Tag = "PrivateFactoryWrapper2";
private readonly IFactory2 _factory2;
private readonly MvxBindingVisitor _bindingVisitor;
private readonly MvxLayoutInflater _inflater;
internal PrivateFactoryWrapper2(IFactory2 factory2, MvxLayoutInflater inflater,
MvxBindingVisitor bindingVisitor)
{
_factory2 = factory2;
_inflater = inflater;
_bindingVisitor = bindingVisitor;
}
[Preserve(Conditional = true)]
#pragma warning disable 8618
public PrivateFactoryWrapper2(IntPtr handle, JniHandleOwnership transfer)
#pragma warning restore 8618
: base(handle, transfer)
{
}
public View? OnCreateView(string name, Context context, IAttributeSet attrs)
{
if (Debug)
MvxLogHost.GetLog<MvxLayoutInflater>()?.Log(LogLevel.Trace, "{Tag} - ... OnCreateView 2 ... {Name}", PrivateFactoryWrapper2Tag, name);
return _bindingVisitor.OnViewCreated(
// The activity's OnCreateView
_factory2.OnCreateView(name, context, attrs),
context, attrs);
}
public View? OnCreateView(View? parent, string name, Context context, IAttributeSet attrs)
{
if (Debug)
MvxLogHost.GetLog<MvxLayoutInflater>()?.Log(LogLevel.Trace, "{Tag} - ... OnCreateView 3 ... {Name}", PrivateFactoryWrapper2Tag, name);
return _bindingVisitor.OnViewCreated(
_inflater.CreateCustomViewInternal(
parent,
// The activity's OnCreateView
_factory2.OnCreateView(parent, name, context, attrs),
name, context, attrs),
context, attrs);
}
}
}
#nullable restore
}