MobileDocumentSource.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using Avalonia.Controls;
  2. using InABox.Avalonia.Platform;
  3. using Microsoft.Maui.ApplicationModel;
  4. namespace InABox.Avalonia
  5. {
  6. public abstract class MobileDocumentSource
  7. {
  8. public abstract Task<MobileDocument> From(TopLevel window);
  9. }
  10. public abstract class MobileDocumentSource<TOptions> : MobileDocumentSource
  11. where TOptions : class, IMobileDocumentOptions, new()
  12. {
  13. public TOptions Options { get; set; }
  14. protected MobileDocumentSource(TOptions options)
  15. {
  16. Options = options;
  17. }
  18. protected abstract Task<bool> IsEnabled();
  19. protected async Task<bool> IsEnabled<TPermission>()
  20. where TPermission : Permissions.BasePermission, new()
  21. {
  22. var status = await Permissions.CheckStatusAsync<TPermission>();
  23. if (status != PermissionStatus.Granted && status != PermissionStatus.Restricted)
  24. status = await Permissions.RequestAsync<TPermission>();
  25. return status == PermissionStatus.Granted;
  26. }
  27. protected abstract Task<ImageFile> Capture(TopLevel window);
  28. public override async Task<MobileDocument> From(TopLevel window)
  29. {
  30. var result = new MobileDocument();
  31. if (await IsEnabled())
  32. {
  33. try
  34. {
  35. var file = await Capture(window);
  36. if (file?.Data != null)
  37. {
  38. result.FileName = Path.GetFileName(file.FileName);
  39. result.Data = file.Data;
  40. //file.OriginalFilename ?? file.Path);
  41. //await using (var stream = await file.OpenReadAsync())
  42. //{
  43. // BinaryReader br = new BinaryReader(file.Stream);
  44. // result.Data = br.ReadBytes((int)file.Stream.Length);
  45. //}
  46. }
  47. ApplyOptions(result);
  48. }
  49. catch (FeatureNotSupportedException fnsEx)
  50. {
  51. MobileLogging.Log(fnsEx, "Capture(FNS)");
  52. MobileDialog.ShowMessage("This operation is not Supported on this Device!");
  53. }
  54. catch (PermissionException pEx)
  55. {
  56. MobileLogging.Log(pEx, "Capture(PERM)");
  57. MobileDialog.ShowMessage("This operation is not Permitted on this Device!");
  58. }
  59. catch (Exception ex)
  60. {
  61. MobileLogging.Log(ex, "Capture(ERR)");
  62. MobileDialog.ShowMessage("Oops! Something went wrong! Please try again..");
  63. }
  64. }
  65. return result;
  66. }
  67. protected abstract void ApplyOptions(MobileDocument document);
  68. }
  69. }