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 <LibGfx/Font/OpenType/Typeface.h>
  8. #include <LibGfx/Font/Typeface.h>
  9. #include <LibGfx/Font/WOFF/Typeface.h>
  10. #include <LibGfx/Font/WOFF2/Typeface.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::Typeface>>> load_vector_font(ByteBuffer const& data)
  27. {
  28. auto promise = Core::Promise<NonnullRefPtr<Gfx::Typeface>>::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::Typeface::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::Typeface::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::Typeface::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. FontFace::~FontFace() = default;
  172. void FontFace::initialize(JS::Realm& realm)
  173. {
  174. Base::initialize(realm);
  175. WEB_SET_PROTOTYPE_FOR_INTERFACE(FontFace);
  176. }
  177. void FontFace::visit_edges(JS::Cell::Visitor& visitor)
  178. {
  179. Base::visit_edges(visitor);
  180. visitor.visit(m_font_status_promise);
  181. }
  182. JS::NonnullGCPtr<JS::Promise> FontFace::loaded() const
  183. {
  184. return verify_cast<JS::Promise>(*m_font_status_promise->promise());
  185. }
  186. // https://drafts.csswg.org/css-font-loading/#dom-fontface-family
  187. WebIDL::ExceptionOr<void> FontFace::set_family(String const& string)
  188. {
  189. auto property = parse_property_string<CSS::PropertyID::FontFamily>(realm(), string);
  190. if (!property)
  191. return WebIDL::SyntaxError::create(realm(), "FontFace.family setter: Invalid font descriptor"_fly_string);
  192. if (m_is_css_connected) {
  193. // FIXME: Propagate to the CSSFontFaceRule and update the font-family property
  194. }
  195. m_family = property->to_string();
  196. return {};
  197. }
  198. // https://drafts.csswg.org/css-font-loading/#dom-fontface-style
  199. WebIDL::ExceptionOr<void> FontFace::set_style(String const& string)
  200. {
  201. auto property = parse_property_string<CSS::PropertyID::FontStyle>(realm(), string);
  202. if (!property)
  203. return WebIDL::SyntaxError::create(realm(), "FontFace.style setter: Invalid font descriptor"_fly_string);
  204. if (m_is_css_connected) {
  205. // FIXME: Propagate to the CSSFontFaceRule and update the font-style property
  206. }
  207. m_style = property->to_string();
  208. return {};
  209. }
  210. // https://drafts.csswg.org/css-font-loading/#dom-fontface-weight
  211. WebIDL::ExceptionOr<void> FontFace::set_weight(String const& string)
  212. {
  213. auto property = parse_property_string<CSS::PropertyID::FontWeight>(realm(), string);
  214. if (!property)
  215. return WebIDL::SyntaxError::create(realm(), "FontFace.weight setter: Invalid font descriptor"_fly_string);
  216. if (m_is_css_connected) {
  217. // FIXME: Propagate to the CSSFontFaceRule and update the font-weight property
  218. }
  219. m_weight = property->to_string();
  220. return {};
  221. }
  222. // https://drafts.csswg.org/css-font-loading/#dom-fontface-stretch
  223. WebIDL::ExceptionOr<void> FontFace::set_stretch(String const& string)
  224. {
  225. auto property = parse_property_string<CSS::PropertyID::FontStretch>(realm(), string);
  226. if (!property)
  227. return WebIDL::SyntaxError::create(realm(), "FontFace.stretch setter: Invalid font descriptor"_fly_string);
  228. if (m_is_css_connected) {
  229. // FIXME: Propagate to the CSSFontFaceRule and update the font-stretch property
  230. }
  231. m_stretch = property->to_string();
  232. return {};
  233. }
  234. // https://drafts.csswg.org/css-font-loading/#dom-fontface-unicoderange
  235. WebIDL::ExceptionOr<void> FontFace::set_unicode_range(String const&)
  236. {
  237. // FIXME: This *should* work, but the <urange> production is hard to parse
  238. // from just a value string in our implementation
  239. return WebIDL::NotSupportedError::create(realm(), "unicode range is not yet implemented"_fly_string);
  240. }
  241. // https://drafts.csswg.org/css-font-loading/#dom-fontface-featuresettings
  242. WebIDL::ExceptionOr<void> FontFace::set_feature_settings(String const&)
  243. {
  244. return WebIDL::NotSupportedError::create(realm(), "feature settings is not yet implemented"_fly_string);
  245. }
  246. // https://drafts.csswg.org/css-font-loading/#dom-fontface-variationsettings
  247. WebIDL::ExceptionOr<void> FontFace::set_variation_settings(String const&)
  248. {
  249. return WebIDL::NotSupportedError::create(realm(), "variation settings is not yet implemented"_fly_string);
  250. }
  251. // https://drafts.csswg.org/css-font-loading/#dom-fontface-display
  252. WebIDL::ExceptionOr<void> FontFace::set_display(String const&)
  253. {
  254. return WebIDL::NotSupportedError::create(realm(), "display is not yet implemented"_fly_string);
  255. }
  256. // https://drafts.csswg.org/css-font-loading/#dom-fontface-ascentoverride
  257. WebIDL::ExceptionOr<void> FontFace::set_ascent_override(String const&)
  258. {
  259. return WebIDL::NotSupportedError::create(realm(), "ascent override is not yet implemented"_fly_string);
  260. }
  261. // https://drafts.csswg.org/css-font-loading/#dom-fontface-descentoverride
  262. WebIDL::ExceptionOr<void> FontFace::set_descent_override(String const&)
  263. {
  264. return WebIDL::NotSupportedError::create(realm(), "descent override is not yet implemented"_fly_string);
  265. }
  266. // https://drafts.csswg.org/css-font-loading/#dom-fontface-linegapoverride
  267. WebIDL::ExceptionOr<void> FontFace::set_line_gap_override(String const&)
  268. {
  269. return WebIDL::NotSupportedError::create(realm(), "line gap override is not yet implemented"_fly_string);
  270. }
  271. // https://drafts.csswg.org/css-font-loading/#dom-fontface-load
  272. JS::NonnullGCPtr<JS::Promise> FontFace::load()
  273. {
  274. // 1. Let font face be the FontFace object on which this method was called.
  275. auto& font_face = *this;
  276. // 2. If font face’s [[Urls]] slot is null, or its status attribute is anything other than "unloaded",
  277. // return font face’s [[FontStatusPromise]] and abort these steps.
  278. if (font_face.m_urls.is_empty() || font_face.m_status != Bindings::FontFaceLoadStatus::Unloaded)
  279. return font_face.loaded();
  280. load_font_source();
  281. return font_face.loaded();
  282. }
  283. void FontFace::load_font_source()
  284. {
  285. VERIFY(!m_urls.is_empty() && m_status == Bindings::FontFaceLoadStatus::Unloaded);
  286. // NOTE: These steps are from the load() method, but can also be called by the user agent when the font
  287. // is needed to render something on the page.
  288. // User agents can initiate font loads on their own, whenever they determine that a given font face is necessary
  289. // to render something on the page. When this happens, they must act as if they had called the corresponding
  290. // FontFace’s load() method described here.
  291. // 3. Otherwise, set font face’s status attribute to "loading", return font face’s [[FontStatusPromise]],
  292. // and continue executing the rest of this algorithm asynchronously.
  293. m_status = Bindings::FontFaceLoadStatus::Loading;
  294. Web::Platform::EventLoopPlugin::the().deferred_invoke([font = JS::make_handle(this)] {
  295. // 4. Using the value of font face’s [[Urls]] slot, attempt to load a font as defined in [CSS-FONTS-3],
  296. // as if it was the value of a @font-face rule’s src descriptor.
  297. // 5. When the load operation completes, successfully or not, queue a task to run the following steps synchronously:
  298. auto on_error = [font] {
  299. HTML::queue_global_task(HTML::Task::Source::FontLoading, HTML::relevant_global_object(*font), JS::create_heap_function(font->heap(), [font = JS::NonnullGCPtr(*font)] {
  300. HTML::TemporaryExecutionContext context(HTML::relevant_settings_object(*font), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  301. // 1. If the attempt to load fails, reject font face’s [[FontStatusPromise]] with a DOMException whose name
  302. // is "NetworkError" and set font face’s status attribute to "error".
  303. font->m_status = Bindings::FontFaceLoadStatus::Error;
  304. WebIDL::reject_promise(font->realm(), font->m_font_status_promise, WebIDL::NetworkError::create(font->realm(), "Failed to load font"_fly_string));
  305. // FIXME: For each FontFaceSet font face is in:
  306. }));
  307. };
  308. auto on_load = [font](FontLoader const& loader) {
  309. // FIXME: We are assuming that the font loader will live as long as the document! This is an unsafe capture
  310. HTML::queue_global_task(HTML::Task::Source::FontLoading, HTML::relevant_global_object(*font), JS::create_heap_function(font->heap(), [font = JS::NonnullGCPtr(*font), &loader] {
  311. HTML::TemporaryExecutionContext context(HTML::relevant_settings_object(*font), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  312. // 2. Otherwise, font face now represents the loaded font; fulfill font face’s [[FontStatusPromise]] with font face
  313. // and set font face’s status attribute to "loaded".
  314. font->m_parsed_font = loader.vector_font();
  315. font->m_status = Bindings::FontFaceLoadStatus::Loaded;
  316. WebIDL::resolve_promise(font->realm(), font->m_font_status_promise, font);
  317. // FIXME: For each FontFaceSet font face is in:
  318. }));
  319. };
  320. // FIXME: We should probably put the 'font cache' on the WindowOrWorkerGlobalScope instead of tying it to the document's style computer
  321. auto& global = HTML::relevant_global_object(*font);
  322. if (is<HTML::Window>(global)) {
  323. auto& window = static_cast<HTML::Window&>(global);
  324. auto& style_computer = const_cast<StyleComputer&>(window.document()->style_computer());
  325. // FIXME: The ParsedFontFace is kind of expensive to create. We should be using a shared sub-object for the data
  326. ParsedFontFace parsed_font_face { font->m_family, font->m_weight.to_number<int>(), 0 /* FIXME: slope */, font->m_urls, font->m_unicode_ranges };
  327. if (auto loader = style_computer.load_font_face(parsed_font_face, move(on_load), move(on_error)); loader.has_value())
  328. loader->start_loading_next_url();
  329. } else {
  330. // FIXME: Don't know how to load fonts in workers! They don't have a StyleComputer
  331. dbgln("FIXME: Worker font loading not implemented");
  332. }
  333. });
  334. }
  335. }