CommunicationService.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System.Text.Json;
  2. using SkiaSharp;
  3. namespace QuestPDF.Previewer;
  4. class CommunicationService
  5. {
  6. public static CommunicationService Instance { get; } = new ();
  7. public event Action<DocumentStructure>? OnDocumentUpdated;
  8. public Action<RenderedPageSnapshot> OnPageSnapshotsProvided { get; set; }
  9. private SocketServer? Server { get; set; }
  10. private readonly JsonSerializerOptions JsonSerializerOptions = new()
  11. {
  12. PropertyNameCaseInsensitive = true
  13. };
  14. private CommunicationService()
  15. {
  16. }
  17. public void Start(int port)
  18. {
  19. Server = new SocketServer("127.0.0.1", port);
  20. Server.OnMessageReceived += async message =>
  21. {
  22. var content = JsonDocument.Parse(message).RootElement;
  23. var channel = content.GetProperty("Channel").GetString();
  24. if (channel == "ping/check")
  25. {
  26. if (OnDocumentUpdated == null)
  27. return;
  28. var response = new SocketMessage<string>
  29. {
  30. Channel = "ping/ok",
  31. Payload = GetType().Assembly.GetName().Version.ToString()
  32. };
  33. Server.SendMessage(JsonSerializer.Serialize(response));
  34. }
  35. else if (channel == "version/check")
  36. {
  37. var response = new SocketMessage<string>
  38. {
  39. Channel = "version/provide",
  40. Payload = GetType().Assembly.GetName().Version.ToString()
  41. };
  42. Server.SendMessage(JsonSerializer.Serialize(response));
  43. }
  44. else if (channel == "preview/update")
  45. {
  46. var documentStructure = content.GetProperty("Payload").Deserialize<DocumentStructure>();
  47. Task.Run(() => OnDocumentUpdated(documentStructure));
  48. }
  49. else if (channel == "preview/updatePage")
  50. {
  51. var previewData = content.GetProperty("Payload").Deserialize<PageSnapshotCommunicationData>();
  52. var image = SKImage.FromEncodedData(previewData.ImageData).ToRasterImage(true);
  53. var renderedPage = new RenderedPageSnapshot
  54. {
  55. ZoomLevel = previewData.ZoomLevel,
  56. PageIndex = previewData.PageIndex,
  57. Image = image
  58. };
  59. Task.Run(() => OnPageSnapshotsProvided(renderedPage));
  60. }
  61. };
  62. Server.Start();
  63. }
  64. public void RequestNewPage(PageSnapshotIndex index)
  65. {
  66. Task.Run(() =>
  67. {
  68. var message = new SocketMessage<PageSnapshotIndex>
  69. {
  70. Channel = "preview/requestPage",
  71. Payload = index
  72. };
  73. Server.SendMessage(JsonSerializer.Serialize(message));
  74. });
  75. }
  76. }