Window.cpp 24 KB

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