PageRenderTime 58ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Shared/PlatformSupport/AssetLoader.cs

https://gitlab.com/kush/Avalonia
C# | 397 lines | 287 code | 54 blank | 56 comment | 57 complexity | 04bb1c366a073eab036ce54e2afcd6d9 MD5 | raw file
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Reflection;
  8. using Avalonia.Platform;
  9. using Avalonia.Utilities;
  10. namespace Avalonia.Shared.PlatformSupport
  11. {
  12. /// <summary>
  13. /// Loads assets compiled into the application binary.
  14. /// </summary>
  15. public class AssetLoader : IAssetLoader
  16. {
  17. private const string AvaloniaResourceName = "!AvaloniaResources";
  18. private static readonly Dictionary<string, AssemblyDescriptor> AssemblyNameCache
  19. = new Dictionary<string, AssemblyDescriptor>();
  20. private AssemblyDescriptor _defaultResmAssembly;
  21. /// <summary>
  22. /// Initializes a new instance of the <see cref="AssetLoader"/> class.
  23. /// </summary>
  24. /// <param name="assembly">
  25. /// The default assembly from which to load resm: assets for which no assembly is specified.
  26. /// </param>
  27. public AssetLoader(Assembly assembly = null)
  28. {
  29. if (assembly == null)
  30. assembly = Assembly.GetEntryAssembly();
  31. if (assembly != null)
  32. _defaultResmAssembly = new AssemblyDescriptor(assembly);
  33. }
  34. /// <summary>
  35. /// Sets the default assembly from which to load assets for which no assembly is specified.
  36. /// </summary>
  37. /// <param name="assembly">The default assembly.</param>
  38. public void SetDefaultAssembly(Assembly assembly)
  39. {
  40. _defaultResmAssembly = new AssemblyDescriptor(assembly);
  41. }
  42. /// <summary>
  43. /// Checks if an asset with the specified URI exists.
  44. /// </summary>
  45. /// <param name="uri">The URI.</param>
  46. /// <param name="baseUri">
  47. /// A base URI to use if <paramref name="uri"/> is relative.
  48. /// </param>
  49. /// <returns>True if the asset could be found; otherwise false.</returns>
  50. public bool Exists(Uri uri, Uri baseUri = null)
  51. {
  52. return GetAsset(uri, baseUri) != null;
  53. }
  54. /// <summary>
  55. /// Opens the asset with the requested URI.
  56. /// </summary>
  57. /// <param name="uri">The URI.</param>
  58. /// <param name="baseUri">
  59. /// A base URI to use if <paramref name="uri"/> is relative.
  60. /// </param>
  61. /// <returns>A stream containing the asset contents.</returns>
  62. /// <exception cref="FileNotFoundException">
  63. /// The asset could not be found.
  64. /// </exception>
  65. public Stream Open(Uri uri, Uri baseUri = null) => OpenAndGetAssembly(uri, baseUri).Item1;
  66. /// <summary>
  67. /// Opens the asset with the requested URI and returns the asset stream and the
  68. /// assembly containing the asset.
  69. /// </summary>
  70. /// <param name="uri">The URI.</param>
  71. /// <param name="baseUri">
  72. /// A base URI to use if <paramref name="uri"/> is relative.
  73. /// </param>
  74. /// <returns>
  75. /// The stream containing the resource contents together with the assembly.
  76. /// </returns>
  77. /// <exception cref="FileNotFoundException">
  78. /// The asset could not be found.
  79. /// </exception>
  80. public (Stream stream, Assembly assembly) OpenAndGetAssembly(Uri uri, Uri baseUri = null)
  81. {
  82. var asset = GetAsset(uri, baseUri);
  83. if (asset == null)
  84. {
  85. throw new FileNotFoundException($"The resource {uri} could not be found.");
  86. }
  87. return (asset.GetStream(), asset.Assembly);
  88. }
  89. /// <summary>
  90. /// Gets all assets of a folder and subfolders that match specified uri.
  91. /// </summary>
  92. /// <param name="uri">The URI.</param>
  93. /// <param name="baseUri">Base URI that is used if <paramref name="uri"/> is relative.</param>
  94. /// <returns>All matching assets as a tuple of the absolute path to the asset and the assembly containing the asset</returns>
  95. public IEnumerable<Uri> GetAssets(Uri uri, Uri baseUri)
  96. {
  97. if (uri.IsAbsoluteUri && uri.Scheme == "resm")
  98. {
  99. var assembly = GetAssembly(uri);
  100. return assembly?.Resources.Where(x => x.Key.Contains(uri.AbsolutePath))
  101. .Select(x =>new Uri($"resm:{x.Key}?assembly={assembly.Name}")) ??
  102. Enumerable.Empty<Uri>();
  103. }
  104. uri = EnsureAbsolute(uri, baseUri);
  105. if (uri.Scheme == "avares")
  106. {
  107. var (asm, path) = GetResAsmAndPath(uri);
  108. if (asm == null)
  109. {
  110. throw new ArgumentException(
  111. "No default assembly, entry assembly or explicit assembly specified; " +
  112. "don't know where to look up for the resource, try specifying assembly explicitly.");
  113. }
  114. if (asm?.AvaloniaResources == null)
  115. return Enumerable.Empty<Uri>();
  116. path = path.TrimEnd('/') + '/';
  117. return asm.AvaloniaResources.Where(r => r.Key.StartsWith(path))
  118. .Select(x => new Uri($"avares://{asm.Name}{x.Key}"));
  119. }
  120. return Enumerable.Empty<Uri>();
  121. }
  122. private Uri EnsureAbsolute(Uri uri, Uri baseUri)
  123. {
  124. if (uri.IsAbsoluteUri)
  125. return uri;
  126. if(baseUri == null)
  127. throw new ArgumentException($"Relative uri {uri} without base url");
  128. if (!baseUri.IsAbsoluteUri)
  129. throw new ArgumentException($"Base uri {baseUri} is relative");
  130. if (baseUri.Scheme == "resm")
  131. throw new ArgumentException(
  132. $"Relative uris for 'resm' scheme aren't supported; {baseUri} uses resm");
  133. return new Uri(baseUri, uri);
  134. }
  135. private IAssetDescriptor GetAsset(Uri uri, Uri baseUri)
  136. {
  137. if (uri.IsAbsoluteUri && uri.Scheme == "resm")
  138. {
  139. var asm = GetAssembly(uri) ?? GetAssembly(baseUri) ?? _defaultResmAssembly;
  140. if (asm == null)
  141. {
  142. throw new ArgumentException(
  143. "No default assembly, entry assembly or explicit assembly specified; " +
  144. "don't know where to look up for the resource, try specifying assembly explicitly.");
  145. }
  146. IAssetDescriptor rv;
  147. var resourceKey = uri.AbsolutePath;
  148. asm.Resources.TryGetValue(resourceKey, out rv);
  149. return rv;
  150. }
  151. uri = EnsureAbsolute(uri, baseUri);
  152. if (uri.Scheme == "avares")
  153. {
  154. var (asm, path) = GetResAsmAndPath(uri);
  155. if (asm.AvaloniaResources == null)
  156. return null;
  157. asm.AvaloniaResources.TryGetValue(path, out var desc);
  158. return desc;
  159. }
  160. throw new ArgumentException($"Unsupported url type: " + uri.Scheme, nameof(uri));
  161. }
  162. private (AssemblyDescriptor asm, string path) GetResAsmAndPath(Uri uri)
  163. {
  164. var asm = GetAssembly(uri.Authority);
  165. return (asm, uri.AbsolutePath);
  166. }
  167. private AssemblyDescriptor GetAssembly(Uri uri)
  168. {
  169. if (uri != null)
  170. {
  171. if (!uri.IsAbsoluteUri)
  172. return null;
  173. if (uri.Scheme == "avares")
  174. return GetResAsmAndPath(uri).asm;
  175. if (uri.Scheme == "resm")
  176. {
  177. var qs = ParseQueryString(uri);
  178. string assemblyName;
  179. if (qs.TryGetValue("assembly", out assemblyName))
  180. {
  181. return GetAssembly(assemblyName);
  182. }
  183. }
  184. }
  185. return null;
  186. }
  187. private AssemblyDescriptor GetAssembly(string name)
  188. {
  189. if (name == null)
  190. throw new ArgumentNullException(nameof(name));
  191. AssemblyDescriptor rv;
  192. if (!AssemblyNameCache.TryGetValue(name, out rv))
  193. {
  194. var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
  195. var match = loadedAssemblies.FirstOrDefault(a => a.GetName().Name == name);
  196. if (match != null)
  197. {
  198. AssemblyNameCache[name] = rv = new AssemblyDescriptor(match);
  199. }
  200. else
  201. {
  202. // iOS does not support loading assemblies dynamically!
  203. //
  204. #if __IOS__
  205. throw new InvalidOperationException(
  206. $"Assembly {name} needs to be referenced and explicitly loaded before loading resources");
  207. #else
  208. AssemblyNameCache[name] = rv = new AssemblyDescriptor(Assembly.Load(name));
  209. #endif
  210. }
  211. }
  212. return rv;
  213. }
  214. private Dictionary<string, string> ParseQueryString(Uri uri)
  215. {
  216. return uri.Query.TrimStart('?')
  217. .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
  218. .Select(p => p.Split('='))
  219. .ToDictionary(p => p[0], p => p[1]);
  220. }
  221. private interface IAssetDescriptor
  222. {
  223. Stream GetStream();
  224. Assembly Assembly { get; }
  225. }
  226. private class AssemblyResourceDescriptor : IAssetDescriptor
  227. {
  228. private readonly Assembly _asm;
  229. private readonly string _name;
  230. public AssemblyResourceDescriptor(Assembly asm, string name)
  231. {
  232. _asm = asm;
  233. _name = name;
  234. }
  235. public Stream GetStream()
  236. {
  237. return _asm.GetManifestResourceStream(_name);
  238. }
  239. public Assembly Assembly => _asm;
  240. }
  241. private class AvaloniaResourceDescriptor : IAssetDescriptor
  242. {
  243. private readonly int _offset;
  244. private readonly int _length;
  245. public Assembly Assembly { get; }
  246. public AvaloniaResourceDescriptor(Assembly asm, int offset, int length)
  247. {
  248. _offset = offset;
  249. _length = length;
  250. Assembly = asm;
  251. }
  252. public Stream GetStream()
  253. {
  254. return new SlicedStream(Assembly.GetManifestResourceStream(AvaloniaResourceName), _offset, _length);
  255. }
  256. }
  257. class SlicedStream : Stream
  258. {
  259. private readonly Stream _baseStream;
  260. private readonly int _from;
  261. public SlicedStream(Stream baseStream, int from, int length)
  262. {
  263. Length = length;
  264. _baseStream = baseStream;
  265. _from = from;
  266. _baseStream.Position = from;
  267. }
  268. public override void Flush()
  269. {
  270. }
  271. public override int Read(byte[] buffer, int offset, int count)
  272. {
  273. return _baseStream.Read(buffer, offset, (int)Math.Min(count, Length - Position));
  274. }
  275. public override long Seek(long offset, SeekOrigin origin)
  276. {
  277. if (origin == SeekOrigin.Begin)
  278. Position = offset;
  279. if (origin == SeekOrigin.End)
  280. Position = _from + Length + offset;
  281. if (origin == SeekOrigin.Current)
  282. Position = Position + offset;
  283. return Position;
  284. }
  285. public override void SetLength(long value) => throw new NotSupportedException();
  286. public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
  287. public override bool CanRead => true;
  288. public override bool CanSeek => _baseStream.CanRead;
  289. public override bool CanWrite => false;
  290. public override long Length { get; }
  291. public override long Position
  292. {
  293. get => _baseStream.Position - _from;
  294. set => _baseStream.Position = value + _from;
  295. }
  296. protected override void Dispose(bool disposing)
  297. {
  298. if (disposing)
  299. _baseStream.Dispose();
  300. }
  301. public override void Close() => _baseStream.Close();
  302. }
  303. private class AssemblyDescriptor
  304. {
  305. public AssemblyDescriptor(Assembly assembly)
  306. {
  307. Assembly = assembly;
  308. if (assembly != null)
  309. {
  310. Resources = assembly.GetManifestResourceNames()
  311. .ToDictionary(n => n, n => (IAssetDescriptor)new AssemblyResourceDescriptor(assembly, n));
  312. Name = assembly.GetName().Name;
  313. using (var resources = assembly.GetManifestResourceStream(AvaloniaResourceName))
  314. {
  315. if (resources != null)
  316. {
  317. Resources.Remove(AvaloniaResourceName);
  318. var indexLength = new BinaryReader(resources).ReadInt32();
  319. var index = AvaloniaResourcesIndexReaderWriter.Read(new SlicedStream(resources, 4, indexLength));
  320. var baseOffset = indexLength + 4;
  321. AvaloniaResources = index.ToDictionary(r => "/" + r.Path.TrimStart('/'), r => (IAssetDescriptor)
  322. new AvaloniaResourceDescriptor(assembly, baseOffset + r.Offset, r.Size));
  323. }
  324. }
  325. }
  326. }
  327. public Assembly Assembly { get; }
  328. public Dictionary<string, IAssetDescriptor> Resources { get; }
  329. public Dictionary<string, IAssetDescriptor> AvaloniaResources { get; }
  330. public string Name { get; }
  331. }
  332. public static void RegisterResUriParsers()
  333. {
  334. if (!UriParser.IsKnownScheme("avares"))
  335. UriParser.Register(new GenericUriParser(
  336. GenericUriParserOptions.GenericAuthority |
  337. GenericUriParserOptions.NoUserInfo |
  338. GenericUriParserOptions.NoPort |
  339. GenericUriParserOptions.NoQuery |
  340. GenericUriParserOptions.NoFragment), "avares", -1);
  341. }
  342. }
  343. }