Window.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. /*
  2. * Copyright (c) 2020-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2022, Sam Atkins <atkinssj@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/AbstractOperations.h>
  8. #include <LibJS/Runtime/FunctionObject.h>
  9. #include <LibWeb/Bindings/IDLAbstractOperations.h>
  10. #include <LibWeb/Bindings/IdleDeadlineWrapper.h>
  11. #include <LibWeb/CSS/Parser/Parser.h>
  12. #include <LibWeb/CSS/ResolvedCSSStyleDeclaration.h>
  13. #include <LibWeb/Crypto/Crypto.h>
  14. #include <LibWeb/DOM/Document.h>
  15. #include <LibWeb/DOM/Event.h>
  16. #include <LibWeb/DOM/EventDispatcher.h>
  17. #include <LibWeb/HTML/BrowsingContext.h>
  18. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  19. #include <LibWeb/HTML/MessageEvent.h>
  20. #include <LibWeb/HTML/PageTransitionEvent.h>
  21. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  22. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  23. #include <LibWeb/HTML/Storage.h>
  24. #include <LibWeb/HTML/Timer.h>
  25. #include <LibWeb/HTML/Window.h>
  26. #include <LibWeb/HighResolutionTime/Performance.h>
  27. #include <LibWeb/Layout/InitialContainingBlock.h>
  28. #include <LibWeb/Page/Page.h>
  29. #include <LibWeb/RequestIdleCallback/IdleDeadline.h>
  30. #include <LibWeb/Selection/Selection.h>
  31. namespace Web::HTML {
  32. // https://html.spec.whatwg.org/#run-the-animation-frame-callbacks
  33. void run_animation_frame_callbacks(DOM::Document& document, double)
  34. {
  35. // FIXME: Bring this closer to the spec.
  36. document.window().animation_frame_callback_driver().run();
  37. }
  38. class IdleCallback : public RefCounted<IdleCallback> {
  39. public:
  40. explicit IdleCallback(Function<JS::Completion(NonnullRefPtr<RequestIdleCallback::IdleDeadline>)> handler, u32 handle)
  41. : m_handler(move(handler))
  42. , m_handle(handle)
  43. {
  44. }
  45. ~IdleCallback() = default;
  46. JS::Completion invoke(NonnullRefPtr<RequestIdleCallback::IdleDeadline> deadline) { return m_handler(move(deadline)); }
  47. u32 handle() const { return m_handle; }
  48. private:
  49. Function<JS::Completion(NonnullRefPtr<RequestIdleCallback::IdleDeadline>)> m_handler;
  50. u32 m_handle { 0 };
  51. };
  52. NonnullRefPtr<Window> Window::create_with_document(DOM::Document& document)
  53. {
  54. return adopt_ref(*new Window(document));
  55. }
  56. Window::Window(DOM::Document& document)
  57. : DOM::EventTarget()
  58. , m_associated_document(document)
  59. , m_performance(make<HighResolutionTime::Performance>(*this))
  60. , m_crypto(Crypto::Crypto::create())
  61. , m_screen(CSS::Screen::create({}, *this))
  62. {
  63. }
  64. Window::~Window() = default;
  65. void Window::set_wrapper(Badge<Bindings::WindowObject>, Bindings::WindowObject& wrapper)
  66. {
  67. m_wrapper = wrapper.make_weak_ptr();
  68. }
  69. void Window::alert(String const& message)
  70. {
  71. if (auto* page = this->page())
  72. page->client().page_did_request_alert(message);
  73. }
  74. bool Window::confirm(String const& message)
  75. {
  76. if (auto* page = this->page())
  77. return page->client().page_did_request_confirm(message);
  78. return false;
  79. }
  80. String Window::prompt(String const& message, String const& default_)
  81. {
  82. if (auto* page = this->page())
  83. return page->client().page_did_request_prompt(message, default_);
  84. return {};
  85. }
  86. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  87. i32 Window::set_timeout(Bindings::TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  88. {
  89. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::No);
  90. }
  91. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  92. i32 Window::set_interval(Bindings::TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  93. {
  94. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::Yes);
  95. }
  96. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeout
  97. void Window::clear_timeout(i32 id)
  98. {
  99. m_timers.remove(id);
  100. }
  101. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-clearinterval
  102. void Window::clear_interval(i32 id)
  103. {
  104. m_timers.remove(id);
  105. }
  106. void Window::deallocate_timer_id(Badge<Timer>, i32 id)
  107. {
  108. m_timer_id_allocator.deallocate(id);
  109. }
  110. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps
  111. i32 Window::run_timer_initialization_steps(Bindings::TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments, Repeat repeat, Optional<i32> previous_id)
  112. {
  113. // 1. Let thisArg be global if that is a WorkerGlobalScope object; otherwise let thisArg be the WindowProxy that corresponds to global.
  114. // 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.
  115. auto id = previous_id.has_value() ? previous_id.value() : m_timer_id_allocator.allocate();
  116. // 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.
  117. // 4. If timeout is less than 0, then set timeout to 0.
  118. if (timeout < 0)
  119. timeout = 0;
  120. // FIXME: 5. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.
  121. // 6. Let callerRealm be the current Realm Record, and calleeRealm be global's relevant Realm.
  122. // FIXME: Implement this when step 9.2 is implemented.
  123. // 7. Let initiating script be the active script.
  124. // 8. Assert: initiating script is not null, since this algorithm is always called from some script.
  125. // 9. Let task be a task that runs the following substeps:
  126. auto task = [weak_window = make_weak_ptr(), handler = move(handler), timeout, arguments = move(arguments), repeat, id]() mutable {
  127. auto window = weak_window.strong_ref();
  128. if (!window)
  129. return;
  130. // 1. If id does not exist in global's map of active timers, then abort these steps.
  131. if (!window->m_timers.contains(id))
  132. return;
  133. handler.visit(
  134. // 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.
  135. [&](Bindings::CallbackType& callback) {
  136. if (auto result = Bindings::IDL::invoke_callback(callback, window->wrapper(), arguments); result.is_error())
  137. HTML::report_exception(result);
  138. },
  139. // 3. Otherwise:
  140. [&](String const& source) {
  141. // 1. Assert: handler is a string.
  142. // FIXME: 2. Perform HostEnsureCanCompileStrings(callerRealm, calleeRealm). If this throws an exception, catch it, report the exception, and abort these steps.
  143. // 3. Let settings object be global's relevant settings object.
  144. auto& settings_object = window->associated_document().relevant_settings_object();
  145. // 4. Let base URL be initiating script's base URL.
  146. auto url = window->associated_document().url();
  147. // 5. Assert: base URL is not null, as initiating script is a classic script or a JavaScript module script.
  148. // 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.
  149. // 7. Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.
  150. auto script = HTML::ClassicScript::create(url.basename(), source, settings_object, url);
  151. // 8. Run the classic script script.
  152. (void)script->run();
  153. });
  154. // 4. If id does not exist in global's map of active timers, then abort these steps.
  155. if (!window->m_timers.contains(id))
  156. return;
  157. switch (repeat) {
  158. // 5. If repeat is true, then perform the timer initialization steps again, given global, handler, timeout, arguments, true, and id.
  159. case Repeat::Yes:
  160. window->run_timer_initialization_steps(handler, timeout, move(arguments), repeat, id);
  161. break;
  162. // 6. Otherwise, remove global's map of active timers[id].
  163. case Repeat::No:
  164. window->m_timers.remove(id);
  165. break;
  166. }
  167. };
  168. // FIXME: 10. Increment nesting level by one.
  169. // FIXME: 11. Set task's timer nesting level to nesting level.
  170. // 12. Let completionStep be an algorithm step which queues a global task on the timer task source given global to run task.
  171. auto completion_step = [weak_window = make_weak_ptr(), task = move(task)]() mutable {
  172. auto window = weak_window.strong_ref();
  173. if (!window)
  174. return;
  175. HTML::queue_global_task(HTML::Task::Source::TimerTask, *window->wrapper(), move(task));
  176. };
  177. // 13. Run steps after a timeout given global, "setTimeout/setInterval", timeout, completionStep, and id.
  178. auto timer = Timer::create(*this, timeout, move(completion_step), id);
  179. m_timers.set(id, timer);
  180. timer->start();
  181. // 14. Return id.
  182. return id;
  183. }
  184. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#run-the-animation-frame-callbacks
  185. i32 Window::request_animation_frame(NonnullOwnPtr<Bindings::CallbackType> js_callback)
  186. {
  187. return m_animation_frame_callback_driver.add([this, js_callback = move(js_callback)](auto) mutable {
  188. // 3. Invoke callback, passing now as the only argument,
  189. auto result = Bindings::IDL::invoke_callback(*js_callback, {}, JS::Value(performance().now()));
  190. // and if an exception is thrown, report the exception.
  191. if (result.is_error())
  192. HTML::report_exception(result);
  193. });
  194. }
  195. void Window::cancel_animation_frame(i32 id)
  196. {
  197. m_animation_frame_callback_driver.remove(id);
  198. }
  199. void Window::did_set_location_href(Badge<Bindings::LocationObject>, AK::URL const& new_href)
  200. {
  201. auto* browsing_context = associated_document().browsing_context();
  202. if (!browsing_context)
  203. return;
  204. browsing_context->loader().load(new_href, FrameLoader::Type::Navigation);
  205. }
  206. void Window::did_call_location_reload(Badge<Bindings::LocationObject>)
  207. {
  208. auto* browsing_context = associated_document().browsing_context();
  209. if (!browsing_context)
  210. return;
  211. browsing_context->loader().load(associated_document().url(), FrameLoader::Type::Reload);
  212. }
  213. void Window::did_call_location_replace(Badge<Bindings::LocationObject>, String url)
  214. {
  215. auto* browsing_context = associated_document().browsing_context();
  216. if (!browsing_context)
  217. return;
  218. auto new_url = associated_document().parse_url(url);
  219. browsing_context->loader().load(move(new_url), FrameLoader::Type::Navigation);
  220. }
  221. bool Window::dispatch_event(NonnullRefPtr<DOM::Event> event)
  222. {
  223. return DOM::EventDispatcher::dispatch(*this, event, true);
  224. }
  225. JS::Object* Window::create_wrapper(JS::GlobalObject& global_object)
  226. {
  227. return &global_object;
  228. }
  229. // https://www.w3.org/TR/cssom-view-1/#dom-window-innerwidth
  230. int Window::inner_width() const
  231. {
  232. // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar (if any),
  233. // or zero if there is no viewport.
  234. if (auto const* browsing_context = associated_document().browsing_context())
  235. return browsing_context->viewport_rect().width();
  236. return 0;
  237. }
  238. // https://www.w3.org/TR/cssom-view-1/#dom-window-innerheight
  239. int Window::inner_height() const
  240. {
  241. // The innerHeight attribute must return the viewport height including the size of a rendered scroll bar (if any),
  242. // or zero if there is no viewport.
  243. if (auto const* browsing_context = associated_document().browsing_context())
  244. return browsing_context->viewport_rect().height();
  245. return 0;
  246. }
  247. Page* Window::page()
  248. {
  249. return associated_document().page();
  250. }
  251. Page const* Window::page() const
  252. {
  253. return associated_document().page();
  254. }
  255. NonnullRefPtr<CSS::CSSStyleDeclaration> Window::get_computed_style(DOM::Element& element) const
  256. {
  257. return CSS::ResolvedCSSStyleDeclaration::create(element);
  258. }
  259. NonnullRefPtr<CSS::MediaQueryList> Window::match_media(String media)
  260. {
  261. auto media_query_list = CSS::MediaQueryList::create(associated_document(), parse_media_query_list(CSS::Parser::ParsingContext(associated_document()), media));
  262. associated_document().add_media_query_list(media_query_list);
  263. return media_query_list;
  264. }
  265. Optional<CSS::MediaFeatureValue> Window::query_media_feature(CSS::MediaFeatureID media_feature) const
  266. {
  267. // FIXME: Many of these should be dependent on the hardware
  268. // https://www.w3.org/TR/mediaqueries-5/#media-descriptor-table
  269. switch (media_feature) {
  270. case CSS::MediaFeatureID::AnyHover:
  271. return CSS::MediaFeatureValue(CSS::ValueID::Hover);
  272. case CSS::MediaFeatureID::AnyPointer:
  273. return CSS::MediaFeatureValue(CSS::ValueID::Fine);
  274. case CSS::MediaFeatureID::AspectRatio:
  275. return CSS::MediaFeatureValue(CSS::Ratio(inner_width(), inner_height()));
  276. case CSS::MediaFeatureID::Color:
  277. return CSS::MediaFeatureValue(8);
  278. case CSS::MediaFeatureID::ColorGamut:
  279. return CSS::MediaFeatureValue(CSS::ValueID::Srgb);
  280. case CSS::MediaFeatureID::ColorIndex:
  281. return CSS::MediaFeatureValue(0);
  282. // FIXME: device-aspect-ratio
  283. // FIXME: device-height
  284. // FIXME: device-width
  285. case CSS::MediaFeatureID::DisplayMode:
  286. // FIXME: Detect if window is fullscreen
  287. return CSS::MediaFeatureValue(CSS::ValueID::Browser);
  288. case CSS::MediaFeatureID::DynamicRange:
  289. return CSS::MediaFeatureValue(CSS::ValueID::Standard);
  290. case CSS::MediaFeatureID::EnvironmentBlending:
  291. return CSS::MediaFeatureValue(CSS::ValueID::Opaque);
  292. case CSS::MediaFeatureID::ForcedColors:
  293. return CSS::MediaFeatureValue(CSS::ValueID::None);
  294. case CSS::MediaFeatureID::Grid:
  295. return CSS::MediaFeatureValue(0);
  296. case CSS::MediaFeatureID::Height:
  297. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_height()));
  298. case CSS::MediaFeatureID::HorizontalViewportSegments:
  299. return CSS::MediaFeatureValue(1);
  300. case CSS::MediaFeatureID::Hover:
  301. return CSS::MediaFeatureValue(CSS::ValueID::Hover);
  302. case CSS::MediaFeatureID::InvertedColors:
  303. return CSS::MediaFeatureValue(CSS::ValueID::None);
  304. case CSS::MediaFeatureID::Monochrome:
  305. return CSS::MediaFeatureValue(0);
  306. case CSS::MediaFeatureID::NavControls:
  307. return CSS::MediaFeatureValue(CSS::ValueID::Back);
  308. case CSS::MediaFeatureID::Orientation:
  309. return CSS::MediaFeatureValue(inner_height() >= inner_width() ? CSS::ValueID::Portrait : CSS::ValueID::Landscape);
  310. case CSS::MediaFeatureID::OverflowBlock:
  311. return CSS::MediaFeatureValue(CSS::ValueID::Scroll);
  312. case CSS::MediaFeatureID::OverflowInline:
  313. return CSS::MediaFeatureValue(CSS::ValueID::Scroll);
  314. case CSS::MediaFeatureID::Pointer:
  315. return CSS::MediaFeatureValue(CSS::ValueID::Fine);
  316. case CSS::MediaFeatureID::PrefersColorScheme: {
  317. if (auto* page = this->page()) {
  318. switch (page->preferred_color_scheme()) {
  319. case CSS::PreferredColorScheme::Light:
  320. return CSS::MediaFeatureValue(CSS::ValueID::Light);
  321. case CSS::PreferredColorScheme::Dark:
  322. return CSS::MediaFeatureValue(CSS::ValueID::Dark);
  323. case CSS::PreferredColorScheme::Auto:
  324. default:
  325. return CSS::MediaFeatureValue(page->palette().is_dark() ? CSS::ValueID::Dark : CSS::ValueID::Light);
  326. }
  327. }
  328. return CSS::MediaFeatureValue(CSS::ValueID::Light);
  329. }
  330. case CSS::MediaFeatureID::PrefersContrast:
  331. // FIXME: Make this a preference
  332. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  333. case CSS::MediaFeatureID::PrefersReducedData:
  334. // FIXME: Make this a preference
  335. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  336. case CSS::MediaFeatureID::PrefersReducedMotion:
  337. // FIXME: Make this a preference
  338. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  339. case CSS::MediaFeatureID::PrefersReducedTransparency:
  340. // FIXME: Make this a preference
  341. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  342. // FIXME: resolution
  343. case CSS::MediaFeatureID::Scan:
  344. return CSS::MediaFeatureValue(CSS::ValueID::Progressive);
  345. case CSS::MediaFeatureID::Scripting:
  346. if (associated_document().is_scripting_enabled())
  347. return CSS::MediaFeatureValue(CSS::ValueID::Enabled);
  348. return CSS::MediaFeatureValue(CSS::ValueID::None);
  349. case CSS::MediaFeatureID::Update:
  350. return CSS::MediaFeatureValue(CSS::ValueID::Fast);
  351. case CSS::MediaFeatureID::VerticalViewportSegments:
  352. return CSS::MediaFeatureValue(1);
  353. case CSS::MediaFeatureID::VideoColorGamut:
  354. return CSS::MediaFeatureValue(CSS::ValueID::Srgb);
  355. case CSS::MediaFeatureID::VideoDynamicRange:
  356. return CSS::MediaFeatureValue(CSS::ValueID::Standard);
  357. case CSS::MediaFeatureID::Width:
  358. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_width()));
  359. default:
  360. break;
  361. }
  362. return {};
  363. }
  364. // https://www.w3.org/TR/cssom-view/#dom-window-scrollx
  365. float Window::scroll_x() const
  366. {
  367. if (auto* page = this->page())
  368. return page->top_level_browsing_context().viewport_scroll_offset().x();
  369. return 0;
  370. }
  371. // https://www.w3.org/TR/cssom-view/#dom-window-scrolly
  372. float Window::scroll_y() const
  373. {
  374. if (auto* page = this->page())
  375. return page->top_level_browsing_context().viewport_scroll_offset().y();
  376. return 0;
  377. }
  378. // https://html.spec.whatwg.org/#fire-a-page-transition-event
  379. void Window::fire_a_page_transition_event(FlyString const& event_name, bool persisted)
  380. {
  381. // To fire a page transition event named eventName at a Window window with a boolean persisted,
  382. // fire an event named eventName at window, using PageTransitionEvent,
  383. // with the persisted attribute initialized to persisted,
  384. HTML::PageTransitionEventInit event_init {};
  385. event_init.persisted = persisted;
  386. auto event = HTML::PageTransitionEvent::create(event_name, event_init);
  387. // ...the cancelable attribute initialized to true,
  388. event->set_cancelable(true);
  389. // the bubbles attribute initialized to true,
  390. event->set_bubbles(true);
  391. // and legacy target override flag set.
  392. dispatch_event(move(event));
  393. }
  394. // https://html.spec.whatwg.org/#dom-queuemicrotask
  395. void Window::queue_microtask(NonnullOwnPtr<Bindings::CallbackType> callback)
  396. {
  397. // The queueMicrotask(callback) method must queue a microtask to invoke callback,
  398. HTML::queue_a_microtask(&associated_document(), [callback = move(callback)]() mutable {
  399. auto result = Bindings::IDL::invoke_callback(*callback, {});
  400. // and if callback throws an exception, report the exception.
  401. if (result.is_error())
  402. HTML::report_exception(result);
  403. });
  404. }
  405. float Window::device_pixel_ratio() const
  406. {
  407. // FIXME: Return 2.0f if we're in HiDPI mode!
  408. return 1.0f;
  409. }
  410. // https://drafts.csswg.org/cssom-view/#dom-window-screenx
  411. int Window::screen_x() const
  412. {
  413. // The screenX and screenLeft attributes must return the x-coordinate, relative to the origin of the Web-exposed screen area,
  414. // of the left of the client window as number of CSS pixels, or zero if there is no such thing.
  415. return 0;
  416. }
  417. // https://drafts.csswg.org/cssom-view/#dom-window-screeny
  418. int Window::screen_y() const
  419. {
  420. // The screenY and screenTop attributes must return the y-coordinate, relative to the origin of the screen of the Web-exposed screen area,
  421. // of the top of the client window as number of CSS pixels, or zero if there is no such thing.
  422. return 0;
  423. }
  424. // https://w3c.github.io/selection-api/#dom-window-getselection
  425. Selection::Selection* Window::get_selection()
  426. {
  427. // FIXME: Implement.
  428. return nullptr;
  429. }
  430. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-localstorage
  431. RefPtr<HTML::Storage> Window::local_storage()
  432. {
  433. // FIXME: Implement according to spec.
  434. static HashMap<Origin, NonnullRefPtr<HTML::Storage>> local_storage_per_origin;
  435. return local_storage_per_origin.ensure(associated_document().origin(), [] {
  436. return HTML::Storage::create();
  437. });
  438. }
  439. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-sessionstorage
  440. RefPtr<HTML::Storage> Window::session_storage()
  441. {
  442. // FIXME: Implement according to spec.
  443. static HashMap<Origin, NonnullRefPtr<HTML::Storage>> session_storage_per_origin;
  444. return session_storage_per_origin.ensure(associated_document().origin(), [] {
  445. return HTML::Storage::create();
  446. });
  447. }
  448. // https://html.spec.whatwg.org/multipage/browsers.html#dom-parent
  449. Window* Window::parent()
  450. {
  451. // 1. Let current be this Window object's browsing context.
  452. auto* current = associated_document().browsing_context();
  453. // 2. If current is null, then return null.
  454. if (!current)
  455. return nullptr;
  456. // 3. If current is a child browsing context of another browsing context parent,
  457. // then return parent's WindowProxy object.
  458. if (current->parent()) {
  459. VERIFY(current->parent()->active_document());
  460. return &current->parent()->active_document()->window();
  461. }
  462. // 4. Assert: current is a top-level browsing context.
  463. VERIFY(current->is_top_level());
  464. // FIXME: 5. Return current's WindowProxy object.
  465. VERIFY(current->active_document());
  466. return &current->active_document()->window();
  467. }
  468. // https://html.spec.whatwg.org/multipage/web-messaging.html#window-post-message-steps
  469. DOM::ExceptionOr<void> Window::post_message(JS::Value message, String const&)
  470. {
  471. // FIXME: This is an ad-hoc hack implementation instead, since we don't currently
  472. // have serialization and deserialization of messages.
  473. HTML::queue_global_task(HTML::Task::Source::PostedMessage, *wrapper(), [strong_this = NonnullRefPtr(*this), message]() mutable {
  474. HTML::MessageEventInit event_init {};
  475. event_init.data = message;
  476. event_init.origin = "<origin>";
  477. strong_this->dispatch_event(HTML::MessageEvent::create(HTML::EventNames::message, event_init));
  478. });
  479. return {};
  480. }
  481. // https://html.spec.whatwg.org/multipage/window-object.html#dom-name
  482. String Window::name() const
  483. {
  484. // 1. If this's browsing context is null, then return the empty string.
  485. if (!browsing_context())
  486. return String::empty();
  487. // 2. Return this's browsing context's name.
  488. return browsing_context()->name();
  489. }
  490. // https://html.spec.whatwg.org/multipage/window-object.html#dom-name
  491. void Window::set_name(String const& name)
  492. {
  493. // 1. If this's browsing context is null, then return.
  494. if (!browsing_context())
  495. return;
  496. // 2. Set this's browsing context's name to the given value.
  497. browsing_context()->set_name(name);
  498. }
  499. // https://w3c.github.io/requestidlecallback/#start-an-idle-period-algorithm
  500. void Window::start_an_idle_period()
  501. {
  502. // 1. Optionally, if the user agent determines the idle period should be delayed, return from this algorithm.
  503. if (!wrapper())
  504. return;
  505. // 2. Let pending_list be window's list of idle request callbacks.
  506. auto& pending_list = m_idle_request_callbacks;
  507. // 3. Let run_list be window's list of runnable idle callbacks.
  508. auto& run_list = m_runnable_idle_callbacks;
  509. run_list.extend(pending_list);
  510. // 4. Clear pending_list.
  511. pending_list.clear();
  512. // FIXME: This might not agree with the spec, but currently we use 100% CPU if we keep queueing tasks
  513. if (run_list.is_empty())
  514. return;
  515. // 5. Queue a task on the queue associated with the idle-task task source,
  516. // which performs the steps defined in the invoke idle callbacks algorithm with window and getDeadline as parameters.
  517. HTML::queue_global_task(HTML::Task::Source::IdleTask, *wrapper(), [window = NonnullRefPtr(*this)]() mutable {
  518. window->invoke_idle_callbacks();
  519. });
  520. }
  521. // https://w3c.github.io/requestidlecallback/#invoke-idle-callbacks-algorithm
  522. void Window::invoke_idle_callbacks()
  523. {
  524. auto& event_loop = main_thread_event_loop();
  525. // 1. If the user-agent believes it should end the idle period early due to newly scheduled high-priority work, return from the algorithm.
  526. // 2. Let now be the current time.
  527. auto now = event_loop.unsafe_shared_current_time();
  528. // 3. If now is less than the result of calling getDeadline and the window's list of runnable idle callbacks is not empty:
  529. if (now < event_loop.compute_deadline() && !m_runnable_idle_callbacks.is_empty()) {
  530. // 1. Pop the top callback from window's list of runnable idle callbacks.
  531. auto callback = m_runnable_idle_callbacks.take_first();
  532. // 2. Let deadlineArg be a new IdleDeadline whose [get deadline time algorithm] is getDeadline.
  533. auto deadline_arg = RequestIdleCallback::IdleDeadline::create();
  534. // 3. Call callback with deadlineArg as its argument. If an uncaught runtime script error occurs, then report the exception.
  535. auto result = callback->invoke(deadline_arg);
  536. if (result.is_error())
  537. HTML::report_exception(result);
  538. // 4. If window's list of runnable idle callbacks is not empty, queue a task which performs the steps
  539. // in the invoke idle callbacks algorithm with getDeadline and window as a parameters and return from this algorithm
  540. HTML::queue_global_task(HTML::Task::Source::IdleTask, *wrapper(), [window = NonnullRefPtr(*this)]() mutable {
  541. window->invoke_idle_callbacks();
  542. });
  543. }
  544. }
  545. // https://w3c.github.io/requestidlecallback/#the-requestidlecallback-method
  546. u32 Window::request_idle_callback(NonnullOwnPtr<Bindings::CallbackType> callback)
  547. {
  548. // 1. Let window be this Window object.
  549. auto& window = *this;
  550. // 2. Increment the window's idle callback identifier by one.
  551. window.m_idle_callback_identifier++;
  552. // 3. Let handle be the current value of window's idle callback identifier.
  553. auto handle = window.m_idle_callback_identifier;
  554. // 4. Push callback to the end of window's list of idle request callbacks, associated with handle.
  555. auto handler = [callback = move(callback)](NonnullRefPtr<RequestIdleCallback::IdleDeadline> deadline) -> JS::Completion {
  556. auto& global_object = callback->callback.cell()->global_object();
  557. auto* wrapped_deadline = Bindings::wrap(global_object, *deadline);
  558. return Bindings::IDL::invoke_callback(const_cast<Bindings::CallbackType&>(*callback), {}, JS::Value(wrapped_deadline));
  559. };
  560. window.m_idle_request_callbacks.append(adopt_ref(*new IdleCallback(move(handler), handle)));
  561. // 5. Return handle and then continue running this algorithm asynchronously.
  562. return handle;
  563. // FIXME: 6. If the timeout property is present in options and has a positive value:
  564. // FIXME: 1. Wait for timeout milliseconds.
  565. // FIXME: 2. Wait until all invocations of this algorithm, whose timeout added to their posted time occurred before this one's, have completed.
  566. // FIXME: 3. Optionally, wait a further user-agent defined length of time.
  567. // FIXME: 4. Queue a task on the queue associated with the idle-task task source, which performs the invoke idle callback timeout algorithm, passing handle and window as arguments.
  568. }
  569. // https://w3c.github.io/requestidlecallback/#the-cancelidlecallback-method
  570. void Window::cancel_idle_callback(u32 handle)
  571. {
  572. // 1. Let window be this Window object.
  573. auto& window = *this;
  574. // 2. Find the entry in either the window's list of idle request callbacks or list of runnable idle callbacks
  575. // that is associated with the value handle.
  576. // 3. If there is such an entry, remove it from both window's list of idle request callbacks and the list of runnable idle callbacks.
  577. window.m_idle_request_callbacks.remove_first_matching([handle](auto& callback) {
  578. return callback->handle() == handle;
  579. });
  580. window.m_runnable_idle_callbacks.remove_first_matching([handle](auto& callback) {
  581. return callback->handle() == handle;
  582. });
  583. }
  584. }