FontFace.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. /*
  2. * Copyright (c) 2024, Andrew Kaster <akaster@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibCore/Promise.h>
  7. #include <LibGfx/Font/Typeface.h>
  8. #include <LibGfx/Font/WOFF/Loader.h>
  9. #include <LibGfx/Font/WOFF2/Loader.h>
  10. #include <LibJS/Heap/Heap.h>
  11. #include <LibJS/Runtime/ArrayBuffer.h>
  12. #include <LibJS/Runtime/Realm.h>
  13. #include <LibWeb/Bindings/FontFacePrototype.h>
  14. #include <LibWeb/Bindings/Intrinsics.h>
  15. #include <LibWeb/CSS/FontFace.h>
  16. #include <LibWeb/CSS/Parser/Parser.h>
  17. #include <LibWeb/CSS/StyleComputer.h>
  18. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  19. #include <LibWeb/HTML/Window.h>
  20. #include <LibWeb/Platform/EventLoopPlugin.h>
  21. #include <LibWeb/WebIDL/AbstractOperations.h>
  22. #include <LibWeb/WebIDL/Buffers.h>
  23. #include <LibWeb/WebIDL/Promise.h>
  24. namespace Web::CSS {
  25. static NonnullRefPtr<Core::Promise<NonnullRefPtr<Gfx::Typeface>>> load_vector_font(ByteBuffer const& data)
  26. {
  27. auto promise = Core::Promise<NonnullRefPtr<Gfx::Typeface>>::construct();
  28. // FIXME: 'Asynchronously' shouldn't mean 'later on the main thread'.
  29. // Can we defer this to a background thread?
  30. Platform::EventLoopPlugin::the().deferred_invoke([&data, promise] {
  31. // FIXME: This should be de-duplicated with StyleComputer::FontLoader::try_load_font
  32. // We don't have the luxury of knowing the MIME type, so we have to try all formats.
  33. auto ttf = Gfx::Typeface::try_load_from_externally_owned_memory(data);
  34. if (!ttf.is_error()) {
  35. promise->resolve(ttf.release_value());
  36. return;
  37. }
  38. auto woff = WOFF::try_load_from_externally_owned_memory(data);
  39. if (!woff.is_error()) {
  40. promise->resolve(woff.release_value());
  41. return;
  42. }
  43. auto woff2 = WOFF2::try_load_from_externally_owned_memory(data);
  44. if (!woff2.is_error()) {
  45. promise->resolve(woff2.release_value());
  46. return;
  47. }
  48. promise->reject(Error::from_string_literal("Automatic format detection failed"));
  49. });
  50. return promise;
  51. }
  52. JS_DEFINE_ALLOCATOR(FontFace);
  53. template<CSS::PropertyID PropertyID>
  54. RefPtr<CSSStyleValue const> parse_property_string(JS::Realm& realm, StringView value)
  55. {
  56. auto parser = CSS::Parser::Parser::create(CSS::Parser::ParsingContext(realm), value);
  57. return parser.parse_as_css_value(PropertyID);
  58. }
  59. // https://drafts.csswg.org/css-font-loading/#font-face-constructor
  60. JS::NonnullGCPtr<FontFace> FontFace::construct_impl(JS::Realm& realm, String family, FontFaceSource source, FontFaceDescriptors const& descriptors)
  61. {
  62. auto& vm = realm.vm();
  63. auto base_url = HTML::relevant_settings_object(realm.global_object()).api_base_url();
  64. // 1. Let font face be a fresh FontFace object. Set font face’s status attribute to "unloaded",
  65. // Set its internal [[FontStatusPromise]] slot to a fresh pending Promise object.
  66. auto promise = WebIDL::create_promise(realm);
  67. // FIXME: Parse the family argument, and the members of the descriptors argument,
  68. // according to the grammars of the corresponding descriptors of the CSS @font-face rule.
  69. // If the source argument is a CSSOMString, parse it according to the grammar of the CSS src descriptor of the @font-face rule.
  70. // If any of them fail to parse correctly, reject font face’s [[FontStatusPromise]] with a DOMException named "SyntaxError",
  71. // set font face’s corresponding attributes to the empty string, and set font face’s status attribute to "error".
  72. // Otherwise, set font face’s corresponding attributes to the serialization of the parsed values.
  73. // 2. (Out of order) If the source argument was a CSSOMString, set font face’s internal [[Urls]]
  74. // slot to the string.
  75. // If the source argument was a BinaryData, set font face’s internal [[Data]] slot
  76. // to the passed argument.
  77. Vector<CSS::ParsedFontFace::Source> sources;
  78. ByteBuffer buffer;
  79. if (auto* string = source.get_pointer<String>()) {
  80. auto parser = CSS::Parser::Parser::create(CSS::Parser::ParsingContext(realm, base_url), *string);
  81. sources = parser.parse_as_font_face_src();
  82. if (sources.is_empty())
  83. WebIDL::reject_promise(realm, promise, WebIDL::SyntaxError::create(realm, "FontFace constructor: Invalid source string"_string));
  84. } else {
  85. auto buffer_source = source.get<JS::Handle<WebIDL::BufferSource>>();
  86. auto maybe_buffer = WebIDL::get_buffer_source_copy(buffer_source->raw_object());
  87. if (maybe_buffer.is_error()) {
  88. VERIFY(maybe_buffer.error().code() == ENOMEM);
  89. auto throw_completion = vm.throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory));
  90. WebIDL::reject_promise(realm, promise, *throw_completion.value());
  91. } else {
  92. buffer = maybe_buffer.release_value();
  93. }
  94. }
  95. if (buffer.is_empty() && sources.is_empty())
  96. WebIDL::reject_promise(realm, promise, WebIDL::SyntaxError::create(realm, "FontFace constructor: Invalid font source"_string));
  97. auto font = realm.heap().allocate<FontFace>(realm, realm, promise, move(sources), move(buffer), move(family), descriptors);
  98. // 1. (continued) Return font face. If font face’s status is "error", terminate this algorithm;
  99. // otherwise, complete the rest of these steps asynchronously.
  100. if (font->status() == Bindings::FontFaceLoadStatus::Error)
  101. return font;
  102. // 3. If font face’s [[Data]] slot is not null, queue a task to run the following steps synchronously:
  103. if (font->m_binary_data.is_empty())
  104. return font;
  105. HTML::queue_global_task(HTML::Task::Source::FontLoading, HTML::relevant_global_object(*font), JS::create_heap_function(vm.heap(), [font] {
  106. // 1. Set font face’s status attribute to "loading".
  107. font->m_status = Bindings::FontFaceLoadStatus::Loading;
  108. // 2. FIXME: For each FontFaceSet font face is in:
  109. // 3. Asynchronously, attempt to parse the data in it as a font.
  110. // When this is completed, successfully or not, queue a task to run the following steps synchronously:
  111. font->m_font_load_promise = load_vector_font(font->m_binary_data);
  112. font->m_font_load_promise->when_resolved([font = JS::make_handle(font)](auto const& vector_font) -> ErrorOr<void> {
  113. HTML::queue_global_task(HTML::Task::Source::FontLoading, HTML::relevant_global_object(*font), JS::create_heap_function(font->heap(), [font = JS::NonnullGCPtr(*font), vector_font] {
  114. HTML::TemporaryExecutionContext context(HTML::relevant_settings_object(*font), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  115. // 1. If the load was successful, font face now represents the parsed font;
  116. // fulfill font face’s [[FontStatusPromise]] with font face, and set its status attribute to "loaded".
  117. // FIXME: Are we supposed to set the properties of the FontFace based on the loaded vector font?
  118. font->m_parsed_font = vector_font;
  119. font->m_status = Bindings::FontFaceLoadStatus::Loaded;
  120. WebIDL::resolve_promise(font->realm(), font->m_font_status_promise, font);
  121. // FIXME: For each FontFaceSet font face is in:
  122. font->m_font_load_promise = nullptr;
  123. }));
  124. return {};
  125. });
  126. font->m_font_load_promise->when_rejected([font = JS::make_handle(font)](auto const& error) {
  127. HTML::queue_global_task(HTML::Task::Source::FontLoading, HTML::relevant_global_object(*font), JS::create_heap_function(font->heap(), [font = JS::NonnullGCPtr(*font), error = Error::copy(error)] {
  128. HTML::TemporaryExecutionContext context(HTML::relevant_settings_object(*font), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  129. // 2. Otherwise, reject font face’s [[FontStatusPromise]] with a DOMException named "SyntaxError"
  130. // and set font face’s status attribute to "error".
  131. font->m_status = Bindings::FontFaceLoadStatus::Error;
  132. WebIDL::reject_promise(font->realm(), font->m_font_status_promise, WebIDL::SyntaxError::create(font->realm(), MUST(String::formatted("Failed to load font: {}", error))));
  133. // FIXME: For each FontFaceSet font face is in:
  134. font->m_font_load_promise = nullptr;
  135. }));
  136. });
  137. }));
  138. return font;
  139. }
  140. FontFace::FontFace(JS::Realm& realm, JS::NonnullGCPtr<WebIDL::Promise> font_status_promise, Vector<ParsedFontFace::Source> urls, ByteBuffer data, String font_family, FontFaceDescriptors const& descriptors)
  141. : Bindings::PlatformObject(realm)
  142. , m_font_status_promise(font_status_promise)
  143. , m_urls(move(urls))
  144. , m_binary_data(move(data))
  145. {
  146. m_family = move(font_family);
  147. m_style = descriptors.style;
  148. m_weight = descriptors.weight;
  149. m_stretch = descriptors.stretch;
  150. m_unicode_range = descriptors.unicode_range;
  151. m_feature_settings = descriptors.feature_settings;
  152. m_variation_settings = descriptors.variation_settings;
  153. m_display = descriptors.display;
  154. m_ascent_override = descriptors.ascent_override;
  155. m_descent_override = descriptors.descent_override;
  156. m_line_gap_override = descriptors.line_gap_override;
  157. // FIXME: Parse from descriptor
  158. // FIXME: Have gettter reflect this member instead of the string
  159. m_unicode_ranges.empend(0x0u, 0x10FFFFu);
  160. if (verify_cast<JS::Promise>(*m_font_status_promise->promise()).state() == JS::Promise::State::Rejected)
  161. m_status = Bindings::FontFaceLoadStatus::Error;
  162. }
  163. FontFace::~FontFace() = default;
  164. void FontFace::initialize(JS::Realm& realm)
  165. {
  166. Base::initialize(realm);
  167. WEB_SET_PROTOTYPE_FOR_INTERFACE(FontFace);
  168. }
  169. void FontFace::visit_edges(JS::Cell::Visitor& visitor)
  170. {
  171. Base::visit_edges(visitor);
  172. visitor.visit(m_font_status_promise);
  173. }
  174. JS::NonnullGCPtr<JS::Promise> FontFace::loaded() const
  175. {
  176. return verify_cast<JS::Promise>(*m_font_status_promise->promise());
  177. }
  178. // https://drafts.csswg.org/css-font-loading/#dom-fontface-family
  179. WebIDL::ExceptionOr<void> FontFace::set_family(String const& string)
  180. {
  181. auto property = parse_property_string<CSS::PropertyID::FontFamily>(realm(), string);
  182. if (!property)
  183. return WebIDL::SyntaxError::create(realm(), "FontFace.family setter: Invalid font descriptor"_string);
  184. if (m_is_css_connected) {
  185. // FIXME: Propagate to the CSSFontFaceRule and update the font-family property
  186. }
  187. m_family = property->to_string();
  188. return {};
  189. }
  190. // https://drafts.csswg.org/css-font-loading/#dom-fontface-style
  191. WebIDL::ExceptionOr<void> FontFace::set_style(String const& string)
  192. {
  193. auto property = parse_property_string<CSS::PropertyID::FontStyle>(realm(), string);
  194. if (!property)
  195. return WebIDL::SyntaxError::create(realm(), "FontFace.style setter: Invalid font descriptor"_string);
  196. if (m_is_css_connected) {
  197. // FIXME: Propagate to the CSSFontFaceRule and update the font-style property
  198. }
  199. m_style = property->to_string();
  200. return {};
  201. }
  202. // https://drafts.csswg.org/css-font-loading/#dom-fontface-weight
  203. WebIDL::ExceptionOr<void> FontFace::set_weight(String const& string)
  204. {
  205. auto property = parse_property_string<CSS::PropertyID::FontWeight>(realm(), string);
  206. if (!property)
  207. return WebIDL::SyntaxError::create(realm(), "FontFace.weight setter: Invalid font descriptor"_string);
  208. if (m_is_css_connected) {
  209. // FIXME: Propagate to the CSSFontFaceRule and update the font-weight property
  210. }
  211. m_weight = property->to_string();
  212. return {};
  213. }
  214. // https://drafts.csswg.org/css-font-loading/#dom-fontface-stretch
  215. WebIDL::ExceptionOr<void> FontFace::set_stretch(String const& string)
  216. {
  217. // NOTE: font-stretch is now an alias for font-width
  218. auto property = parse_property_string<CSS::PropertyID::FontWidth>(realm(), string);
  219. if (!property)
  220. return WebIDL::SyntaxError::create(realm(), "FontFace.stretch setter: Invalid font descriptor"_string);
  221. if (m_is_css_connected) {
  222. // FIXME: Propagate to the CSSFontFaceRule and update the font-width property
  223. }
  224. m_stretch = property->to_string();
  225. return {};
  226. }
  227. // https://drafts.csswg.org/css-font-loading/#dom-fontface-unicoderange
  228. WebIDL::ExceptionOr<void> FontFace::set_unicode_range(String const&)
  229. {
  230. // FIXME: This *should* work, but the <urange> production is hard to parse
  231. // from just a value string in our implementation
  232. return WebIDL::NotSupportedError::create(realm(), "unicode range is not yet implemented"_string);
  233. }
  234. // https://drafts.csswg.org/css-font-loading/#dom-fontface-featuresettings
  235. WebIDL::ExceptionOr<void> FontFace::set_feature_settings(String const&)
  236. {
  237. return WebIDL::NotSupportedError::create(realm(), "feature settings is not yet implemented"_string);
  238. }
  239. // https://drafts.csswg.org/css-font-loading/#dom-fontface-variationsettings
  240. WebIDL::ExceptionOr<void> FontFace::set_variation_settings(String const&)
  241. {
  242. return WebIDL::NotSupportedError::create(realm(), "variation settings is not yet implemented"_string);
  243. }
  244. // https://drafts.csswg.org/css-font-loading/#dom-fontface-display
  245. WebIDL::ExceptionOr<void> FontFace::set_display(String const&)
  246. {
  247. return WebIDL::NotSupportedError::create(realm(), "display is not yet implemented"_string);
  248. }
  249. // https://drafts.csswg.org/css-font-loading/#dom-fontface-ascentoverride
  250. WebIDL::ExceptionOr<void> FontFace::set_ascent_override(String const&)
  251. {
  252. return WebIDL::NotSupportedError::create(realm(), "ascent override is not yet implemented"_string);
  253. }
  254. // https://drafts.csswg.org/css-font-loading/#dom-fontface-descentoverride
  255. WebIDL::ExceptionOr<void> FontFace::set_descent_override(String const&)
  256. {
  257. return WebIDL::NotSupportedError::create(realm(), "descent override is not yet implemented"_string);
  258. }
  259. // https://drafts.csswg.org/css-font-loading/#dom-fontface-linegapoverride
  260. WebIDL::ExceptionOr<void> FontFace::set_line_gap_override(String const&)
  261. {
  262. return WebIDL::NotSupportedError::create(realm(), "line gap override is not yet implemented"_string);
  263. }
  264. // https://drafts.csswg.org/css-font-loading/#dom-fontface-load
  265. JS::NonnullGCPtr<JS::Promise> FontFace::load()
  266. {
  267. // 1. Let font face be the FontFace object on which this method was called.
  268. auto& font_face = *this;
  269. // 2. If font face’s [[Urls]] slot is null, or its status attribute is anything other than "unloaded",
  270. // return font face’s [[FontStatusPromise]] and abort these steps.
  271. if (font_face.m_urls.is_empty() || font_face.m_status != Bindings::FontFaceLoadStatus::Unloaded)
  272. return font_face.loaded();
  273. load_font_source();
  274. return font_face.loaded();
  275. }
  276. void FontFace::load_font_source()
  277. {
  278. VERIFY(!m_urls.is_empty() && m_status == Bindings::FontFaceLoadStatus::Unloaded);
  279. // NOTE: These steps are from the load() method, but can also be called by the user agent when the font
  280. // is needed to render something on the page.
  281. // User agents can initiate font loads on their own, whenever they determine that a given font face is necessary
  282. // to render something on the page. When this happens, they must act as if they had called the corresponding
  283. // FontFace’s load() method described here.
  284. // 3. Otherwise, set font face’s status attribute to "loading", return font face’s [[FontStatusPromise]],
  285. // and continue executing the rest of this algorithm asynchronously.
  286. m_status = Bindings::FontFaceLoadStatus::Loading;
  287. Web::Platform::EventLoopPlugin::the().deferred_invoke([font = JS::make_handle(this)] {
  288. // 4. Using the value of font face’s [[Urls]] slot, attempt to load a font as defined in [CSS-FONTS-3],
  289. // as if it was the value of a @font-face rule’s src descriptor.
  290. // 5. When the load operation completes, successfully or not, queue a task to run the following steps synchronously:
  291. auto on_error = [font] {
  292. HTML::queue_global_task(HTML::Task::Source::FontLoading, HTML::relevant_global_object(*font), JS::create_heap_function(font->heap(), [font = JS::NonnullGCPtr(*font)] {
  293. HTML::TemporaryExecutionContext context(HTML::relevant_settings_object(*font), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  294. // 1. If the attempt to load fails, reject font face’s [[FontStatusPromise]] with a DOMException whose name
  295. // is "NetworkError" and set font face’s status attribute to "error".
  296. font->m_status = Bindings::FontFaceLoadStatus::Error;
  297. WebIDL::reject_promise(font->realm(), font->m_font_status_promise, WebIDL::NetworkError::create(font->realm(), "Failed to load font"_string));
  298. // FIXME: For each FontFaceSet font face is in:
  299. }));
  300. };
  301. auto on_load = [font](FontLoader const& loader) {
  302. // FIXME: We are assuming that the font loader will live as long as the document! This is an unsafe capture
  303. HTML::queue_global_task(HTML::Task::Source::FontLoading, HTML::relevant_global_object(*font), JS::create_heap_function(font->heap(), [font = JS::NonnullGCPtr(*font), &loader] {
  304. HTML::TemporaryExecutionContext context(HTML::relevant_settings_object(*font), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  305. // 2. Otherwise, font face now represents the loaded font; fulfill font face’s [[FontStatusPromise]] with font face
  306. // and set font face’s status attribute to "loaded".
  307. font->m_parsed_font = loader.vector_font();
  308. font->m_status = Bindings::FontFaceLoadStatus::Loaded;
  309. WebIDL::resolve_promise(font->realm(), font->m_font_status_promise, font);
  310. // FIXME: For each FontFaceSet font face is in:
  311. }));
  312. };
  313. // FIXME: We should probably put the 'font cache' on the WindowOrWorkerGlobalScope instead of tying it to the document's style computer
  314. auto& global = HTML::relevant_global_object(*font);
  315. if (is<HTML::Window>(global)) {
  316. auto& window = static_cast<HTML::Window&>(global);
  317. auto& style_computer = const_cast<StyleComputer&>(window.document()->style_computer());
  318. // FIXME: The ParsedFontFace is kind of expensive to create. We should be using a shared sub-object for the data
  319. ParsedFontFace parsed_font_face {
  320. font->m_family,
  321. font->m_weight.to_number<int>(),
  322. 0, // FIXME: slope
  323. Gfx::FontWidth::Normal, // FIXME: width
  324. font->m_urls,
  325. font->m_unicode_ranges,
  326. {}, // FIXME: ascent_override
  327. {}, // FIXME: descent_override
  328. {}, // FIXME: line_gap_override
  329. FontDisplay::Auto, // FIXME: font_display
  330. {}, // font-named-instance doesn't exist in FontFace
  331. {}, // font-language-override doesn't exist in FontFace
  332. {}, // FIXME: feature_settings
  333. {}, // FIXME: variation_settings
  334. };
  335. if (auto loader = style_computer.load_font_face(parsed_font_face, move(on_load), move(on_error)); loader.has_value())
  336. loader->start_loading_next_url();
  337. } else {
  338. // FIXME: Don't know how to load fonts in workers! They don't have a StyleComputer
  339. dbgln("FIXME: Worker font loading not implemented");
  340. }
  341. });
  342. }
  343. }