DocumentLoading.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2023, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
  4. * Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Debug.h>
  9. #include <AK/LexicalPath.h>
  10. #include <LibGemini/Document.h>
  11. #include <LibGfx/ImageFormats/ImageDecoder.h>
  12. #include <LibMarkdown/Document.h>
  13. #include <LibTextCodec/Decoder.h>
  14. #include <LibWeb/DOM/Document.h>
  15. #include <LibWeb/DOM/DocumentLoading.h>
  16. #include <LibWeb/HTML/HTMLHeadElement.h>
  17. #include <LibWeb/HTML/Navigable.h>
  18. #include <LibWeb/HTML/NavigationParams.h>
  19. #include <LibWeb/HTML/Parser/HTMLEncodingDetection.h>
  20. #include <LibWeb/HTML/Parser/HTMLParser.h>
  21. #include <LibWeb/Loader/GeneratedPagesLoader.h>
  22. #include <LibWeb/Namespace.h>
  23. #include <LibWeb/XML/XMLDocumentBuilder.h>
  24. namespace Web {
  25. static WebIDL::ExceptionOr<JS::NonnullGCPtr<DOM::Document>> load_markdown_document(HTML::NavigationParams& navigation_params)
  26. {
  27. auto extra_head_contents = R"~~~(
  28. <style>
  29. .zoomable {
  30. cursor: zoom-in;
  31. max-width: 100%;
  32. }
  33. .zoomable.zoomed-in {
  34. cursor: zoom-out;
  35. max-width: none;
  36. }
  37. </style>
  38. <script>
  39. function imageClickEventListener(event) {
  40. let image = event.target;
  41. if (image.classList.contains("zoomable")) {
  42. image.classList.toggle("zoomed-in");
  43. }
  44. }
  45. function processImages() {
  46. let images = document.querySelectorAll("img");
  47. let windowWidth = window.innerWidth;
  48. images.forEach((image) => {
  49. if (image.naturalWidth > windowWidth) {
  50. image.classList.add("zoomable");
  51. } else {
  52. image.classList.remove("zoomable");
  53. image.classList.remove("zoomed-in");
  54. }
  55. image.addEventListener("click", imageClickEventListener);
  56. });
  57. }
  58. document.addEventListener("load", () => {
  59. processImages();
  60. });
  61. window.addEventListener("resize", () => {
  62. processImages();
  63. });
  64. </script>
  65. )~~~"sv;
  66. return create_document_for_inline_content(navigation_params.navigable.ptr(), navigation_params.id, [&](DOM::Document& document) {
  67. auto& realm = document.realm();
  68. auto process_body = [&document, url = navigation_params.response->url().value(), extra_head_contents](ByteBuffer data) {
  69. auto markdown_document = Markdown::Document::parse(data);
  70. if (!markdown_document)
  71. return;
  72. auto parser = HTML::HTMLParser::create(document, markdown_document->render_to_html(extra_head_contents), "utf-8");
  73. parser->run(document.url());
  74. };
  75. auto process_body_error = [](auto) {
  76. dbgln("FIXME: Load html page with an error if read of body failed.");
  77. };
  78. navigation_params.response->body()->fully_read(
  79. realm,
  80. move(process_body),
  81. move(process_body_error),
  82. JS::NonnullGCPtr { realm.global_object() })
  83. .release_value_but_fixme_should_propagate_errors();
  84. });
  85. }
  86. static bool build_gemini_document(DOM::Document& document, ByteBuffer const& data)
  87. {
  88. StringView gemini_data { data };
  89. auto gemini_document = Gemini::Document::parse(gemini_data, document.url());
  90. ByteString html_data = gemini_document->render_to_html();
  91. dbgln_if(GEMINI_DEBUG, "Gemini data:\n\"\"\"{}\"\"\"", gemini_data);
  92. dbgln_if(GEMINI_DEBUG, "Converted to HTML:\n\"\"\"{}\"\"\"", html_data);
  93. auto parser = HTML::HTMLParser::create(document, html_data, "utf-8");
  94. parser->run(document.url());
  95. return true;
  96. }
  97. bool build_xml_document(DOM::Document& document, ByteBuffer const& data, Optional<String> content_encoding)
  98. {
  99. Optional<TextCodec::Decoder&> decoder;
  100. // The actual HTTP headers and other metadata, not the headers as mutated or implied by the algorithms given in this specification,
  101. // are the ones that must be used when determining the character encoding according to the rules given in the above specifications.
  102. if (content_encoding.has_value())
  103. decoder = TextCodec::decoder_for(*content_encoding);
  104. if (!decoder.has_value()) {
  105. auto encoding = HTML::run_encoding_sniffing_algorithm(document, data);
  106. decoder = TextCodec::decoder_for(encoding);
  107. }
  108. VERIFY(decoder.has_value());
  109. // Well-formed XML documents contain only properly encoded characters
  110. if (!decoder->validate(data))
  111. return false;
  112. auto source = decoder->to_utf8(data).release_value_but_fixme_should_propagate_errors();
  113. XML::Parser parser(source, { .resolve_external_resource = resolve_xml_resource });
  114. XMLDocumentBuilder builder { document };
  115. auto result = parser.parse_with_listener(builder);
  116. return !result.is_error() && !builder.has_error();
  117. }
  118. bool parse_document(DOM::Document& document, ByteBuffer const& data, [[maybe_unused]] Optional<String> content_encoding)
  119. {
  120. auto& mime_type = document.content_type();
  121. if (mime_type == "text/gemini")
  122. return build_gemini_document(document, data);
  123. return false;
  124. }
  125. static bool is_supported_document_mime_type(StringView mime_type)
  126. {
  127. if (mime_type == "text/html")
  128. return true;
  129. if (mime_type.ends_with("+xml"sv) || mime_type.is_one_of("text/xml", "application/xml"))
  130. return true;
  131. if (mime_type.starts_with("image/"sv))
  132. return true;
  133. if (mime_type.starts_with("video/"sv))
  134. return true;
  135. if (mime_type.starts_with("audio/"sv))
  136. return true;
  137. if (mime_type == "text/plain" || mime_type == "application/json")
  138. return true;
  139. if (mime_type == "text/markdown")
  140. return true;
  141. if (mime_type == "text/gemini")
  142. return true;
  143. return false;
  144. }
  145. // https://html.spec.whatwg.org/multipage/document-lifecycle.html#navigate-html
  146. static WebIDL::ExceptionOr<JS::NonnullGCPtr<DOM::Document>> load_html_document(HTML::NavigationParams& navigation_params)
  147. {
  148. // To load an HTML document, given navigation params navigationParams:
  149. // 1. Let document be the result of creating and initializing a Document object given "html", "text/html", and navigationParams.
  150. auto document = TRY(DOM::Document::create_and_initialize(DOM::Document::Type::HTML, "text/html"_string, navigation_params));
  151. // 2. If document's URL is about:blank, then populate with html/head/body given document.
  152. // FIXME: The additional check for a non-empty body fixes issues with loading javascript urls in iframes, which
  153. // default to an "about:blank" url. Is this a spec bug?
  154. if (document->url_string() == "about:blank"_string
  155. && navigation_params.response->body()->length().value_or(0) == 0) {
  156. TRY(document->populate_with_html_head_and_body());
  157. // Nothing else is added to the document, so mark it as loaded.
  158. HTML::HTMLParser::the_end(document);
  159. }
  160. // 3. Otherwise, create an HTML parser and associate it with the document.
  161. // Each task that the networking task source places on the task queue while fetching runs must then fill the
  162. // parser's input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate
  163. // processing of the input stream.
  164. // The first task that the networking task source places on the task queue while fetching runs must process link
  165. // headers given document, navigationParams's response, and "media", after the task has been processed by the
  166. // HTML parser.
  167. // Before any script execution occurs, the user agent must wait for scripts may run for the newly-created
  168. // document to be true for document.
  169. // When no more bytes are available, the user agent must queue a global task on the networking task source given
  170. // document's relevant global object to have the parser to process the implied EOF character, which eventually
  171. // causes a load event to be fired.
  172. else {
  173. // FIXME: Parse as we receive the document data, instead of waiting for the whole document to be fetched first.
  174. auto process_body = [document, url = navigation_params.response->url().value()](ByteBuffer data) {
  175. auto parser = HTML::HTMLParser::create_with_uncertain_encoding(document, data);
  176. parser->run(url);
  177. };
  178. auto process_body_error = [](auto) {
  179. dbgln("FIXME: Load html page with an error if read of body failed.");
  180. };
  181. auto& realm = document->realm();
  182. TRY(navigation_params.response->body()->fully_read(realm, move(process_body), move(process_body_error), JS::NonnullGCPtr { realm.global_object() }));
  183. }
  184. // 4. Return document.
  185. return document;
  186. }
  187. // https://html.spec.whatwg.org/multipage/document-lifecycle.html#read-xml
  188. static WebIDL::ExceptionOr<JS::NonnullGCPtr<DOM::Document>> load_xml_document(HTML::NavigationParams& navigation_params, MimeSniff::MimeType type)
  189. {
  190. // When faced with displaying an XML file inline, provided navigation params navigationParams and a string type, user agents
  191. // must follow the requirements defined in XML and Namespaces in XML, XML Media Types, DOM, and other relevant specifications
  192. // to create and initialize a Document object document, given "xml", type, and navigationParams, and return that Document.
  193. // They must also create a corresponding XML parser. [XML] [XMLNS] [RFC7303] [DOM]
  194. //
  195. // Note: At the time of writing, the XML specification community had not actually yet specified how XML and the DOM interact.
  196. //
  197. // The first task that the networking task source places on the task queue while fetching runs must process link headers
  198. // given document, navigationParams's response, and "media", after the task has been processed by the XML parser.
  199. //
  200. // The actual HTTP headers and other metadata, not the headers as mutated or implied by the algorithms given in this
  201. // specification, are the ones that must be used when determining the character encoding according to the rules given in the
  202. // above specifications. Once the character encoding is established, the document's character encoding must be set to that
  203. // character encoding.
  204. //
  205. // Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be
  206. // true for the newly-created Document.
  207. //
  208. // Once parsing is complete, the user agent must set document's during-loading navigation ID for WebDriver BiDi to null.
  209. //
  210. // Note: For HTML documents this is reset when parsing is complete, after firing the load event.
  211. //
  212. // Error messages from the parse process (e.g., XML namespace well-formedness errors) may be reported inline by mutating
  213. // the Document.
  214. // FIXME: Actually follow the spec! This is just the ad-hoc code we had before, modified somewhat.
  215. auto document = TRY(DOM::Document::create_and_initialize(DOM::Document::Type::XML, "application/xhtml+xml"_string, navigation_params));
  216. Optional<String> content_encoding;
  217. if (auto maybe_encoding = type.parameters().get("charset"sv); maybe_encoding.has_value())
  218. content_encoding = maybe_encoding.value();
  219. auto process_body = [document, url = navigation_params.response->url().value(), content_encoding = move(content_encoding)](ByteBuffer data) {
  220. Optional<TextCodec::Decoder&> decoder;
  221. // The actual HTTP headers and other metadata, not the headers as mutated or implied by the algorithms given in this specification,
  222. // are the ones that must be used when determining the character encoding according to the rules given in the above specifications.
  223. if (content_encoding.has_value())
  224. decoder = TextCodec::decoder_for(*content_encoding);
  225. if (!decoder.has_value()) {
  226. auto encoding = HTML::run_encoding_sniffing_algorithm(document, data);
  227. decoder = TextCodec::decoder_for(encoding);
  228. }
  229. VERIFY(decoder.has_value());
  230. // Well-formed XML documents contain only properly encoded characters
  231. if (!decoder->validate(data)) {
  232. // FIXME: Insert error message into the document.
  233. dbgln("XML Document contains improperly-encoded characters");
  234. return;
  235. }
  236. auto source = decoder->to_utf8(data);
  237. if (source.is_error()) {
  238. // FIXME: Insert error message into the document.
  239. dbgln("Failed to decode XML document: {}", source.error());
  240. return;
  241. }
  242. XML::Parser parser(source.value(), { .resolve_external_resource = resolve_xml_resource });
  243. XMLDocumentBuilder builder { document };
  244. auto result = parser.parse_with_listener(builder);
  245. if (result.is_error()) {
  246. // FIXME: Insert error message into the document.
  247. dbgln("Failed to parse XML document: {}", result.error());
  248. }
  249. };
  250. auto process_body_error = [](auto) {
  251. dbgln("FIXME: Load html page with an error if read of body failed.");
  252. };
  253. auto& realm = document->realm();
  254. TRY(navigation_params.response->body()->fully_read(realm, move(process_body), move(process_body_error), JS::NonnullGCPtr { realm.global_object() }));
  255. return document;
  256. }
  257. // https://html.spec.whatwg.org/multipage/document-lifecycle.html#navigate-text
  258. static WebIDL::ExceptionOr<JS::NonnullGCPtr<DOM::Document>> load_text_document(HTML::NavigationParams& navigation_params, MimeSniff::MimeType type)
  259. {
  260. // To load a text document, given a navigation params navigationParams and a string type:
  261. // 1. Let document be the result of creating and initializing a Document object given "html", type, and navigationParams.
  262. auto document = TRY(DOM::Document::create_and_initialize(DOM::Document::Type::XML, type.essence(), navigation_params));
  263. // FIXME: 2. Set document's parser cannot change the mode flag to true.
  264. // 3. Set document's mode to "no-quirks".
  265. document->set_quirks_mode(DOM::QuirksMode::No);
  266. // 4. Create an HTML parser and associate it with the document. Act as if the tokenizer had emitted a start tag token
  267. // with the tag name "pre" followed by a single U+000A LINE FEED (LF) character, and switch the HTML parser's tokenizer
  268. // to the PLAINTEXT state. Each task that the networking task source places on the task queue while fetching runs must
  269. // then fill the parser's input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate
  270. // processing of the input stream.
  271. // document's encoding must be set to the character encoding used to decode the document during parsing.
  272. // The first task that the networking task source places on the task queue while fetching runs must process link
  273. // headers given document, navigationParams's response, and "media", after the task has been processed by the HTML parser.
  274. // Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to be
  275. // true for document.
  276. // When no more bytes are available, the user agent must queue a global task on the networking task source given
  277. // document's relevant global object to have the parser to process the implied EOF character, which eventually causes a
  278. // load event to be fired.
  279. // FIXME: Parse as we receive the document data, instead of waiting for the whole document to be fetched first.
  280. auto process_body = [document, url = navigation_params.response->url().value()](ByteBuffer data) {
  281. auto encoding = run_encoding_sniffing_algorithm(document, data);
  282. dbgln_if(HTML_PARSER_DEBUG, "The encoding sniffing algorithm returned encoding '{}'", encoding);
  283. auto parser = HTML::HTMLParser::create_for_scripting(document);
  284. parser->tokenizer().update_insertion_point();
  285. parser->tokenizer().insert_input_at_insertion_point("<pre>\n"sv);
  286. parser->run();
  287. parser->tokenizer().switch_to(HTML::HTMLTokenizer::State::PLAINTEXT);
  288. parser->tokenizer().insert_input_at_insertion_point(data);
  289. parser->tokenizer().insert_eof();
  290. parser->run(url);
  291. document->set_encoding(MUST(String::from_byte_string(encoding)));
  292. // 5. User agents may add content to the head element of document, e.g., linking to a style sheet, providing
  293. // script, or giving the document a title.
  294. auto title = MUST(String::from_byte_string(LexicalPath::basename(url.to_byte_string())));
  295. auto title_element = MUST(DOM::create_element(document, HTML::TagNames::title, Namespace::HTML));
  296. MUST(document->head()->append_child(title_element));
  297. auto title_text = document->heap().allocate<DOM::Text>(document->realm(), document, title);
  298. MUST(title_element->append_child(*title_text));
  299. };
  300. auto process_body_error = [](auto) {
  301. dbgln("FIXME: Load html page with an error if read of body failed.");
  302. };
  303. auto& realm = document->realm();
  304. TRY(navigation_params.response->body()->fully_read(realm, move(process_body), move(process_body_error), JS::NonnullGCPtr { realm.global_object() }));
  305. // 6. Return document.
  306. return document;
  307. }
  308. // https://html.spec.whatwg.org/multipage/document-lifecycle.html#navigate-media
  309. static WebIDL::ExceptionOr<JS::NonnullGCPtr<DOM::Document>> load_media_document(HTML::NavigationParams& navigation_params, MimeSniff::MimeType type)
  310. {
  311. // To load a media document, given navigationParams and a string type:
  312. // 1. Let document be the result of creating and initializing a Document object given "html", type, and navigationParams.
  313. auto document = TRY(DOM::Document::create_and_initialize(DOM::Document::Type::XML, type.essence(), navigation_params));
  314. // 2. Set document's mode to "no-quirks".
  315. document->set_quirks_mode(DOM::QuirksMode::No);
  316. // 3. Populate with html/head/body given document.
  317. TRY(document->populate_with_html_head_and_body());
  318. // 4. Append an element host element for the media, as described below, to the body element.
  319. // 5. Set the appropriate attribute of the element host element, as described below, to the address of the image,
  320. // video, or audio resource.
  321. // 6. User agents may add content to the head element of document, or attributes to host element, e.g., to link
  322. // to a style sheet, to provide a script, to give the document a title, or to make the media autoplay.
  323. auto insert_title = [](auto& document, auto title) -> WebIDL::ExceptionOr<void> {
  324. auto title_element = TRY(DOM::create_element(document, HTML::TagNames::title, Namespace::HTML));
  325. TRY(document->head()->append_child(title_element));
  326. auto title_text = document->heap().template allocate<DOM::Text>(document->realm(), document, title);
  327. TRY(title_element->append_child(*title_text));
  328. return {};
  329. };
  330. auto url_string = document->url_string();
  331. if (type.is_image()) {
  332. auto img_element = TRY(DOM::create_element(document, HTML::TagNames::img, Namespace::HTML));
  333. TRY(img_element->set_attribute(HTML::AttributeNames::src, url_string));
  334. TRY(document->body()->append_child(img_element));
  335. TRY(insert_title(document, MUST(String::from_byte_string(LexicalPath::basename(url_string.to_byte_string())))));
  336. } else if (type.type() == "video"sv) {
  337. auto video_element = TRY(DOM::create_element(document, HTML::TagNames::video, Namespace::HTML));
  338. TRY(video_element->set_attribute(HTML::AttributeNames::src, url_string));
  339. TRY(video_element->set_attribute(HTML::AttributeNames::autoplay, String {}));
  340. TRY(video_element->set_attribute(HTML::AttributeNames::controls, String {}));
  341. TRY(document->body()->append_child(video_element));
  342. TRY(insert_title(document, MUST(String::from_byte_string(LexicalPath::basename(url_string.to_byte_string())))));
  343. } else if (type.type() == "audio"sv) {
  344. auto audio_element = TRY(DOM::create_element(document, HTML::TagNames::audio, Namespace::HTML));
  345. TRY(audio_element->set_attribute(HTML::AttributeNames::src, url_string));
  346. TRY(audio_element->set_attribute(HTML::AttributeNames::autoplay, String {}));
  347. TRY(audio_element->set_attribute(HTML::AttributeNames::controls, String {}));
  348. TRY(document->body()->append_child(audio_element));
  349. TRY(insert_title(document, MUST(String::from_byte_string(LexicalPath::basename(url_string.to_byte_string())))));
  350. } else {
  351. // FIXME: According to https://mimesniff.spec.whatwg.org/#audio-or-video-mime-type we might have to deal with
  352. // "application/ogg" and figure out whether it's audio or video.
  353. VERIFY_NOT_REACHED();
  354. }
  355. // FIXME: 7. Process link headers given document, navigationParams's response, and "media".
  356. // 8. Act as if the user agent had stopped parsing document.
  357. // FIXME: We should not need to force the media file to load before saying that parsing has completed!
  358. // However, if we don't, then we get stuck in HTMLParser::the_end() waiting for the media file to load, which
  359. // never happens.
  360. auto& realm = document->realm();
  361. TRY(navigation_params.response->body()->fully_read(
  362. realm,
  363. [document](auto) { HTML::HTMLParser::the_end(document); },
  364. [](auto) {},
  365. JS::NonnullGCPtr { realm.global_object() }));
  366. // 9. Return document.
  367. return document;
  368. // The element host element to create for the media is the element given in the table below in the second cell of
  369. // the row whose first cell describes the media. The appropriate attribute to set is the one given by the third cell
  370. // in that same row.
  371. // Type of media | Element for the media | Appropriate attribute
  372. // -------------------------------------------------------------
  373. // Image | img | src
  374. // Video | video | src
  375. // Audio | audio | src
  376. // Before any script execution occurs, the user agent must wait for scripts may run for the newly-created document to
  377. // be true for the Document.
  378. }
  379. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#loading-a-document
  380. JS::GCPtr<DOM::Document> load_document(HTML::NavigationParams navigation_params)
  381. {
  382. // To load a document given navigation params navigationParams, source snapshot params sourceSnapshotParams,
  383. // and origin initiatorOrigin, perform the following steps. They return a Document or null.
  384. // 1. Let type be the computed type of navigationParams's response.
  385. auto extracted_mime_type = navigation_params.response->header_list()->extract_mime_type().release_value_but_fixme_should_propagate_errors();
  386. if (!extracted_mime_type.has_value())
  387. return nullptr;
  388. auto type = extracted_mime_type.release_value();
  389. VERIFY(navigation_params.response->body());
  390. // 2. If the user agent has been configured to process resources of the given type using some mechanism other than
  391. // rendering the content in a navigable, then skip this step.
  392. // Otherwise, if the type is one of the following types:
  393. // -> an HTML MIME type
  394. if (type.is_html()) {
  395. // Return the result of loading an HTML document, given navigationParams.
  396. return load_html_document(navigation_params).release_value_but_fixme_should_propagate_errors();
  397. }
  398. // -> an XML MIME type that is not an explicitly supported XML MIME type
  399. // FIXME: that is not an explicitly supported XML MIME type
  400. if (type.is_xml()) {
  401. // Return the result of loading an XML document given navigationParams and type.
  402. return load_xml_document(navigation_params, type).release_value_but_fixme_should_propagate_errors();
  403. }
  404. // -> a JavaScript MIME type
  405. // -> a JSON MIME type that is not an explicitly supported JSON MIME type
  406. // -> "text/css"
  407. // -> "text/plain"
  408. // -> "text/vtt"
  409. if (type.is_javascript()
  410. || type.is_json()
  411. || type.essence() == "text/css"_string
  412. || type.essence() == "text/plain"_string
  413. || type.essence() == "text/vtt"_string) {
  414. // Return the result of loading a text document given navigationParams and type.
  415. return load_text_document(navigation_params, type).release_value_but_fixme_should_propagate_errors();
  416. }
  417. // -> "multipart/x-mixed-replace"
  418. if (type.essence() == "multipart/x-mixed-replace"_string) {
  419. // FIXME: Return the result of loading a multipart/x-mixed-replace document, given navigationParams,
  420. // sourceSnapshotParams, and initiatorOrigin.
  421. }
  422. // -> A supported image, video, or audio type
  423. if (type.is_image()
  424. || type.is_audio_or_video()) {
  425. // Return the result of loading a media document given navigationParams and type.
  426. return load_media_document(navigation_params, type).release_value_but_fixme_should_propagate_errors();
  427. }
  428. // -> "application/pdf"
  429. // -> "text/pdf"
  430. if (type.essence() == "application/pdf"_string
  431. || type.essence() == "text/pdf"_string) {
  432. // FIXME: If the user agent's PDF viewer supported is true, return the result of creating a document for inline
  433. // content that doesn't have a DOM given navigationParams's navigable.
  434. }
  435. // Otherwise, proceed onward.
  436. // 3. If, given type, the new resource is to be handled by displaying some sort of inline content, e.g., a
  437. // native rendering of the content or an error message because the specified type is not supported, then
  438. // return the result of creating a document for inline content that doesn't have a DOM given navigationParams's
  439. // navigable, navigationParams's id, and navigationParams's navigation timing type.
  440. if (type.essence() == "text/markdown"sv)
  441. return load_markdown_document(navigation_params).release_value_but_fixme_should_propagate_errors();
  442. // FIXME: 4. Otherwise, the document's type is such that the resource will not affect navigationParams's navigable,
  443. // e.g., because the resource is to be handed to an external application or because it is an unknown type
  444. // that will be processed as a download. Hand-off to external software given navigationParams's response,
  445. // navigationParams's navigable, navigationParams's final sandboxing flag set, sourceSnapshotParams's has
  446. // transient activation, and initiatorOrigin.
  447. // FIXME: Start of old, ad-hoc code
  448. if (!is_supported_document_mime_type(type.essence()))
  449. return nullptr;
  450. auto document = DOM::Document::create_and_initialize(DOM::Document::Type::HTML, "text/html"_string, navigation_params).release_value_but_fixme_should_propagate_errors();
  451. document->set_content_type(type.essence());
  452. auto& realm = document->realm();
  453. if (navigation_params.response->body()) {
  454. Optional<String> content_encoding = type.parameters().get("charset"sv);
  455. auto process_body = [document, url = navigation_params.response->url().value(), encoding = move(content_encoding)](ByteBuffer bytes) {
  456. if (parse_document(*document, bytes, move(encoding)))
  457. return;
  458. document->remove_all_children(true);
  459. auto error_html = load_error_page(url).release_value_but_fixme_should_propagate_errors();
  460. auto parser = HTML::HTMLParser::create(document, error_html, "utf-8");
  461. document->set_url(AK::URL("about:error"));
  462. parser->run();
  463. };
  464. auto process_body_error = [](auto) {
  465. dbgln("FIXME: Load html page with an error if read of body failed.");
  466. };
  467. navigation_params.response->body()->fully_read(
  468. realm,
  469. move(process_body),
  470. move(process_body_error),
  471. JS::NonnullGCPtr { realm.global_object() })
  472. .release_value_but_fixme_should_propagate_errors();
  473. }
  474. return document;
  475. // FIXME: End of old, ad-hoc code
  476. // 5. Return null.
  477. return nullptr;
  478. }
  479. }