closure.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright (c) 2010 LearnBoost <tj@learnboost.com>
  2. #pragma once
  3. #include "Canvas.h"
  4. #ifdef HAVE_JPEG
  5. #include <jpeglib.h>
  6. #endif
  7. #include <nan.h>
  8. #include <png.h>
  9. #include <stdint.h> // node < 7 uses libstdc++ on macOS which lacks complete c++11
  10. #include <vector>
  11. #ifndef PAGE_SIZE
  12. #define PAGE_SIZE 4096
  13. #endif
  14. /*
  15. * Image encoding closures.
  16. */
  17. struct Closure {
  18. std::vector<uint8_t> vec;
  19. Nan::Callback cb;
  20. Canvas* canvas = nullptr;
  21. cairo_status_t status = CAIRO_STATUS_SUCCESS;
  22. static cairo_status_t writeVec(void *c, const uint8_t *odata, unsigned len) {
  23. Closure* closure = static_cast<Closure*>(c);
  24. try {
  25. closure->vec.insert(closure->vec.end(), odata, odata + len);
  26. } catch (const std::bad_alloc &) {
  27. return CAIRO_STATUS_NO_MEMORY;
  28. }
  29. return CAIRO_STATUS_SUCCESS;
  30. }
  31. Closure(Canvas* canvas) : canvas(canvas) {};
  32. };
  33. struct PdfSvgClosure : Closure {
  34. PdfSvgClosure(Canvas* canvas) : Closure(canvas) {};
  35. };
  36. struct PngClosure : Closure {
  37. uint32_t compressionLevel = 6;
  38. uint32_t filters = PNG_ALL_FILTERS;
  39. uint32_t resolution = 0; // 0 = unspecified
  40. // Indexed PNGs:
  41. uint32_t nPaletteColors = 0;
  42. uint8_t* palette = nullptr;
  43. uint8_t backgroundIndex = 0;
  44. PngClosure(Canvas* canvas) : Closure(canvas) {};
  45. };
  46. #ifdef HAVE_JPEG
  47. struct JpegClosure : Closure {
  48. uint32_t quality = 75;
  49. uint32_t chromaSubsampling = 2;
  50. bool progressive = false;
  51. jpeg_destination_mgr* jpeg_dest_mgr = nullptr;
  52. static void init_destination(j_compress_ptr cinfo);
  53. static boolean empty_output_buffer(j_compress_ptr cinfo);
  54. static void term_destination(j_compress_ptr cinfo);
  55. JpegClosure(Canvas* canvas) : Closure(canvas) {
  56. jpeg_dest_mgr = new jpeg_destination_mgr;
  57. jpeg_dest_mgr->init_destination = init_destination;
  58. jpeg_dest_mgr->empty_output_buffer = empty_output_buffer;
  59. jpeg_dest_mgr->term_destination = term_destination;
  60. };
  61. ~JpegClosure() {
  62. delete jpeg_dest_mgr;
  63. }
  64. };
  65. #endif