HTMLCanvasElement.cpp 12 KB

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