FrameLoader.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Debug.h>
  27. #include <AK/LexicalPath.h>
  28. #include <AK/SourceGenerator.h>
  29. #include <LibGemini/Document.h>
  30. #include <LibGfx/ImageDecoder.h>
  31. #include <LibMarkdown/Document.h>
  32. #include <LibWeb/DOM/Document.h>
  33. #include <LibWeb/DOM/ElementFactory.h>
  34. #include <LibWeb/DOM/Text.h>
  35. #include <LibWeb/HTML/HTMLIFrameElement.h>
  36. #include <LibWeb/HTML/Parser/HTMLDocumentParser.h>
  37. #include <LibWeb/Loader/FrameLoader.h>
  38. #include <LibWeb/Loader/ResourceLoader.h>
  39. #include <LibWeb/Namespace.h>
  40. #include <LibWeb/Page/Frame.h>
  41. #include <LibWeb/Page/Page.h>
  42. namespace Web {
  43. FrameLoader::FrameLoader(Frame& frame)
  44. : m_frame(frame)
  45. {
  46. }
  47. FrameLoader::~FrameLoader()
  48. {
  49. }
  50. static bool build_markdown_document(DOM::Document& document, const ByteBuffer& data)
  51. {
  52. auto markdown_document = Markdown::Document::parse(data);
  53. if (!markdown_document)
  54. return false;
  55. HTML::HTMLDocumentParser parser(document, markdown_document->render_to_html(), "utf-8");
  56. parser.run(document.url());
  57. return true;
  58. }
  59. static bool build_text_document(DOM::Document& document, const ByteBuffer& data)
  60. {
  61. auto html_element = document.create_element("html");
  62. document.append_child(html_element);
  63. auto head_element = document.create_element("head");
  64. html_element->append_child(head_element);
  65. auto title_element = document.create_element("title");
  66. head_element->append_child(title_element);
  67. auto title_text = document.create_text_node(document.url().basename());
  68. title_element->append_child(title_text);
  69. auto body_element = document.create_element("body");
  70. html_element->append_child(body_element);
  71. auto pre_element = document.create_element("pre");
  72. body_element->append_child(pre_element);
  73. pre_element->append_child(document.create_text_node(String::copy(data)));
  74. return true;
  75. }
  76. static bool build_image_document(DOM::Document& document, const ByteBuffer& data)
  77. {
  78. auto image_decoder = Gfx::ImageDecoder::create(data.data(), data.size());
  79. auto bitmap = image_decoder->bitmap();
  80. if (!bitmap)
  81. return false;
  82. auto html_element = document.create_element("html");
  83. document.append_child(html_element);
  84. auto head_element = document.create_element("head");
  85. html_element->append_child(head_element);
  86. auto title_element = document.create_element("title");
  87. head_element->append_child(title_element);
  88. auto basename = LexicalPath(document.url().path()).basename();
  89. auto title_text = adopt(*new DOM::Text(document, String::formatted("{} [{}x{}]", basename, bitmap->width(), bitmap->height())));
  90. title_element->append_child(title_text);
  91. auto body_element = document.create_element("body");
  92. html_element->append_child(body_element);
  93. auto image_element = document.create_element("img");
  94. image_element->set_attribute(HTML::AttributeNames::src, document.url().to_string());
  95. body_element->append_child(image_element);
  96. return true;
  97. }
  98. static bool build_gemini_document(DOM::Document& document, const ByteBuffer& data)
  99. {
  100. StringView gemini_data { data };
  101. auto gemini_document = Gemini::Document::parse(gemini_data, document.url());
  102. String html_data = gemini_document->render_to_html();
  103. #if GEMINI_DEBUG
  104. dbgln("Gemini data:\n\"\"\"{}\"\"\"", gemini_data);
  105. dbgln("Converted to HTML:\n\"\"\"{}\"\"\"", html_data);
  106. #endif
  107. HTML::HTMLDocumentParser parser(document, html_data, "utf-8");
  108. parser.run(document.url());
  109. return true;
  110. }
  111. bool FrameLoader::parse_document(DOM::Document& document, const ByteBuffer& data)
  112. {
  113. auto& mime_type = document.content_type();
  114. if (mime_type == "text/html" || mime_type == "image/svg+xml") {
  115. HTML::HTMLDocumentParser parser(document, data, document.encoding());
  116. parser.run(document.url());
  117. return true;
  118. }
  119. if (mime_type.starts_with("image/"))
  120. return build_image_document(document, data);
  121. if (mime_type == "text/plain" || mime_type == "application/json")
  122. return build_text_document(document, data);
  123. if (mime_type == "text/markdown")
  124. return build_markdown_document(document, data);
  125. if (mime_type == "text/gemini")
  126. return build_gemini_document(document, data);
  127. return false;
  128. }
  129. bool FrameLoader::load(const LoadRequest& request, Type type)
  130. {
  131. if (!request.is_valid()) {
  132. load_error_page(request.url(), "Invalid request");
  133. return false;
  134. }
  135. auto& url = request.url();
  136. set_resource(ResourceLoader::the().load_resource(Resource::Type::Generic, request));
  137. if (type == Type::Navigation) {
  138. if (auto* page = frame().page())
  139. page->client().page_did_start_loading(url);
  140. }
  141. if (type == Type::IFrame)
  142. return true;
  143. if (url.protocol() == "http" || url.protocol() == "https") {
  144. URL favicon_url;
  145. favicon_url.set_protocol(url.protocol());
  146. favicon_url.set_host(url.host());
  147. favicon_url.set_port(url.port());
  148. favicon_url.set_path("/favicon.ico");
  149. ResourceLoader::the().load(
  150. favicon_url,
  151. [this, favicon_url](auto data, auto&, auto) {
  152. dbgln("Favicon downloaded, {} bytes from {}", data.size(), favicon_url);
  153. auto decoder = Gfx::ImageDecoder::create(data.data(), data.size());
  154. auto bitmap = decoder->bitmap();
  155. if (!bitmap) {
  156. dbgln("Could not decode favicon {}", favicon_url);
  157. return;
  158. }
  159. dbgln("Decoded favicon, {}", bitmap->size());
  160. if (auto* page = frame().page())
  161. page->client().page_did_change_favicon(*bitmap);
  162. });
  163. }
  164. return true;
  165. }
  166. bool FrameLoader::load(const URL& url, Type type)
  167. {
  168. dbgln("FrameLoader::load: {}", url);
  169. if (!url.is_valid()) {
  170. load_error_page(url, "Invalid URL");
  171. return false;
  172. }
  173. auto request = LoadRequest::create_for_url_on_page(url, frame().page());
  174. return load(request, type);
  175. }
  176. void FrameLoader::load_html(const StringView& html, const URL& url)
  177. {
  178. auto document = DOM::Document::create(url);
  179. HTML::HTMLDocumentParser parser(document, html, "utf-8");
  180. parser.run(url);
  181. frame().set_document(&parser.document());
  182. }
  183. // FIXME: Use an actual templating engine (our own one when it's built, preferably
  184. // with a way to check these usages at compile time)
  185. void FrameLoader::load_error_page(const URL& failed_url, const String& error)
  186. {
  187. auto error_page_url = "file:///res/html/error.html";
  188. ResourceLoader::the().load(
  189. error_page_url,
  190. [this, failed_url, error](auto data, auto&, auto) {
  191. VERIFY(!data.is_null());
  192. StringBuilder builder;
  193. SourceGenerator generator { builder };
  194. generator.set("failed_url", escape_html_entities(failed_url.to_string()));
  195. generator.set("error", escape_html_entities(error));
  196. generator.append(data);
  197. auto document = HTML::parse_html_document(generator.as_string_view(), failed_url, "utf-8");
  198. VERIFY(document);
  199. frame().set_document(document);
  200. },
  201. [](auto& error, auto) {
  202. dbgln("Failed to load error page: {}", error);
  203. VERIFY_NOT_REACHED();
  204. });
  205. }
  206. void FrameLoader::resource_did_load()
  207. {
  208. auto url = resource()->url();
  209. if (!resource()->has_encoded_data()) {
  210. load_error_page(url, "No data");
  211. return;
  212. }
  213. // FIXME: Also check HTTP status code before redirecting
  214. auto location = resource()->response_headers().get("Location");
  215. if (location.has_value()) {
  216. load(url.complete_url(location.value()), FrameLoader::Type::Navigation);
  217. return;
  218. }
  219. dbgln("I believe this content has MIME type '{}', , encoding '{}'", resource()->mime_type(), resource()->encoding());
  220. auto document = DOM::Document::create();
  221. document->set_url(url);
  222. document->set_encoding(resource()->encoding());
  223. document->set_content_type(resource()->mime_type());
  224. frame().set_document(document);
  225. if (!parse_document(*document, resource()->encoded_data())) {
  226. load_error_page(url, "Failed to parse content.");
  227. return;
  228. }
  229. // FIXME: Support multiple instances of the Set-Cookie response header.
  230. auto set_cookie = resource()->response_headers().get("Set-Cookie");
  231. if (set_cookie.has_value())
  232. document->set_cookie(set_cookie.value(), Cookie::Source::Http);
  233. if (!url.fragment().is_empty())
  234. frame().scroll_to_anchor(url.fragment());
  235. if (auto* host_element = frame().host_element()) {
  236. // FIXME: Perhaps in the future we'll have a better common base class for <frame> and <iframe>
  237. VERIFY(is<HTML::HTMLIFrameElement>(*host_element));
  238. downcast<HTML::HTMLIFrameElement>(*host_element).content_frame_did_load({});
  239. }
  240. if (auto* page = frame().page())
  241. page->client().page_did_finish_loading(url);
  242. }
  243. void FrameLoader::resource_did_fail()
  244. {
  245. load_error_page(resource()->url(), resource()->error());
  246. }
  247. }