/
DependencyObjectGenerator.cs
871 lines (721 loc) · 28.8 KB
/
DependencyObjectGenerator.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
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
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Uno.Extensions;
using Uno.Roslyn;
using Uno.UI.SourceGenerators.Helpers;
using Uno.UI.SourceGenerators.XamlGenerator;
#if NETFRAMEWORK
using Uno.SourceGeneration;
#endif
namespace Uno.UI.SourceGenerators.DependencyObject
{
[Generator]
public class DependencyObjectGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
// Debugger.Launch();
// No initialization required for this one
DependenciesInitializer.Init();
}
public void Execute(GeneratorExecutionContext context)
{
if (PlatformHelper.IsValidPlatform(context))
{
var visitor = new SerializationMethodsGenerator(context);
visitor.Visit(context.Compilation.SourceModule);
}
}
private class SerializationMethodsGenerator : SymbolVisitor
{
private readonly GeneratorExecutionContext _context;
private readonly INamedTypeSymbol? _dependencyObjectSymbol;
private readonly INamedTypeSymbol? _unoViewgroupSymbol;
private readonly INamedTypeSymbol? _iosViewSymbol;
private readonly INamedTypeSymbol? _macosViewSymbol;
private readonly INamedTypeSymbol? _androidViewSymbol;
private readonly INamedTypeSymbol? _javaObjectSymbol;
private readonly INamedTypeSymbol? _androidActivitySymbol;
private readonly INamedTypeSymbol? _androidFragmentSymbol;
private readonly INamedTypeSymbol? _bindableAttributeSymbol;
private readonly INamedTypeSymbol? _iFrameworkElementSymbol;
public SerializationMethodsGenerator(GeneratorExecutionContext context)
{
_context = context;
var comp = context.Compilation;
_dependencyObjectSymbol = comp.GetTypeByMetadataName(XamlConstants.Types.DependencyObject);
_unoViewgroupSymbol = comp.GetTypeByMetadataName("Uno.UI.UnoViewGroup");
_iosViewSymbol = comp.GetTypeByMetadataName("UIKit.UIView");
_macosViewSymbol = comp.GetTypeByMetadataName("AppKit.NSView");
_androidViewSymbol = comp.GetTypeByMetadataName("Android.Views.View");
_javaObjectSymbol = comp.GetTypeByMetadataName("Java.Lang.Object");
_androidActivitySymbol = comp.GetTypeByMetadataName("Android.App.Activity");
_androidFragmentSymbol = comp.GetTypeByMetadataName("AndroidX.Fragment.App.Fragment");
_bindableAttributeSymbol = comp.GetTypeByMetadataName("Windows.UI.Xaml.Data.BindableAttribute");
_iFrameworkElementSymbol = comp.GetTypeByMetadataName(XamlConstants.Types.IFrameworkElement);
}
public override void VisitNamedType(INamedTypeSymbol type)
{
foreach (var t in type.GetTypeMembers())
{
VisitNamedType(t);
}
ProcessType(type);
}
public override void VisitModule(IModuleSymbol symbol)
{
VisitNamespace(symbol.GlobalNamespace);
}
public override void VisitNamespace(INamespaceSymbol symbol)
{
foreach (var n in symbol.GetNamespaceMembers())
{
VisitNamespace(n);
}
foreach (var t in symbol.GetTypeMembers())
{
VisitNamedType(t);
}
}
private void ProcessType(INamedTypeSymbol typeSymbol)
{
if (typeSymbol.TypeKind != TypeKind.Class)
{
return;
}
var isDependencyObject = typeSymbol.Interfaces.Any(t => SymbolEqualityComparer.Default.Equals(t, _dependencyObjectSymbol))
&& (typeSymbol.BaseType?.GetAllInterfaces().None(t => SymbolEqualityComparer.Default.Equals(t, _dependencyObjectSymbol)) ?? true);
if (isDependencyObject)
{
if (_context.GetMSBuildPropertyValue("_IsUnoUISolution") != "true")
{
if (typeSymbol.Is(_iosViewSymbol))
{
throw new InvalidOperationException("A 'UIKit.UIView' shouldn't implement 'DependencyObject'. Inherit 'FrameworkElement' instead.");
}
else if (typeSymbol.Is(_androidViewSymbol))
{
throw new InvalidOperationException("An 'Android.Views.View' shouldn't implement 'DependencyObject'. Inherit 'FrameworkElement' instead.");
}
else if (typeSymbol.Is(_macosViewSymbol))
{
throw new InvalidOperationException("An 'AppKit.NSView' shouldn't implement 'DependencyObject'. Inherit 'FrameworkElement' instead.");
}
}
var builder = new IndentedStringBuilder();
builder.AppendLineInvariant("// <auto-generated>");
builder.AppendLineInvariant("// ******************************************************************");
builder.AppendLineInvariant("// This file has been generated by Uno.UI (DependencyObjectGenerator)");
builder.AppendLineInvariant("// ******************************************************************");
builder.AppendLineInvariant("// </auto-generated>");
builder.AppendLine();
builder.AppendLineInvariant("#pragma warning disable 1591 // Ignore missing XML comment warnings");
builder.AppendLineInvariant($"using System;");
builder.AppendLineInvariant($"using System.Linq;");
builder.AppendLineInvariant($"using System.Collections.Generic;");
builder.AppendLineInvariant($"using System.Collections;");
builder.AppendLineInvariant($"using System.Diagnostics.CodeAnalysis;");
builder.AppendLineInvariant($"using Uno.Disposables;");
builder.AppendLineInvariant($"using System.Runtime.CompilerServices;");
builder.AppendLineInvariant($"using Uno.Extensions;");
builder.AppendLineInvariant($"using Uno.Logging;");
builder.AppendLineInvariant($"using Uno.UI;");
builder.AppendLineInvariant($"using Uno.UI.DataBinding;");
builder.AppendLineInvariant($"using Windows.UI.Xaml;");
builder.AppendLineInvariant($"using Windows.UI.Xaml.Data;");
builder.AppendLineInvariant($"using Uno.Diagnostics.Eventing;");
using (builder.BlockInvariant($"namespace {typeSymbol.ContainingNamespace}"))
{
using (GenerateNestingContainers(builder, typeSymbol))
{
if (_bindableAttributeSymbol != null && typeSymbol.FindAttribute(_bindableAttributeSymbol) == null)
{
builder.AppendLineInvariant(@"[global::Windows.UI.Xaml.Data.Bindable]");
}
using (builder.BlockInvariant($"partial class {typeSymbol.Name} : IDependencyObjectStoreProvider, IWeakReferenceProvider"))
{
GenerateDependencyObjectImplementation(builder);
GenerateIBinderImplementation(typeSymbol, builder);
}
}
}
_context.AddSource(HashBuilder.BuildIDFromSymbol(typeSymbol), builder.ToString());
}
}
private IDisposable GenerateNestingContainers(IndentedStringBuilder builder, INamedTypeSymbol? typeSymbol)
{
var disposables = new List<IDisposable>();
while (typeSymbol?.ContainingType != null)
{
disposables.Add(builder.BlockInvariant($"partial class {typeSymbol?.ContainingType.Name}"));
typeSymbol = typeSymbol?.ContainingType;
}
return new DisposableAction(() => disposables.ForEach(d => d.Dispose()));
}
private void GenerateIBinderImplementation(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder)
{
WriteInitializer(typeSymbol, builder);
WriteToStringOverride(typeSymbol, builder);
WriteAndroidEqualityOverride(typeSymbol, builder);
WriteAndroidBinderDetails(typeSymbol, builder);
WriteAndroidAttachedToWindow(typeSymbol, builder);
WriteAttachToWindow(typeSymbol, builder);
WriteViewDidMoveToWindow(typeSymbol, builder);
WriteiOSMoveToSuperView(typeSymbol, builder);
WriteMacOSViewWillMoveToSuperview(typeSymbol, builder);
WriteDispose(typeSymbol, builder);
WriteBinderImplementation(typeSymbol, builder);
}
private void WriteToStringOverride(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder)
{
var hasNoToString = typeSymbol
.GetMethods()
.Where(m => IsNotDependencyObjectGeneratorSourceFile(m))
.None(m => m.Name == "ToString");
if (hasNoToString)
{
builder.AppendFormatInvariant(@"public override string ToString() => GetType().FullName;");
}
}
private void WriteiOSMoveToSuperView(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder)
{
var isiosView = typeSymbol.Is(_iosViewSymbol);
var hasNoWillMoveToSuperviewMethod = typeSymbol
.GetMethods()
.Where(m => IsNotDependencyObjectGeneratorSourceFile(m))
.None(m => m.Name == "WillMoveToSuperview");
var overridesWillMoveToSuperview = isiosView && hasNoWillMoveToSuperviewMethod;
if (overridesWillMoveToSuperview)
{
builder.AppendFormatInvariant(@"
public override void WillMoveToSuperview(UIKit.UIView newsuper)
{{
base.WillMoveToSuperview(newsuper);
WillMoveToSuperviewPartial(newsuper);
SyncBinder(newsuper, Window);
}}
partial void WillMoveToSuperviewPartial(UIKit.UIView newsuper);
private void SyncBinder(UIKit.UIView superview, UIKit.UIWindow window)
{{
if(superview == null && window == null)
{{
TemplatedParent = null;
}}
}}
");
}
else
{
builder.AppendLine($"// Skipped _iosViewSymbol: {typeSymbol.Is(_iosViewSymbol)}, hasNoWillMoveToSuperviewMethod: {hasNoWillMoveToSuperviewMethod}");
}
}
private void WriteMacOSViewWillMoveToSuperview(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder)
{
var isiosView = typeSymbol.Is(_macosViewSymbol);
var hasNoWillMoveToSuperviewMethod = typeSymbol
.GetMethods()
.Where(m => IsNotDependencyObjectGeneratorSourceFile(m))
.None(m => m.Name == "ViewWillMoveToSuperview");
var overridesWillMoveToSuperview = isiosView && hasNoWillMoveToSuperviewMethod;
if (overridesWillMoveToSuperview)
{
builder.AppendFormatInvariant(@"
public override void ViewWillMoveToSuperview(AppKit.NSView newsuper)
{{
base.ViewWillMoveToSuperview(newsuper);
WillMoveToSuperviewPartial(newsuper);
SyncBinder(newsuper, Window);
}}
partial void WillMoveToSuperviewPartial(AppKit.NSView newsuper);
private void SyncBinder(AppKit.NSView superview, AppKit.NSWindow window)
{{
if(superview == null && window == null)
{{
TemplatedParent = null;
}}
}}
");
}
else
{
builder.AppendLine($"// Skipped _macosViewSymbol: {typeSymbol.Is(_macosViewSymbol)}, hasNoViewWillMoveToSuperviewMethod: {hasNoWillMoveToSuperviewMethod}");
}
}
private void WriteAndroidAttachedToWindow(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder)
{
var isAndroidView = typeSymbol.Is(_androidViewSymbol);
var isAndroidActivity = typeSymbol.Is(_androidActivitySymbol);
var isAndroidFragment = typeSymbol.Is(_androidFragmentSymbol);
var isUnoViewGroup = typeSymbol.Is(_unoViewgroupSymbol);
var implementsIFrameworkElement = typeSymbol.Interfaces.Any(t => SymbolEqualityComparer.Default.Equals(t, _iFrameworkElementSymbol));
var hasOverridesAttachedToWindowAndroid = isAndroidView &&
typeSymbol
.GetMethods()
.Where(m => IsNotDependencyObjectGeneratorSourceFile(m))
.None(m => m.Name == "OnAttachedToWindow");
if (isAndroidView || isAndroidActivity || isAndroidFragment)
{
if (!isAndroidActivity && !isAndroidFragment)
{
WriteRegisterLoadActions(typeSymbol, builder);
}
builder.AppendLine($@"
#if {hasOverridesAttachedToWindowAndroid} //Is Android view (that doesn't already override OnAttachedToWindow)
#if {isUnoViewGroup} //Is UnoViewGroup
// Both methods below are implementation of abstract methods
// which are called from onAttachedToWindow in Java.
protected override void OnNativeLoaded()
{{
_loadActions.ForEach(a => a.Item1());
BinderAttachedToWindow();
}}
protected override void OnNativeUnloaded()
{{
_loadActions.ForEach(a => a.Item2());
BinderDetachedFromWindow();
}}
#else //Not UnoViewGroup
protected override void OnAttachedToWindow()
{{
base.OnAttachedToWindow();
__Store.Parent = base.Parent;
#if {implementsIFrameworkElement} //Is IFrameworkElement
OnLoading();
OnLoaded();
#endif
_loadActions.ForEach(a => a.Item1());
BinderAttachedToWindow();
}}
protected override void OnDetachedFromWindow()
{{
base.OnDetachedFromWindow();
_loadActions.ForEach(a => a.Item2());
#if {implementsIFrameworkElement} //Is IFrameworkElement
OnUnloaded();
#endif
if(base.Parent == null)
{{
__Store.Parent = null;
}}
BinderDetachedFromWindow();
}}
#endif // IsUnoViewGroup
#endif // OverridesAttachedToWindow
private void BinderAttachedToWindow()
{{
OnAttachedToWindowPartial();
}}
private void BinderDetachedFromWindow()
{{
OnDetachedFromWindowPartial();
}}
/// <summary>
/// A method called when the control is attached to the Window (equivalent of Loaded)
/// </summary>
partial void OnAttachedToWindowPartial();
/// <summary>
/// A method called when the control is attached to the Window (equivalent of Unloaded)
/// </summary>
partial void OnDetachedFromWindowPartial();
");
}
}
private static void WriteRegisterLoadActions(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder)
{
builder.AppendLine($@"
// A list of actions to be executed on Load and Unload
private List<(Action loaded, Action unloaded)> _loadActions = new List<(Action loaded, Action unloaded)>(2);
/// <summary>
/// Registers actions to be executed when the control is Loaded and Unloaded.
/// </summary>
/// <param name=""loaded""></param>
/// <param name=""unloaded""></param>
/// <returns></returns>
/// <remarks>The loaded action may be executed immediately if the control is already loaded.</remarks>
public IDisposable RegisterLoadActions(Action loaded, Action unloaded)
{{
var actions = (loaded, unloaded);
_loadActions.Add(actions);
#if __ANDROID__
if(this.IsLoaded())
#elif __IOS__ || __MACOS__
if(Window != null)
#else
#error Unsupported platform
#endif
{{
loaded();
}}
return Disposable.Create(() => _loadActions.Remove(actions));
}}
");
}
private void WriteAttachToWindow(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder)
{
var hasOverridesAttachedToWindowiOS = typeSymbol.Is(_iosViewSymbol) &&
typeSymbol
.GetMethods()
.Where(m => m.Name == "MovedToWindow")
.Where(m => IsNotDependencyObjectGeneratorSourceFile(m))
.None();
if (hasOverridesAttachedToWindowiOS)
{
WriteRegisterLoadActions(typeSymbol, builder);
builder.AppendLine($@"
public override void MovedToWindow()
{{
base.MovedToWindow();
if(Window != null)
{{
_loadActions.ForEach(a => a.loaded());
OnAttachedToWindowPartial();
}}
else
{{
_loadActions.ForEach(a => a.unloaded());
OnDetachedFromWindowPartial();
}}
}}
/// <summary>
/// A method called when the control is attached to the Window (equivalent of Loaded)
/// </summary>
partial void OnAttachedToWindowPartial();
/// <summary>
/// A method called when the control is attached to the Window (equivalent of Unloaded)
/// </summary>
partial void OnDetachedFromWindowPartial();
");
}
else
{
builder.AppendLine($@"// hasOverridesAttachedToWindowiOS=false");
}
}
private void WriteViewDidMoveToWindow(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder)
{
var hasOverridesAttachedToWindowiOS = typeSymbol.Is(_macosViewSymbol) &&
typeSymbol
.GetMethods()
.Where(m => m.Name == "ViewDidMoveToWindow")
.Where(m => IsNotDependencyObjectGeneratorSourceFile(m))
.None();
if (hasOverridesAttachedToWindowiOS)
{
WriteRegisterLoadActions(typeSymbol, builder);
builder.AppendLine($@"
public override void ViewDidMoveToWindow()
{{
base.ViewDidMoveToWindow();
if(Window != null)
{{
_loadActions.ForEach(a => a.loaded());
OnAttachedToWindowPartial();
}}
else
{{
_loadActions.ForEach(a => a.unloaded());
OnDetachedFromWindowPartial();
}}
}}
/// <summary>
/// A method called when the control is attached to the Window (equivalent of Loaded)
/// </summary>
partial void OnAttachedToWindowPartial();
/// <summary>
/// A method called when the control is attached to the Window (equivalent of Unloaded)
/// </summary>
partial void OnDetachedFromWindowPartial();
");
}
else
{
builder.AppendLine($@"// hasOverridesAttachedToWindowiOS=false");
}
}
private static bool IsNotDependencyObjectGeneratorSourceFile(IMethodSymbol m)
{
return !m.Locations.FirstOrDefault()?.SourceTree?.FilePath.Contains(nameof(DependencyObjectGenerator)) ?? true;
}
private void WriteAndroidBinderDetails(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder)
{
var hasBinderDetails = typeSymbol.Is(_androidViewSymbol);
if (hasBinderDetails)
{
builder.AppendLine($@"
///<summary>
/// Should not be used directly.
/// Helper method to provide Xaml debugging information to tools like Stetho.
///</summary>
[Java.Interop.ExportField(""xamlBinder"")]
public BinderDetails GetBinderDetail()
{{
return null;
}}
partial void UpdateBinderDetails()
{{
if (BinderDetails.IsBinderDetailsEnabled)
{{
var field = this.Class.GetField(""xamlBinder"");
field.Set(this, new BinderDetails(this));
}}
}}
");
}
}
private static void WriteInitializer(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder)
{
var content = $@"
private readonly static IEventProvider _binderTrace = Tracing.Get(DependencyObjectStore.TraceProvider.Id);
private BinderReferenceHolder _refHolder;
public event Windows.Foundation.TypedEventHandler<DependencyObject, DataContextChangedEventArgs> DataContextChanged;
partial void InitializeBinder();
private void __InitializeBinder()
{{
if(BinderReferenceHolder.IsEnabled)
{{
_refHolder = new BinderReferenceHolder(this.GetType(), this);
UpdateBinderDetails();
}}
}}
partial void UpdateBinderDetails();
/// <summary>
/// Obsolete method kept for binary compatibility
/// </summary>
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public void ClearBindings()
{{
__Store.ClearBindings();
}}
/// <summary>
/// Obsolete method kept for binary compatibility
/// </summary>
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public void RestoreBindings()
{{
__Store.RestoreBindings();
}}
/// <summary>
/// Obsolete method kept for binary compatibility
/// </summary>
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
[global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public void ApplyCompiledBindings()
{{
}}
private global::Uno.UI.DataBinding.ManagedWeakReference _selfWeakReference;
global::Uno.UI.DataBinding.ManagedWeakReference IWeakReferenceProvider.WeakReference
{{
get
{{
if(_selfWeakReference == null)
{{
_selfWeakReference = global::Uno.UI.DataBinding.WeakReferencePool.RentSelfWeakReference(this);
}}
return _selfWeakReference;
}}
}}
";
builder.AppendLine(content);
}
private void WriteDispose(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder)
{
var hasDispose = typeSymbol.Is(_androidViewSymbol) || typeSymbol.Is(_iosViewSymbol) || typeSymbol.Is(_macosViewSymbol);
if (hasDispose)
{
builder.AppendLine($@"
#if __IOS__ || __MACOS__
private bool _isDisposed;
[SuppressMessage(
""Microsoft.Usage"",
""CA2215:DisposeMethodsShouldCallBaseClassDispose"",
Justification = ""The dispose is re-scheduled using the ValidateDispose method"")]
protected sealed override void Dispose(bool disposing)
{{
if(_isDisposed)
{{
base.Dispose(disposing);
return;
}}
if (disposing)
{{
// __Store may be null if the control has been recreated from
// a native representation via the IntPtr ctor, particularly on iOS.
__Store?.Dispose();
var subviews = Subviews;
RequestCollect(subviews);
foreach (var v in subviews)
{{
v.RemoveFromSuperview();
}}
base.Dispose(disposing);
_isDisposed = true;
}}
else
{{
GC.ReRegisterForFinalize(this);
Dispatcher.RunIdleAsync(_ => Dispose());
}}
}}
#if __IOS__
private void RequestCollect(UIKit.UIView[] subviews)
#elif __MACOS__
private void RequestCollect(AppKit.NSView[] subviews)
#endif
{{
if(subviews.Length != 0)
{{
BinderCollector.RequestCollect();
}}
}}
#endif
");
}
}
private void WriteBinderImplementation(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder)
{
var virtualModifier = typeSymbol.IsSealed ? "" : "virtual";
var protectedModifier = typeSymbol.IsSealed ? "private" : "internal protected";
builder.AppendLine($@"
#region DataContext DependencyProperty
public object DataContext
{{
get => GetValue(DataContextProperty);
set => SetValue(DataContextProperty, value);
}}
// Using a DependencyProperty as the backing store for DataContext. This enables animation, styling, binding, etc...
public static DependencyProperty DataContextProperty {{ get ; }} =
DependencyProperty.Register(
name: nameof(DataContext),
propertyType: typeof(object),
ownerType: typeof({typeSymbol.Name}),
typeMetadata: new FrameworkPropertyMetadata(
defaultValue: null,
options: FrameworkPropertyMetadataOptions.Inherits,
propertyChangedCallback: (s, e) => (({typeSymbol.Name})s).OnDataContextChanged(e)
)
);
{protectedModifier} {virtualModifier} void OnDataContextChanged(DependencyPropertyChangedEventArgs e)
{{
OnDataContextChangedPartial(e);
DataContextChanged?.Invoke(this, new DataContextChangedEventArgs(DataContext));
}}
#endregion
#region TemplatedParent DependencyProperty
public DependencyObject TemplatedParent
{{
get => (DependencyObject)GetValue(TemplatedParentProperty);
set => SetValue(TemplatedParentProperty, value);
}}
// Using a DependencyProperty as the backing store for TemplatedParent. This enables animation, styling, binding, etc...
public static DependencyProperty TemplatedParentProperty {{ get ; }} =
DependencyProperty.Register(
name: nameof(TemplatedParent),
propertyType: typeof(DependencyObject),
ownerType: typeof({typeSymbol.Name}),
typeMetadata: new FrameworkPropertyMetadata(
defaultValue: null,
options: FrameworkPropertyMetadataOptions.Inherits | FrameworkPropertyMetadataOptions.ValueDoesNotInheritDataContext | FrameworkPropertyMetadataOptions.WeakStorage,
propertyChangedCallback: (s, e) => (({typeSymbol.Name})s).OnTemplatedParentChanged(e)
)
);
{protectedModifier} {virtualModifier} void OnTemplatedParentChanged(DependencyPropertyChangedEventArgs e)
{{
__Store.SetTemplatedParent(e.NewValue as FrameworkElement);
OnTemplatedParentChangedPartial(e);
}}
#endregion
public void SetBinding(object target, string dependencyProperty, global::Windows.UI.Xaml.Data.BindingBase binding)
{{
__Store.SetBinding(target, dependencyProperty, binding);
}}
public void SetBinding(string dependencyProperty, global::Windows.UI.Xaml.Data.BindingBase binding)
{{
__Store.SetBinding(dependencyProperty, binding);
}}
public void SetBinding(DependencyProperty dependencyProperty, global::Windows.UI.Xaml.Data.BindingBase binding)
{{
__Store.SetBinding(dependencyProperty, binding);
}}
public void SetBindingValue(object value, [CallerMemberName] string propertyName = null)
{{
__Store.SetBindingValue(value, propertyName);
}}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal bool IsAutoPropertyInheritanceEnabled {{ get => __Store.IsAutoPropertyInheritanceEnabled; set => __Store.IsAutoPropertyInheritanceEnabled = value; }}
partial void OnDataContextChangedPartial(DependencyPropertyChangedEventArgs e);
partial void OnTemplatedParentChangedPartial(DependencyPropertyChangedEventArgs e);
public global::Windows.UI.Xaml.Data.BindingExpression GetBindingExpression(DependencyProperty dependencyProperty)
=> __Store.GetBindingExpression(dependencyProperty);
public void ResumeBindings()
=>__Store.ResumeBindings();
public void SuspendBindings() =>
__Store.SuspendBindings();
");
}
private void WriteAndroidEqualityOverride(INamedTypeSymbol typeSymbol, IndentedStringBuilder builder)
{
var hasEqualityOverride = typeSymbol
.GetMethods()
.Where(m => m.Name == "Equals")
.Where(m => IsNotDependencyObjectGeneratorSourceFile(m))
.None()
&& (typeSymbol.BaseType?.GetMethods().None(m => m.Name == "Equals" && m.IsSealed) ?? true);
if (hasEqualityOverride && typeSymbol.Is(_androidViewSymbol))
{
builder.AppendLine($@"
public override int GetHashCode()
{{
// For the the current kind of type, we do not need to call back
// to android for the GetHashCode implementation. The .NET proxy hash is
// enough. This way, we do not get to pay the price of the interop to get
// this value.
return RuntimeHelpers.GetHashCode(this);
}}
public override bool Equals(object other)
{{
// For the the current kind of type, we do not need to call back
// to android for the Equals implementation. We assume that proxies are
// one-to-one mapping with native instances, making the reference comparison
// of proxies enough to do the job.
return RuntimeHelpers.ReferenceEquals(this, other);
}}
");
}
}
private static void GenerateDependencyObjectImplementation(IndentedStringBuilder builder)
{
builder.AppendLineInvariant(@"private DependencyObjectStore __storeBackingField;");
builder.AppendLineInvariant(@"public Windows.UI.Core.CoreDispatcher Dispatcher => Windows.UI.Core.CoreDispatcher.Main;");
builder.AppendLineInvariant(@"#if HAS_UNO_WINUI");
builder.AppendLineInvariant(@"public global::Microsoft.System.DispatcherQueue DispatcherQueue => global::Microsoft.System.DispatcherQueue.GetForCurrentThread();");
builder.AppendLineInvariant(@"#endif");
using (builder.BlockInvariant($"private DependencyObjectStore __Store"))
{
using (builder.BlockInvariant($"get"))
{
using (builder.BlockInvariant($"if(__storeBackingField == null)"))
{
builder.AppendLineInvariant("__storeBackingField = new DependencyObjectStore(this, DataContextProperty, TemplatedParentProperty);");
builder.AppendLineInvariant("__InitializeBinder();");
}
builder.AppendLineInvariant("return __storeBackingField;");
}
}
builder.AppendLineInvariant(@"public bool IsStoreInitialized => __storeBackingField != null;");
builder.AppendLineInvariant(@"DependencyObjectStore IDependencyObjectStoreProvider.Store => __Store;");
builder.AppendLineInvariant("public object GetValue(DependencyProperty dp) => __Store.GetValue(dp);");
builder.AppendLineInvariant("public void SetValue(DependencyProperty dp, object value) => __Store.SetValue(dp, value);");
builder.AppendLineInvariant("public void ClearValue(DependencyProperty dp) => __Store.ClearValue(dp);");
builder.AppendLineInvariant("public object ReadLocalValue(DependencyProperty dp) => __Store.ReadLocalValue(dp);");
builder.AppendLineInvariant("public object GetAnimationBaseValue(DependencyProperty dp) => __Store.GetAnimationBaseValue(dp);");
builder.AppendLineInvariant("public long RegisterPropertyChangedCallback(DependencyProperty dp, DependencyPropertyChangedCallback callback) => __Store.RegisterPropertyChangedCallback(dp, callback);");
builder.AppendLineInvariant("public void UnregisterPropertyChangedCallback(DependencyProperty dp, long token) => __Store.UnregisterPropertyChangedCallback(dp, token);");
}
}
}
}