HTMLCanvasElement.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <andreas@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Base64.h>
  7. #include <AK/Checked.h>
  8. #include <AK/MemoryStream.h>
  9. #include <LibGfx/Bitmap.h>
  10. #include <LibGfx/ImageFormats/JPEGWriter.h>
  11. #include <LibGfx/ImageFormats/PNGWriter.h>
  12. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  13. #include <LibWeb/Bindings/HTMLCanvasElementPrototype.h>
  14. #include <LibWeb/CSS/StyleComputer.h>
  15. #include <LibWeb/CSS/StyleValues/CSSKeywordValue.h>
  16. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
  17. #include <LibWeb/CSS/StyleValues/RatioStyleValue.h>
  18. #include <LibWeb/CSS/StyleValues/StyleValueList.h>
  19. #include <LibWeb/DOM/Document.h>
  20. #include <LibWeb/HTML/CanvasRenderingContext2D.h>
  21. #include <LibWeb/HTML/HTMLCanvasElement.h>
  22. #include <LibWeb/HTML/Numbers.h>
  23. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  24. #include <LibWeb/HTML/TraversableNavigable.h>
  25. #include <LibWeb/Layout/CanvasBox.h>
  26. #include <LibWeb/Platform/EventLoopPlugin.h>
  27. #include <LibWeb/WebGL/WebGLRenderingContext.h>
  28. #include <LibWeb/WebIDL/AbstractOperations.h>
  29. namespace Web::HTML {
  30. GC_DEFINE_ALLOCATOR(HTMLCanvasElement);
  31. static constexpr auto max_canvas_area = 16384 * 16384;
  32. HTMLCanvasElement::HTMLCanvasElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  33. : HTMLElement(document, move(qualified_name))
  34. {
  35. }
  36. HTMLCanvasElement::~HTMLCanvasElement() = default;
  37. void HTMLCanvasElement::initialize(JS::Realm& realm)
  38. {
  39. Base::initialize(realm);
  40. WEB_SET_PROTOTYPE_FOR_INTERFACE(HTMLCanvasElement);
  41. }
  42. void HTMLCanvasElement::visit_edges(Cell::Visitor& visitor)
  43. {
  44. Base::visit_edges(visitor);
  45. m_context.visit(
  46. [&](GC::Ref<CanvasRenderingContext2D>& context) {
  47. visitor.visit(context);
  48. },
  49. [&](GC::Ref<WebGL::WebGLRenderingContext>& context) {
  50. visitor.visit(context);
  51. },
  52. [](Empty) {
  53. });
  54. }
  55. void HTMLCanvasElement::apply_presentational_hints(CSS::StyleProperties& style) const
  56. {
  57. // https://html.spec.whatwg.org/multipage/rendering.html#attributes-for-embedded-content-and-images
  58. // The width and height attributes map to the aspect-ratio property on canvas elements.
  59. // FIXME: Multiple elements have aspect-ratio presentational hints, make this into a helper function
  60. // https://html.spec.whatwg.org/multipage/rendering.html#map-to-the-aspect-ratio-property
  61. // if element has both attributes w and h, and parsing those attributes' values using the rules for parsing non-negative integers doesn't generate an error for either
  62. auto w = parse_non_negative_integer(get_attribute_value(HTML::AttributeNames::width));
  63. auto h = parse_non_negative_integer(get_attribute_value(HTML::AttributeNames::height));
  64. if (w.has_value() && h.has_value())
  65. // then the user agent is expected to use the parsed integers as a presentational hint for the 'aspect-ratio' property of the form auto w / h.
  66. style.set_property(CSS::PropertyID::AspectRatio,
  67. CSS::StyleValueList::create(CSS::StyleValueVector {
  68. CSS::CSSKeywordValue::create(CSS::Keyword::Auto),
  69. CSS::RatioStyleValue::create(CSS::Ratio { static_cast<double>(w.value()), static_cast<double>(h.value()) }) },
  70. CSS::StyleValueList::Separator::Space));
  71. }
  72. // https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-width
  73. WebIDL::UnsignedLong HTMLCanvasElement::width() const
  74. {
  75. // The width and height IDL attributes must reflect the respective content attributes of the same name, with the same defaults.
  76. // https://html.spec.whatwg.org/multipage/canvas.html#obtain-numeric-values
  77. // The rules for parsing non-negative integers must be used to obtain their numeric values.
  78. // If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead.
  79. // The width attribute defaults to 300
  80. if (auto width_string = get_attribute(HTML::AttributeNames::width); width_string.has_value()) {
  81. if (auto width = parse_non_negative_integer(*width_string); width.has_value() && *width <= 2147483647)
  82. return *width;
  83. }
  84. return 300;
  85. }
  86. // https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-height
  87. WebIDL::UnsignedLong HTMLCanvasElement::height() const
  88. {
  89. // The width and height IDL attributes must reflect the respective content attributes of the same name, with the same defaults.
  90. // https://html.spec.whatwg.org/multipage/canvas.html#obtain-numeric-values
  91. // The rules for parsing non-negative integers must be used to obtain their numeric values.
  92. // If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead.
  93. // the height attribute defaults to 150
  94. if (auto height_string = get_attribute(HTML::AttributeNames::height); height_string.has_value()) {
  95. if (auto height = parse_non_negative_integer(*height_string); height.has_value() && *height <= 2147483647)
  96. return *height;
  97. }
  98. return 150;
  99. }
  100. void HTMLCanvasElement::reset_context_to_default_state()
  101. {
  102. m_context.visit(
  103. [](GC::Ref<CanvasRenderingContext2D>& context) {
  104. context->reset_to_default_state();
  105. },
  106. [](GC::Ref<WebGL::WebGLRenderingContext>& context) {
  107. context->reset_to_default_state();
  108. },
  109. [](Empty) {
  110. // Do nothing.
  111. });
  112. }
  113. void HTMLCanvasElement::notify_context_about_canvas_size_change()
  114. {
  115. m_context.visit(
  116. [&](GC::Ref<CanvasRenderingContext2D>& context) {
  117. context->set_size(bitmap_size_for_canvas());
  118. },
  119. [&](GC::Ref<WebGL::WebGLRenderingContext>& context) {
  120. context->set_size(bitmap_size_for_canvas());
  121. },
  122. [](Empty) {
  123. // Do nothing.
  124. });
  125. }
  126. WebIDL::ExceptionOr<void> HTMLCanvasElement::set_width(unsigned value)
  127. {
  128. if (value > 2147483647)
  129. value = 300;
  130. TRY(set_attribute(HTML::AttributeNames::width, String::number(value)));
  131. notify_context_about_canvas_size_change();
  132. reset_context_to_default_state();
  133. return {};
  134. }
  135. WebIDL::ExceptionOr<void> HTMLCanvasElement::set_height(WebIDL::UnsignedLong value)
  136. {
  137. if (value > 2147483647)
  138. value = 150;
  139. TRY(set_attribute(HTML::AttributeNames::height, String::number(value)));
  140. notify_context_about_canvas_size_change();
  141. reset_context_to_default_state();
  142. return {};
  143. }
  144. GC::Ptr<Layout::Node> HTMLCanvasElement::create_layout_node(CSS::StyleProperties style)
  145. {
  146. return heap().allocate<Layout::CanvasBox>(document(), *this, move(style));
  147. }
  148. void HTMLCanvasElement::adjust_computed_style(CSS::StyleProperties& style)
  149. {
  150. // https://drafts.csswg.org/css-display-3/#unbox
  151. if (style.display().is_contents())
  152. style.set_property(CSS::PropertyID::Display, CSS::DisplayStyleValue::create(CSS::Display::from_short(CSS::Display::Short::None)));
  153. }
  154. HTMLCanvasElement::HasOrCreatedContext HTMLCanvasElement::create_2d_context()
  155. {
  156. if (!m_context.has<Empty>())
  157. return m_context.has<GC::Ref<CanvasRenderingContext2D>>() ? HasOrCreatedContext::Yes : HasOrCreatedContext::No;
  158. m_context = CanvasRenderingContext2D::create(realm(), *this);
  159. return HasOrCreatedContext::Yes;
  160. }
  161. JS::ThrowCompletionOr<HTMLCanvasElement::HasOrCreatedContext> HTMLCanvasElement::create_webgl_context(JS::Value options)
  162. {
  163. if (!m_context.has<Empty>())
  164. return m_context.has<GC::Ref<WebGL::WebGLRenderingContext>>() ? HasOrCreatedContext::Yes : HasOrCreatedContext::No;
  165. auto maybe_context = TRY(WebGL::WebGLRenderingContext::create(realm(), *this, options));
  166. if (!maybe_context)
  167. return HasOrCreatedContext::No;
  168. m_context = GC::Ref<WebGL::WebGLRenderingContext>(*maybe_context);
  169. return HasOrCreatedContext::Yes;
  170. }
  171. // https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-getcontext
  172. JS::ThrowCompletionOr<HTMLCanvasElement::RenderingContext> HTMLCanvasElement::get_context(String const& type, JS::Value options)
  173. {
  174. // 1. If options is not an object, then set options to null.
  175. if (!options.is_object())
  176. options = JS::js_null();
  177. // 2. Set options to the result of converting options to a JavaScript value.
  178. // NOTE: No-op.
  179. // 3. Run the steps in the cell of the following table whose column header matches this canvas element's canvas context mode and whose row header matches contextId:
  180. // NOTE: See the spec for the full table.
  181. if (type == "2d"sv) {
  182. if (create_2d_context() == HasOrCreatedContext::Yes)
  183. return GC::make_root(*m_context.get<GC::Ref<HTML::CanvasRenderingContext2D>>());
  184. return Empty {};
  185. }
  186. // NOTE: The WebGL spec says "experimental-webgl" is also acceptable and must be equivalent to "webgl". Other engines accept this, so we do too.
  187. if (type.is_one_of("webgl"sv, "experimental-webgl"sv)) {
  188. if (TRY(create_webgl_context(options)) == HasOrCreatedContext::Yes)
  189. return GC::make_root(*m_context.get<GC::Ref<WebGL::WebGLRenderingContext>>());
  190. return Empty {};
  191. }
  192. return Empty {};
  193. }
  194. Gfx::IntSize HTMLCanvasElement::bitmap_size_for_canvas(size_t minimum_width, size_t minimum_height) const
  195. {
  196. auto width = max(this->width(), minimum_width);
  197. auto height = max(this->height(), minimum_height);
  198. Checked<size_t> area = width;
  199. area *= height;
  200. if (area.has_overflow()) {
  201. dbgln("Refusing to create {}x{} canvas (overflow)", width, height);
  202. return {};
  203. }
  204. if (area.value() > max_canvas_area) {
  205. dbgln("Refusing to create {}x{} canvas (exceeds maximum size)", width, height);
  206. return {};
  207. }
  208. return Gfx::IntSize(width, height);
  209. }
  210. struct SerializeBitmapResult {
  211. ByteBuffer buffer;
  212. StringView mime_type;
  213. };
  214. // https://html.spec.whatwg.org/multipage/canvas.html#a-serialisation-of-the-bitmap-as-a-file
  215. static ErrorOr<SerializeBitmapResult> serialize_bitmap(Gfx::Bitmap const& bitmap, StringView type, JS::Value quality)
  216. {
  217. // If type is an image format that supports variable quality (such as "image/jpeg"), quality is given, and type is not "image/png", then,
  218. // if quality is a Number in the range 0.0 to 1.0 inclusive, the user agent must treat quality as the desired quality level.
  219. // Otherwise, the user agent must use its default quality value, as if the quality argument had not been given.
  220. bool valid_quality = quality.is_number() && quality.as_double() >= 0.0 && quality.as_double() <= 1.0;
  221. if (type.equals_ignoring_ascii_case("image/jpeg"sv)) {
  222. AllocatingMemoryStream file;
  223. Gfx::JPEGWriter::Options jpeg_options;
  224. if (valid_quality)
  225. jpeg_options.quality = static_cast<int>(quality.as_double() * 100);
  226. TRY(Gfx::JPEGWriter::encode(file, bitmap, jpeg_options));
  227. return SerializeBitmapResult { TRY(file.read_until_eof()), "image/jpeg"sv };
  228. }
  229. // User agents must support PNG ("image/png"). User agents may support other types.
  230. // If the user agent does not support the requested type, then it must create the file using the PNG format. [PNG]
  231. return SerializeBitmapResult { TRY(Gfx::PNGWriter::encode(bitmap)), "image/png"sv };
  232. }
  233. // https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-todataurl
  234. String HTMLCanvasElement::to_data_url(StringView type, JS::Value quality)
  235. {
  236. // It is possible the the canvas doesn't have a associated bitmap so create one
  237. allocate_painting_surface_if_needed();
  238. auto surface = this->surface();
  239. auto size = bitmap_size_for_canvas();
  240. if (!surface) {
  241. // If the context is not initialized yet, we need to allocate transparent surface for serialization
  242. auto skia_backend_context = navigable()->traversable_navigable()->skia_backend_context();
  243. surface = Gfx::PaintingSurface::create_with_size(skia_backend_context, size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied);
  244. }
  245. // FIXME: 1. If this canvas element's bitmap's origin-clean flag is set to false, then throw a "SecurityError" DOMException.
  246. // 2. If this canvas element's bitmap has no pixels (i.e. either its horizontal dimension or its vertical dimension is zero)
  247. // then return the string "data:,". (This is the shortest data: URL; it represents the empty string in a text/plain resource.)
  248. if (!surface)
  249. return "data:,"_string;
  250. // 3. Let file be a serialization of this canvas element's bitmap as a file, passing type and quality if given.
  251. auto snapshot = Gfx::ImmutableBitmap::create_snapshot_from_painting_surface(*surface);
  252. auto bitmap = MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, surface->size()));
  253. surface->read_into_bitmap(*bitmap);
  254. auto file = serialize_bitmap(bitmap, type, move(quality));
  255. // 4. If file is null then return "data:,".
  256. if (file.is_error()) {
  257. dbgln("HTMLCanvasElement: Failed to encode canvas bitmap to {}: {}", type, file.error());
  258. return "data:,"_string;
  259. }
  260. // 5. Return a data: URL representing file. [RFC2397]
  261. auto base64_encoded_or_error = encode_base64(file.value().buffer);
  262. if (base64_encoded_or_error.is_error()) {
  263. return "data:,"_string;
  264. }
  265. return MUST(URL::create_with_data(file.value().mime_type, base64_encoded_or_error.release_value(), true).to_string());
  266. }
  267. // https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-toblob
  268. WebIDL::ExceptionOr<void> HTMLCanvasElement::to_blob(GC::Ref<WebIDL::CallbackType> callback, StringView type, JS::Value quality)
  269. {
  270. // It is possible the the canvas doesn't have a associated bitmap so create one
  271. allocate_painting_surface_if_needed();
  272. auto surface = this->surface();
  273. auto size = bitmap_size_for_canvas();
  274. if (!surface) {
  275. // If the context is not initialized yet, we need to allocate transparent surface for serialization
  276. auto skia_backend_context = navigable()->traversable_navigable()->skia_backend_context();
  277. surface = Gfx::PaintingSurface::create_with_size(skia_backend_context, size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied);
  278. }
  279. // FIXME: 1. If this canvas element's bitmap's origin-clean flag is set to false, then throw a "SecurityError" DOMException.
  280. // 2. Let result be null.
  281. RefPtr<Gfx::Bitmap> bitmap_result;
  282. // 3. If this canvas element's bitmap has pixels (i.e., neither its horizontal dimension nor its vertical dimension is zero),
  283. // then set result to a copy of this canvas element's bitmap.
  284. if (surface) {
  285. bitmap_result = MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, surface->size()));
  286. surface->read_into_bitmap(*bitmap_result);
  287. }
  288. // 4. Run these steps in parallel:
  289. Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap(), [this, callback, bitmap_result, type, quality] {
  290. // 1. If result is non-null, then set result to a serialization of result as a file with type and quality if given.
  291. Optional<SerializeBitmapResult> file_result;
  292. if (bitmap_result) {
  293. if (auto result = serialize_bitmap(*bitmap_result, type, move(quality)); !result.is_error())
  294. file_result = result.release_value();
  295. }
  296. // 2. Queue an element task on the canvas blob serialization task source given the canvas element to run these steps:
  297. queue_an_element_task(Task::Source::CanvasBlobSerializationTask, [this, callback, file_result = move(file_result)] {
  298. auto maybe_error = Bindings::throw_dom_exception_if_needed(vm(), [&]() -> WebIDL::ExceptionOr<void> {
  299. // 1. If result is non-null, then set result to a new Blob object, created in the relevant realm of this canvas element, representing result. [FILEAPI]
  300. GC::Ptr<FileAPI::Blob> blob_result;
  301. if (file_result.has_value())
  302. blob_result = FileAPI::Blob::create(realm(), file_result->buffer, TRY_OR_THROW_OOM(vm(), String::from_utf8(file_result->mime_type)));
  303. // 2. Invoke callback with « result ».
  304. TRY(WebIDL::invoke_callback(*callback, {}, move(blob_result)));
  305. return {};
  306. });
  307. if (maybe_error.is_throw_completion())
  308. report_exception(maybe_error.throw_completion(), realm());
  309. });
  310. }));
  311. return {};
  312. }
  313. void HTMLCanvasElement::present()
  314. {
  315. if (auto surface = this->surface())
  316. surface->flush();
  317. m_context.visit(
  318. [](GC::Ref<CanvasRenderingContext2D>&) {
  319. // Do nothing, CRC2D writes directly to the canvas bitmap.
  320. },
  321. [](GC::Ref<WebGL::WebGLRenderingContext>& context) {
  322. context->present();
  323. },
  324. [](Empty) {
  325. // Do nothing.
  326. });
  327. }
  328. RefPtr<Gfx::PaintingSurface> HTMLCanvasElement::surface() const
  329. {
  330. return m_context.visit(
  331. [&](GC::Ref<CanvasRenderingContext2D> const& context) {
  332. return context->surface();
  333. },
  334. [&](GC::Ref<WebGL::WebGLRenderingContext> const& context) -> RefPtr<Gfx::PaintingSurface> {
  335. return context->surface();
  336. },
  337. [](Empty) -> RefPtr<Gfx::PaintingSurface> {
  338. return {};
  339. });
  340. }
  341. void HTMLCanvasElement::allocate_painting_surface_if_needed()
  342. {
  343. m_context.visit(
  344. [&](GC::Ref<CanvasRenderingContext2D>& context) {
  345. context->allocate_painting_surface_if_needed();
  346. },
  347. [&](GC::Ref<WebGL::WebGLRenderingContext>& context) {
  348. context->allocate_painting_surface_if_needed();
  349. },
  350. [](Empty) {
  351. // Do nothing.
  352. });
  353. }
  354. }