-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ControlFetcherMixin.cs
249 lines (214 loc) · 10.1 KB
/
ControlFetcherMixin.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
// Copyright (c) 2023 .NET Foundation and Contributors. All rights reserved.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System.Collections.Concurrent;
using System.Reflection;
using System.Runtime.CompilerServices;
using Android.App;
using Android.Views;
namespace ReactiveUI;
/// <summary>
/// Control Fetcher Mix-in helps you automatically wire-up Activities and
/// Fragments via property names, similar to Butter Knife, as well as allows
/// you to fetch controls manually.
/// </summary>
public static partial class ControlFetcherMixin
{
private static readonly ConcurrentDictionary<Assembly, Dictionary<string, int>> _controlIds = new();
private static readonly ConditionalWeakTable<object, Dictionary<string, View?>> _viewCache = [];
/// <summary>
/// Gets the control from an activity.
/// </summary>
/// <param name="activity">The activity.</param>
/// <param name="propertyName">The property name.</param>
/// <returns>The return view.</returns>
public static View? GetControl(this Activity activity, [CallerMemberName] string? propertyName = null) // TODO: Create Test
=> GetCachedControl(propertyName, activity, () => activity.FindViewById(GetControlIdByName(activity.GetType().Assembly, propertyName)));
/// <summary>
/// Gets the control from a view.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="assembly">The assembly containing the user-defined view.</param>
/// <param name="propertyName">The property.</param>
/// <returns>The return view.</returns>
public static View? GetControl(this View view, Assembly assembly, [CallerMemberName] string? propertyName = null) // TODO: Create Test
=> GetCachedControl(propertyName, view, () => view.FindViewById(GetControlIdByName(assembly, propertyName)));
/// <summary>
/// Wires a control to a property.
/// </summary>
/// <param name="layoutHost">The layout view host.</param>
/// <param name="resolveMembers">The resolve members.</param>
public static void WireUpControls(this ILayoutViewHost layoutHost, ResolveStrategy resolveMembers = ResolveStrategy.Implicit) // TODO: Create Test
{
if (layoutHost is null)
{
throw new ArgumentNullException(nameof(layoutHost));
}
var members = layoutHost.GetWireUpMembers(resolveMembers).ToList();
foreach (var member in members)
{
try
{
var view = layoutHost.View?.GetControl(layoutHost.GetType().Assembly, member.GetResourceName());
member.SetValue(layoutHost, view);
}
catch (Exception ex)
{
throw new
MissingFieldException("Failed to wire up the Property " + member.Name + " to a View in your layout with a corresponding identifier", ex);
}
}
}
/// <summary>
/// Wires a control to a property.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="resolveMembers">The resolve members.</param>
public static void WireUpControls(this View view, ResolveStrategy resolveMembers = ResolveStrategy.Implicit) // TODO: Create Test
{
if (view is null)
{
throw new ArgumentNullException(nameof(view));
}
var members = view.GetWireUpMembers(resolveMembers);
foreach (var member in members)
{
try
{
// Find the android control with the same name
var currentView = view.GetControl(view.GetType().Assembly, member.GetResourceName());
// Set the activity field's value to the view with that identifier
member.SetValue(view, currentView);
}
catch (Exception ex)
{
throw new
MissingFieldException("Failed to wire up the Property " + member.Name + " to a View in your layout with a corresponding identifier", ex);
}
}
}
/// <summary>
/// Wires a control to a property.
/// This should be called in the Fragment's OnCreateView, with the newly inflated layout.
/// </summary>
/// <param name="fragment">The fragment.</param>
/// <param name="inflatedView">The inflated view.</param>
/// <param name="resolveMembers">The resolve members.</param>
[Obsolete("This class is obsoleted in this android platform")]
public static void WireUpControls(this Fragment fragment, View inflatedView, ResolveStrategy resolveMembers = ResolveStrategy.Implicit) // TODO: Create Test
{
if (fragment is null)
{
throw new ArgumentNullException(nameof(fragment));
}
var members = fragment.GetWireUpMembers(resolveMembers);
foreach (var member in members)
{
try
{
// Find the android control with the same name from the view
var view = inflatedView.GetControl(fragment.GetType().Assembly, member.GetResourceName());
// Set the activity field's value to the view with that identifier
member.SetValue(fragment, view);
}
catch (Exception ex)
{
throw new
MissingFieldException("Failed to wire up the Property " + member.Name + " to a View in your layout with a corresponding identifier", ex);
}
}
}
/// <summary>
/// Wires a control to a property.
/// </summary>
/// <param name="activity">The Activity.</param>
/// <param name="resolveMembers">The resolve members.</param>
public static void WireUpControls(this Activity activity, ResolveStrategy resolveMembers = ResolveStrategy.Implicit) // TODO: Create Test
{
if (activity is null)
{
throw new ArgumentNullException(nameof(activity));
}
var members = activity.GetWireUpMembers(resolveMembers);
foreach (var member in members)
{
try
{
// Find the android control with the same name
var view = activity.GetControl(member.GetResourceName());
// Set the activity field's value to the view with that identifier
member.SetValue(activity, view);
}
catch (Exception ex)
{
throw new
MissingFieldException("Failed to wire up the Property " + member.Name + " to a View in your layout with a corresponding identifier", ex);
}
}
}
internal static IEnumerable<PropertyInfo> GetWireUpMembers(this object @this, ResolveStrategy resolveStrategy)
{
var members = @this.GetType().GetRuntimeProperties();
return resolveStrategy switch
{
ResolveStrategy.ExplicitOptIn =>
members.Where(member => member.GetCustomAttribute<WireUpResourceAttribute>(true) is not null),
ResolveStrategy.ExplicitOptOut =>
members.Where(member => typeof(View).IsAssignableFrom(member.PropertyType) && member.GetCustomAttribute<IgnoreResourceAttribute>(true) is null),
// Implicit matches the Default.
_ => members.Where(member => member.PropertyType.IsSubclassOf(typeof(View)) || member.GetCustomAttribute<WireUpResourceAttribute>(true) is not null),
};
}
internal static string GetResourceName(this PropertyInfo member)
{
var resourceNameOverride = member.GetCustomAttribute<WireUpResourceAttribute>()?.ResourceNameOverride;
return resourceNameOverride ?? member.Name;
}
private static View? GetCachedControl(string? propertyName, object rootView, Func<View?> fetchControlFromView)
{
if (propertyName is null)
{
throw new ArgumentNullException(nameof(propertyName));
}
if (fetchControlFromView is null)
{
throw new ArgumentNullException(nameof(fetchControlFromView));
}
var ourViewCache = _viewCache.GetOrCreateValue(rootView);
if (ourViewCache.TryGetValue(propertyName, out var ret))
{
return ret;
}
ret = fetchControlFromView();
ourViewCache.Add(propertyName, ret);
return ret;
}
private static int GetControlIdByName(Assembly assembly, string? name)
{
if (name is null)
{
throw new ArgumentNullException(nameof(name));
}
var ids = _controlIds.GetOrAdd(
assembly,
currentAssembly =>
{
#if NET8_0_OR_GREATER
var resources = Assembly.Load(currentAssembly
.GetReferencedAssemblies()
.First(an => an.FullName.StartsWith("_Microsoft.Android.Resource.Designer")).ToString())
.GetModules()
.SelectMany(x => x.GetTypes())
.First(x => x.Name == "ResourceConstant");
#else
var resources = currentAssembly.GetModules().SelectMany(x => x.GetTypes()).First(x => x.Name == "Resource");
#endif
var idType = resources.GetNestedType("Id") ?? throw new InvalidOperationException("Id is not a valid nested type in the resources.");
return idType.GetFields()
.Where(x => x.FieldType == typeof(int))
.ToDictionary(k => k.Name, v => ((int?)v.GetRawConstantValue()) ?? 0, StringComparer.InvariantCultureIgnoreCase);
});
return ids[name];
}
}