Window.cpp 28 KB

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