FontFace.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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/Loader.h>
  10. #include <LibGfx/Font/WOFF2/Loader.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::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::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<CSSStyleValue const> parse_property_string(JS::Realm& realm, StringView value)
  56. {
  57. auto parser = CSS::Parser::Parser::create(CSS::Parser::ParsingContext(realm), value);
  58. return parser.parse_as_css_value(PropertyID);
  59. }
  60. // https://drafts.csswg.org/css-font-loading/#font-face-constructor
  61. JS::NonnullGCPtr<FontFace> FontFace::construct_impl(JS::Realm& realm, String family, FontFaceSource source, FontFaceDescriptors const& descriptors)
  62. {
  63. auto& vm = realm.vm();
  64. auto base_url = HTML::relevant_settings_object(realm.global_object()).api_base_url();
  65. // 1. Let font face be a fresh FontFace object. Set font face’s status attribute to "unloaded",
  66. // Set its internal [[FontStatusPromise]] slot to a fresh pending Promise object.
  67. auto promise = WebIDL::create_promise(realm);
  68. // FIXME: Parse the family argument, and the members of the descriptors argument,
  69. // according to the grammars of the corresponding descriptors of the CSS @font-face rule.
  70. // If the source argument is a CSSOMString, parse it according to the grammar of the CSS src descriptor of the @font-face rule.
  71. // If any of them fail to parse correctly, reject font face’s [[FontStatusPromise]] with a DOMException named "SyntaxError",
  72. // set font face’s corresponding attributes to the empty string, and set font face’s status attribute to "error".
  73. // Otherwise, set font face’s corresponding attributes to the serialization of the parsed values.
  74. // 2. (Out of order) If the source argument was a CSSOMString, set font face’s internal [[Urls]]
  75. // slot to the string.
  76. // If the source argument was a BinaryData, set font face’s internal [[Data]] slot
  77. // to the passed argument.
  78. Vector<CSS::ParsedFontFace::Source> sources;
  79. ByteBuffer buffer;
  80. if (auto* string = source.get_pointer<String>()) {
  81. auto parser = CSS::Parser::Parser::create(CSS::Parser::ParsingContext(realm, base_url), *string);
  82. sources = parser.parse_as_font_face_src();
  83. if (sources.is_empty())
  84. WebIDL::reject_promise(realm, promise, WebIDL::SyntaxError::create(realm, "FontFace constructor: Invalid source string"_fly_string));
  85. } else {
  86. auto buffer_source = source.get<JS::Handle<WebIDL::BufferSource>>();
  87. auto maybe_buffer = WebIDL::get_buffer_source_copy(buffer_source->raw_object());
  88. if (maybe_buffer.is_error()) {
  89. VERIFY(maybe_buffer.error().code() == ENOMEM);
  90. auto throw_completion = vm.throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory));
  91. WebIDL::reject_promise(realm, promise, *throw_completion.value());
  92. } else {
  93. buffer = maybe_buffer.release_value();
  94. }
  95. }
  96. if (buffer.is_empty() && sources.is_empty())
  97. WebIDL::reject_promise(realm, promise, WebIDL::SyntaxError::create(realm, "FontFace constructor: Invalid font source"_fly_string));
  98. auto font = realm.heap().allocate<FontFace>(realm, realm, promise, move(sources), move(buffer), move(family), descriptors);
  99. // 1. (continued) Return font face. If font face’s status is "error", terminate this algorithm;
  100. // otherwise, complete the rest of these steps asynchronously.
  101. if (font->status() == Bindings::FontFaceLoadStatus::Error)
  102. return font;
  103. // 3. If font face’s [[Data]] slot is not null, queue a task to run the following steps synchronously:
  104. if (font->m_binary_data.is_empty())
  105. return font;
  106. HTML::queue_global_task(HTML::Task::Source::FontLoading, HTML::relevant_global_object(*font), JS::create_heap_function(vm.heap(), [font] {
  107. // 1. Set font face’s status attribute to "loading".
  108. font->m_status = Bindings::FontFaceLoadStatus::Loading;
  109. // 2. FIXME: For each FontFaceSet font face is in:
  110. // 3. Asynchronously, attempt to parse the data in it as a font.
  111. // When this is completed, successfully or not, queue a task to run the following steps synchronously:
  112. font->m_font_load_promise = load_vector_font(font->m_binary_data);
  113. font->m_font_load_promise->when_resolved([font = JS::make_handle(font)](auto const& vector_font) -> ErrorOr<void> {
  114. 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] {
  115. HTML::TemporaryExecutionContext context(HTML::relevant_settings_object(*font), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  116. // 1. If the load was successful, font face now represents the parsed font;
  117. // fulfill font face’s [[FontStatusPromise]] with font face, and set its status attribute to "loaded".
  118. // FIXME: Are we supposed to set the properties of the FontFace based on the loaded vector font?
  119. font->m_parsed_font = vector_font;
  120. font->m_status = Bindings::FontFaceLoadStatus::Loaded;
  121. WebIDL::resolve_promise(font->realm(), font->m_font_status_promise, font);
  122. // FIXME: For each FontFaceSet font face is in:
  123. font->m_font_load_promise = nullptr;
  124. }));
  125. return {};
  126. });
  127. font->m_font_load_promise->when_rejected([font = JS::make_handle(font)](auto const& error) {
  128. 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)] {
  129. HTML::TemporaryExecutionContext context(HTML::relevant_settings_object(*font), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
  130. // 2. Otherwise, reject font face’s [[FontStatusPromise]] with a DOMException named "SyntaxError"
  131. // and set font face’s status attribute to "error".
  132. font->m_status = Bindings::FontFaceLoadStatus::Error;
  133. WebIDL::reject_promise(font->realm(), font->m_font_status_promise, WebIDL::SyntaxError::create(font->realm(), MUST(String::formatted("Failed to load font: {}", error))));
  134. // FIXME: For each FontFaceSet font face is in:
  135. font->m_font_load_promise = nullptr;
  136. }));
  137. });
  138. }));
  139. return font;
  140. }
  141. FontFace::FontFace(JS::Realm& realm, JS::NonnullGCPtr<WebIDL::Promise> font_status_promise, Vector<ParsedFontFace::Source> urls, ByteBuffer data, String font_family, FontFaceDescriptors const& descriptors)
  142. : Bindings::PlatformObject(realm)
  143. , m_font_status_promise(font_status_promise)
  144. , m_urls(move(urls))
  145. , m_binary_data(move(data))
  146. {
  147. m_family = move(font_family);
  148. m_style = descriptors.style;
  149. m_weight = descriptors.weight;
  150. m_stretch = descriptors.stretch;
  151. m_unicode_range = descriptors.unicode_range;
  152. m_feature_settings = descriptors.feature_settings;
  153. m_variation_settings = descriptors.variation_settings;
  154. m_display = descriptors.display;
  155. m_ascent_override = descriptors.ascent_override;
  156. m_descent_override = descriptors.descent_override;
  157. m_line_gap_override = descriptors.line_gap_override;
  158. // FIXME: Parse from descriptor
  159. // FIXME: Have gettter reflect this member instead of the string
  160. m_unicode_ranges.empend(0x0u, 0x10FFFFu);
  161. if (verify_cast<JS::Promise>(*m_font_status_promise->promise()).state() == JS::Promise::State::Rejected)
  162. m_status = Bindings::FontFaceLoadStatus::Error;
  163. }
  164. FontFace::~FontFace() = default;
  165. void FontFace::initialize(JS::Realm& realm)
  166. {
  167. Base::initialize(realm);
  168. WEB_SET_PROTOTYPE_FOR_INTERFACE(FontFace);
  169. }
  170. void FontFace::visit_edges(JS::Cell::Visitor& visitor)
  171. {
  172. Base::visit_edges(visitor);
  173. visitor.visit(m_font_status_promise);
  174. }
  175. JS::NonnullGCPtr<JS::Promise> FontFace::loaded() const
  176. {
  177. return verify_cast<JS::Promise>(*m_font_status_promise->promise());
  178. }
  179. // https://drafts.csswg.org/css-font-loading/#dom-fontface-family
  180. WebIDL::ExceptionOr<void> FontFace::set_family(String const& string)
  181. {
  182. auto property = parse_property_string<CSS::PropertyID::FontFamily>(realm(), string);
  183. if (!property)
  184. return WebIDL::SyntaxError::create(realm(), "FontFace.family setter: Invalid font descriptor"_fly_string);
  185. if (m_is_css_connected) {
  186. // FIXME: Propagate to the CSSFontFaceRule and update the font-family property
  187. }
  188. m_family = property->to_string();
  189. return {};
  190. }
  191. // https://drafts.csswg.org/css-font-loading/#dom-fontface-style
  192. WebIDL::ExceptionOr<void> FontFace::set_style(String const& string)
  193. {
  194. auto property = parse_property_string<CSS::PropertyID::FontStyle>(realm(), string);
  195. if (!property)
  196. return WebIDL::SyntaxError::create(realm(), "FontFace.style setter: Invalid font descriptor"_fly_string);
  197. if (m_is_css_connected) {
  198. // FIXME: Propagate to the CSSFontFaceRule and update the font-style property
  199. }
  200. m_style = property->to_string();
  201. return {};
  202. }
  203. // https://drafts.csswg.org/css-font-loading/#dom-fontface-weight
  204. WebIDL::ExceptionOr<void> FontFace::set_weight(String const& string)
  205. {
  206. auto property = parse_property_string<CSS::PropertyID::FontWeight>(realm(), string);
  207. if (!property)
  208. return WebIDL::SyntaxError::create(realm(), "FontFace.weight setter: Invalid font descriptor"_fly_string);
  209. if (m_is_css_connected) {
  210. // FIXME: Propagate to the CSSFontFaceRule and update the font-weight property
  211. }
  212. m_weight = property->to_string();
  213. return {};
  214. }
  215. // https://drafts.csswg.org/css-font-loading/#dom-fontface-stretch
  216. WebIDL::ExceptionOr<void> FontFace::set_stretch(String const& string)
  217. {
  218. auto property = parse_property_string<CSS::PropertyID::FontStretch>(realm(), string);
  219. if (!property)
  220. return WebIDL::SyntaxError::create(realm(), "FontFace.stretch setter: Invalid font descriptor"_fly_string);
  221. if (m_is_css_connected) {
  222. // FIXME: Propagate to the CSSFontFaceRule and update the font-stretch 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"_fly_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"_fly_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"_fly_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"_fly_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"_fly_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"_fly_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"_fly_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"_fly_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 { font->m_family, font->m_weight.to_number<int>(), 0 /* FIXME: slope */, font->m_urls, font->m_unicode_ranges };
  320. if (auto loader = style_computer.load_font_face(parsed_font_face, move(on_load), move(on_error)); loader.has_value())
  321. loader->start_loading_next_url();
  322. } else {
  323. // FIXME: Don't know how to load fonts in workers! They don't have a StyleComputer
  324. dbgln("FIXME: Worker font loading not implemented");
  325. }
  326. });
  327. }
  328. }