CanvasPathClipper.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2023, MacDue <macdue@dueutil.tech>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <LibGfx/Painter.h>
  8. #include <LibGfx/Path.h>
  9. namespace Web::HTML {
  10. struct CanvasClip {
  11. Gfx::Path path;
  12. Gfx::Painter::WindingRule winding_rule;
  13. };
  14. class CanvasPathClipper {
  15. public:
  16. static ErrorOr<CanvasPathClipper> create(Gfx::Painter&, CanvasClip const& canvas_clip);
  17. ErrorOr<void> apply_clip(Gfx::Painter& painter);
  18. private:
  19. CanvasPathClipper(RefPtr<Gfx::Bitmap const> saved_clip_region, Gfx::IntRect bounding_box, CanvasClip const& canvas_clip)
  20. : m_saved_clip_region(saved_clip_region)
  21. , m_bounding_box(bounding_box)
  22. , m_canvas_clip(canvas_clip)
  23. {
  24. }
  25. RefPtr<Gfx::Bitmap const> m_saved_clip_region;
  26. Gfx::IntRect m_bounding_box;
  27. CanvasClip const& m_canvas_clip;
  28. };
  29. class ScopedCanvasPathClip {
  30. AK_MAKE_NONMOVABLE(ScopedCanvasPathClip);
  31. AK_MAKE_NONCOPYABLE(ScopedCanvasPathClip);
  32. public:
  33. ScopedCanvasPathClip(Gfx::Painter& painter, Optional<CanvasClip> const& canvas_clip)
  34. : m_painter(painter)
  35. {
  36. if (canvas_clip.has_value()) {
  37. auto clipper = CanvasPathClipper::create(painter, *canvas_clip);
  38. if (!clipper.is_error())
  39. m_canvas_clipper = clipper.release_value();
  40. else
  41. dbgln("CRC2D Error: Failed to apply canvas clip path: {}", clipper.error());
  42. }
  43. }
  44. ~ScopedCanvasPathClip()
  45. {
  46. if (m_canvas_clipper.has_value())
  47. m_canvas_clipper->apply_clip(m_painter).release_value_but_fixme_should_propagate_errors();
  48. }
  49. private:
  50. Gfx::Painter& m_painter;
  51. Optional<CanvasPathClipper> m_canvas_clipper;
  52. };
  53. }