BrushLibrary.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using Avalonia.Platform;
  2. using PixiEditor.ChangeableDocument.Changeables.Graph.Interfaces;
  3. using PixiEditor.Helpers;
  4. using PixiEditor.Models.BrushEngine;
  5. using PixiEditor.Models.IO;
  6. namespace PixiEditor.Models.Controllers;
  7. internal class BrushLibrary
  8. {
  9. private List<Brush> brushes = new List<Brush>();
  10. public IReadOnlyList<Brush> Brushes => brushes;
  11. private string pathToBrushes;
  12. public string PathToBrushes => pathToBrushes;
  13. public BrushLibrary(string pathToBrushes)
  14. {
  15. this.pathToBrushes = pathToBrushes;
  16. }
  17. private void LoadBuiltIn()
  18. {
  19. Uri brushesUri = new Uri("avares://PixiEditor/Data/Brushes/");
  20. var assets = AssetLoader.GetAssets(brushesUri, null);
  21. foreach (var asset in assets)
  22. {
  23. string localPath = asset.LocalPath;
  24. if (localPath.EndsWith(".pixi", StringComparison.OrdinalIgnoreCase))
  25. {
  26. try
  27. {
  28. var fullUri = new Uri(brushesUri, asset);
  29. using var stream = AssetLoader.Open(fullUri);
  30. byte[] buffer = new byte[stream.Length];
  31. stream.ReadExactly(buffer, 0, buffer.Length);
  32. var doc = Importer.ImportDocument(buffer, null);
  33. var brush = new Brush(Path.GetFileNameWithoutExtension(localPath), doc);
  34. brushes.Add(brush);
  35. }
  36. catch (Exception ex)
  37. {
  38. Console.WriteLine($"Failed to load built-in brush from {asset}: {ex.Message}");
  39. }
  40. }
  41. }
  42. }
  43. private void LoadBrushesFromPath(string path)
  44. {
  45. if (!Directory.Exists(path))
  46. return;
  47. var brushFiles = Directory.GetFiles(path, "*.pixi", SearchOption.AllDirectories);
  48. foreach (var file in brushFiles)
  49. {
  50. try
  51. {
  52. var doc = Importer.ImportDocument(file, false);
  53. var brush = new Brush(Path.GetFileNameWithoutExtension(file), doc);
  54. brushes.Add(brush);
  55. }
  56. catch (Exception ex)
  57. {
  58. Console.WriteLine($"Failed to load brush from {file}: {ex.Message}");
  59. }
  60. }
  61. }
  62. public void LoadBrushes()
  63. {
  64. LoadBuiltIn();
  65. LoadBrushesFromPath(pathToBrushes);
  66. }
  67. public void Add(Brush brush)
  68. {
  69. if (!brushes.Contains(brush))
  70. brushes.Add(brush);
  71. }
  72. }