ImageRequest.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /*
  2. * Copyright (c) 2023, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/HashTable.h>
  7. #include <LibGfx/Bitmap.h>
  8. #include <LibWeb/Fetch/Fetching/Fetching.h>
  9. #include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
  10. #include <LibWeb/Fetch/Infrastructure/FetchController.h>
  11. #include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
  12. #include <LibWeb/HTML/AnimatedBitmapDecodedImageData.h>
  13. #include <LibWeb/HTML/DecodedImageData.h>
  14. #include <LibWeb/HTML/ImageRequest.h>
  15. #include <LibWeb/HTML/ListOfAvailableImages.h>
  16. #include <LibWeb/Platform/ImageCodecPlugin.h>
  17. #include <LibWeb/SVG/SVGDecodedImageData.h>
  18. namespace Web::HTML {
  19. static HashTable<ImageRequest*>& shareable_image_requests()
  20. {
  21. static HashTable<ImageRequest*> requests;
  22. return requests;
  23. }
  24. ErrorOr<NonnullRefPtr<ImageRequest>> ImageRequest::create(Page& page)
  25. {
  26. return adopt_nonnull_ref_or_enomem(new (nothrow) ImageRequest(page));
  27. }
  28. ErrorOr<NonnullRefPtr<ImageRequest>> ImageRequest::get_shareable_or_create(Page& page, AK::URL const& url)
  29. {
  30. for (auto& it : shareable_image_requests()) {
  31. if (it->current_url() == url)
  32. return *it;
  33. }
  34. auto request = TRY(create(page));
  35. request->set_current_url(url);
  36. return request;
  37. }
  38. ImageRequest::ImageRequest(Page& page)
  39. : m_page(page)
  40. {
  41. shareable_image_requests().set(this);
  42. }
  43. ImageRequest::~ImageRequest()
  44. {
  45. shareable_image_requests().remove(this);
  46. }
  47. // https://html.spec.whatwg.org/multipage/images.html#img-available
  48. bool ImageRequest::is_available() const
  49. {
  50. // When an image request's state is either partially available or completely available, the image request is said to be available.
  51. return m_state == State::PartiallyAvailable || m_state == State::CompletelyAvailable;
  52. }
  53. ImageRequest::State ImageRequest::state() const
  54. {
  55. return m_state;
  56. }
  57. void ImageRequest::set_state(State state)
  58. {
  59. m_state = state;
  60. }
  61. AK::URL const& ImageRequest::current_url() const
  62. {
  63. return m_current_url;
  64. }
  65. void ImageRequest::set_current_url(AK::URL url)
  66. {
  67. m_current_url = move(url);
  68. }
  69. // https://html.spec.whatwg.org/multipage/images.html#abort-the-image-request
  70. void abort_the_image_request(JS::Realm& realm, ImageRequest* image_request)
  71. {
  72. // 1. If image request is null, then return.
  73. if (!image_request)
  74. return;
  75. // 2. Forget image request's image data, if any.
  76. image_request->set_image_data(nullptr);
  77. // 3. Abort any instance of the fetching algorithm for image request,
  78. // discarding any pending tasks generated by that algorithm.
  79. if (auto fetch_controller = image_request->fetch_controller())
  80. fetch_controller->abort(realm, {});
  81. image_request->set_fetch_controller(nullptr);
  82. }
  83. RefPtr<DecodedImageData const> ImageRequest::image_data() const
  84. {
  85. return m_image_data;
  86. }
  87. void ImageRequest::set_image_data(RefPtr<DecodedImageData const> data)
  88. {
  89. m_image_data = move(data);
  90. }
  91. // https://html.spec.whatwg.org/multipage/images.html#prepare-an-image-for-presentation
  92. void ImageRequest::prepare_for_presentation(HTMLImageElement&)
  93. {
  94. // FIXME: 1. Let exifTagMap be the EXIF tags obtained from req's image data, as defined by the relevant codec. [EXIF]
  95. // FIXME: 2. Let physicalWidth and physicalHeight be the width and height obtained from req's image data, as defined by the relevant codec.
  96. // FIXME: 3. Let dimX be the value of exifTagMap's tag 0xA002 (PixelXDimension).
  97. // FIXME: 4. Let dimY be the value of exifTagMap's tag 0xA003 (PixelYDimension).
  98. // FIXME: 5. Let resX be the value of exifTagMap's tag 0x011A (XResolution).
  99. // FIXME: 6. Let resY be the value of exifTagMap's tag 0x011B (YResolution).
  100. // FIXME: 7. Let resUnit be the value of exifTagMap's tag 0x0128 (ResolutionUnit).
  101. // FIXME: 8. If either dimX or dimY is not a positive integer, then return.
  102. // FIXME: 9. If either resX or resY is not a positive floating-point number, then return.
  103. // FIXME: 10. If resUnit is not equal to 2 (Inch), then return.
  104. // FIXME: 11. Let widthFromDensity be the value of physicalWidth, multiplied by 72 and divided by resX.
  105. // FIXME: 12. Let heightFromDensity be the value of physicalHeight, multiplied by 72 and divided by resY.
  106. // FIXME: 13. If widthFromDensity is not equal to dimX or heightFromDensity is not equal to dimY, then return.
  107. // FIXME: 14. If req's image data is CORS-cross-origin, then set img's intrinsic dimensions to dimX and dimY, scale img's pixel data accordingly, and return.
  108. // FIXME: 15. Set req's preferred density-corrected dimensions to a struct with its width set to dimX and its height set to dimY.
  109. // FIXME: 16. Update req's img element's presentation appropriately.
  110. }
  111. JS::GCPtr<Fetch::Infrastructure::FetchController> ImageRequest::fetch_controller()
  112. {
  113. return m_fetch_controller.ptr();
  114. }
  115. void ImageRequest::set_fetch_controller(JS::GCPtr<Fetch::Infrastructure::FetchController> fetch_controller)
  116. {
  117. m_fetch_controller = move(fetch_controller);
  118. }
  119. void ImageRequest::fetch_image(JS::Realm& realm, JS::NonnullGCPtr<Fetch::Infrastructure::Request> request)
  120. {
  121. Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
  122. fetch_algorithms_input.process_response = [this, &realm, request](JS::NonnullGCPtr<Fetch::Infrastructure::Response> response) {
  123. // FIXME: If the response is CORS cross-origin, we must use its internal response to query any of its data. See:
  124. // https://github.com/whatwg/html/issues/9355
  125. response = response->unsafe_response();
  126. // 26. As soon as possible, jump to the first applicable entry from the following list:
  127. // FIXME: - If the resource type is multipart/x-mixed-replace
  128. // - If the resource type and data corresponds to a supported image format, as described below
  129. // - The next task that is queued by the networking task source while the image is being fetched must run the following steps:
  130. auto process_body = [this, request, response](ByteBuffer data) {
  131. auto extracted_mime_type = response->header_list()->extract_mime_type().release_value_but_fixme_should_propagate_errors();
  132. auto mime_type = extracted_mime_type.has_value() ? extracted_mime_type.value().essence().bytes_as_string_view() : StringView {};
  133. handle_successful_fetch(request->url(), mime_type, move(data));
  134. };
  135. auto process_body_error = [this](auto) {
  136. handle_failed_fetch();
  137. };
  138. if (response->body().has_value())
  139. response->body().value().fully_read(realm, move(process_body), move(process_body_error), JS::NonnullGCPtr { realm.global_object() }).release_value_but_fixme_should_propagate_errors();
  140. };
  141. // 25. Fetch the image: Fetch request.
  142. // Return from this algorithm, and run the remaining steps as part of the fetch's processResponse for the response response.
  143. auto fetch_controller = Fetch::Fetching::fetch(
  144. realm,
  145. request,
  146. Fetch::Infrastructure::FetchAlgorithms::create(realm.vm(), move(fetch_algorithms_input)))
  147. .release_value_but_fixme_should_propagate_errors();
  148. set_fetch_controller(fetch_controller);
  149. }
  150. void ImageRequest::add_callbacks(JS::SafeFunction<void()> on_finish, JS::SafeFunction<void()> on_fail)
  151. {
  152. if (is_available()) {
  153. if (on_finish)
  154. on_finish();
  155. return;
  156. }
  157. if (state() == ImageRequest::State::Broken) {
  158. if (on_fail)
  159. on_fail();
  160. return;
  161. }
  162. m_callbacks.append({ move(on_finish), move(on_fail) });
  163. }
  164. void ImageRequest::handle_successful_fetch(AK::URL const& url_string, StringView mime_type, ByteBuffer data)
  165. {
  166. // AD-HOC: At this point, things gets very ad-hoc.
  167. // FIXME: Bring this closer to spec.
  168. bool const is_svg_image = mime_type == "image/svg+xml"sv || url_string.basename().ends_with(".svg"sv);
  169. RefPtr<DecodedImageData> image_data;
  170. auto handle_failed_decode = [&] {
  171. for (auto& callback : m_callbacks) {
  172. if (callback.on_fail)
  173. callback.on_fail();
  174. }
  175. };
  176. if (is_svg_image) {
  177. auto result = SVG::SVGDecodedImageData::create(m_page, url_string, data);
  178. if (result.is_error())
  179. return handle_failed_decode();
  180. image_data = result.release_value();
  181. } else {
  182. auto result = Web::Platform::ImageCodecPlugin::the().decode_image(data.bytes());
  183. if (!result.has_value())
  184. return handle_failed_decode();
  185. Vector<AnimatedBitmapDecodedImageData::Frame> frames;
  186. for (auto& frame : result.value().frames) {
  187. frames.append(AnimatedBitmapDecodedImageData::Frame {
  188. .bitmap = frame.bitmap,
  189. .duration = static_cast<int>(frame.duration),
  190. });
  191. }
  192. image_data = AnimatedBitmapDecodedImageData::create(move(frames), result.value().loop_count, result.value().is_animated).release_value_but_fixme_should_propagate_errors();
  193. }
  194. set_image_data(image_data);
  195. // 2. Set image request to the completely available state.
  196. set_state(ImageRequest::State::CompletelyAvailable);
  197. for (auto& callback : m_callbacks) {
  198. if (callback.on_finish)
  199. callback.on_finish();
  200. }
  201. }
  202. void ImageRequest::handle_failed_fetch()
  203. {
  204. for (auto& callback : m_callbacks) {
  205. if (callback.on_fail)
  206. callback.on_fail();
  207. }
  208. }
  209. }