Window.cpp 14 KB

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