Window.cpp 14 KB

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