CanvasState.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  3. * Copyright (c) 2023, MacDue <macdue@dueutil.tech>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/Variant.h>
  9. #include <AK/Vector.h>
  10. #include <LibGfx/AffineTransform.h>
  11. #include <LibGfx/Color.h>
  12. #include <LibGfx/PaintStyle.h>
  13. #include <LibWeb/HTML/CanvasGradient.h>
  14. namespace Web::HTML {
  15. // https://html.spec.whatwg.org/multipage/canvas.html#canvasstate
  16. class CanvasState {
  17. public:
  18. virtual ~CanvasState() = default;
  19. void save();
  20. void restore();
  21. void reset();
  22. bool is_context_lost();
  23. using FillOrStrokeVariant = Variant<Gfx::Color, JS::Handle<CanvasGradient>>;
  24. struct FillOrStrokeStyle {
  25. FillOrStrokeStyle(Gfx::Color color)
  26. : m_fill_or_stoke_style(color)
  27. {
  28. }
  29. FillOrStrokeStyle(JS::Handle<CanvasGradient> gradient)
  30. : m_fill_or_stoke_style(gradient)
  31. {
  32. }
  33. NonnullRefPtr<Gfx::PaintStyle> to_gfx_paint_style();
  34. Optional<Gfx::Color> as_color() const;
  35. Gfx::Color to_color_but_fixme_should_accept_any_paint_style() const;
  36. Variant<DeprecatedString, JS::Handle<CanvasGradient>> to_js_fill_or_stoke_style() const
  37. {
  38. if (auto* handle = m_fill_or_stoke_style.get_pointer<JS::Handle<CanvasGradient>>())
  39. return *handle;
  40. return m_fill_or_stoke_style.get<Gfx::Color>().to_deprecated_string();
  41. }
  42. private:
  43. FillOrStrokeVariant m_fill_or_stoke_style;
  44. RefPtr<Gfx::PaintStyle> m_color_paint_style { nullptr };
  45. };
  46. // https://html.spec.whatwg.org/multipage/canvas.html#drawing-state
  47. struct DrawingState {
  48. Gfx::AffineTransform transform;
  49. FillOrStrokeStyle fill_style { Gfx::Color::Black };
  50. FillOrStrokeStyle stroke_style { Gfx::Color::Black };
  51. float line_width { 1 };
  52. };
  53. DrawingState& drawing_state() { return m_drawing_state; }
  54. DrawingState const& drawing_state() const { return m_drawing_state; }
  55. void clear_drawing_state_stack() { m_drawing_state_stack.clear(); }
  56. void reset_drawing_state() { m_drawing_state = {}; }
  57. virtual void reset_to_default_state() = 0;
  58. protected:
  59. CanvasState() = default;
  60. private:
  61. DrawingState m_drawing_state;
  62. Vector<DrawingState> m_drawing_state_stack;
  63. // https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-context-lost
  64. bool m_context_lost { false };
  65. };
  66. }