HTMLCanvasElement.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.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/CSS/StyleComputer.h>
  14. #include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
  15. #include <LibWeb/CSS/StyleValues/RatioStyleValue.h>
  16. #include <LibWeb/CSS/StyleValues/StyleValueList.h>
  17. #include <LibWeb/DOM/Document.h>
  18. #include <LibWeb/HTML/CanvasRenderingContext2D.h>
  19. #include <LibWeb/HTML/HTMLCanvasElement.h>
  20. #include <LibWeb/HTML/Numbers.h>
  21. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  22. #include <LibWeb/Layout/CanvasBox.h>
  23. #include <LibWeb/Platform/EventLoopPlugin.h>
  24. #include <LibWeb/WebIDL/AbstractOperations.h>
  25. namespace Web::HTML {
  26. JS_DEFINE_ALLOCATOR(HTMLCanvasElement);
  27. static constexpr auto max_canvas_area = 16384 * 16384;
  28. HTMLCanvasElement::HTMLCanvasElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  29. : HTMLElement(document, move(qualified_name))
  30. {
  31. }
  32. HTMLCanvasElement::~HTMLCanvasElement() = default;
  33. void HTMLCanvasElement::initialize(JS::Realm& realm)
  34. {
  35. Base::initialize(realm);
  36. WEB_SET_PROTOTYPE_FOR_INTERFACE(HTMLCanvasElement);
  37. }
  38. void HTMLCanvasElement::visit_edges(Cell::Visitor& visitor)
  39. {
  40. Base::visit_edges(visitor);
  41. m_context.visit(
  42. [&](JS::NonnullGCPtr<CanvasRenderingContext2D>& context) {
  43. visitor.visit(context);
  44. },
  45. [&](JS::NonnullGCPtr<WebGL::WebGLRenderingContext>& context) {
  46. visitor.visit(context);
  47. },
  48. [](Empty) {
  49. });
  50. }
  51. void HTMLCanvasElement::apply_presentational_hints(CSS::StyleProperties& style) const
  52. {
  53. // https://html.spec.whatwg.org/multipage/rendering.html#attributes-for-embedded-content-and-images
  54. // The width and height attributes map to the aspect-ratio property on canvas elements.
  55. // FIXME: Multiple elements have aspect-ratio presentational hints, make this into a helper function
  56. // https://html.spec.whatwg.org/multipage/rendering.html#map-to-the-aspect-ratio-property
  57. // 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
  58. auto w = parse_non_negative_integer(get_attribute_value(HTML::AttributeNames::width));
  59. auto h = parse_non_negative_integer(get_attribute_value(HTML::AttributeNames::height));
  60. if (w.has_value() && h.has_value())
  61. // 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.
  62. style.set_property(CSS::PropertyID::AspectRatio,
  63. CSS::StyleValueList::create(CSS::StyleValueVector {
  64. CSS::IdentifierStyleValue::create(CSS::ValueID::Auto),
  65. CSS::RatioStyleValue::create(CSS::Ratio { static_cast<double>(w.value()), static_cast<double>(h.value()) }) },
  66. CSS::StyleValueList::Separator::Space));
  67. }
  68. unsigned HTMLCanvasElement::width() const
  69. {
  70. // https://html.spec.whatwg.org/multipage/canvas.html#obtain-numeric-values
  71. // The rules for parsing non-negative integers must be used to obtain their numeric values.
  72. // If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead.
  73. // The width attribute defaults to 300
  74. return parse_non_negative_integer(get_attribute_value(HTML::AttributeNames::width)).value_or(300);
  75. }
  76. unsigned HTMLCanvasElement::height() const
  77. {
  78. // https://html.spec.whatwg.org/multipage/canvas.html#obtain-numeric-values
  79. // The rules for parsing non-negative integers must be used to obtain their numeric values.
  80. // If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead.
  81. // the height attribute defaults to 150
  82. return parse_non_negative_integer(get_attribute_value(HTML::AttributeNames::height)).value_or(150);
  83. }
  84. void HTMLCanvasElement::reset_context_to_default_state()
  85. {
  86. m_context.visit(
  87. [](JS::NonnullGCPtr<CanvasRenderingContext2D>& context) {
  88. context->reset_to_default_state();
  89. },
  90. [](JS::NonnullGCPtr<WebGL::WebGLRenderingContext>&) {
  91. TODO();
  92. },
  93. [](Empty) {
  94. // Do nothing.
  95. });
  96. }
  97. WebIDL::ExceptionOr<void> HTMLCanvasElement::set_width(unsigned value)
  98. {
  99. TRY(set_attribute(HTML::AttributeNames::width, MUST(String::number(value))));
  100. m_bitmap = nullptr;
  101. reset_context_to_default_state();
  102. return {};
  103. }
  104. WebIDL::ExceptionOr<void> HTMLCanvasElement::set_height(unsigned value)
  105. {
  106. TRY(set_attribute(HTML::AttributeNames::height, MUST(String::number(value))));
  107. m_bitmap = nullptr;
  108. reset_context_to_default_state();
  109. return {};
  110. }
  111. JS::GCPtr<Layout::Node> HTMLCanvasElement::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style)
  112. {
  113. return heap().allocate_without_realm<Layout::CanvasBox>(document(), *this, move(style));
  114. }
  115. HTMLCanvasElement::HasOrCreatedContext HTMLCanvasElement::create_2d_context()
  116. {
  117. if (!m_context.has<Empty>())
  118. return m_context.has<JS::NonnullGCPtr<CanvasRenderingContext2D>>() ? HasOrCreatedContext::Yes : HasOrCreatedContext::No;
  119. m_context = CanvasRenderingContext2D::create(realm(), *this);
  120. return HasOrCreatedContext::Yes;
  121. }
  122. JS::ThrowCompletionOr<HTMLCanvasElement::HasOrCreatedContext> HTMLCanvasElement::create_webgl_context(JS::Value options)
  123. {
  124. if (!m_context.has<Empty>())
  125. return m_context.has<JS::NonnullGCPtr<WebGL::WebGLRenderingContext>>() ? HasOrCreatedContext::Yes : HasOrCreatedContext::No;
  126. auto maybe_context = TRY(WebGL::WebGLRenderingContext::create(realm(), *this, options));
  127. if (!maybe_context)
  128. return HasOrCreatedContext::No;
  129. m_context = JS::NonnullGCPtr<WebGL::WebGLRenderingContext>(*maybe_context);
  130. return HasOrCreatedContext::Yes;
  131. }
  132. // https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-getcontext
  133. JS::ThrowCompletionOr<HTMLCanvasElement::RenderingContext> HTMLCanvasElement::get_context(String const& type, JS::Value options)
  134. {
  135. // 1. If options is not an object, then set options to null.
  136. if (!options.is_object())
  137. options = JS::js_null();
  138. // 2. Set options to the result of converting options to a JavaScript value.
  139. // NOTE: No-op.
  140. // 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:
  141. // NOTE: See the spec for the full table.
  142. if (type == "2d"sv) {
  143. if (create_2d_context() == HasOrCreatedContext::Yes)
  144. return JS::make_handle(*m_context.get<JS::NonnullGCPtr<HTML::CanvasRenderingContext2D>>());
  145. return Empty {};
  146. }
  147. // NOTE: The WebGL spec says "experimental-webgl" is also acceptable and must be equivalent to "webgl". Other engines accept this, so we do too.
  148. if (type.is_one_of("webgl"sv, "experimental-webgl"sv)) {
  149. if (TRY(create_webgl_context(options)) == HasOrCreatedContext::Yes)
  150. return JS::make_handle(*m_context.get<JS::NonnullGCPtr<WebGL::WebGLRenderingContext>>());
  151. return Empty {};
  152. }
  153. return Empty {};
  154. }
  155. static Gfx::IntSize bitmap_size_for_canvas(HTMLCanvasElement const& canvas, size_t minimum_width, size_t minimum_height)
  156. {
  157. auto width = max(canvas.width(), minimum_width);
  158. auto height = max(canvas.height(), minimum_height);
  159. Checked<size_t> area = width;
  160. area *= height;
  161. if (area.has_overflow()) {
  162. dbgln("Refusing to create {}x{} canvas (overflow)", width, height);
  163. return {};
  164. }
  165. if (area.value() > max_canvas_area) {
  166. dbgln("Refusing to create {}x{} canvas (exceeds maximum size)", width, height);
  167. return {};
  168. }
  169. return Gfx::IntSize(width, height);
  170. }
  171. bool HTMLCanvasElement::create_bitmap(size_t minimum_width, size_t minimum_height)
  172. {
  173. auto size = bitmap_size_for_canvas(*this, minimum_width, minimum_height);
  174. if (size.is_empty()) {
  175. m_bitmap = nullptr;
  176. return false;
  177. }
  178. if (!m_bitmap || m_bitmap->size() != size) {
  179. auto bitmap_or_error = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, size);
  180. if (bitmap_or_error.is_error())
  181. return false;
  182. m_bitmap = bitmap_or_error.release_value_but_fixme_should_propagate_errors();
  183. }
  184. return m_bitmap;
  185. }
  186. struct SerializeBitmapResult {
  187. ByteBuffer buffer;
  188. StringView mime_type;
  189. };
  190. // https://html.spec.whatwg.org/multipage/canvas.html#a-serialisation-of-the-bitmap-as-a-file
  191. static ErrorOr<SerializeBitmapResult> serialize_bitmap(Gfx::Bitmap const& bitmap, StringView type, Optional<double> quality)
  192. {
  193. // If type is an image format that supports variable quality (such as "image/jpeg"), quality is given, and type is not "image/png", then,
  194. // if Type(quality) is Number, and quality is in the range 0.0 to 1.0 inclusive, the user agent must treat quality as the desired quality level.
  195. // Otherwise, the user agent must use its default quality value, as if the quality argument had not been given.
  196. if (quality.has_value() && !(*quality >= 0.0 && *quality <= 1.0))
  197. quality = OptionalNone {};
  198. if (type.equals_ignoring_ascii_case("image/jpeg"sv)) {
  199. AllocatingMemoryStream file;
  200. Gfx::JPEGWriter::Options jpeg_options;
  201. if (quality.has_value())
  202. jpeg_options.quality = static_cast<int>(quality.value() * 100);
  203. TRY(Gfx::JPEGWriter::encode(file, bitmap, jpeg_options));
  204. return SerializeBitmapResult { TRY(file.read_until_eof()), "image/jpeg"sv };
  205. }
  206. // User agents must support PNG ("image/png"). User agents may support other types.
  207. // If the user agent does not support the requested type, then it must create the file using the PNG format. [PNG]
  208. return SerializeBitmapResult { TRY(Gfx::PNGWriter::encode(bitmap)), "image/png"sv };
  209. }
  210. // https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-todataurl
  211. String HTMLCanvasElement::to_data_url(StringView type, Optional<double> quality)
  212. {
  213. // It is possible the the canvas doesn't have a associated bitmap so create one
  214. if (!bitmap())
  215. create_bitmap();
  216. // FIXME: 1. If this canvas element's bitmap's origin-clean flag is set to false, then throw a "SecurityError" DOMException.
  217. // 2. If this canvas element's bitmap has no pixels (i.e. either its horizontal dimension or its vertical dimension is zero)
  218. // then return the string "data:,". (This is the shortest data: URL; it represents the empty string in a text/plain resource.)
  219. if (!m_bitmap)
  220. return "data:,"_string;
  221. // 3. Let file be a serialization of this canvas element's bitmap as a file, passing type and quality if given.
  222. auto file = serialize_bitmap(*m_bitmap, type, move(quality));
  223. // 4. If file is null then return "data:,".
  224. if (file.is_error()) {
  225. dbgln("HTMLCanvasElement: Failed to encode canvas bitmap to {}: {}", type, file.error());
  226. return "data:,"_string;
  227. }
  228. // 5. Return a data: URL representing file. [RFC2397]
  229. auto base64_encoded_or_error = encode_base64(file.value().buffer);
  230. if (base64_encoded_or_error.is_error()) {
  231. return "data:,"_string;
  232. }
  233. return MUST(URL::create_with_data(file.value().mime_type, base64_encoded_or_error.release_value(), true).to_string());
  234. }
  235. // https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-toblob
  236. WebIDL::ExceptionOr<void> HTMLCanvasElement::to_blob(JS::NonnullGCPtr<WebIDL::CallbackType> callback, StringView type, Optional<double> quality)
  237. {
  238. // It is possible the the canvas doesn't have a associated bitmap so create one
  239. if (!bitmap())
  240. create_bitmap();
  241. // FIXME: 1. If this canvas element's bitmap's origin-clean flag is set to false, then throw a "SecurityError" DOMException.
  242. // 2. Let result be null.
  243. RefPtr<Gfx::Bitmap> bitmap_result;
  244. // 3. If this canvas element's bitmap has pixels (i.e., neither its horizontal dimension nor its vertical dimension is zero),
  245. // then set result to a copy of this canvas element's bitmap.
  246. if (m_bitmap)
  247. bitmap_result = TRY_OR_THROW_OOM(vm(), m_bitmap->clone());
  248. // 4. Run these steps in parallel:
  249. Platform::EventLoopPlugin::the().deferred_invoke([this, callback, bitmap_result, type, quality] {
  250. // 1. If result is non-null, then set result to a serialization of result as a file with type and quality if given.
  251. Optional<SerializeBitmapResult> file_result;
  252. if (bitmap_result) {
  253. if (auto result = serialize_bitmap(*bitmap_result, type, move(quality)); !result.is_error())
  254. file_result = result.release_value();
  255. }
  256. // 2. Queue an element task on the canvas blob serialization task source given the canvas element to run these steps:
  257. queue_an_element_task(Task::Source::CanvasBlobSerializationTask, [this, callback, file_result = move(file_result)] {
  258. auto maybe_error = Bindings::throw_dom_exception_if_needed(vm(), [&]() -> WebIDL::ExceptionOr<void> {
  259. // 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]
  260. JS::GCPtr<FileAPI::Blob> blob_result;
  261. if (file_result.has_value())
  262. blob_result = FileAPI::Blob::create(realm(), file_result->buffer, TRY_OR_THROW_OOM(vm(), String::from_utf8(file_result->mime_type)));
  263. // 2. Invoke callback with « result ».
  264. TRY(WebIDL::invoke_callback(*callback, {}, move(blob_result)));
  265. return {};
  266. });
  267. if (maybe_error.is_throw_completion())
  268. report_exception(maybe_error.throw_completion(), realm());
  269. });
  270. });
  271. return {};
  272. }
  273. void HTMLCanvasElement::present()
  274. {
  275. m_context.visit(
  276. [](JS::NonnullGCPtr<CanvasRenderingContext2D>&) {
  277. // Do nothing, CRC2D writes directly to the canvas bitmap.
  278. },
  279. [](JS::NonnullGCPtr<WebGL::WebGLRenderingContext>& context) {
  280. context->present();
  281. },
  282. [](Empty) {
  283. // Do nothing.
  284. });
  285. }
  286. }