Window.cpp 14 KB

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