FontFace.cpp 19 KB

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