/
ResourceManager.cs
474 lines (402 loc) · 13.3 KB
/
ResourceManager.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
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Android.Content;
using Android.Content.Res;
using Android.Graphics;
using Android.Graphics.Drawables;
using Xamarin.Forms.Internals;
using Path = System.IO.Path;
#if __ANDROID_29__
using AndroidAppCompat = AndroidX.AppCompat.Content.Res.AppCompatResources;
#else
using AndroidAppCompat = Android.Support.V7.Content.Res.AppCompatResources;
#endif
using System.ComponentModel;
namespace Xamarin.Forms.Platform.Android
{
public static class ResourceManager
{
const string _drawableDefType = "drawable";
readonly static Lazy<ImageCache> _lruCache = new Lazy<ImageCache>(() => new ImageCache());
static ImageCache GetCache() => _lruCache.Value;
static Assembly _assembly;
static Type FindType(string name, string altName)
{
return _assembly.GetTypes().FirstOrDefault(x => x.Name == name || x.Name == altName);
}
static Type _drawableClass;
static Type _resourceClass;
static Type _styleClass;
static Type _layoutClass;
public static Type DrawableClass {
get {
if (_drawableClass == null)
_drawableClass = FindType("Drawable", "Resource_Drawable");
return _drawableClass;
}
set
{
_drawableClass = value;
}
}
public static Type ResourceClass {
get {
if (_resourceClass == null)
_resourceClass = FindType("Id", "Resource_Id");
return _resourceClass;
}
set
{
_resourceClass = value;
}
}
public static Type StyleClass {
get {
if (_styleClass == null)
_styleClass = FindType("Style", "Resource_Style");
return _styleClass;
}
set
{
_styleClass = value;
}
}
public static Type LayoutClass {
get {
if (_layoutClass == null)
_layoutClass = FindType("Layout", "Resource_Layout");
return _layoutClass;
}
set
{
_layoutClass = value;
}
}
internal static async Task<Drawable> GetFormsDrawableAsync(this Context context, ImageSource imageSource, CancellationToken cancellationToken = default(CancellationToken))
{
if (imageSource == null || imageSource.IsEmpty)
return null;
// try take a shortcut for files
if (imageSource is FileImageSource fileImageSource)
{
var file = fileImageSource.File;
var id = IdFromTitle(file, DrawableClass);
// try the drawables via id
if (id != 0)
{
var drawable = AndroidAppCompat.GetDrawable(context, id);
if (drawable != null)
return drawable;
}
// try a direct file on the file system
if (File.Exists(file))
{
using (var bitmap = await BitmapFactory.DecodeFileAsync(file).ConfigureAwait(false))
{
if (bitmap != null)
return new BitmapDrawable(context.Resources, bitmap);
}
}
// try the bitmap resources via id
if (id != 0)
{
using (var bitmap = await BitmapFactory.DecodeResourceAsync(context.Resources, id).ConfigureAwait(false))
{
if (bitmap != null)
return new BitmapDrawable(context.Resources, bitmap);
}
}
}
// fall back to the handler
using (var bitmap = await context.GetFormsBitmapAsync(imageSource, cancellationToken).ConfigureAwait(false))
{
if (bitmap != null)
return new BitmapDrawable(context.Resources, bitmap);
}
return null;
}
internal static async Task<Bitmap> GetFormsBitmapAsync(this Context context, ImageSource imageSource, CancellationToken cancellationToken = default(CancellationToken))
{
if (imageSource == null || imageSource.IsEmpty)
return null;
var handler = Registrar.Registered.GetHandlerForObject<IImageSourceHandler>(imageSource);
if (handler == null)
return null;
try
{
return await handler.LoadImageAsync(imageSource, context, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
Internals.Log.Warning("Image loading", "Image load cancelled");
}
catch (Exception ex)
{
Internals.Log.Warning("Image loading", $"Image load failed: {ex}");
}
return null;
}
static bool IsDrawableSourceValid(this IVisualElementRenderer renderer, BindableObject bindable, out BindableObject element)
{
if ((renderer is IDisposedState disposed && disposed.IsDisposed) || (renderer != null && renderer.View == null))
element = null;
else if (bindable != null)
element = bindable;
else
element = renderer.Element;
return element != null;
}
internal static Task ApplyDrawableAsync(this IShellContext shellContext, BindableObject bindable, BindableProperty imageSourceProperty, Action<Drawable> onSet, Action<bool> onLoading = null, CancellationToken cancellationToken = default(CancellationToken))
{
_ = shellContext ?? throw new ArgumentNullException(nameof(shellContext));
var renderer = shellContext as IVisualElementRenderer ?? throw new InvalidOperationException($"The shell context {shellContext.GetType()} must be a {typeof(IVisualElementRenderer)}.");
return renderer.ApplyDrawableAsync(bindable, imageSourceProperty, shellContext.AndroidContext, onSet, onLoading, cancellationToken);
}
internal static Task ApplyDrawableAsync(this IVisualElementRenderer renderer,
BindableProperty imageSourceProperty,
Context context,
Action<Drawable> onSet,
Action<bool> onLoading = null,
CancellationToken cancellationToken = default(CancellationToken))
{
return renderer.ApplyDrawableAsync(null, imageSourceProperty, context, onSet, onLoading, cancellationToken);
}
internal static async Task ApplyDrawableAsync(this IVisualElementRenderer renderer,
BindableObject bindable,
BindableProperty imageSourceProperty,
Context context,
Action<Drawable> onSet,
Action<bool> onLoading = null,
CancellationToken cancellationToken = default(CancellationToken))
{
_ = context ?? throw new ArgumentNullException(nameof(context));
_ = imageSourceProperty ?? throw new ArgumentNullException(nameof(imageSourceProperty));
_ = onSet ?? throw new ArgumentNullException(nameof(onSet));
// make sure things are good before we start
BindableObject element = null;
if (!renderer.IsDrawableSourceValid(bindable, out element))
return;
onLoading?.Invoke(true);
if (element.GetValue(imageSourceProperty) is ImageSource initialSource && !initialSource.IsEmpty)
{
try
{
string cacheKey = String.Empty;
// Todo improve for other sources
// volley the requests better up front so that if the same request comes in it isn't requeued
if (initialSource is UriImageSource uri && uri.CachingEnabled)
{
cacheKey = Device.PlatformServices.GetMD5Hash(uri.Uri.ToString());
var cacheObject = await GetCache().GetAsync(cacheKey, uri.CacheValidity, async () =>
{
var drawable = await context.GetFormsDrawableAsync(initialSource, cancellationToken);
return drawable;
});
Drawable returnValue = null;
if (cacheObject is Bitmap bitmap)
returnValue = new BitmapDrawable(context.Resources, bitmap);
else
returnValue = cacheObject as Drawable;
if (!renderer.IsDrawableSourceValid(bindable, out element))
return;
// only set if we are still on the same image
if (element.GetValue(imageSourceProperty) == initialSource)
{
using (returnValue)
onSet(returnValue);
}
}
else
{
using (var drawable = await context.GetFormsDrawableAsync(initialSource, cancellationToken))
{
if (!renderer.IsDrawableSourceValid(bindable, out element))
return;
// only set if we are still on the same image
if (element.GetValue(imageSourceProperty) == initialSource)
{
onSet(drawable);
}
}
}
}
finally
{
if (element != null && onLoading != null)
{
// only mark as finished if we are still on the same image
if (element.GetValue(imageSourceProperty) == initialSource)
onLoading.Invoke(false);
}
}
}
else
{
onSet(null);
onLoading?.Invoke(false);
}
}
internal static async Task ApplyDrawableAsync(this Context context,
BindableObject bindable,
BindableProperty imageSourceProperty,
Action<Drawable> onSet,
Action<bool> onLoading = null,
CancellationToken cancellationToken = default(CancellationToken))
{
await ApplyDrawableAsync(null, bindable, imageSourceProperty, context, onSet, onLoading, cancellationToken);
}
public static Bitmap GetBitmap(this Resources resource, FileImageSource fileImageSource)
{
var file = fileImageSource.File;
var bitmap = GetBitmap(resource, file);
if (bitmap != null)
return bitmap;
return BitmapFactory.DecodeFile(file);
}
public static Bitmap GetBitmap(this Resources resource, string name)
{
return BitmapFactory.DecodeResource(resource, IdFromTitle(name, DrawableClass, _drawableDefType, resource));
}
public static Bitmap GetBitmap(this Resources resource, string name, Context context)
{
return BitmapFactory.DecodeResource(resource, IdFromTitle(name, DrawableClass, _drawableDefType, resource, context.PackageName));
}
public static Task<Bitmap> GetBitmapAsync(this Resources resource, string name)
{
return BitmapFactory.DecodeResourceAsync(resource, IdFromTitle(name, DrawableClass, _drawableDefType, resource));
}
public static Task<Bitmap> GetBitmapAsync(this Resources resource, string name, Context context)
{
return BitmapFactory.DecodeResourceAsync(resource, IdFromTitle(name, DrawableClass, _drawableDefType, resource, context.PackageName));
}
[Obsolete("GetDrawable(this Resources, string) is obsolete as of version 2.5. "
+ "Please use GetDrawable(this Context, string) instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public static Drawable GetDrawable(this Resources resource, string name)
{
int id = IdFromTitle(name, DrawableClass, _drawableDefType, resource);
if (id == 0)
{
Log.Warning("Could not load image named: {0}", name);
return null;
}
return AndroidAppCompat.GetDrawable(Forms.Context, id);
}
[EditorBrowsable(EditorBrowsableState.Never)]
static void LogInfoToPreviewer(string message)
{
Java.Lang.Class designerHost = Java.Lang.Class.FromType(typeof(ImageRenderer)).ClassLoader.LoadClass("mono.android.HostProcessConnection");
Java.Lang.Reflect.Method reportMethod = designerHost.GetMethod("logInfo", Java.Lang.Class.FromType(typeof(Java.Lang.String)));
reportMethod.Invoke(null, message);
}
public static Drawable GetDrawable(this Context context, string name)
{
int id = IdFromTitle(name, DrawableClass, _drawableDefType, context);
if (id == 0)
{
Log.Warning("Could not load image named: {0}", name);
return null;
}
return AndroidAppCompat.GetDrawable(context, id);
}
public static int GetDrawableByName(string name)
{
return IdFromTitle(name, DrawableClass);
}
public static int GetResourceByName(string name)
{
return IdFromTitle(name, ResourceClass);
}
public static int GetLayoutByName(string name)
{
return IdFromTitle(name, LayoutClass);
}
public static int GetLayout(this Context context, string name)
{
return IdFromTitle(name, LayoutClass, "layout", context);
}
public static int GetStyleByName(string name)
{
return IdFromTitle(name, StyleClass);
}
public static int GetStyle(this Context context, string name)
{
return IdFromTitle(name, StyleClass, "style", context);
}
public static void Init(Assembly masterAssembly)
{
_assembly = masterAssembly;
}
static int IdFromTitle(string title, Type type)
{
if (title == null)
return 0;
string name = Path.GetFileNameWithoutExtension(title);
int id = GetId(type, name);
return id;
}
static int IdFromTitle(string title, Type resourceType, string defType, Resources resource)
{
return IdFromTitle(title, resourceType, defType, resource, AppCompat.Platform.GetPackageName());
}
static int IdFromTitle(string title, Type resourceType, string defType, Context context)
{
return IdFromTitle(title, resourceType, defType, context.Resources, context.PackageName);
}
static int IdFromTitle(string title, Type resourceType, string defType, Resources resource, string packageName)
{
int id = 0;
if (title == null)
return id;
string name = Path.GetFileNameWithoutExtension(title);
id = GetId(resourceType, name);
if (id > 0)
return id;
if (packageName != null)
{
id = resource.GetIdentifier(name, defType, packageName);
if (id > 0)
return id;
}
id = resource.GetIdentifier(name, defType, null);
return id;
}
static int GetId(Type type, string memberName)
{
// This may legitimately be null in designer scenarios
if (type == null)
return 0;
object value = null;
var fields = type.GetFields();
for (int i = 0; i < fields.Length; i++)
{
var field = fields[i];
if (field.Name == memberName)
{
value = field.GetValue(type);
break;
}
}
if (value == null)
{
var properties = type.GetProperties();
for (int i = 0; i < properties.Length; i++)
{
var prop = properties[i];
if (prop.Name == memberName)
{
value = prop.GetValue(type);
break;
}
}
}
if (value is int result)
return result;
return 0;
}
}
}