FontFace.cpp 19 KB

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