WindowOrWorkerGlobalScope.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /*
  2. * Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
  3. * Copyright (c) 2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Base64.h>
  9. #include <AK/QuickSort.h>
  10. #include <AK/String.h>
  11. #include <AK/Utf8View.h>
  12. #include <AK/Vector.h>
  13. #include <LibTextCodec/Decoder.h>
  14. #include <LibWeb/Bindings/MainThreadVM.h>
  15. #include <LibWeb/Fetch/FetchMethod.h>
  16. #include <LibWeb/Forward.h>
  17. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  18. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  19. #include <LibWeb/HTML/Scripting/Environments.h>
  20. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  21. #include <LibWeb/HTML/StructuredSerialize.h>
  22. #include <LibWeb/HTML/Timer.h>
  23. #include <LibWeb/HTML/Window.h>
  24. #include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
  25. #include <LibWeb/HighResolutionTime/SupportedPerformanceTypes.h>
  26. #include <LibWeb/Infra/Base64.h>
  27. #include <LibWeb/PerformanceTimeline/EntryTypes.h>
  28. #include <LibWeb/PerformanceTimeline/PerformanceObserver.h>
  29. #include <LibWeb/PerformanceTimeline/PerformanceObserverEntryList.h>
  30. #include <LibWeb/UserTiming/PerformanceMark.h>
  31. #include <LibWeb/UserTiming/PerformanceMeasure.h>
  32. #include <LibWeb/WebIDL/AbstractOperations.h>
  33. #include <LibWeb/WebIDL/DOMException.h>
  34. #include <LibWeb/WebIDL/ExceptionOr.h>
  35. namespace Web::HTML {
  36. WindowOrWorkerGlobalScopeMixin::~WindowOrWorkerGlobalScopeMixin() = default;
  37. void WindowOrWorkerGlobalScopeMixin::initialize(JS::Realm&)
  38. {
  39. #define __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(entry_type, cpp_class) \
  40. m_performance_entry_buffer_map.set(entry_type, \
  41. PerformanceTimeline::PerformanceEntryTuple { \
  42. .performance_entry_buffer = {}, \
  43. .max_buffer_size = cpp_class::max_buffer_size(), \
  44. .available_from_timeline = cpp_class::available_from_timeline(), \
  45. .dropped_entries_count = 0, \
  46. });
  47. ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES
  48. #undef __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES
  49. }
  50. void WindowOrWorkerGlobalScopeMixin::visit_edges(JS::Cell::Visitor& visitor)
  51. {
  52. for (auto& it : m_timers)
  53. visitor.visit(it.value);
  54. for (auto& observer : m_registered_performance_observer_objects)
  55. visitor.visit(observer);
  56. for (auto& entry : m_performance_entry_buffer_map)
  57. entry.value.visit_edges(visitor);
  58. }
  59. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-origin
  60. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::origin() const
  61. {
  62. auto& vm = this_impl().vm();
  63. // The origin getter steps are to return this's relevant settings object's origin, serialized.
  64. return TRY_OR_THROW_OOM(vm, String::from_deprecated_string(relevant_settings_object(this_impl()).origin().serialize()));
  65. }
  66. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-issecurecontext
  67. bool WindowOrWorkerGlobalScopeMixin::is_secure_context() const
  68. {
  69. // The isSecureContext getter steps are to return true if this's relevant settings object is a secure context, or false otherwise.
  70. return HTML::is_secure_context(relevant_settings_object(this_impl()));
  71. }
  72. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-crossoriginisolated
  73. bool WindowOrWorkerGlobalScopeMixin::cross_origin_isolated() const
  74. {
  75. // The crossOriginIsolated getter steps are to return this's relevant settings object's cross-origin isolated capability.
  76. return relevant_settings_object(this_impl()).cross_origin_isolated_capability() == CanUseCrossOriginIsolatedAPIs::Yes;
  77. }
  78. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-btoa
  79. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::btoa(String const& data) const
  80. {
  81. auto& vm = this_impl().vm();
  82. auto& realm = *vm.current_realm();
  83. // The btoa(data) method must throw an "InvalidCharacterError" DOMException if data contains any character whose code point is greater than U+00FF.
  84. Vector<u8> byte_string;
  85. byte_string.ensure_capacity(data.bytes().size());
  86. for (u32 code_point : Utf8View(data)) {
  87. if (code_point > 0xff)
  88. return WebIDL::InvalidCharacterError::create(realm, "Data contains characters outside the range U+0000 and U+00FF");
  89. byte_string.append(code_point);
  90. }
  91. // Otherwise, the user agent must convert data to a byte sequence whose nth byte is the eight-bit representation of the nth code point of data,
  92. // and then must apply forgiving-base64 encode to that byte sequence and return the result.
  93. return TRY_OR_THROW_OOM(vm, encode_base64(byte_string.span()));
  94. }
  95. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob
  96. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::atob(String const& data) const
  97. {
  98. auto& vm = this_impl().vm();
  99. auto& realm = *vm.current_realm();
  100. // 1. Let decodedData be the result of running forgiving-base64 decode on data.
  101. auto decoded_data = Infra::decode_forgiving_base64(data.bytes_as_string_view());
  102. // 2. If decodedData is failure, then throw an "InvalidCharacterError" DOMException.
  103. if (decoded_data.is_error())
  104. return WebIDL::InvalidCharacterError::create(realm, "Input string is not valid base64 data");
  105. // 3. Return decodedData.
  106. // decode_base64() returns a byte string. LibJS uses UTF-8 for strings. Use Latin1Decoder to convert bytes 128-255 to UTF-8.
  107. auto decoder = TextCodec::decoder_for("windows-1252"sv);
  108. VERIFY(decoder.has_value());
  109. return TRY_OR_THROW_OOM(vm, decoder->to_utf8(decoded_data.value()));
  110. }
  111. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-queuemicrotask
  112. void WindowOrWorkerGlobalScopeMixin::queue_microtask(WebIDL::CallbackType& callback)
  113. {
  114. auto& vm = this_impl().vm();
  115. auto& realm = *vm.current_realm();
  116. JS::GCPtr<DOM::Document> document;
  117. if (is<Window>(this_impl()))
  118. document = &static_cast<Window&>(this_impl()).associated_document();
  119. // The queueMicrotask(callback) method must queue a microtask to invoke callback, and if callback throws an exception, report the exception.
  120. HTML::queue_a_microtask(document, [&callback, &realm] {
  121. auto result = WebIDL::invoke_callback(callback, {});
  122. if (result.is_error())
  123. HTML::report_exception(result, realm);
  124. });
  125. }
  126. // https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone
  127. WebIDL::ExceptionOr<JS::Value> WindowOrWorkerGlobalScopeMixin::structured_clone(JS::Value value, StructuredSerializeOptions const& options) const
  128. {
  129. auto& vm = this_impl().vm();
  130. (void)options;
  131. // 1. Let serialized be ? StructuredSerializeWithTransfer(value, options["transfer"]).
  132. // FIXME: Use WithTransfer variant of the AO
  133. auto serialized = TRY(structured_serialize(vm, value));
  134. // 2. Let deserializeRecord be ? StructuredDeserializeWithTransfer(serialized, this's relevant realm).
  135. // FIXME: Use WithTransfer variant of the AO
  136. auto deserialized = TRY(structured_deserialize(vm, serialized, relevant_realm(this_impl()), {}));
  137. // 3. Return deserializeRecord.[[Deserialized]].
  138. return deserialized;
  139. }
  140. JS::NonnullGCPtr<JS::Promise> WindowOrWorkerGlobalScopeMixin::fetch(Fetch::RequestInfo const& input, Fetch::RequestInit const& init) const
  141. {
  142. auto& vm = this_impl().vm();
  143. return Fetch::fetch(vm, input, init);
  144. }
  145. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  146. i32 WindowOrWorkerGlobalScopeMixin::set_timeout(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  147. {
  148. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::No);
  149. }
  150. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  151. i32 WindowOrWorkerGlobalScopeMixin::set_interval(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  152. {
  153. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::Yes);
  154. }
  155. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeout
  156. void WindowOrWorkerGlobalScopeMixin::clear_timeout(i32 id)
  157. {
  158. m_timers.remove(id);
  159. }
  160. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-clearinterval
  161. void WindowOrWorkerGlobalScopeMixin::clear_interval(i32 id)
  162. {
  163. m_timers.remove(id);
  164. }
  165. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps
  166. i32 WindowOrWorkerGlobalScopeMixin::run_timer_initialization_steps(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments, Repeat repeat, Optional<i32> previous_id, Optional<AK::URL> base_url)
  167. {
  168. // 1. Let thisArg be global if that is a WorkerGlobalScope object; otherwise let thisArg be the WindowProxy that corresponds to global.
  169. // 2. If previousId was given, let id be previousId; otherwise, let id be an implementation-defined integer that is greater than zero and does not already exist in global's map of active timers.
  170. auto id = previous_id.has_value() ? previous_id.value() : m_timer_id_allocator.allocate();
  171. // FIXME: 3. If the surrounding agent's event loop's currently running task is a task that was created by this algorithm, then let nesting level be the task's timer nesting level. Otherwise, let nesting level be zero.
  172. // 4. If timeout is less than 0, then set timeout to 0.
  173. if (timeout < 0)
  174. timeout = 0;
  175. // FIXME: 5. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.
  176. // 6. Let callerRealm be the current Realm Record, and calleeRealm be global's relevant Realm.
  177. // FIXME: Implement this when step 9.3.2 is implemented.
  178. // FIXME: The active script becomes null on repeated setInterval callbacks. In JS::VM::get_active_script_or_module,
  179. // the execution context stack is empty on the repeated invocations, thus it returns null. We will need
  180. // to figure out why it becomes empty. But all we need from the active script is the base URL, so we
  181. // grab it on the first invocation an reuse it on repeated invocations.
  182. if (!base_url.has_value()) {
  183. // 7. Let initiating script be the active script.
  184. auto const* initiating_script = Web::Bindings::active_script();
  185. // 8. Assert: initiating script is not null, since this algorithm is always called from some script.
  186. VERIFY(initiating_script);
  187. base_url = initiating_script->base_url();
  188. }
  189. // 9. Let task be a task that runs the following substeps:
  190. JS::SafeFunction<void()> task = [this, handler = move(handler), timeout, arguments = move(arguments), repeat, id, base_url = move(base_url)]() mutable {
  191. // 1. If id does not exist in global's map of active timers, then abort these steps.
  192. if (!m_timers.contains(id))
  193. return;
  194. handler.visit(
  195. // 2. If handler is a Function, then invoke handler given arguments with the callback this value set to thisArg. If this throws an exception, catch it, and report the exception.
  196. [&](JS::Handle<WebIDL::CallbackType> const& callback) {
  197. if (auto result = WebIDL::invoke_callback(*callback, &this_impl(), arguments); result.is_error())
  198. report_exception(result, this_impl().realm());
  199. },
  200. // 3. Otherwise:
  201. [&](String const& source) {
  202. // 1. Assert: handler is a string.
  203. // FIXME: 2. Perform HostEnsureCanCompileStrings(callerRealm, calleeRealm). If this throws an exception, catch it, report the exception, and abort these steps.
  204. // 3. Let settings object be global's relevant settings object.
  205. auto& settings_object = relevant_settings_object(this_impl());
  206. // 4. Let base URL be initiating script's base URL.
  207. // 5. Assert: base URL is not null, as initiating script is a classic script or a JavaScript module script.
  208. VERIFY(base_url.has_value());
  209. // 6. Let fetch options be a script fetch options whose cryptographic nonce is initiating script's fetch options's cryptographic nonce, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is initiating script's fetch options's credentials mode, and referrer policy is initiating script's fetch options's referrer policy.
  210. // 7. Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.
  211. auto script = ClassicScript::create(base_url->basename(), source, settings_object, *base_url);
  212. // 8. Run the classic script script.
  213. (void)script->run();
  214. });
  215. // 4. If id does not exist in global's map of active timers, then abort these steps.
  216. if (!m_timers.contains(id))
  217. return;
  218. switch (repeat) {
  219. // 5. If repeat is true, then perform the timer initialization steps again, given global, handler, timeout, arguments, true, and id.
  220. case Repeat::Yes:
  221. run_timer_initialization_steps(handler, timeout, move(arguments), repeat, id, move(base_url));
  222. break;
  223. // 6. Otherwise, remove global's map of active timers[id].
  224. case Repeat::No:
  225. m_timers.remove(id);
  226. break;
  227. }
  228. };
  229. // FIXME: 10. Increment nesting level by one.
  230. // FIXME: 11. Set task's timer nesting level to nesting level.
  231. // 12. Let completionStep be an algorithm step which queues a global task on the timer task source given global to run task.
  232. JS::SafeFunction<void()> completion_step = [this, task = move(task)]() mutable {
  233. queue_global_task(Task::Source::TimerTask, this_impl(), move(task));
  234. };
  235. // 13. Run steps after a timeout given global, "setTimeout/setInterval", timeout, completionStep, and id.
  236. auto timer = Timer::create(this_impl(), timeout, move(completion_step), id);
  237. m_timers.set(id, timer);
  238. timer->start();
  239. // 14. Return id.
  240. return id;
  241. }
  242. // 1. https://www.w3.org/TR/performance-timeline/#dfn-relevant-performance-entry-tuple
  243. PerformanceTimeline::PerformanceEntryTuple& WindowOrWorkerGlobalScopeMixin::relevant_performance_entry_tuple(FlyString const& entry_type)
  244. {
  245. // 1. Let map be the performance entry buffer map associated with globalObject.
  246. // 2. Return the result of getting the value of an entry from map, given entryType as the key.
  247. auto tuple = m_performance_entry_buffer_map.get(entry_type);
  248. // This shouldn't be called with entry types that aren't in `ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES`.
  249. VERIFY(tuple.has_value());
  250. return tuple.value();
  251. }
  252. // https://www.w3.org/TR/performance-timeline/#dfn-queue-a-performanceentry
  253. void WindowOrWorkerGlobalScopeMixin::queue_performance_entry(JS::NonnullGCPtr<PerformanceTimeline::PerformanceEntry> new_entry)
  254. {
  255. // 1. Let interested observers be an initially empty set of PerformanceObserver objects.
  256. Vector<JS::Handle<PerformanceTimeline::PerformanceObserver>> interested_observers;
  257. // 2. Let entryType be newEntry’s entryType value.
  258. auto const& entry_type = new_entry->entry_type();
  259. // 3. Let relevantGlobal be newEntry's relevant global object.
  260. // NOTE: Already is `this`.
  261. // 4. For each registered performance observer regObs in relevantGlobal's list of registered performance observer
  262. // objects:
  263. for (auto const& registered_observer : m_registered_performance_observer_objects) {
  264. // 1. If regObs's options list contains a PerformanceObserverInit options whose entryTypes member includes entryType
  265. // or whose type member equals to entryType:
  266. auto iterator = registered_observer->options_list().find_if([&entry_type](PerformanceTimeline::PerformanceObserverInit const& entry) {
  267. if (entry.entry_types.has_value())
  268. return entry.entry_types->contains_slow(String::from_utf8(entry_type).release_value_but_fixme_should_propagate_errors());
  269. VERIFY(entry.type.has_value());
  270. return entry.type.value() == entry_type;
  271. });
  272. if (!iterator.is_end()) {
  273. // 1. If should add entry with newEntry and options returns true, append regObs's observer to interested observers.
  274. if (new_entry->should_add_entry(*iterator) == PerformanceTimeline::ShouldAddEntry::Yes)
  275. interested_observers.append(registered_observer);
  276. }
  277. }
  278. // 5. For each observer in interested observers:
  279. for (auto const& observer : interested_observers) {
  280. // 1. Append newEntry to observer's observer buffer.
  281. observer->append_to_observer_buffer({}, new_entry);
  282. }
  283. // 6. Let tuple be the relevant performance entry tuple of entryType and relevantGlobal.
  284. auto& tuple = relevant_performance_entry_tuple(entry_type);
  285. // 7. Let isBufferFull be the return value of the determine if a performance entry buffer is full algorithm with tuple
  286. // as input.
  287. bool is_buffer_full = tuple.is_full();
  288. // 8. Let shouldAdd be the result of should add entry with newEntry as input.
  289. auto should_add = new_entry->should_add_entry();
  290. // 9. If isBufferFull is false and shouldAdd is true, append newEntry to tuple's performance entry buffer.
  291. if (!is_buffer_full && should_add == PerformanceTimeline::ShouldAddEntry::Yes)
  292. tuple.performance_entry_buffer.append(new_entry);
  293. // 10. Queue the PerformanceObserver task with relevantGlobal as input.
  294. queue_the_performance_observer_task();
  295. }
  296. void WindowOrWorkerGlobalScopeMixin::clear_performance_entry_buffer(Badge<HighResolutionTime::Performance>, FlyString const& entry_type)
  297. {
  298. auto& tuple = relevant_performance_entry_tuple(entry_type);
  299. tuple.performance_entry_buffer.clear();
  300. }
  301. void WindowOrWorkerGlobalScopeMixin::remove_entries_from_performance_entry_buffer(Badge<HighResolutionTime::Performance>, FlyString const& entry_type, String entry_name)
  302. {
  303. auto& tuple = relevant_performance_entry_tuple(entry_type);
  304. tuple.performance_entry_buffer.remove_all_matching([&entry_name](JS::Handle<PerformanceTimeline::PerformanceEntry> const& entry) {
  305. return entry->name() == entry_name;
  306. });
  307. }
  308. // https://www.w3.org/TR/performance-timeline/#dfn-filter-buffer-map-by-name-and-type
  309. ErrorOr<Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>>> WindowOrWorkerGlobalScopeMixin::filter_buffer_map_by_name_and_type(Optional<String> name, Optional<String> type) const
  310. {
  311. // 1. Let result be an initially empty list.
  312. Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>> result;
  313. // 2. Let map be the performance entry buffer map associated with the relevant global object of this.
  314. auto const& map = m_performance_entry_buffer_map;
  315. // 3. Let tuple list be an empty list.
  316. Vector<PerformanceTimeline::PerformanceEntryTuple const&> tuple_list;
  317. // 4. If type is not null, append the result of getting the value of entry on map given type as key to tuple list.
  318. // Otherwise, assign the result of get the values on map to tuple list.
  319. if (type.has_value()) {
  320. auto maybe_tuple = map.get(type.value());
  321. if (maybe_tuple.has_value())
  322. TRY(tuple_list.try_append(maybe_tuple.release_value()));
  323. } else {
  324. for (auto const& it : map)
  325. TRY(tuple_list.try_append(it.value));
  326. }
  327. // 5. For each tuple in tuple list, run the following steps:
  328. for (auto const& tuple : tuple_list) {
  329. // 1. Let buffer be tuple's performance entry buffer.
  330. auto const& buffer = tuple.performance_entry_buffer;
  331. // 2. If tuple's availableFromTimeline is false, continue to the next tuple.
  332. if (tuple.available_from_timeline == PerformanceTimeline::AvailableFromTimeline::No)
  333. continue;
  334. // 3. Let entries be the result of running filter buffer by name and type with buffer, name and type as inputs.
  335. auto entries = TRY(filter_buffer_by_name_and_type(buffer, name, type));
  336. // 4. For each entry in entries, append entry to result.
  337. TRY(result.try_extend(entries));
  338. }
  339. // 6. Sort results's entries in chronological order with respect to startTime
  340. quick_sort(result, [](auto const& left_entry, auto const& right_entry) {
  341. return left_entry->start_time() < right_entry->start_time();
  342. });
  343. // 7. Return result.
  344. return result;
  345. }
  346. void WindowOrWorkerGlobalScopeMixin::register_performance_observer(Badge<PerformanceTimeline::PerformanceObserver>, JS::NonnullGCPtr<PerformanceTimeline::PerformanceObserver> observer)
  347. {
  348. m_registered_performance_observer_objects.set(observer, AK::HashSetExistingEntryBehavior::Keep);
  349. }
  350. void WindowOrWorkerGlobalScopeMixin::unregister_performance_observer(Badge<PerformanceTimeline::PerformanceObserver>, JS::NonnullGCPtr<PerformanceTimeline::PerformanceObserver> observer)
  351. {
  352. m_registered_performance_observer_objects.remove(observer);
  353. }
  354. bool WindowOrWorkerGlobalScopeMixin::has_registered_performance_observer(JS::NonnullGCPtr<PerformanceTimeline::PerformanceObserver> observer)
  355. {
  356. return m_registered_performance_observer_objects.contains(observer);
  357. }
  358. // https://w3c.github.io/performance-timeline/#dfn-queue-the-performanceobserver-task
  359. void WindowOrWorkerGlobalScopeMixin::queue_the_performance_observer_task()
  360. {
  361. // 1. If relevantGlobal's performance observer task queued flag is set, terminate these steps.
  362. if (m_performance_observer_task_queued)
  363. return;
  364. // 2. Set relevantGlobal's performance observer task queued flag.
  365. m_performance_observer_task_queued = true;
  366. // 3. Queue a task that consists of running the following substeps. The task source for the queued task is the performance
  367. // timeline task source.
  368. queue_global_task(Task::Source::PerformanceTimeline, this_impl(), [this]() {
  369. auto& realm = this_impl().realm();
  370. // 1. Unset performance observer task queued flag of relevantGlobal.
  371. m_performance_observer_task_queued = false;
  372. // 2. Let notifyList be a copy of relevantGlobal's list of registered performance observer objects.
  373. auto notify_list = m_registered_performance_observer_objects;
  374. // 3. For each registered performance observer object registeredObserver in notifyList, run these steps:
  375. for (auto& registered_observer : notify_list) {
  376. // 1. Let po be registeredObserver's observer.
  377. // 2. Let entries be a copy of po’s observer buffer.
  378. // 4. Empty po’s observer buffer.
  379. auto entries = registered_observer->take_records();
  380. // 3. If entries is empty, return.
  381. // FIXME: Do they mean `continue`?
  382. if (entries.is_empty())
  383. continue;
  384. Vector<JS::NonnullGCPtr<PerformanceTimeline::PerformanceEntry>> entries_as_gc_ptrs;
  385. for (auto& entry : entries)
  386. entries_as_gc_ptrs.append(*entry);
  387. // 5. Let observerEntryList be a new PerformanceObserverEntryList, with its entry list set to entries.
  388. auto observer_entry_list = realm.heap().allocate<PerformanceTimeline::PerformanceObserverEntryList>(realm, realm, move(entries_as_gc_ptrs));
  389. // 6. Let droppedEntriesCount be null.
  390. Optional<u64> dropped_entries_count;
  391. // 7. If po's requires dropped entries is set, perform the following steps:
  392. if (registered_observer->requires_dropped_entries()) {
  393. // 1. Set droppedEntriesCount to 0.
  394. dropped_entries_count = 0;
  395. // 2. For each PerformanceObserverInit item in registeredObserver's options list:
  396. for (auto const& item : registered_observer->options_list()) {
  397. // 1. For each DOMString entryType that appears either as item's type or in item's entryTypes:
  398. auto increment_dropped_entries_count = [this, &dropped_entries_count](FlyString const& type) {
  399. // 1. Let map be relevantGlobal's performance entry buffer map.
  400. auto const& map = m_performance_entry_buffer_map;
  401. // 2. Let tuple be the result of getting the value of entry on map given entryType as key.
  402. auto const& tuple = map.get(type);
  403. VERIFY(tuple.has_value());
  404. // 3. Increase droppedEntriesCount by tuple's dropped entries count.
  405. dropped_entries_count.value() += tuple->dropped_entries_count;
  406. };
  407. if (item.type.has_value()) {
  408. increment_dropped_entries_count(item.type.value());
  409. } else {
  410. VERIFY(item.entry_types.has_value());
  411. for (auto const& type : item.entry_types.value())
  412. increment_dropped_entries_count(type);
  413. }
  414. }
  415. // 3. Set po's requires dropped entries to false.
  416. registered_observer->unset_requires_dropped_entries({});
  417. }
  418. // 8. Let callbackOptions be a PerformanceObserverCallbackOptions with its droppedEntriesCount set to
  419. // droppedEntriesCount if droppedEntriesCount is not null, otherwise unset.
  420. auto callback_options = JS::Object::create(realm, realm.intrinsics().object_prototype());
  421. if (dropped_entries_count.has_value())
  422. MUST(callback_options->create_data_property("droppedEntriesCount", JS::Value(dropped_entries_count.value())));
  423. // 9. Call po’s observer callback with observerEntryList as the first argument, with po as the second
  424. // argument and as callback this value, and with callbackOptions as the third argument.
  425. // If this throws an exception, report the exception.
  426. auto completion = WebIDL::invoke_callback(registered_observer->callback(), registered_observer, observer_entry_list, registered_observer, callback_options);
  427. if (completion.is_abrupt())
  428. HTML::report_exception(completion, realm);
  429. }
  430. });
  431. }
  432. }