Window.cpp 30 KB

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