WindowOrWorkerGlobalScope.cpp 26 KB

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