Window.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /*
  2. * Copyright (c) 2020-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, 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/DOM/Timer.h>
  18. #include <LibWeb/DOM/Window.h>
  19. #include <LibWeb/HTML/BrowsingContext.h>
  20. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  21. #include <LibWeb/HTML/PageTransitionEvent.h>
  22. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  23. #include <LibWeb/HTML/Storage.h>
  24. #include <LibWeb/HighResolutionTime/Performance.h>
  25. #include <LibWeb/Layout/InitialContainingBlock.h>
  26. #include <LibWeb/Page/Page.h>
  27. #include <LibWeb/Selection/Selection.h>
  28. namespace Web::DOM {
  29. class RequestAnimationFrameCallback : public RefCounted<RequestAnimationFrameCallback> {
  30. public:
  31. explicit RequestAnimationFrameCallback(i32 id, Function<void(i32)> handler)
  32. : m_id(id)
  33. , m_handler(move(handler))
  34. {
  35. }
  36. ~RequestAnimationFrameCallback() = default;
  37. i32 id() const { return m_id; }
  38. bool is_cancelled() const { return !m_handler; }
  39. void cancel() { m_handler = nullptr; }
  40. void invoke() { m_handler(m_id); }
  41. private:
  42. i32 m_id { 0 };
  43. Function<void(i32)> m_handler;
  44. };
  45. struct RequestAnimationFrameDriver {
  46. RequestAnimationFrameDriver()
  47. {
  48. m_timer = Core::Timer::create_single_shot(16, [] {
  49. HTML::main_thread_event_loop().schedule();
  50. });
  51. }
  52. NonnullRefPtr<RequestAnimationFrameCallback> add(Function<void(i32)> handler)
  53. {
  54. auto id = m_id_allocator.allocate();
  55. auto callback = adopt_ref(*new RequestAnimationFrameCallback { id, move(handler) });
  56. m_callbacks.set(id, callback);
  57. if (!m_timer->is_active())
  58. m_timer->start();
  59. return callback;
  60. }
  61. bool remove(i32 id)
  62. {
  63. auto it = m_callbacks.find(id);
  64. if (it == m_callbacks.end())
  65. return false;
  66. m_callbacks.remove(it);
  67. m_id_allocator.deallocate(id);
  68. return true;
  69. }
  70. void run()
  71. {
  72. auto taken_callbacks = move(m_callbacks);
  73. for (auto& it : taken_callbacks) {
  74. if (!it.value->is_cancelled())
  75. it.value->invoke();
  76. }
  77. }
  78. private:
  79. HashMap<i32, NonnullRefPtr<RequestAnimationFrameCallback>> m_callbacks;
  80. IDAllocator m_id_allocator;
  81. RefPtr<Core::Timer> m_timer;
  82. };
  83. static RequestAnimationFrameDriver& request_animation_frame_driver()
  84. {
  85. static RequestAnimationFrameDriver driver;
  86. return driver;
  87. }
  88. // https://html.spec.whatwg.org/#run-the-animation-frame-callbacks
  89. void run_animation_frame_callbacks(DOM::Document&, double)
  90. {
  91. // FIXME: Bring this closer to the spec.
  92. request_animation_frame_driver().run();
  93. }
  94. NonnullRefPtr<Window> Window::create_with_document(Document& document)
  95. {
  96. return adopt_ref(*new Window(document));
  97. }
  98. Window::Window(Document& document)
  99. : EventTarget()
  100. , m_associated_document(document)
  101. , m_performance(make<HighResolutionTime::Performance>(*this))
  102. , m_crypto(Crypto::Crypto::create())
  103. , m_screen(CSS::Screen::create({}, *this))
  104. {
  105. }
  106. Window::~Window()
  107. {
  108. }
  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. i32 Window::set_interval(NonnullOwnPtr<Bindings::CallbackType> callback, i32 interval)
  131. {
  132. auto timer = Timer::create_interval(*this, interval, move(callback));
  133. m_timers.set(timer->id(), timer);
  134. return timer->id();
  135. }
  136. i32 Window::set_timeout(NonnullOwnPtr<Bindings::CallbackType> callback, i32 interval)
  137. {
  138. auto timer = Timer::create_timeout(*this, interval, move(callback));
  139. m_timers.set(timer->id(), timer);
  140. return timer->id();
  141. }
  142. void Window::timer_did_fire(Badge<Timer>, Timer& timer)
  143. {
  144. NonnullRefPtr<Timer> strong_timer { timer };
  145. if (timer.type() == Timer::Type::Timeout) {
  146. m_timers.remove(timer.id());
  147. }
  148. // We should not be here if there's no JS wrapper for the Window object.
  149. VERIFY(wrapper());
  150. HTML::queue_global_task(HTML::Task::Source::TimerTask, *wrapper(), [this, strong_this = NonnullRefPtr(*this), strong_timer = NonnullRefPtr(timer)]() mutable {
  151. auto result = Bindings::IDL::invoke_callback(strong_timer->callback(), wrapper());
  152. if (result.is_error())
  153. HTML::report_exception(result);
  154. });
  155. }
  156. i32 Window::allocate_timer_id(Badge<Timer>)
  157. {
  158. return m_timer_id_allocator.allocate();
  159. }
  160. void Window::deallocate_timer_id(Badge<Timer>, i32 id)
  161. {
  162. m_timer_id_allocator.deallocate(id);
  163. }
  164. void Window::clear_timeout(i32 timer_id)
  165. {
  166. m_timers.remove(timer_id);
  167. }
  168. void Window::clear_interval(i32 timer_id)
  169. {
  170. m_timers.remove(timer_id);
  171. }
  172. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#run-the-animation-frame-callbacks
  173. i32 Window::request_animation_frame(NonnullOwnPtr<Bindings::CallbackType> js_callback)
  174. {
  175. auto callback = request_animation_frame_driver().add([this, js_callback = move(js_callback)](i32 id) mutable {
  176. // 3. Invoke callback, passing now as the only argument,
  177. auto result = Bindings::IDL::invoke_callback(*js_callback, {}, JS::Value(performance().now()));
  178. // and if an exception is thrown, report the exception.
  179. if (result.is_error())
  180. HTML::report_exception(result);
  181. m_request_animation_frame_callbacks.remove(id);
  182. });
  183. m_request_animation_frame_callbacks.set(callback->id(), callback);
  184. return callback->id();
  185. }
  186. void Window::cancel_animation_frame(i32 id)
  187. {
  188. auto it = m_request_animation_frame_callbacks.find(id);
  189. if (it == m_request_animation_frame_callbacks.end())
  190. return;
  191. it->value->cancel();
  192. m_request_animation_frame_callbacks.remove(it);
  193. }
  194. void Window::did_set_location_href(Badge<Bindings::LocationObject>, AK::URL const& new_href)
  195. {
  196. auto* browsing_context = associated_document().browsing_context();
  197. if (!browsing_context)
  198. return;
  199. browsing_context->loader().load(new_href, FrameLoader::Type::Navigation);
  200. }
  201. void Window::did_call_location_reload(Badge<Bindings::LocationObject>)
  202. {
  203. auto* browsing_context = associated_document().browsing_context();
  204. if (!browsing_context)
  205. return;
  206. browsing_context->loader().load(associated_document().url(), FrameLoader::Type::Reload);
  207. }
  208. void Window::did_call_location_replace(Badge<Bindings::LocationObject>, String url)
  209. {
  210. auto* browsing_context = associated_document().browsing_context();
  211. if (!browsing_context)
  212. return;
  213. auto new_url = associated_document().parse_url(url);
  214. browsing_context->loader().load(move(new_url), FrameLoader::Type::Navigation);
  215. }
  216. bool Window::dispatch_event(NonnullRefPtr<Event> event)
  217. {
  218. return EventDispatcher::dispatch(*this, event, true);
  219. }
  220. JS::Object* Window::create_wrapper(JS::GlobalObject& global_object)
  221. {
  222. return &global_object;
  223. }
  224. // https://www.w3.org/TR/cssom-view-1/#dom-window-innerwidth
  225. int Window::inner_width() const
  226. {
  227. // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar (if any),
  228. // or zero if there is no viewport.
  229. if (auto const* browsing_context = associated_document().browsing_context())
  230. return browsing_context->viewport_rect().width();
  231. return 0;
  232. }
  233. // https://www.w3.org/TR/cssom-view-1/#dom-window-innerheight
  234. int Window::inner_height() const
  235. {
  236. // The innerHeight attribute must return the viewport height including the size of a rendered scroll bar (if any),
  237. // or zero if there is no viewport.
  238. if (auto const* browsing_context = associated_document().browsing_context())
  239. return browsing_context->viewport_rect().height();
  240. return 0;
  241. }
  242. Page* Window::page()
  243. {
  244. return associated_document().page();
  245. }
  246. Page const* Window::page() const
  247. {
  248. return associated_document().page();
  249. }
  250. NonnullRefPtr<CSS::CSSStyleDeclaration> Window::get_computed_style(DOM::Element& element) const
  251. {
  252. return CSS::ResolvedCSSStyleDeclaration::create(element);
  253. }
  254. NonnullRefPtr<CSS::MediaQueryList> Window::match_media(String media)
  255. {
  256. auto media_query_list = CSS::MediaQueryList::create(associated_document(), parse_media_query_list(CSS::ParsingContext(associated_document()), media));
  257. associated_document().add_media_query_list(media_query_list);
  258. return media_query_list;
  259. }
  260. Optional<CSS::MediaFeatureValue> Window::query_media_feature(FlyString const& name) const
  261. {
  262. // FIXME: Many of these should be dependent on the hardware
  263. // MEDIAQUERIES-4 properties - https://www.w3.org/TR/mediaqueries-4/#media-descriptor-table
  264. if (name.equals_ignoring_case("any-hover"sv))
  265. return CSS::MediaFeatureValue("hover");
  266. if (name.equals_ignoring_case("any-pointer"sv))
  267. return CSS::MediaFeatureValue("fine");
  268. // FIXME: aspect-ratio
  269. if (name.equals_ignoring_case("color"sv))
  270. return CSS::MediaFeatureValue(32);
  271. if (name.equals_ignoring_case("color-gamut"sv))
  272. return CSS::MediaFeatureValue("srgb");
  273. if (name.equals_ignoring_case("color-index"sv))
  274. return CSS::MediaFeatureValue(0);
  275. // FIXME: device-aspect-ratio
  276. // FIXME: device-height
  277. // FIXME: device-width
  278. if (name.equals_ignoring_case("grid"sv))
  279. return CSS::MediaFeatureValue(0);
  280. if (name.equals_ignoring_case("height"sv))
  281. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_height()));
  282. if (name.equals_ignoring_case("hover"sv))
  283. return CSS::MediaFeatureValue("hover");
  284. if (name.equals_ignoring_case("monochrome"sv))
  285. return CSS::MediaFeatureValue(0);
  286. if (name.equals_ignoring_case("orientation"sv))
  287. return CSS::MediaFeatureValue(inner_height() >= inner_width() ? "portrait" : "landscape");
  288. if (name.equals_ignoring_case("overflow-block"sv))
  289. return CSS::MediaFeatureValue("scroll");
  290. if (name.equals_ignoring_case("overflow-inline"sv))
  291. return CSS::MediaFeatureValue("scroll");
  292. if (name.equals_ignoring_case("pointer"sv))
  293. return CSS::MediaFeatureValue("fine");
  294. // FIXME: resolution
  295. if (name.equals_ignoring_case("scan"sv))
  296. return CSS::MediaFeatureValue("progressive");
  297. if (name.equals_ignoring_case("update"sv))
  298. return CSS::MediaFeatureValue("fast");
  299. if (name.equals_ignoring_case("width"sv))
  300. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_width()));
  301. // MEDIAQUERIES-5 properties - https://www.w3.org/TR/mediaqueries-5/#media-descriptor-table
  302. if (name.equals_ignoring_case("prefers-color-scheme")) {
  303. if (auto* page = this->page()) {
  304. switch (page->preferred_color_scheme()) {
  305. case CSS::PreferredColorScheme::Light:
  306. return CSS::MediaFeatureValue("light");
  307. case CSS::PreferredColorScheme::Dark:
  308. return CSS::MediaFeatureValue("dark");
  309. case CSS::PreferredColorScheme::Auto:
  310. default:
  311. return CSS::MediaFeatureValue(page->palette().is_dark() ? "dark" : "light");
  312. }
  313. }
  314. }
  315. return {};
  316. }
  317. // https://www.w3.org/TR/cssom-view/#dom-window-scrollx
  318. float Window::scroll_x() const
  319. {
  320. if (auto* page = this->page())
  321. return page->top_level_browsing_context().viewport_scroll_offset().x();
  322. return 0;
  323. }
  324. // https://www.w3.org/TR/cssom-view/#dom-window-scrolly
  325. float Window::scroll_y() const
  326. {
  327. if (auto* page = this->page())
  328. return page->top_level_browsing_context().viewport_scroll_offset().y();
  329. return 0;
  330. }
  331. // https://html.spec.whatwg.org/#fire-a-page-transition-event
  332. void Window::fire_a_page_transition_event(FlyString const& event_name, bool persisted)
  333. {
  334. // To fire a page transition event named eventName at a Window window with a boolean persisted,
  335. // fire an event named eventName at window, using PageTransitionEvent,
  336. // with the persisted attribute initialized to persisted,
  337. HTML::PageTransitionEventInit event_init {};
  338. event_init.persisted = persisted;
  339. auto event = HTML::PageTransitionEvent::create(event_name, event_init);
  340. // ...the cancelable attribute initialized to true,
  341. event->set_cancelable(true);
  342. // the bubbles attribute initialized to true,
  343. event->set_bubbles(true);
  344. // and legacy target override flag set.
  345. dispatch_event(move(event));
  346. }
  347. // https://html.spec.whatwg.org/#dom-queuemicrotask
  348. void Window::queue_microtask(NonnullOwnPtr<Bindings::CallbackType> callback)
  349. {
  350. // The queueMicrotask(callback) method must queue a microtask to invoke callback,
  351. HTML::queue_a_microtask(&associated_document(), [callback = move(callback)]() mutable {
  352. auto result = Bindings::IDL::invoke_callback(*callback, {});
  353. // and if callback throws an exception, report the exception.
  354. if (result.is_error())
  355. HTML::report_exception(result);
  356. });
  357. }
  358. float Window::device_pixel_ratio() const
  359. {
  360. // FIXME: Return 2.0f if we're in HiDPI mode!
  361. return 1.0f;
  362. }
  363. // https://drafts.csswg.org/cssom-view/#dom-window-screenx
  364. int Window::screen_x() const
  365. {
  366. // The screenX and screenLeft attributes must return the x-coordinate, relative to the origin of the Web-exposed screen area,
  367. // of the left of the client window as number of CSS pixels, or zero if there is no such thing.
  368. return 0;
  369. }
  370. // https://drafts.csswg.org/cssom-view/#dom-window-screeny
  371. int Window::screen_y() const
  372. {
  373. // The screenY and screenTop attributes must return the y-coordinate, relative to the origin of the screen of the Web-exposed screen area,
  374. // of the top of the client window as number of CSS pixels, or zero if there is no such thing.
  375. return 0;
  376. }
  377. // https://w3c.github.io/selection-api/#dom-window-getselection
  378. Selection::Selection* Window::get_selection()
  379. {
  380. // FIXME: Implement.
  381. return nullptr;
  382. }
  383. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-localstorage
  384. RefPtr<HTML::Storage> Window::local_storage()
  385. {
  386. // FIXME: Implement according to spec.
  387. static HashMap<Origin, NonnullRefPtr<HTML::Storage>> local_storage_per_origin;
  388. return local_storage_per_origin.ensure(associated_document().origin(), [] {
  389. return HTML::Storage::create();
  390. });
  391. }
  392. }