HTMLCanvasElement.cpp 19 KB

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