Window.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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 = [weak_window = make_weak_ptr(), handler = move(handler), timeout, arguments = move(arguments), repeat, id]() mutable {
  171. auto window = weak_window.strong_ref();
  172. if (!window)
  173. return;
  174. // 1. If id does not exist in global's map of active timers, then abort these steps.
  175. if (!window->m_timers.contains(id))
  176. return;
  177. handler.visit(
  178. // 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.
  179. [&](Bindings::CallbackType& callback) {
  180. if (auto result = Bindings::IDL::invoke_callback(callback, window->wrapper(), arguments); result.is_error())
  181. HTML::report_exception(result);
  182. },
  183. // 3. Otherwise:
  184. [&](String const& source) {
  185. // 1. Assert: handler is a string.
  186. // 2. FIXME: Perform HostEnsureCanCompileStrings(callerRealm, calleeRealm). If this throws an exception, catch it, report the exception, and abort these steps.
  187. // 3. Let settings object be global's relevant settings object.
  188. auto& settings_object = window->associated_document().relevant_settings_object();
  189. // 4. Let base URL be initiating script's base URL.
  190. auto url = window->associated_document().url();
  191. // 5. Assert: base URL is not null, as initiating script is a classic script or a JavaScript module script.
  192. // 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.
  193. // 7. Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.
  194. auto script = HTML::ClassicScript::create(url.basename(), source, settings_object, url);
  195. // 8. Run the classic script script.
  196. (void)script->run();
  197. });
  198. // 4. If id does not exist in global's map of active timers, then abort these steps.
  199. if (!window->m_timers.contains(id))
  200. return;
  201. switch (repeat) {
  202. // 5. If repeat is true, then perform the timer initialization steps again, given global, handler, timeout, arguments, true, and id.
  203. case Repeat::Yes:
  204. window->run_timer_initialization_steps(handler, timeout, move(arguments), repeat, id);
  205. break;
  206. // 6. Otherwise, remove global's map of active timers[id].
  207. case Repeat::No:
  208. window->m_timers.remove(id);
  209. break;
  210. }
  211. };
  212. // 10. FIXME: Increment nesting level by one.
  213. // 11. FIXME: Set task's timer nesting level to nesting level.
  214. // 12. Let completionStep be an algorithm step which queues a global task on the timer task source given global to run task.
  215. auto completion_step = [weak_window = make_weak_ptr(), task = move(task)]() mutable {
  216. auto window = weak_window.strong_ref();
  217. if (!window)
  218. return;
  219. HTML::queue_global_task(HTML::Task::Source::TimerTask, *window->wrapper(), move(task));
  220. };
  221. // 13. Run steps after a timeout given global, "setTimeout/setInterval", timeout, completionStep, and id.
  222. auto timer = Timer::create(*this, timeout, move(completion_step), id);
  223. m_timers.set(id, timer);
  224. timer->start();
  225. // 14. Return id.
  226. return id;
  227. }
  228. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#run-the-animation-frame-callbacks
  229. i32 Window::request_animation_frame(NonnullOwnPtr<Bindings::CallbackType> js_callback)
  230. {
  231. auto callback = request_animation_frame_driver().add([this, js_callback = move(js_callback)](i32 id) mutable {
  232. // 3. Invoke callback, passing now as the only argument,
  233. auto result = Bindings::IDL::invoke_callback(*js_callback, {}, JS::Value(performance().now()));
  234. // and if an exception is thrown, report the exception.
  235. if (result.is_error())
  236. HTML::report_exception(result);
  237. m_request_animation_frame_callbacks.remove(id);
  238. });
  239. m_request_animation_frame_callbacks.set(callback->id(), callback);
  240. return callback->id();
  241. }
  242. void Window::cancel_animation_frame(i32 id)
  243. {
  244. auto it = m_request_animation_frame_callbacks.find(id);
  245. if (it == m_request_animation_frame_callbacks.end())
  246. return;
  247. it->value->cancel();
  248. m_request_animation_frame_callbacks.remove(it);
  249. }
  250. void Window::did_set_location_href(Badge<Bindings::LocationObject>, AK::URL const& new_href)
  251. {
  252. auto* browsing_context = associated_document().browsing_context();
  253. if (!browsing_context)
  254. return;
  255. browsing_context->loader().load(new_href, FrameLoader::Type::Navigation);
  256. }
  257. void Window::did_call_location_reload(Badge<Bindings::LocationObject>)
  258. {
  259. auto* browsing_context = associated_document().browsing_context();
  260. if (!browsing_context)
  261. return;
  262. browsing_context->loader().load(associated_document().url(), FrameLoader::Type::Reload);
  263. }
  264. void Window::did_call_location_replace(Badge<Bindings::LocationObject>, String url)
  265. {
  266. auto* browsing_context = associated_document().browsing_context();
  267. if (!browsing_context)
  268. return;
  269. auto new_url = associated_document().parse_url(url);
  270. browsing_context->loader().load(move(new_url), FrameLoader::Type::Navigation);
  271. }
  272. bool Window::dispatch_event(NonnullRefPtr<DOM::Event> event)
  273. {
  274. return DOM::EventDispatcher::dispatch(*this, event, true);
  275. }
  276. JS::Object* Window::create_wrapper(JS::GlobalObject& global_object)
  277. {
  278. return &global_object;
  279. }
  280. // https://www.w3.org/TR/cssom-view-1/#dom-window-innerwidth
  281. int Window::inner_width() const
  282. {
  283. // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar (if any),
  284. // or zero if there is no viewport.
  285. if (auto const* browsing_context = associated_document().browsing_context())
  286. return browsing_context->viewport_rect().width();
  287. return 0;
  288. }
  289. // https://www.w3.org/TR/cssom-view-1/#dom-window-innerheight
  290. int Window::inner_height() const
  291. {
  292. // The innerHeight attribute must return the viewport height including the size of a rendered scroll bar (if any),
  293. // or zero if there is no viewport.
  294. if (auto const* browsing_context = associated_document().browsing_context())
  295. return browsing_context->viewport_rect().height();
  296. return 0;
  297. }
  298. Page* Window::page()
  299. {
  300. return associated_document().page();
  301. }
  302. Page const* Window::page() const
  303. {
  304. return associated_document().page();
  305. }
  306. NonnullRefPtr<CSS::CSSStyleDeclaration> Window::get_computed_style(DOM::Element& element) const
  307. {
  308. return CSS::ResolvedCSSStyleDeclaration::create(element);
  309. }
  310. NonnullRefPtr<CSS::MediaQueryList> Window::match_media(String media)
  311. {
  312. auto media_query_list = CSS::MediaQueryList::create(associated_document(), parse_media_query_list(CSS::ParsingContext(associated_document()), media));
  313. associated_document().add_media_query_list(media_query_list);
  314. return media_query_list;
  315. }
  316. Optional<CSS::MediaFeatureValue> Window::query_media_feature(CSS::MediaFeatureID media_feature) const
  317. {
  318. // FIXME: Many of these should be dependent on the hardware
  319. // https://www.w3.org/TR/mediaqueries-5/#media-descriptor-table
  320. switch (media_feature) {
  321. case CSS::MediaFeatureID::AnyHover:
  322. return CSS::MediaFeatureValue(CSS::ValueID::Hover);
  323. case CSS::MediaFeatureID::AnyPointer:
  324. return CSS::MediaFeatureValue(CSS::ValueID::Fine);
  325. case CSS::MediaFeatureID::AspectRatio:
  326. return CSS::MediaFeatureValue(CSS::Ratio(inner_width(), inner_height()));
  327. case CSS::MediaFeatureID::Color:
  328. return CSS::MediaFeatureValue(8);
  329. case CSS::MediaFeatureID::ColorGamut:
  330. return CSS::MediaFeatureValue(CSS::ValueID::Srgb);
  331. case CSS::MediaFeatureID::ColorIndex:
  332. return CSS::MediaFeatureValue(0);
  333. // FIXME: device-aspect-ratio
  334. // FIXME: device-height
  335. // FIXME: device-width
  336. case CSS::MediaFeatureID::DisplayMode:
  337. // FIXME: Detect if window is fullscreen
  338. return CSS::MediaFeatureValue(CSS::ValueID::Browser);
  339. case CSS::MediaFeatureID::DynamicRange:
  340. return CSS::MediaFeatureValue(CSS::ValueID::Standard);
  341. case CSS::MediaFeatureID::EnvironmentBlending:
  342. return CSS::MediaFeatureValue(CSS::ValueID::Opaque);
  343. case CSS::MediaFeatureID::ForcedColors:
  344. return CSS::MediaFeatureValue(CSS::ValueID::None);
  345. case CSS::MediaFeatureID::Grid:
  346. return CSS::MediaFeatureValue(0);
  347. case CSS::MediaFeatureID::Height:
  348. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_height()));
  349. case CSS::MediaFeatureID::HorizontalViewportSegments:
  350. return CSS::MediaFeatureValue(1);
  351. case CSS::MediaFeatureID::Hover:
  352. return CSS::MediaFeatureValue(CSS::ValueID::Hover);
  353. case CSS::MediaFeatureID::InvertedColors:
  354. return CSS::MediaFeatureValue(CSS::ValueID::None);
  355. case CSS::MediaFeatureID::Monochrome:
  356. return CSS::MediaFeatureValue(0);
  357. case CSS::MediaFeatureID::NavControls:
  358. return CSS::MediaFeatureValue(CSS::ValueID::Back);
  359. case CSS::MediaFeatureID::Orientation:
  360. return CSS::MediaFeatureValue(inner_height() >= inner_width() ? CSS::ValueID::Portrait : CSS::ValueID::Landscape);
  361. case CSS::MediaFeatureID::OverflowBlock:
  362. return CSS::MediaFeatureValue(CSS::ValueID::Scroll);
  363. case CSS::MediaFeatureID::OverflowInline:
  364. return CSS::MediaFeatureValue(CSS::ValueID::Scroll);
  365. case CSS::MediaFeatureID::Pointer:
  366. return CSS::MediaFeatureValue(CSS::ValueID::Fine);
  367. case CSS::MediaFeatureID::PrefersColorScheme: {
  368. if (auto* page = this->page()) {
  369. switch (page->preferred_color_scheme()) {
  370. case CSS::PreferredColorScheme::Light:
  371. return CSS::MediaFeatureValue(CSS::ValueID::Light);
  372. case CSS::PreferredColorScheme::Dark:
  373. return CSS::MediaFeatureValue(CSS::ValueID::Dark);
  374. case CSS::PreferredColorScheme::Auto:
  375. default:
  376. return CSS::MediaFeatureValue(page->palette().is_dark() ? CSS::ValueID::Dark : CSS::ValueID::Light);
  377. }
  378. }
  379. return CSS::MediaFeatureValue(CSS::ValueID::Light);
  380. }
  381. case CSS::MediaFeatureID::PrefersContrast:
  382. // FIXME: Make this a preference
  383. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  384. case CSS::MediaFeatureID::PrefersReducedData:
  385. // FIXME: Make this a preference
  386. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  387. case CSS::MediaFeatureID::PrefersReducedMotion:
  388. // FIXME: Make this a preference
  389. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  390. case CSS::MediaFeatureID::PrefersReducedTransparency:
  391. // FIXME: Make this a preference
  392. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  393. // FIXME: resolution
  394. case CSS::MediaFeatureID::Scan:
  395. return CSS::MediaFeatureValue(CSS::ValueID::Progressive);
  396. case CSS::MediaFeatureID::Scripting:
  397. if (associated_document().is_scripting_enabled())
  398. return CSS::MediaFeatureValue(CSS::ValueID::Enabled);
  399. return CSS::MediaFeatureValue(CSS::ValueID::None);
  400. case CSS::MediaFeatureID::Update:
  401. return CSS::MediaFeatureValue(CSS::ValueID::Fast);
  402. case CSS::MediaFeatureID::VerticalViewportSegments:
  403. return CSS::MediaFeatureValue(1);
  404. case CSS::MediaFeatureID::VideoColorGamut:
  405. return CSS::MediaFeatureValue(CSS::ValueID::Srgb);
  406. case CSS::MediaFeatureID::VideoDynamicRange:
  407. return CSS::MediaFeatureValue(CSS::ValueID::Standard);
  408. case CSS::MediaFeatureID::Width:
  409. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_width()));
  410. default:
  411. break;
  412. }
  413. return {};
  414. }
  415. // https://www.w3.org/TR/cssom-view/#dom-window-scrollx
  416. float Window::scroll_x() const
  417. {
  418. if (auto* page = this->page())
  419. return page->top_level_browsing_context().viewport_scroll_offset().x();
  420. return 0;
  421. }
  422. // https://www.w3.org/TR/cssom-view/#dom-window-scrolly
  423. float Window::scroll_y() const
  424. {
  425. if (auto* page = this->page())
  426. return page->top_level_browsing_context().viewport_scroll_offset().y();
  427. return 0;
  428. }
  429. // https://html.spec.whatwg.org/#fire-a-page-transition-event
  430. void Window::fire_a_page_transition_event(FlyString const& event_name, bool persisted)
  431. {
  432. // To fire a page transition event named eventName at a Window window with a boolean persisted,
  433. // fire an event named eventName at window, using PageTransitionEvent,
  434. // with the persisted attribute initialized to persisted,
  435. HTML::PageTransitionEventInit event_init {};
  436. event_init.persisted = persisted;
  437. auto event = HTML::PageTransitionEvent::create(event_name, event_init);
  438. // ...the cancelable attribute initialized to true,
  439. event->set_cancelable(true);
  440. // the bubbles attribute initialized to true,
  441. event->set_bubbles(true);
  442. // and legacy target override flag set.
  443. dispatch_event(move(event));
  444. }
  445. // https://html.spec.whatwg.org/#dom-queuemicrotask
  446. void Window::queue_microtask(NonnullOwnPtr<Bindings::CallbackType> callback)
  447. {
  448. // The queueMicrotask(callback) method must queue a microtask to invoke callback,
  449. HTML::queue_a_microtask(&associated_document(), [callback = move(callback)]() mutable {
  450. auto result = Bindings::IDL::invoke_callback(*callback, {});
  451. // and if callback throws an exception, report the exception.
  452. if (result.is_error())
  453. HTML::report_exception(result);
  454. });
  455. }
  456. float Window::device_pixel_ratio() const
  457. {
  458. // FIXME: Return 2.0f if we're in HiDPI mode!
  459. return 1.0f;
  460. }
  461. // https://drafts.csswg.org/cssom-view/#dom-window-screenx
  462. int Window::screen_x() const
  463. {
  464. // The screenX and screenLeft attributes must return the x-coordinate, relative to the origin of the Web-exposed screen area,
  465. // of the left of the client window as number of CSS pixels, or zero if there is no such thing.
  466. return 0;
  467. }
  468. // https://drafts.csswg.org/cssom-view/#dom-window-screeny
  469. int Window::screen_y() const
  470. {
  471. // The screenY and screenTop attributes must return the y-coordinate, relative to the origin of the screen of the Web-exposed screen area,
  472. // of the top of the client window as number of CSS pixels, or zero if there is no such thing.
  473. return 0;
  474. }
  475. // https://w3c.github.io/selection-api/#dom-window-getselection
  476. Selection::Selection* Window::get_selection()
  477. {
  478. // FIXME: Implement.
  479. return nullptr;
  480. }
  481. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-localstorage
  482. RefPtr<HTML::Storage> Window::local_storage()
  483. {
  484. // FIXME: Implement according to spec.
  485. static HashMap<Origin, NonnullRefPtr<HTML::Storage>> local_storage_per_origin;
  486. return local_storage_per_origin.ensure(associated_document().origin(), [] {
  487. return HTML::Storage::create();
  488. });
  489. }
  490. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-sessionstorage
  491. RefPtr<HTML::Storage> Window::session_storage()
  492. {
  493. // FIXME: Implement according to spec.
  494. static HashMap<Origin, NonnullRefPtr<HTML::Storage>> session_storage_per_origin;
  495. return session_storage_per_origin.ensure(associated_document().origin(), [] {
  496. return HTML::Storage::create();
  497. });
  498. }
  499. // https://html.spec.whatwg.org/multipage/browsers.html#dom-parent
  500. Window* Window::parent()
  501. {
  502. // 1. Let current be this Window object's browsing context.
  503. auto* current = associated_document().browsing_context();
  504. // 2. If current is null, then return null.
  505. if (!current)
  506. return nullptr;
  507. // 3. If current is a child browsing context of another browsing context parent,
  508. // then return parent's WindowProxy object.
  509. if (current->parent()) {
  510. VERIFY(current->parent()->active_document());
  511. return &current->parent()->active_document()->window();
  512. }
  513. // 4. Assert: current is a top-level browsing context.
  514. VERIFY(current->is_top_level());
  515. // FIXME: 5. Return current's WindowProxy object.
  516. VERIFY(current->active_document());
  517. return &current->active_document()->window();
  518. }
  519. // https://html.spec.whatwg.org/multipage/web-messaging.html#window-post-message-steps
  520. DOM::ExceptionOr<void> Window::post_message(JS::Value message, String const&)
  521. {
  522. // FIXME: This is an ad-hoc hack implementation instead, since we don't currently
  523. // have serialization and deserialization of messages.
  524. HTML::queue_global_task(HTML::Task::Source::PostedMessage, *wrapper(), [strong_this = NonnullRefPtr(*this), message]() mutable {
  525. HTML::MessageEventInit event_init {};
  526. event_init.data = message;
  527. event_init.origin = "<origin>";
  528. strong_this->dispatch_event(HTML::MessageEvent::create(HTML::EventNames::message, event_init));
  529. });
  530. return {};
  531. }
  532. // https://html.spec.whatwg.org/multipage/window-object.html#dom-name
  533. String Window::name() const
  534. {
  535. // 1. If this's browsing context is null, then return the empty string.
  536. if (!browsing_context())
  537. return String::empty();
  538. // 2. Return this's browsing context's name.
  539. return browsing_context()->name();
  540. }
  541. // https://html.spec.whatwg.org/multipage/window-object.html#dom-name
  542. void Window::set_name(String const& name)
  543. {
  544. // 1. If this's browsing context is null, then return.
  545. if (!browsing_context())
  546. return;
  547. // 2. Set this's browsing context's name to the given value.
  548. browsing_context()->set_name(name);
  549. }
  550. }