Window.cpp 30 KB

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