Window.cpp 27 KB

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