PreviewerWindowViewModel.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System.Collections.ObjectModel;
  2. using System.Diagnostics;
  3. using ReactiveUI;
  4. using Unit = System.Reactive.Unit;
  5. using Avalonia.Threading;
  6. namespace QuestPDF.Previewer
  7. {
  8. internal class PreviewerWindowViewModel : ReactiveObject
  9. {
  10. private ObservableCollection<PreviewPage> _pages = new();
  11. public ObservableCollection<PreviewPage> Pages
  12. {
  13. get => _pages;
  14. set => this.RaiseAndSetIfChanged(ref _pages, value);
  15. }
  16. private float _currentScroll;
  17. public float CurrentScroll
  18. {
  19. get => _currentScroll;
  20. set => this.RaiseAndSetIfChanged(ref _currentScroll, value);
  21. }
  22. private float _scrollViewportSize;
  23. public float ScrollViewportSize
  24. {
  25. get => _scrollViewportSize;
  26. set
  27. {
  28. this.RaiseAndSetIfChanged(ref _scrollViewportSize, value);
  29. VerticalScrollbarVisible = value < 1;
  30. }
  31. }
  32. private bool _verticalScrollbarVisible;
  33. public bool VerticalScrollbarVisible
  34. {
  35. get => _verticalScrollbarVisible;
  36. private set => Dispatcher.UIThread.Post(() => this.RaiseAndSetIfChanged(ref _verticalScrollbarVisible, value));
  37. }
  38. public ReactiveCommand<Unit, Unit> ShowPdfCommand { get; }
  39. public ReactiveCommand<Unit, Unit> ShowDocumentationCommand { get; }
  40. public ReactiveCommand<Unit, Unit> SponsorProjectCommand { get; }
  41. public PreviewerWindowViewModel()
  42. {
  43. CommunicationService.Instance.OnDocumentRefreshed += HandleUpdatePreview;
  44. ShowPdfCommand = ReactiveCommand.Create(ShowPdf);
  45. ShowDocumentationCommand = ReactiveCommand.Create(() => OpenLink("https://www.questpdf.com/api-reference/index.html"));
  46. SponsorProjectCommand = ReactiveCommand.Create(() => OpenLink("https://github.com/sponsors/QuestPDF"));
  47. }
  48. private void ShowPdf()
  49. {
  50. var filePath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.pdf");
  51. Helpers.GeneratePdfFromDocumentSnapshots(filePath, Pages);
  52. OpenLink(filePath);
  53. }
  54. private void OpenLink(string path)
  55. {
  56. using var openBrowserProcess = new Process
  57. {
  58. StartInfo = new()
  59. {
  60. UseShellExecute = true,
  61. FileName = path
  62. }
  63. };
  64. openBrowserProcess.Start();
  65. }
  66. private void HandleUpdatePreview(ICollection<PreviewPage> pages)
  67. {
  68. var oldPages = Pages;
  69. Pages.Clear();
  70. Pages = new ObservableCollection<PreviewPage>(pages);
  71. foreach (var page in oldPages)
  72. page.Picture.Dispose();
  73. }
  74. }
  75. }