Window.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836
  1. /*
  2. * Copyright (c) 2020-2023, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2021-2022, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Utf8View.h>
  9. #include <LibIPC/File.h>
  10. #include <LibJS/Runtime/AbstractOperations.h>
  11. #include <LibJS/Runtime/Accessor.h>
  12. #include <LibJS/Runtime/Completion.h>
  13. #include <LibJS/Runtime/Error.h>
  14. #include <LibJS/Runtime/FunctionObject.h>
  15. #include <LibJS/Runtime/GlobalEnvironment.h>
  16. #include <LibJS/Runtime/NativeFunction.h>
  17. #include <LibJS/Runtime/Shape.h>
  18. #include <LibTextCodec/Decoder.h>
  19. #include <LibURL/Origin.h>
  20. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  21. #include <LibWeb/Bindings/WindowExposedInterfaces.h>
  22. #include <LibWeb/Bindings/WindowPrototype.h>
  23. #include <LibWeb/CSS/MediaQueryList.h>
  24. #include <LibWeb/CSS/Parser/Parser.h>
  25. #include <LibWeb/CSS/ResolvedCSSStyleDeclaration.h>
  26. #include <LibWeb/CSS/Screen.h>
  27. #include <LibWeb/DOM/Document.h>
  28. #include <LibWeb/DOM/Element.h>
  29. #include <LibWeb/DOM/Event.h>
  30. #include <LibWeb/DOM/EventDispatcher.h>
  31. #include <LibWeb/DOM/HTMLCollection.h>
  32. #include <LibWeb/DOMURL/DOMURL.h>
  33. #include <LibWeb/HTML/AnimationFrameCallbackDriver.h>
  34. #include <LibWeb/HTML/BrowsingContext.h>
  35. #include <LibWeb/HTML/CloseWatcherManager.h>
  36. #include <LibWeb/HTML/CustomElements/CustomElementRegistry.h>
  37. #include <LibWeb/HTML/DocumentState.h>
  38. #include <LibWeb/HTML/EventHandler.h>
  39. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  40. #include <LibWeb/HTML/Focus.h>
  41. #include <LibWeb/HTML/HTMLEmbedElement.h>
  42. #include <LibWeb/HTML/HTMLFormElement.h>
  43. #include <LibWeb/HTML/HTMLImageElement.h>
  44. #include <LibWeb/HTML/HTMLObjectElement.h>
  45. #include <LibWeb/HTML/Location.h>
  46. #include <LibWeb/HTML/MessageEvent.h>
  47. #include <LibWeb/HTML/MessagePort.h>
  48. #include <LibWeb/HTML/Navigation.h>
  49. #include <LibWeb/HTML/Navigator.h>
  50. #include <LibWeb/HTML/PageTransitionEvent.h>
  51. #include <LibWeb/HTML/Parser/HTMLParser.h>
  52. #include <LibWeb/HTML/Scripting/Environments.h>
  53. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  54. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  55. #include <LibWeb/HTML/Storage.h>
  56. #include <LibWeb/HTML/TokenizedFeatures.h>
  57. #include <LibWeb/HTML/TraversableNavigable.h>
  58. #include <LibWeb/HTML/Window.h>
  59. #include <LibWeb/HTML/WindowProxy.h>
  60. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  61. #include <LibWeb/Infra/CharacterTypes.h>
  62. #include <LibWeb/Internals/Inspector.h>
  63. #include <LibWeb/Internals/Internals.h>
  64. #include <LibWeb/Layout/Viewport.h>
  65. #include <LibWeb/Page/Page.h>
  66. #include <LibWeb/Painting/PaintableBox.h>
  67. #include <LibWeb/RequestIdleCallback/IdleDeadline.h>
  68. #include <LibWeb/Selection/Selection.h>
  69. #include <LibWeb/WebIDL/AbstractOperations.h>
  70. namespace Web::HTML {
  71. GC_DEFINE_ALLOCATOR(Window);
  72. // https://html.spec.whatwg.org/#run-the-animation-frame-callbacks
  73. void run_animation_frame_callbacks(DOM::Document& document, double now)
  74. {
  75. // FIXME: Bring this closer to the spec.
  76. document.window()->animation_frame_callback_driver().run(now);
  77. }
  78. class IdleCallback : public RefCounted<IdleCallback> {
  79. public:
  80. explicit IdleCallback(ESCAPING Function<JS::Completion(GC::Ref<RequestIdleCallback::IdleDeadline>)> handler, u32 handle)
  81. : m_handler(move(handler))
  82. , m_handle(handle)
  83. {
  84. }
  85. ~IdleCallback() = default;
  86. JS::Completion invoke(GC::Ref<RequestIdleCallback::IdleDeadline> deadline) { return m_handler(deadline); }
  87. u32 handle() const { return m_handle; }
  88. private:
  89. Function<JS::Completion(GC::Ref<RequestIdleCallback::IdleDeadline>)> m_handler;
  90. u32 m_handle { 0 };
  91. };
  92. GC::Ref<Window> Window::create(JS::Realm& realm)
  93. {
  94. return realm.create<Window>(realm);
  95. }
  96. Window::Window(JS::Realm& realm)
  97. : DOM::EventTarget(realm)
  98. {
  99. m_legacy_platform_object_flags = LegacyPlatformObjectFlags {
  100. .supports_named_properties = true,
  101. .has_legacy_unenumerable_named_properties_interface_extended_attribute = true,
  102. .has_global_interface_extended_attribute = true,
  103. };
  104. }
  105. void Window::visit_edges(JS::Cell::Visitor& visitor)
  106. {
  107. Base::visit_edges(visitor);
  108. WindowOrWorkerGlobalScopeMixin::visit_edges(visitor);
  109. visitor.visit(m_associated_document);
  110. visitor.visit(m_current_event);
  111. visitor.visit(m_screen);
  112. visitor.visit(m_location);
  113. visitor.visit(m_navigator);
  114. visitor.visit(m_navigation);
  115. visitor.visit(m_custom_element_registry);
  116. visitor.visit(m_animation_frame_callback_driver);
  117. visitor.visit(m_pdf_viewer_plugin_objects);
  118. visitor.visit(m_pdf_viewer_mime_type_objects);
  119. visitor.visit(m_count_queuing_strategy_size_function);
  120. visitor.visit(m_byte_length_queuing_strategy_size_function);
  121. visitor.visit(m_close_watcher_manager);
  122. }
  123. void Window::finalize()
  124. {
  125. Base::finalize();
  126. WindowOrWorkerGlobalScopeMixin::finalize();
  127. }
  128. Window::~Window() = default;
  129. // https://html.spec.whatwg.org/multipage/window-object.html#window-open-steps
  130. WebIDL::ExceptionOr<GC::Ptr<WindowProxy>> Window::window_open_steps(StringView url, StringView target, StringView features)
  131. {
  132. auto [target_navigable, no_opener, window_type] = TRY(window_open_steps_internal(url, target, features));
  133. if (target_navigable == nullptr)
  134. return nullptr;
  135. // 14. If noopener is true or windowType is "new with no opener", then return null.
  136. if (no_opener == TokenizedFeature::NoOpener::Yes || window_type == Navigable::WindowType::NewWithNoOpener)
  137. return nullptr;
  138. // 15. Return targetNavigable's active WindowProxy.
  139. return target_navigable->active_window_proxy();
  140. }
  141. // https://html.spec.whatwg.org/multipage/window-object.html#window-open-steps
  142. WebIDL::ExceptionOr<Window::OpenedWindow> Window::window_open_steps_internal(StringView url, StringView target, StringView features)
  143. {
  144. // 1. If the event loop's termination nesting level is nonzero, return null.
  145. if (main_thread_event_loop().termination_nesting_level() != 0)
  146. return OpenedWindow {};
  147. // 2. Let sourceDocument be the entry global object's associated Document.
  148. auto& source_document = verify_cast<Window>(entry_global_object()).associated_document();
  149. // 3. Let urlRecord be null.
  150. Optional<URL::URL> url_record;
  151. // 4. If url is not the empty string, then:
  152. if (!url.is_empty()) {
  153. // FIXME: 1. Set urlRecord to the result of encoding-parsing a URL given url, relative to sourceDocument.
  154. url_record = entry_settings_object().parse_url(url);
  155. // 2. If urlRecord is failure, then throw a "SyntaxError" DOMException.
  156. if (!url_record->is_valid())
  157. return WebIDL::SyntaxError::create(realm(), MUST(String::formatted("Invalid URL '{}'", url)));
  158. }
  159. // 5. If target is the empty string, then set target to "_blank".
  160. if (target.is_empty())
  161. target = "_blank"sv;
  162. // 6. Let tokenizedFeatures be the result of tokenizing features.
  163. auto tokenized_features = tokenize_open_features(features);
  164. // 7. Let noopener and noreferrer be false.
  165. auto no_opener = TokenizedFeature::NoOpener::No;
  166. auto no_referrer = TokenizedFeature::NoReferrer::No;
  167. // 8. If tokenizedFeatures["noopener"] exists, then:
  168. if (auto no_opener_feature = tokenized_features.get("noopener"sv); no_opener_feature.has_value()) {
  169. // 1. Set noopener to the result of parsing tokenizedFeatures["noopener"] as a boolean feature.
  170. no_opener = parse_boolean_feature<TokenizedFeature::NoOpener>(*no_opener_feature);
  171. // 2. Remove tokenizedFeatures["noopener"].
  172. tokenized_features.remove("noopener"sv);
  173. }
  174. // 9. If tokenizedFeatures["noreferrer"] exists, then:
  175. if (auto no_referrer_feature = tokenized_features.get("noreferrer"sv); no_referrer_feature.has_value()) {
  176. // 1. Set noreferrer to the result of parsing tokenizedFeatures["noreferrer"] as a boolean feature.
  177. no_referrer = parse_boolean_feature<TokenizedFeature::NoReferrer>(*no_referrer_feature);
  178. // 2. Remove tokenizedFeatures["noreferrer"].
  179. tokenized_features.remove("noreferrer"sv);
  180. }
  181. // 10. Let referrerPolicy be the empty string.
  182. auto referrer_policy = ReferrerPolicy::ReferrerPolicy::EmptyString;
  183. // 11. If noreferrer is true, then set noopener to true and set referrerPolicy to "no-referrer".
  184. if (no_referrer == TokenizedFeature::NoReferrer::Yes) {
  185. no_opener = TokenizedFeature::NoOpener::Yes;
  186. referrer_policy = ReferrerPolicy::ReferrerPolicy::NoReferrer;
  187. }
  188. // 12. Let targetNavigable and windowType be the result of applying the rules for choosing a navigable given target, sourceDocument's node navigable, and noopener.
  189. VERIFY(source_document.navigable());
  190. auto [target_navigable, window_type] = source_document.navigable()->choose_a_navigable(target, no_opener, ActivateTab::Yes, tokenized_features);
  191. // 13. If targetNavigable is null, then return null.
  192. if (target_navigable == nullptr)
  193. return OpenedWindow {};
  194. // 14. If windowType is either "new and unrestricted" or "new with no opener", then:
  195. if (window_type == Navigable::WindowType::NewAndUnrestricted || window_type == Navigable::WindowType::NewWithNoOpener) {
  196. // 1. Set the target browsing context's is popup to the result of checking if a popup window is requested, given tokenizedFeatures.
  197. target_navigable->set_is_popup(check_if_a_popup_window_is_requested(tokenized_features));
  198. // 2. Set up browsing context features for target browsing context given tokenizedFeatures. [CSSOMVIEW]
  199. // NOTE: This is implemented in choose_a_navigable when creating the top level traversable.
  200. // 3. If urlRecord is null, then set urlRecord to a URL record representing about:blank.
  201. if (!url_record.has_value())
  202. url_record = URL::URL("about:blank"sv);
  203. // 4. If urlRecord matches about:blank, then perform the URL and history update steps given targetNavigable's active document and urlRecord.
  204. if (url_matches_about_blank(url_record.value())) {
  205. // AD-HOC: Mark the initial about:blank for the new window as load complete
  206. // FIXME: We do this other places too when creating a new about:blank document. Perhaps it's worth a spec issue?
  207. HTML::HTMLParser::the_end(*target_navigable->active_document());
  208. perform_url_and_history_update_steps(*target_navigable->active_document(), url_record.release_value());
  209. }
  210. // 5. Otherwise, navigate targetNavigable to urlRecord using sourceDocument, with referrerPolicy set to referrerPolicy and exceptionsEnabled set to true.
  211. else {
  212. TRY(target_navigable->navigate({ .url = url_record.release_value(), .source_document = source_document, .exceptions_enabled = true, .referrer_policy = referrer_policy }));
  213. }
  214. }
  215. // 15. Otherwise:
  216. else {
  217. // 1. If urlRecord is not null, then navigate targetNavigable to urlRecord using sourceDocument, with referrerPolicy set to referrerPolicy and exceptionsEnabled set to true.
  218. if (url_record.has_value())
  219. TRY(target_navigable->navigate({ .url = url_record.release_value(), .source_document = source_document, .exceptions_enabled = true, .referrer_policy = referrer_policy }));
  220. // 2. If noopener is false, then set targetNavigable's active browsing context's opener browsing context to sourceDocument's browsing context.
  221. if (no_opener == TokenizedFeature::NoOpener::No)
  222. target_navigable->active_browsing_context()->set_opener_browsing_context(source_document.browsing_context());
  223. }
  224. return OpenedWindow { target_navigable, no_opener, window_type };
  225. }
  226. bool Window::dispatch_event(DOM::Event& event)
  227. {
  228. return DOM::EventDispatcher::dispatch(*this, event, true);
  229. }
  230. Page& Window::page()
  231. {
  232. return associated_document().page();
  233. }
  234. Page const& Window::page() const
  235. {
  236. return associated_document().page();
  237. }
  238. Optional<CSS::MediaFeatureValue> Window::query_media_feature(CSS::MediaFeatureID media_feature) const
  239. {
  240. // FIXME: Many of these should be dependent on the hardware
  241. // https://www.w3.org/TR/mediaqueries-5/#media-descriptor-table
  242. switch (media_feature) {
  243. case CSS::MediaFeatureID::AnyHover:
  244. return CSS::MediaFeatureValue(CSS::Keyword::Hover);
  245. case CSS::MediaFeatureID::AnyPointer:
  246. return CSS::MediaFeatureValue(CSS::Keyword::Fine);
  247. case CSS::MediaFeatureID::AspectRatio:
  248. return CSS::MediaFeatureValue(CSS::Ratio(inner_width(), inner_height()));
  249. case CSS::MediaFeatureID::Color:
  250. return CSS::MediaFeatureValue(8);
  251. case CSS::MediaFeatureID::ColorGamut:
  252. return CSS::MediaFeatureValue(CSS::Keyword::Srgb);
  253. case CSS::MediaFeatureID::ColorIndex:
  254. return CSS::MediaFeatureValue(0);
  255. // FIXME: device-aspect-ratio
  256. case CSS::MediaFeatureID::DeviceHeight:
  257. return CSS::MediaFeatureValue(CSS::Length::make_px(page().web_exposed_screen_area().height()));
  258. case CSS::MediaFeatureID::DeviceWidth:
  259. return CSS::MediaFeatureValue(CSS::Length::make_px(page().web_exposed_screen_area().width()));
  260. case CSS::MediaFeatureID::DisplayMode:
  261. // FIXME: Detect if window is fullscreen
  262. return CSS::MediaFeatureValue(CSS::Keyword::Browser);
  263. case CSS::MediaFeatureID::DynamicRange:
  264. return CSS::MediaFeatureValue(CSS::Keyword::Standard);
  265. case CSS::MediaFeatureID::EnvironmentBlending:
  266. return CSS::MediaFeatureValue(CSS::Keyword::Opaque);
  267. case CSS::MediaFeatureID::ForcedColors:
  268. return CSS::MediaFeatureValue(CSS::Keyword::None);
  269. case CSS::MediaFeatureID::Grid:
  270. return CSS::MediaFeatureValue(0);
  271. case CSS::MediaFeatureID::Height:
  272. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_height()));
  273. case CSS::MediaFeatureID::HorizontalViewportSegments:
  274. return CSS::MediaFeatureValue(1);
  275. case CSS::MediaFeatureID::Hover:
  276. return CSS::MediaFeatureValue(CSS::Keyword::Hover);
  277. case CSS::MediaFeatureID::InvertedColors:
  278. return CSS::MediaFeatureValue(CSS::Keyword::None);
  279. case CSS::MediaFeatureID::Monochrome:
  280. return CSS::MediaFeatureValue(0);
  281. case CSS::MediaFeatureID::NavControls:
  282. return CSS::MediaFeatureValue(CSS::Keyword::Back);
  283. case CSS::MediaFeatureID::Orientation:
  284. return CSS::MediaFeatureValue(inner_height() >= inner_width() ? CSS::Keyword::Portrait : CSS::Keyword::Landscape);
  285. case CSS::MediaFeatureID::OverflowBlock:
  286. return CSS::MediaFeatureValue(CSS::Keyword::Scroll);
  287. case CSS::MediaFeatureID::OverflowInline:
  288. return CSS::MediaFeatureValue(CSS::Keyword::Scroll);
  289. case CSS::MediaFeatureID::Pointer:
  290. return CSS::MediaFeatureValue(CSS::Keyword::Fine);
  291. case CSS::MediaFeatureID::PrefersColorScheme: {
  292. switch (page().preferred_color_scheme()) {
  293. case CSS::PreferredColorScheme::Light:
  294. return CSS::MediaFeatureValue(CSS::Keyword::Light);
  295. case CSS::PreferredColorScheme::Dark:
  296. return CSS::MediaFeatureValue(CSS::Keyword::Dark);
  297. case CSS::PreferredColorScheme::Auto:
  298. default:
  299. return CSS::MediaFeatureValue(page().palette().is_dark() ? CSS::Keyword::Dark : CSS::Keyword::Light);
  300. }
  301. }
  302. case CSS::MediaFeatureID::PrefersContrast:
  303. switch (page().preferred_contrast()) {
  304. case CSS::PreferredContrast::Less:
  305. return CSS::MediaFeatureValue(CSS::Keyword::Less);
  306. case CSS::PreferredContrast::More:
  307. return CSS::MediaFeatureValue(CSS::Keyword::More);
  308. case CSS::PreferredContrast::NoPreference:
  309. return CSS::MediaFeatureValue(CSS::Keyword::NoPreference);
  310. case CSS::PreferredContrast::Auto:
  311. default:
  312. // FIXME: Fallback to system settings
  313. return CSS::MediaFeatureValue(CSS::Keyword::NoPreference);
  314. }
  315. case CSS::MediaFeatureID::PrefersReducedData:
  316. // FIXME: Make this a preference
  317. return CSS::MediaFeatureValue(CSS::Keyword::NoPreference);
  318. case CSS::MediaFeatureID::PrefersReducedMotion:
  319. switch (page().preferred_motion()) {
  320. case CSS::PreferredMotion::NoPreference:
  321. return CSS::MediaFeatureValue(CSS::Keyword::NoPreference);
  322. case CSS::PreferredMotion::Reduce:
  323. return CSS::MediaFeatureValue(CSS::Keyword::Reduce);
  324. case CSS::PreferredMotion::Auto:
  325. default:
  326. // FIXME: Fallback to system settings
  327. return CSS::MediaFeatureValue(CSS::Keyword::NoPreference);
  328. }
  329. case CSS::MediaFeatureID::PrefersReducedTransparency:
  330. // FIXME: Make this a preference
  331. return CSS::MediaFeatureValue(CSS::Keyword::NoPreference);
  332. case CSS::MediaFeatureID::Resolution:
  333. return CSS::MediaFeatureValue(CSS::Resolution(device_pixel_ratio(), CSS::Resolution::Type::Dppx));
  334. case CSS::MediaFeatureID::Scan:
  335. return CSS::MediaFeatureValue(CSS::Keyword::Progressive);
  336. case CSS::MediaFeatureID::Scripting:
  337. if (associated_document().is_scripting_enabled())
  338. return CSS::MediaFeatureValue(CSS::Keyword::Enabled);
  339. return CSS::MediaFeatureValue(CSS::Keyword::None);
  340. case CSS::MediaFeatureID::Update:
  341. return CSS::MediaFeatureValue(CSS::Keyword::Fast);
  342. case CSS::MediaFeatureID::VerticalViewportSegments:
  343. return CSS::MediaFeatureValue(1);
  344. case CSS::MediaFeatureID::VideoColorGamut:
  345. return CSS::MediaFeatureValue(CSS::Keyword::Srgb);
  346. case CSS::MediaFeatureID::VideoDynamicRange:
  347. return CSS::MediaFeatureValue(CSS::Keyword::Standard);
  348. case CSS::MediaFeatureID::Width:
  349. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_width()));
  350. default:
  351. break;
  352. }
  353. return {};
  354. }
  355. // https://html.spec.whatwg.org/#fire-a-page-transition-event
  356. void Window::fire_a_page_transition_event(FlyString const& event_name, bool persisted)
  357. {
  358. // To fire a page transition event named eventName at a Window window with a boolean persisted,
  359. // fire an event named eventName at window, using PageTransitionEvent,
  360. // with the persisted attribute initialized to persisted,
  361. PageTransitionEventInit event_init {};
  362. event_init.persisted = persisted;
  363. auto event = PageTransitionEvent::create(associated_document().realm(), event_name, event_init);
  364. // ...the cancelable attribute initialized to true,
  365. event->set_cancelable(true);
  366. // the bubbles attribute initialized to true,
  367. event->set_bubbles(true);
  368. // isTrusted is a convenience that indicates whether an event is dispatched by the user agent (as opposed to using dispatchEvent())
  369. event->set_is_trusted(true);
  370. // and legacy target override flag set.
  371. dispatch_event(event);
  372. }
  373. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-localstorage
  374. WebIDL::ExceptionOr<GC::Ref<Storage>> Window::local_storage()
  375. {
  376. // FIXME: Implement according to spec.
  377. static HashMap<URL::Origin, GC::Root<Storage>> local_storage_per_origin;
  378. auto storage = local_storage_per_origin.ensure(associated_document().origin(), [this]() -> GC::Root<Storage> {
  379. return Storage::create(realm());
  380. });
  381. return GC::Ref { *storage };
  382. }
  383. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-sessionstorage
  384. WebIDL::ExceptionOr<GC::Ref<Storage>> Window::session_storage()
  385. {
  386. // FIXME: Implement according to spec.
  387. static HashMap<URL::Origin, GC::Root<Storage>> session_storage_per_origin;
  388. auto storage = session_storage_per_origin.ensure(associated_document().origin(), [this]() -> GC::Root<Storage> {
  389. return Storage::create(realm());
  390. });
  391. return GC::Ref { *storage };
  392. }
  393. // https://html.spec.whatwg.org/multipage/interaction.html#sticky-activation
  394. bool Window::has_sticky_activation() const
  395. {
  396. // When the current high resolution time given W
  397. auto current_time = HighResolutionTime::current_high_resolution_time(*this);
  398. // is greater than or equal to the last activation timestamp in W
  399. if (current_time >= m_last_activation_timestamp) {
  400. // W is said to have sticky activation.
  401. return true;
  402. }
  403. return false;
  404. }
  405. // https://html.spec.whatwg.org/multipage/interaction.html#transient-activation
  406. bool Window::has_transient_activation() const
  407. {
  408. // The transient activation duration is expected be at most a few seconds, so that the user can possibly
  409. // perceive the link between an interaction with the page and the page calling the activation-gated API.
  410. static constexpr HighResolutionTime::DOMHighResTimeStamp transient_activation_duration_ms = 5000;
  411. // When the current high resolution time given W
  412. auto current_time = HighResolutionTime::current_high_resolution_time(*this);
  413. // is greater than or equal to the last activation timestamp in W
  414. if (current_time >= m_last_activation_timestamp) {
  415. // and less than the last activation timestamp in W plus the transient activation duration
  416. if (current_time < m_last_activation_timestamp + transient_activation_duration_ms) {
  417. // then W is said to have transient activation.
  418. return true;
  419. }
  420. }
  421. return false;
  422. }
  423. // https://html.spec.whatwg.org/multipage/interaction.html#history-action-activation
  424. bool Window::has_history_action_activation() const
  425. {
  426. // When the last history-action activation timestamp of W is not equal to the last activation timestamp of W, then W is said to have history-action activation.
  427. return m_last_history_action_activation_timestamp != m_last_activation_timestamp;
  428. }
  429. // https://html.spec.whatwg.org/multipage/interaction.html#consume-history-action-user-activation
  430. void Window::consume_history_action_user_activation()
  431. {
  432. auto navigable = this->navigable();
  433. // 1. If W's navigable is null, then return.
  434. if (navigable == nullptr)
  435. return;
  436. // 2. Let top be W's navigable's top-level traversable.
  437. auto top = navigable->top_level_traversable();
  438. // 3. Let navigables be the inclusive descendant navigables of top's active document.
  439. auto navigables = top->active_document()->inclusive_descendant_navigables();
  440. // 4. Let windows be the list of Window objects constructed by taking the active window of each item in navigables.
  441. GC::MarkedVector<GC::Ptr<Window>> windows(heap());
  442. for (auto& n : navigables)
  443. windows.append(n->active_window());
  444. // 5. For each window in windows, set window's last history-action activation timestamp to window's last activation timestamp.
  445. for (auto& window : windows)
  446. window->set_last_history_action_activation_timestamp(window->last_activation_timestamp());
  447. }
  448. // https://html.spec.whatwg.org/multipage/interaction.html#consume-user-activation
  449. void Window::consume_user_activation()
  450. {
  451. auto navigable = this->navigable();
  452. // 1. If W's navigable is null, then return.
  453. if (navigable == nullptr)
  454. return;
  455. // 2. Let top be W's navigable's top-level traversable.
  456. auto top = navigable->top_level_traversable();
  457. // 3. Let navigables be the inclusive descendant navigables of top's active document.
  458. auto navigables = top->active_document()->inclusive_descendant_navigables();
  459. // 4. Let windows be the list of Window objects constructed by taking the active window of each item in navigables.
  460. GC::MarkedVector<GC::Ptr<Window>> windows(heap());
  461. for (auto& n : navigables)
  462. windows.append(n->active_window());
  463. // 5. For each window in windows, if window's last activation timestamp is not positive infinity, then set window's last activation timestamp to negative infinity.
  464. for (auto& window : windows) {
  465. if (window->last_activation_timestamp() != AK::Infinity<HighResolutionTime::DOMHighResTimeStamp>)
  466. window->set_last_activation_timestamp(-AK::Infinity<HighResolutionTime::DOMHighResTimeStamp>);
  467. }
  468. }
  469. // https://w3c.github.io/requestidlecallback/#start-an-idle-period-algorithm
  470. void Window::start_an_idle_period()
  471. {
  472. // 1. Optionally, if the user agent determines the idle period should be delayed, return from this algorithm.
  473. // 2. Let pending_list be window's list of idle request callbacks.
  474. auto& pending_list = m_idle_request_callbacks;
  475. // 3. Let run_list be window's list of runnable idle callbacks.
  476. auto& run_list = m_runnable_idle_callbacks;
  477. run_list.extend(pending_list);
  478. // 4. Clear pending_list.
  479. pending_list.clear();
  480. // FIXME: This might not agree with the spec, but currently we use 100% CPU if we keep queueing tasks
  481. if (run_list.is_empty())
  482. return;
  483. // 5. Queue a task on the queue associated with the idle-task task source,
  484. // which performs the steps defined in the invoke idle callbacks algorithm with window and getDeadline as parameters.
  485. queue_global_task(Task::Source::IdleTask, *this, GC::create_function(heap(), [this] {
  486. invoke_idle_callbacks();
  487. }));
  488. }
  489. // https://w3c.github.io/requestidlecallback/#invoke-idle-callbacks-algorithm
  490. void Window::invoke_idle_callbacks()
  491. {
  492. auto& event_loop = main_thread_event_loop();
  493. // 1. If the user-agent believes it should end the idle period early due to newly scheduled high-priority work, return from the algorithm.
  494. // 2. Let now be the current time.
  495. auto now = HighResolutionTime::unsafe_shared_current_time();
  496. // 3. If now is less than the result of calling getDeadline and the window's list of runnable idle callbacks is not empty:
  497. if (now < event_loop.compute_deadline() && !m_runnable_idle_callbacks.is_empty()) {
  498. // 1. Pop the top callback from window's list of runnable idle callbacks.
  499. auto callback = m_runnable_idle_callbacks.take_first();
  500. // 2. Let deadlineArg be a new IdleDeadline whose [get deadline time algorithm] is getDeadline.
  501. auto deadline_arg = RequestIdleCallback::IdleDeadline::create(realm());
  502. // 3. Call callback with deadlineArg as its argument. If an uncaught runtime script error occurs, then report the exception.
  503. auto result = callback->invoke(deadline_arg);
  504. if (result.is_error())
  505. report_exception(result, realm());
  506. // 4. If window's list of runnable idle callbacks is not empty, queue a task which performs the steps
  507. // in the invoke idle callbacks algorithm with getDeadline and window as a parameters and return from this algorithm
  508. queue_global_task(Task::Source::IdleTask, *this, GC::create_function(heap(), [this] {
  509. invoke_idle_callbacks();
  510. }));
  511. }
  512. }
  513. void Window::set_associated_document(DOM::Document& document)
  514. {
  515. m_associated_document = &document;
  516. }
  517. void Window::set_current_event(DOM::Event* event)
  518. {
  519. m_current_event = event;
  520. }
  521. BrowsingContext const* Window::browsing_context() const
  522. {
  523. return m_associated_document->browsing_context();
  524. }
  525. BrowsingContext* Window::browsing_context()
  526. {
  527. return m_associated_document->browsing_context();
  528. }
  529. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#window-navigable
  530. GC::Ptr<Navigable> Window::navigable() const
  531. {
  532. // A Window's navigable is the navigable whose active document is the Window's associated Document's, or null if there is no such navigable.
  533. return Navigable::navigable_with_active_document(*m_associated_document);
  534. }
  535. // https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-plugin-objects
  536. Vector<GC::Ref<Plugin>> Window::pdf_viewer_plugin_objects()
  537. {
  538. // Each Window object has a PDF viewer plugin objects list. If the user agent's PDF viewer supported is false, then it is the empty list.
  539. // Otherwise, it is a list containing five Plugin objects, whose names are, respectively:
  540. // 0. "PDF Viewer"
  541. // 1. "Chrome PDF Viewer"
  542. // 2. "Chromium PDF Viewer"
  543. // 3. "Microsoft Edge PDF Viewer"
  544. // 4. "WebKit built-in PDF"
  545. // The values of the above list form the PDF viewer plugin names list. https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-plugin-names
  546. if (!page().pdf_viewer_supported())
  547. return {};
  548. if (m_pdf_viewer_plugin_objects.is_empty()) {
  549. // FIXME: Propagate errors.
  550. m_pdf_viewer_plugin_objects.append(realm().create<Plugin>(realm(), "PDF Viewer"_string));
  551. m_pdf_viewer_plugin_objects.append(realm().create<Plugin>(realm(), "Chrome PDF Viewer"_string));
  552. m_pdf_viewer_plugin_objects.append(realm().create<Plugin>(realm(), "Chromium PDF Viewer"_string));
  553. m_pdf_viewer_plugin_objects.append(realm().create<Plugin>(realm(), "Microsoft Edge PDF Viewer"_string));
  554. m_pdf_viewer_plugin_objects.append(realm().create<Plugin>(realm(), "WebKit built-in PDF"_string));
  555. }
  556. return m_pdf_viewer_plugin_objects;
  557. }
  558. // https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-mime-type-objects
  559. Vector<GC::Ref<MimeType>> Window::pdf_viewer_mime_type_objects()
  560. {
  561. // Each Window object has a PDF viewer mime type objects list. If the user agent's PDF viewer supported is false, then it is the empty list.
  562. // Otherwise, it is a list containing two MimeType objects, whose types are, respectively:
  563. // 0. "application/pdf"
  564. // 1. "text/pdf"
  565. // The values of the above list form the PDF viewer mime types list. https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-mime-types
  566. if (!page().pdf_viewer_supported())
  567. return {};
  568. if (m_pdf_viewer_mime_type_objects.is_empty()) {
  569. m_pdf_viewer_mime_type_objects.append(realm().create<MimeType>(realm(), "application/pdf"_string));
  570. m_pdf_viewer_mime_type_objects.append(realm().create<MimeType>(realm(), "text/pdf"_string));
  571. }
  572. return m_pdf_viewer_mime_type_objects;
  573. }
  574. // https://streams.spec.whatwg.org/#count-queuing-strategy-size-function
  575. GC::Ref<WebIDL::CallbackType> Window::count_queuing_strategy_size_function()
  576. {
  577. auto& realm = this->realm();
  578. if (!m_count_queuing_strategy_size_function) {
  579. // 1. Let steps be the following steps:
  580. auto steps = [](auto const&) {
  581. // 1. Return 1.
  582. return 1.0;
  583. };
  584. // 2. Let F be ! CreateBuiltinFunction(steps, 0, "size", « », globalObject’s relevant Realm).
  585. auto function = JS::NativeFunction::create(realm, move(steps), 0, "size", &realm);
  586. // 3. Set globalObject’s count queuing strategy size function to a Function that represents a reference to F, with callback context equal to globalObject’s relevant settings object.
  587. m_count_queuing_strategy_size_function = realm.create<WebIDL::CallbackType>(*function, relevant_settings_object(*this));
  588. }
  589. return GC::Ref { *m_count_queuing_strategy_size_function };
  590. }
  591. // https://streams.spec.whatwg.org/#byte-length-queuing-strategy-size-function
  592. GC::Ref<WebIDL::CallbackType> Window::byte_length_queuing_strategy_size_function()
  593. {
  594. auto& realm = this->realm();
  595. if (!m_byte_length_queuing_strategy_size_function) {
  596. // 1. Let steps be the following steps, given chunk:
  597. auto steps = [](JS::VM& vm) {
  598. auto chunk = vm.argument(0);
  599. // 1. Return ? GetV(chunk, "byteLength").
  600. return chunk.get(vm, vm.names.byteLength);
  601. };
  602. // 2. Let F be ! CreateBuiltinFunction(steps, 1, "size", « », globalObject’s relevant Realm).
  603. auto function = JS::NativeFunction::create(realm, move(steps), 1, "size", &realm);
  604. // 3. Set globalObject’s byte length queuing strategy size function to a Function that represents a reference to F, with callback context equal to globalObject’s relevant settings object.
  605. m_byte_length_queuing_strategy_size_function = realm.create<WebIDL::CallbackType>(*function, relevant_settings_object(*this));
  606. }
  607. return GC::Ref { *m_byte_length_queuing_strategy_size_function };
  608. }
  609. static bool s_inspector_object_exposed = false;
  610. static bool s_internals_object_exposed = false;
  611. void Window::set_inspector_object_exposed(bool exposed)
  612. {
  613. s_inspector_object_exposed = exposed;
  614. }
  615. void Window::set_internals_object_exposed(bool exposed)
  616. {
  617. s_internals_object_exposed = exposed;
  618. }
  619. WebIDL::ExceptionOr<void> Window::initialize_web_interfaces(Badge<WindowEnvironmentSettingsObject>)
  620. {
  621. auto& realm = this->realm();
  622. add_window_exposed_interfaces(*this);
  623. WEB_SET_PROTOTYPE_FOR_INTERFACE(Window);
  624. Bindings::WindowGlobalMixin::initialize(realm, *this);
  625. WindowOrWorkerGlobalScopeMixin::initialize(realm);
  626. if (s_inspector_object_exposed)
  627. define_direct_property("inspector", realm.create<Internals::Inspector>(realm), JS::default_attributes);
  628. if (s_internals_object_exposed)
  629. define_direct_property("internals", realm.create<Internals::Internals>(realm), JS::default_attributes);
  630. return {};
  631. }
  632. // https://webidl.spec.whatwg.org/#platform-object-setprototypeof
  633. JS::ThrowCompletionOr<bool> Window::internal_set_prototype_of(JS::Object* prototype)
  634. {
  635. // 1. Return ? SetImmutablePrototype(O, V).
  636. return set_immutable_prototype(prototype);
  637. }
  638. // https://html.spec.whatwg.org/multipage/window-object.html#dom-window
  639. GC::Ref<WindowProxy> Window::window() const
  640. {
  641. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  642. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  643. }
  644. // https://html.spec.whatwg.org/multipage/window-object.html#dom-self
  645. GC::Ref<WindowProxy> Window::self() const
  646. {
  647. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  648. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  649. }
  650. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-document-2
  651. GC::Ref<DOM::Document const> Window::document() const
  652. {
  653. // The document getter steps are to return this's associated Document.
  654. return associated_document();
  655. }
  656. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-name
  657. String Window::name() const
  658. {
  659. // 1. If this's navigable is null, then return the empty string.
  660. if (!navigable())
  661. return String {};
  662. // 2. Return this's navigable's target name.
  663. return navigable()->target_name();
  664. }
  665. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#apis-for-creating-and-navigating-browsing-contexts-by-name:dom-name
  666. void Window::set_name(String const& name)
  667. {
  668. // 1. If this's navigable is null, then return.
  669. if (!navigable())
  670. return;
  671. // 2. Set this's navigable's active session history entry's document state's navigable target name to the given value.
  672. navigable()->active_session_history_entry()->document_state()->set_navigable_target_name(name);
  673. }
  674. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-window-status
  675. String Window::status() const
  676. {
  677. // the status attribute on the Window object must, on getting, return the last string it was set to
  678. return m_status;
  679. }
  680. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-window-close
  681. void Window::close()
  682. {
  683. // 1. Let thisTraversable be this's navigable.
  684. auto traversable = navigable();
  685. // 2. If thisTraversable is not a top-level traversable, then return.
  686. if (!traversable || !traversable->is_top_level_traversable())
  687. return;
  688. // 3. If thisTraversable's is closing is true, then return.
  689. if (traversable->is_closing())
  690. return;
  691. // 4. Let browsingContext be thisTraversable's active browsing context.
  692. auto browsing_context = traversable->active_browsing_context();
  693. // 5. Let sourceSnapshotParams be the result of snapshotting source snapshot params given thisTraversable's active document.
  694. auto source_snapshot_params = traversable->active_document()->snapshot_source_snapshot_params();
  695. auto& incumbent_global_object = verify_cast<HTML::Window>(HTML::incumbent_global_object());
  696. // 6. If all the following are true:
  697. if (
  698. // thisTraversable is script-closable;
  699. traversable->is_script_closable()
  700. // the incumbent global object's browsing context is familiar with browsingContext; and
  701. && incumbent_global_object.browsing_context()->is_familiar_with(*browsing_context)
  702. // the incumbent global object's navigable is allowed by sandboxing to navigate thisTraversable, given sourceSnapshotParams,
  703. && incumbent_global_object.navigable()->allowed_by_sandboxing_to_navigate(*traversable, source_snapshot_params))
  704. // then:
  705. {
  706. // 1. Set thisTraversable's is closing to true.
  707. traversable->set_closing(true);
  708. // 2. Queue a task on the DOM manipulation task source to definitely close thisTraversable.
  709. HTML::queue_global_task(HTML::Task::Source::DOMManipulation, incumbent_global_object, GC::create_function(heap(), [traversable] {
  710. verify_cast<TraversableNavigable>(*traversable).definitely_close_top_level_traversable();
  711. }));
  712. }
  713. }
  714. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-window-closed
  715. bool Window::closed() const
  716. {
  717. // The closed getter steps are to return true if this's browsing context is null or its is closing is true;
  718. // otherwise false.
  719. if (!browsing_context())
  720. return true;
  721. // FIXME: The spec seems a bit out of date. The `is closing` flag is on the navigable, not the browsing context.
  722. if (auto navigable = this->navigable(); !navigable || navigable->is_closing())
  723. return true;
  724. return false;
  725. }
  726. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-window-status
  727. void Window::set_status(String const& status)
  728. {
  729. // on setting, must set itself to the new value.
  730. m_status = status;
  731. }
  732. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-location
  733. GC::Ref<Location> Window::location()
  734. {
  735. auto& realm = this->realm();
  736. // The Window object's location getter steps are to return this's Location object.
  737. if (!m_location)
  738. m_location = realm.create<Location>(realm);
  739. return GC::Ref { *m_location };
  740. }
  741. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-history
  742. GC::Ref<History> Window::history() const
  743. {
  744. // The history getter steps are to return this's associated Document's history object.
  745. return associated_document().history();
  746. }
  747. // https://html.spec.whatwg.org/multipage/interaction.html#dom-window-focus
  748. void Window::focus()
  749. {
  750. // 1. Let current be this Window object's navigable.
  751. auto current = navigable();
  752. // 2. If current is null, then return.
  753. if (!current)
  754. return;
  755. // 3. Run the focusing steps with current.
  756. // FIXME: We should pass in the browsing context itself instead of the active document, however the focusing steps don't currently accept browsing contexts.
  757. // Passing in a browsing context always makes it resolve to its active document for focus, so this is fine for now.
  758. run_focusing_steps(current->active_document());
  759. // FIXME: 4. If current is a top-level traversable, user agents are encouraged to trigger some sort of notification to
  760. // indicate to the user that the page is attempting to gain focus.
  761. }
  762. // https://html.spec.whatwg.org/multipage/interaction.html#dom-window-blur
  763. void Window::blur()
  764. {
  765. // The blur() method steps are to do nothing.
  766. }
  767. // https://html.spec.whatwg.org/multipage/window-object.html#dom-frames
  768. GC::Ref<WindowProxy> Window::frames() const
  769. {
  770. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  771. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  772. }
  773. // https://html.spec.whatwg.org/multipage/window-object.html#dom-length
  774. u32 Window::length()
  775. {
  776. // The length getter steps are to return this's associated Document's document-tree child navigables's size.
  777. return associated_document().document_tree_child_navigables().size();
  778. }
  779. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-top
  780. GC::Ptr<WindowProxy const> Window::top() const
  781. {
  782. // 1. If this's navigable is null, then return null.
  783. auto navigable = this->navigable();
  784. if (!navigable)
  785. return {};
  786. // 2. Return this's navigable's top-level traversable's active WindowProxy.
  787. return navigable->top_level_traversable()->active_window_proxy();
  788. }
  789. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-opener
  790. GC::Ptr<WindowProxy const> Window::opener() const
  791. {
  792. // 1. Let current be this's browsing context.
  793. auto const* current = browsing_context();
  794. // 2. If current is null, then return null.
  795. if (!current)
  796. return {};
  797. // 3. If current's opener browsing context is null, then return null.
  798. auto opener_browsing_context = current->opener_browsing_context();
  799. if (!opener_browsing_context)
  800. return {};
  801. // 4. Return current's opener browsing context's WindowProxy object.
  802. return opener_browsing_context->window_proxy();
  803. }
  804. WebIDL::ExceptionOr<void> Window::set_opener(JS::Value value)
  805. {
  806. // 1. If the given value is null and this's browsing context is non-null, then set this's browsing context's opener browsing context to null.
  807. auto* browsing_context = this->browsing_context();
  808. if (value.is_null() && browsing_context)
  809. browsing_context->set_opener_browsing_context(nullptr);
  810. // 2. If the given value is non-null, then perform ? DefinePropertyOrThrow(this, "opener", { [[Value]]: the given value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }).
  811. if (!value.is_null()) {
  812. static JS::PropertyKey opener_property_key { "opener", JS::PropertyKey::StringMayBeNumber::No };
  813. TRY(define_property_or_throw(opener_property_key, { .value = value, .writable = true, .enumerable = true, .configurable = true }));
  814. }
  815. return {};
  816. }
  817. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-parent
  818. GC::Ptr<WindowProxy const> Window::parent() const
  819. {
  820. // 1. Let navigable be this's navigable.
  821. auto navigable = this->navigable();
  822. // 2. If navigable is null, then return null.
  823. if (!navigable)
  824. return {};
  825. // 3. If navigable's parent is not null, then set navigable to navigable's parent.
  826. if (auto parent = navigable->parent())
  827. navigable = parent;
  828. // 4. Return navigable's active WindowProxy.
  829. return navigable->active_window_proxy();
  830. }
  831. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-frameelement
  832. // https://whatpr.org/html/9893/nav-history-apis.html#dom-frameelement
  833. GC::Ptr<DOM::Element const> Window::frame_element() const
  834. {
  835. // 1. Let current be this's node navigable.
  836. auto current = navigable();
  837. // 2. If current is null, then return null.
  838. if (!current)
  839. return {};
  840. // 3. Let container be current's container.
  841. auto container = current->container();
  842. // 4. If container is null, then return null.
  843. if (!container)
  844. return {};
  845. // 5. If container's node document's origin is not same origin-domain with the current principal settings object's origin, then return null.
  846. if (!container->document().origin().is_same_origin_domain(current_principal_settings_object().origin()))
  847. return {};
  848. // 6. Return container.
  849. return container;
  850. }
  851. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-open
  852. WebIDL::ExceptionOr<GC::Ptr<WindowProxy>> Window::open(Optional<String> const& url, Optional<String> const& target, Optional<String> const& features)
  853. {
  854. // The open(url, target, features) method steps are to run the window open steps with url, target, and features.
  855. return window_open_steps(*url, *target, *features);
  856. }
  857. // https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator
  858. GC::Ref<Navigator> Window::navigator()
  859. {
  860. auto& realm = this->realm();
  861. // The navigator and clientInformation getter steps are to return this's associated Navigator.
  862. if (!m_navigator)
  863. m_navigator = realm.create<Navigator>(realm);
  864. return GC::Ref { *m_navigator };
  865. }
  866. // https://html.spec.whatwg.org/multipage/interaction.html#close-watcher-manager
  867. GC::Ref<CloseWatcherManager> Window::close_watcher_manager()
  868. {
  869. auto& realm = this->realm();
  870. if (!m_close_watcher_manager)
  871. m_close_watcher_manager = realm.create<CloseWatcherManager>(realm);
  872. return GC::Ref { *m_close_watcher_manager };
  873. }
  874. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-alert
  875. void Window::alert(String const& message)
  876. {
  877. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#simple-dialogs
  878. // Note: This method is defined using two overloads, instead of using an optional argument,
  879. // for historical reasons. The practical impact of this is that alert(undefined) is
  880. // treated as alert("undefined"), but alert() is treated as alert("").
  881. // FIXME: Make this fully spec compliant.
  882. page().did_request_alert(message);
  883. }
  884. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-confirm
  885. bool Window::confirm(Optional<String> const& message)
  886. {
  887. // FIXME: Make this fully spec compliant.
  888. // NOTE: `message` has an IDL-provided default value and is never empty.
  889. return page().did_request_confirm(*message);
  890. }
  891. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-prompt
  892. Optional<String> Window::prompt(Optional<String> const& message, Optional<String> const& default_)
  893. {
  894. // FIXME: Make this fully spec compliant.
  895. return page().did_request_prompt(*message, *default_);
  896. }
  897. // https://html.spec.whatwg.org/multipage/web-messaging.html#window-post-message-steps
  898. WebIDL::ExceptionOr<void> Window::window_post_message_steps(JS::Value message, WindowPostMessageOptions const& options)
  899. {
  900. // 1. Let targetRealm be targetWindow's realm.
  901. auto& target_realm = this->realm();
  902. // 2. Let incumbentSettings be the incumbent settings object.
  903. auto& incumbent_settings = incumbent_settings_object();
  904. // 3. Let targetOrigin be options["targetOrigin"].
  905. Variant<String, URL::Origin> target_origin = options.target_origin;
  906. // 4. If targetOrigin is a single U+002F SOLIDUS character (/), then set targetOrigin to incumbentSettings's origin.
  907. if (options.target_origin == "/"sv) {
  908. target_origin = incumbent_settings.origin();
  909. }
  910. // 5. Otherwise, if targetOrigin is not a single U+002A ASTERISK character (*), then:
  911. else if (options.target_origin != "*"sv) {
  912. // 1. Let parsedURL be the result of running the URL parser on targetOrigin.
  913. auto parsed_url = DOMURL::parse(options.target_origin);
  914. // 2. If parsedURL is failure, then throw a "SyntaxError" DOMException.
  915. if (!parsed_url.is_valid())
  916. return WebIDL::SyntaxError::create(target_realm, MUST(String::formatted("Invalid URL for targetOrigin: '{}'", options.target_origin)));
  917. // 3. Set targetOrigin to parsedURL's origin.
  918. target_origin = parsed_url.origin();
  919. }
  920. // 6. Let transfer be options["transfer"].
  921. auto& transfer = options.transfer;
  922. // 7. Let serializeWithTransferResult be StructuredSerializeWithTransfer(message, transfer). Rethrow any exceptions.
  923. auto serialize_with_transfer_result = TRY(structured_serialize_with_transfer(target_realm.vm(), message, transfer));
  924. // 8. Queue a global task on the posted message task source given targetWindow to run the following steps:
  925. queue_global_task(Task::Source::PostedMessage, *this, GC::create_function(heap(), [this, serialize_with_transfer_result = move(serialize_with_transfer_result), target_origin = move(target_origin), &incumbent_settings, &target_realm]() mutable {
  926. // 1. If the targetOrigin argument is not a single literal U+002A ASTERISK character (*) and targetWindow's
  927. // associated Document's origin is not same origin with targetOrigin, then return.
  928. // NOTE: Due to step 4 and 5 above, the only time it's not '*' is if target_origin contains an Origin.
  929. if (!target_origin.has<String>()) {
  930. auto const& actual_target_origin = target_origin.get<URL::Origin>();
  931. if (!document()->origin().is_same_origin(actual_target_origin))
  932. return;
  933. }
  934. // 2. Let origin be the serialization of incumbentSettings's origin.
  935. auto origin = incumbent_settings.origin().serialize();
  936. // 3. Let source be the WindowProxy object corresponding to incumbentSettings's global object (a Window object).
  937. auto& source = verify_cast<WindowProxy>(incumbent_settings.realm().global_environment().global_this_value());
  938. // 4. Let deserializeRecord be StructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm).
  939. auto temporary_execution_context = TemporaryExecutionContext { target_realm };
  940. auto deserialize_record_or_error = structured_deserialize_with_transfer(vm(), serialize_with_transfer_result);
  941. // If this throws an exception, catch it, fire an event named messageerror at targetWindow, using MessageEvent,
  942. // with the origin attribute initialized to origin and the source attribute initialized to source, and then return.
  943. if (deserialize_record_or_error.is_exception()) {
  944. MessageEventInit message_event_init {};
  945. message_event_init.origin = MUST(String::from_byte_string(origin));
  946. message_event_init.source = GC::make_root(source);
  947. auto message_error_event = MessageEvent::create(target_realm, EventNames::messageerror, message_event_init);
  948. dispatch_event(message_error_event);
  949. return;
  950. }
  951. // 5. Let messageClone be deserializeRecord.[[Deserialized]].
  952. auto deserialize_record = deserialize_record_or_error.release_value();
  953. auto message_clone = deserialize_record.deserialized;
  954. // 6. Let newPorts be a new frozen array consisting of all MessagePort objects in deserializeRecord.[[TransferredValues]],
  955. // if any, maintaining their relative order.
  956. // FIXME: Use a FrozenArray
  957. Vector<GC::Root<MessagePort>> new_ports;
  958. for (auto const& object : deserialize_record.transferred_values) {
  959. if (is<HTML::MessagePort>(*object)) {
  960. new_ports.append(verify_cast<MessagePort>(*object));
  961. }
  962. }
  963. // 7. Fire an event named message at targetWindow, using MessageEvent, with the origin attribute initialized to origin,
  964. // the source attribute initialized to source, the data attribute initialized to messageClone, and the ports attribute
  965. // initialized to newPorts.
  966. MessageEventInit message_event_init {};
  967. message_event_init.origin = MUST(String::from_byte_string(origin));
  968. message_event_init.source = GC::make_root(source);
  969. message_event_init.data = message_clone;
  970. message_event_init.ports = move(new_ports);
  971. auto message_event = MessageEvent::create(target_realm, EventNames::message, message_event_init);
  972. message_event->set_is_trusted(true);
  973. dispatch_event(message_event);
  974. }));
  975. return {};
  976. }
  977. // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-window-postmessage-options
  978. WebIDL::ExceptionOr<void> Window::post_message(JS::Value message, WindowPostMessageOptions const& options)
  979. {
  980. // The Window interface's postMessage(message, options) method steps are to run the window post message steps given
  981. // this, message, and options.
  982. return window_post_message_steps(message, options);
  983. }
  984. // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-window-postmessage
  985. WebIDL::ExceptionOr<void> Window::post_message(JS::Value message, String const& target_origin, Vector<GC::Root<JS::Object>> const& transfer)
  986. {
  987. // The Window interface's postMessage(message, targetOrigin, transfer) method steps are to run the window post message
  988. // steps given this, message, and «[ "targetOrigin" → targetOrigin, "transfer" → transfer ]».
  989. return window_post_message_steps(message, WindowPostMessageOptions { { .transfer = transfer }, target_origin });
  990. }
  991. // https://dom.spec.whatwg.org/#dom-window-event
  992. Variant<GC::Root<DOM::Event>, JS::Value> Window::event() const
  993. {
  994. // The event getter steps are to return this’s current event.
  995. if (auto* current_event = this->current_event())
  996. return make_root(const_cast<DOM::Event&>(*current_event));
  997. return JS::js_undefined();
  998. }
  999. // https://w3c.github.io/csswg-drafts/cssom/#dom-window-getcomputedstyle
  1000. GC::Ref<CSS::CSSStyleDeclaration> Window::get_computed_style(DOM::Element& element, Optional<String> const& pseudo_element) const
  1001. {
  1002. // 1. Let doc be elt’s node document.
  1003. // 2. Let obj be elt.
  1004. Optional<CSS::Selector::PseudoElement::Type> obj_pseudo;
  1005. // 3. If pseudoElt is provided, is not the empty string, and starts with a colon, then:
  1006. if (pseudo_element.has_value() && pseudo_element.value().starts_with(':')) {
  1007. // 1. Parse pseudoElt as a <pseudo-element-selector>, and let type be the result.
  1008. auto type = parse_pseudo_element_selector(CSS::Parser::ParsingContext(associated_document()), pseudo_element.value());
  1009. // 2. If type is failure, or is an ::slotted() or ::part() pseudo-element, let obj be null.
  1010. // FIXME: We can't pass a null element to ResolvedCSSStyleDeclaration
  1011. if (!type.has_value()) {
  1012. }
  1013. // 3. Otherwise let obj be the given pseudo-element of elt.
  1014. else {
  1015. // TODO: Keep the function arguments of the pseudo-element if there are any.
  1016. obj_pseudo = type.value().type();
  1017. }
  1018. }
  1019. // AD-HOC: Just return a ResolvedCSSStyleDeclaration because that's what we have for now.
  1020. // FIXME: Implement CSSStyleProperties, and then follow the rest of these steps instead.
  1021. return realm().create<CSS::ResolvedCSSStyleDeclaration>(element, obj_pseudo);
  1022. // 4. Let decls be an empty list of CSS declarations.
  1023. // 5. If obj is not null, and elt is connected, part of the flat tree, and its shadow-including root
  1024. // has a browsing context which either doesn’t have a browsing context container, or whose browsing
  1025. // context container is being rendered, set decls to a list of all longhand properties that are
  1026. // supported CSS properties, in lexicographical order, with the value being the resolved value
  1027. // computed for obj using the style rules associated with doc. Additionally, append to decls all
  1028. // the custom properties whose computed value for obj is not the guaranteed-invalid value.
  1029. // 6. Return a live CSSStyleProperties object with the following properties:
  1030. // computed flag
  1031. // Set.
  1032. // readonly flag
  1033. // Set.
  1034. // declarations
  1035. // decls.
  1036. // parent CSS rule
  1037. // Null.
  1038. // owner node
  1039. // obj.
  1040. }
  1041. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-matchmedia
  1042. WebIDL::ExceptionOr<GC::Ref<CSS::MediaQueryList>> Window::match_media(String const& query)
  1043. {
  1044. // 1. Let parsed media query list be the result of parsing query.
  1045. auto parsed_media_query_list = parse_media_query_list(CSS::Parser::ParsingContext(associated_document()), query);
  1046. // 2. Return a new MediaQueryList object, with this's associated Document as the document, with parsed media query list as its associated media query list.
  1047. auto media_query_list = realm().create<CSS::MediaQueryList>(associated_document(), move(parsed_media_query_list));
  1048. associated_document().add_media_query_list(media_query_list);
  1049. return media_query_list;
  1050. }
  1051. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screen
  1052. GC::Ref<CSS::Screen> Window::screen()
  1053. {
  1054. // The screen attribute must return the Screen object associated with the Window object.
  1055. if (!m_screen)
  1056. m_screen = realm().create<CSS::Screen>(*this);
  1057. return GC::Ref { *m_screen };
  1058. }
  1059. GC::Ptr<CSS::VisualViewport> Window::visual_viewport()
  1060. {
  1061. // If the associated document is fully active, the visualViewport attribute must return
  1062. // the VisualViewport object associated with the Window object’s associated document.
  1063. if (associated_document().is_fully_active())
  1064. return associated_document().visual_viewport();
  1065. // Otherwise, it must return null.
  1066. return nullptr;
  1067. }
  1068. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-innerwidth
  1069. i32 Window::inner_width() const
  1070. {
  1071. // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar (if any),
  1072. // or zero if there is no viewport.
  1073. if (auto const navigable = associated_document().navigable())
  1074. return navigable->viewport_rect().width().to_int();
  1075. return 0;
  1076. }
  1077. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-innerheight
  1078. i32 Window::inner_height() const
  1079. {
  1080. // The innerHeight attribute must return the viewport height including the size of a rendered scroll bar (if any),
  1081. // or zero if there is no viewport.
  1082. if (auto const navigable = associated_document().navigable())
  1083. return navigable->viewport_rect().height().to_int();
  1084. return 0;
  1085. }
  1086. // https://drafts.csswg.org/cssom-view/#dom-window-moveto
  1087. void Window::move_to(long, long) const
  1088. {
  1089. // 1. Optionally, return.
  1090. return;
  1091. // NOTE: For now, the other steps are unimplemented because we always return in step 1.
  1092. // FIXME: Implement these for popup windows?
  1093. // 2. Let target be this's relevant global object's browsing context.
  1094. // 3. If target is not an auxiliary browsing context that was created by a script (as opposed to by an action of the user), then return.
  1095. // 4. Optionally, clamp x and y in a user-agent-defined manner so that the window does not move outside the available space.
  1096. // 5. Move target’s window such that the window’s top left corner is at coordinates (x, y) relative to the top left corner of the output device, measured in CSS pixels of target. The positive axes are rightward and downward.
  1097. }
  1098. // https://drafts.csswg.org/cssom-view/#dom-window-moveby
  1099. void Window::move_by(long, long) const
  1100. {
  1101. // 1. Optionally, return.
  1102. return;
  1103. // NOTE: For now, the other steps are unimplemented because we always return in step 1.
  1104. // FIXME: Implement these for popup windows?
  1105. // 2. Let target be this's relevant global object's browsing context.
  1106. // 3. If target is not an auxiliary browsing context that was created by a script (as opposed to by an action of the user), then return.
  1107. // 4. Optionally, clamp x and y in a user-agent-defined manner so that the window does not move outside the available space.
  1108. // 5. Move target’s window x CSS pixels of target rightward and y CSS pixels of target downward.
  1109. }
  1110. // https://drafts.csswg.org/cssom-view/#dom-window-resizeto
  1111. void Window::resize_to(long, long) const
  1112. {
  1113. // 1. Optionally, return.
  1114. return;
  1115. // NOTE: For now, the other steps are unimplemented because we always return in step 1.
  1116. // FIXME: Implement these for popup windows?
  1117. // 2. Let target be this's relevant global object's browsing context.
  1118. // 3. If target is not an auxiliary browsing context that was created by a script (as opposed to by an action of the user), then return.
  1119. // 4. Optionally, clamp width and height in a user-agent-defined manner so that the window does not get too small or bigger than the available space.
  1120. // 5. Resize target’s window by moving its right and bottom edges such that the distance between the left and right edges of the viewport are width CSS pixels of target and the distance between the top and bottom edges of the viewport are height CSS pixels of target.
  1121. // 6. Optionally, move target’s window in a user-agent-defined manner so that it does not grow outside the available space.
  1122. }
  1123. // https://drafts.csswg.org/cssom-view/#dom-window-resizeby
  1124. void Window::resize_by(long, long) const
  1125. {
  1126. // 1. Optionally, return.
  1127. return;
  1128. // NOTE: For now, the other steps are unimplemented because we always return in step 1.
  1129. // FIXME: Implement these for popup windows?
  1130. // 2. Let target be this's relevant global object's browsing context.
  1131. // 3. If target is not an auxiliary browsing context that was created by a script (as opposed to by an action of the user), then return.
  1132. // 4. Optionally, clamp x and y in a user-agent-defined manner so that the window does not get too small or bigger than the available space.
  1133. // 5. Resize target’s window by moving its right edge x CSS pixels of target rightward and its bottom edge y CSS pixels of target downward.
  1134. // 6. Optionally, move target’s window in a user-agent-defined manner so that it does not grow outside the available space.
  1135. }
  1136. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrollx
  1137. double Window::scroll_x() const
  1138. {
  1139. // The scrollX attribute must return the x-coordinate, relative to the initial containing block origin,
  1140. // of the left of the viewport, or zero if there is no viewport.
  1141. if (auto const navigable = associated_document().navigable())
  1142. return navigable->viewport_rect().x().to_double();
  1143. return 0;
  1144. }
  1145. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrolly
  1146. double Window::scroll_y() const
  1147. {
  1148. // The scrollY attribute must return the y-coordinate, relative to the initial containing block origin,
  1149. // of the top of the viewport, or zero if there is no viewport.
  1150. if (auto const navigable = associated_document().navigable())
  1151. return navigable->viewport_rect().y().to_double();
  1152. return 0;
  1153. }
  1154. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scroll
  1155. void Window::scroll(ScrollToOptions const& options)
  1156. {
  1157. // 4. If there is no viewport, abort these steps.
  1158. auto navigable = associated_document().navigable();
  1159. if (!navigable)
  1160. return;
  1161. // 1. If invoked with one argument, follow these substeps:
  1162. // 1. Let options be the argument.
  1163. auto viewport_rect = navigable->viewport_rect().to_type<float>();
  1164. // 2. Let x be the value of the left dictionary member of options, if present, or the viewport’s current scroll
  1165. // position on the x axis otherwise.
  1166. auto x = options.left.value_or(viewport_rect.x());
  1167. // 3. Let y be the value of the top dictionary member of options, if present, or the viewport’s current scroll
  1168. // position on the y axis otherwise.
  1169. auto y = options.top.value_or(viewport_rect.y());
  1170. // 3. Normalize non-finite values for x and y.
  1171. x = HTML::normalize_non_finite_values(x);
  1172. y = HTML::normalize_non_finite_values(y);
  1173. // 5. Let viewport width be the width of the viewport excluding the width of the scroll bar, if any.
  1174. auto viewport_width = viewport_rect.width();
  1175. // 6. Let viewport height be the height of the viewport excluding the height of the scroll bar, if any.
  1176. auto viewport_height = viewport_rect.height();
  1177. auto const document = navigable->active_document();
  1178. VERIFY(document);
  1179. // Make sure layout is up-to-date before looking at scrollable overflow metrics.
  1180. document->update_layout();
  1181. VERIFY(document->paintable_box());
  1182. auto scrolling_area = document->paintable_box()->scrollable_overflow_rect()->to_type<float>();
  1183. // 7. FIXME: For now we always assume overflow direction is rightward
  1184. // -> If the viewport has rightward overflow direction
  1185. // Let x be max(0, min(x, viewport scrolling area width - viewport width)).
  1186. x = max(0.0f, min(x, scrolling_area.width() - viewport_width));
  1187. // -> If the viewport has leftward overflow direction
  1188. // Let x be min(0, max(x, viewport width - viewport scrolling area width)).
  1189. // 8. FIXME: For now we always assume overflow direction is downward
  1190. // -> If the viewport has downward overflow direction
  1191. // Let y be max(0, min(y, viewport scrolling area height - viewport height)).
  1192. y = max(0.0f, min(y, scrolling_area.height() - viewport_height));
  1193. // -> If the viewport has upward overflow direction
  1194. // Let y be min(0, max(y, viewport height - viewport scrolling area height)).
  1195. // FIXME: 9. Let position be the scroll position the viewport would have by aligning the x-coordinate x of the viewport
  1196. // scrolling area with the left of the viewport and aligning the y-coordinate y of the viewport scrolling area
  1197. // with the top of the viewport.
  1198. auto position = Gfx::FloatPoint { x, y };
  1199. // 10. If position is the same as the viewport’s current scroll position, and the viewport does not have an ongoing
  1200. // smooth scroll, abort these steps.
  1201. if (position == viewport_rect.location())
  1202. return;
  1203. // 11. Let document be the viewport’s associated Document.
  1204. // NOTE: document is already defined above.
  1205. // 12. Perform a scroll of the viewport to position, document’s root element as the associated element, if there is
  1206. // one, or null otherwise, and the scroll behavior being the value of the behavior dictionary member of options.
  1207. navigable->perform_scroll_of_viewport({ x, y });
  1208. }
  1209. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scroll
  1210. void Window::scroll(double x, double y)
  1211. {
  1212. // 2. If invoked with two arguments, follow these substeps:
  1213. // 1. Let options be null converted to a ScrollToOptions dictionary. [WEBIDL]
  1214. auto options = ScrollToOptions {};
  1215. // 2. Let x and y be the arguments, respectively.
  1216. options.left = x;
  1217. options.top = y;
  1218. scroll(options);
  1219. }
  1220. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrollby
  1221. void Window::scroll_by(ScrollToOptions options)
  1222. {
  1223. // 2. Normalize non-finite values for the left and top dictionary members of options.
  1224. auto left = HTML::normalize_non_finite_values(options.left);
  1225. auto top = HTML::normalize_non_finite_values(options.top);
  1226. // 3. Add the value of scrollX to the left dictionary member.
  1227. options.left = left + scroll_x();
  1228. // 4. Add the value of scrollY to the top dictionary member.
  1229. options.top = top + scroll_y();
  1230. // 5. Act as if the scroll() method was invoked with options as the only argument.
  1231. scroll(options);
  1232. }
  1233. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrollby
  1234. void Window::scroll_by(double x, double y)
  1235. {
  1236. // 1. If invoked with two arguments, follow these substeps:
  1237. // 1. Let options be null converted to a ScrollToOptions dictionary. [WEBIDL]
  1238. auto options = ScrollToOptions {};
  1239. // 2. Let x and y be the arguments, respectively.
  1240. // 3. Let the left dictionary member of options have the value x.
  1241. options.left = x;
  1242. // 4. Let the top dictionary member of options have the value y.
  1243. options.top = y;
  1244. scroll_by(options);
  1245. }
  1246. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screenx
  1247. i32 Window::screen_x() const
  1248. {
  1249. // The screenX and screenLeft attributes must return the x-coordinate, relative to the origin of the Web-exposed
  1250. // screen area, of the left of the client window as number of CSS pixels, or zero if there is no such thing.
  1251. return page().window_position().x().value();
  1252. }
  1253. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screeny
  1254. i32 Window::screen_y() const
  1255. {
  1256. // The screenY and screenTop attributes must return the y-coordinate, relative to the origin of the screen of the
  1257. // Web-exposed screen area, of the top of the client window as number of CSS pixels, or zero if there is no such thing.
  1258. return page().window_position().y().value();
  1259. }
  1260. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-outerwidth
  1261. i32 Window::outer_width() const
  1262. {
  1263. // The outerWidth attribute must return the width of the client window. If there is no client window this
  1264. // attribute must return zero.
  1265. return page().window_size().width().value();
  1266. }
  1267. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-outerheight
  1268. i32 Window::outer_height() const
  1269. {
  1270. // The outerHeight attribute must return the height of the client window. If there is no client window this
  1271. // attribute must return zero.
  1272. return page().window_size().height().value();
  1273. }
  1274. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-devicepixelratio
  1275. double Window::device_pixel_ratio() const
  1276. {
  1277. // 1. If there is no output device, return 1 and abort these steps.
  1278. // 2. Let CSS pixel size be the size of a CSS pixel at the current page zoom and using a scale factor of 1.0.
  1279. // 3. Let device pixel size be the vertical size of a device pixel of the output device.
  1280. // 4. Return the result of dividing CSS pixel size by device pixel size.
  1281. return page().client().device_pixels_per_css_pixel();
  1282. }
  1283. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-animationframeprovider-requestanimationframe
  1284. WebIDL::UnsignedLong Window::request_animation_frame(GC::Ref<WebIDL::CallbackType> callback)
  1285. {
  1286. // FIXME: Make this fully spec compliant. Currently implements a mix of 'requestAnimationFrame()' and 'run the animation frame callbacks'.
  1287. return animation_frame_callback_driver().add(GC::create_function(heap(), [this, callback](double now) {
  1288. // 3. Invoke callback, passing now as the only argument, and if an exception is thrown, report the exception.
  1289. auto result = WebIDL::invoke_callback(*callback, {}, JS::Value(now));
  1290. if (result.is_error())
  1291. report_exception(result, realm());
  1292. }));
  1293. }
  1294. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#animationframeprovider-cancelanimationframe
  1295. void Window::cancel_animation_frame(WebIDL::UnsignedLong handle)
  1296. {
  1297. // 1. If this is not supported, then throw a "NotSupportedError" DOMException.
  1298. // NOTE: Doesn't apply in this Window-specific implementation.
  1299. // 2. Let callbacks be this's target object's map of animation frame callbacks.
  1300. // 3. Remove callbacks[handle].
  1301. (void)animation_frame_callback_driver().remove(handle);
  1302. }
  1303. AnimationFrameCallbackDriver& Window::animation_frame_callback_driver()
  1304. {
  1305. if (!m_animation_frame_callback_driver)
  1306. m_animation_frame_callback_driver = realm().create<AnimationFrameCallbackDriver>();
  1307. return *m_animation_frame_callback_driver;
  1308. }
  1309. bool Window::has_animation_frame_callbacks()
  1310. {
  1311. if (!m_animation_frame_callback_driver)
  1312. return false;
  1313. return m_animation_frame_callback_driver->has_callbacks();
  1314. }
  1315. // https://w3c.github.io/requestidlecallback/#dom-window-requestidlecallback
  1316. u32 Window::request_idle_callback(WebIDL::CallbackType& callback, RequestIdleCallback::IdleRequestOptions const& options)
  1317. {
  1318. // 1. Let window be this Window object.
  1319. // 2. Increment the window's idle callback identifier by one.
  1320. m_idle_callback_identifier++;
  1321. // 3. Let handle be the current value of window's idle callback identifier.
  1322. auto handle = m_idle_callback_identifier;
  1323. // 4. Push callback to the end of window's list of idle request callbacks, associated with handle.
  1324. auto handler = [callback = GC::make_root(callback)](GC::Ref<RequestIdleCallback::IdleDeadline> deadline) -> JS::Completion {
  1325. return WebIDL::invoke_callback(*callback, {}, deadline.ptr());
  1326. };
  1327. m_idle_request_callbacks.append(adopt_ref(*new IdleCallback(move(handler), handle)));
  1328. // 5. Return handle and then continue running this algorithm asynchronously.
  1329. return handle;
  1330. // FIXME: 6. If the timeout property is present in options and has a positive value:
  1331. // FIXME: 1. Wait for timeout milliseconds.
  1332. // FIXME: 2. Wait until all invocations of this algorithm, whose timeout added to their posted time occurred before this one's, have completed.
  1333. // FIXME: 3. Optionally, wait a further user-agent defined length of time.
  1334. // FIXME: 4. Queue a task on the queue associated with the idle-task task source, which performs the invoke idle callback timeout algorithm, passing handle and window as arguments.
  1335. (void)options;
  1336. }
  1337. // https://w3c.github.io/requestidlecallback/#dom-window-cancelidlecallback
  1338. void Window::cancel_idle_callback(u32 handle)
  1339. {
  1340. // 1. Let window be this Window object.
  1341. // 2. Find the entry in either the window's list of idle request callbacks or list of runnable idle callbacks
  1342. // that is associated with the value handle.
  1343. // 3. If there is such an entry, remove it from both window's list of idle request callbacks and the list of runnable idle callbacks.
  1344. m_idle_request_callbacks.remove_first_matching([&](auto& callback) {
  1345. return callback->handle() == handle;
  1346. });
  1347. m_runnable_idle_callbacks.remove_first_matching([&](auto& callback) {
  1348. return callback->handle() == handle;
  1349. });
  1350. }
  1351. // https://w3c.github.io/selection-api/#dom-window-getselection
  1352. GC::Ptr<Selection::Selection> Window::get_selection() const
  1353. {
  1354. // The method must invoke and return the result of getSelection() on this's Window.document attribute.
  1355. return associated_document().get_selection();
  1356. }
  1357. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-window-captureevents
  1358. void Window::capture_events()
  1359. {
  1360. // Do nothing.
  1361. }
  1362. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-releaseevents
  1363. void Window::release_events()
  1364. {
  1365. // Do nothing.
  1366. }
  1367. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation
  1368. GC::Ref<Navigation> Window::navigation()
  1369. {
  1370. // Upon creation of the Window object, its navigation API must be set
  1371. // to a new Navigation object created in the Window object's relevant realm.
  1372. if (!m_navigation) {
  1373. auto& realm = relevant_realm(*this);
  1374. m_navigation = realm.create<Navigation>(realm);
  1375. }
  1376. // The navigation getter steps are to return this's navigation API.
  1377. return *m_navigation;
  1378. }
  1379. // https://html.spec.whatwg.org/multipage/custom-elements.html#dom-window-customelements
  1380. GC::Ref<CustomElementRegistry> Window::custom_elements()
  1381. {
  1382. auto& realm = this->realm();
  1383. // The customElements attribute of the Window interface must return the CustomElementRegistry object for that Window object.
  1384. if (!m_custom_element_registry)
  1385. m_custom_element_registry = realm.create<CustomElementRegistry>(realm);
  1386. return GC::Ref { *m_custom_element_registry };
  1387. }
  1388. // https://html.spec.whatwg.org/#document-tree-child-navigable-target-name-property-set
  1389. OrderedHashMap<FlyString, GC::Ref<Navigable>> Window::document_tree_child_navigable_target_name_property_set()
  1390. {
  1391. // The document-tree child navigable target name property set of a Window object window is the return value of running these steps:
  1392. // 1. Let children be the document-tree child navigables of window's associated Document.
  1393. auto children = associated_document().document_tree_child_navigables();
  1394. // 2. Let firstNamedChildren be an empty ordered set.
  1395. OrderedHashMap<FlyString, GC::Ref<Navigable>> first_named_children;
  1396. // 3. For each navigable of children:
  1397. for (auto const& navigable : children) {
  1398. // 1. Let name be navigable's target name.
  1399. auto const& name = navigable->target_name();
  1400. // 2. If name is the empty string, then continue.
  1401. if (name.is_empty())
  1402. continue;
  1403. // 3. If firstNamedChildren contains a navigable whose target name is name, then continue.
  1404. if (first_named_children.contains(name))
  1405. continue;
  1406. // 4. Append navigable to firstNamedChildren.
  1407. (void)first_named_children.set(name, *navigable);
  1408. }
  1409. // 4. Let names be an empty ordered set.
  1410. OrderedHashMap<FlyString, GC::Ref<Navigable>> names;
  1411. // 5. For each navigable of firstNamedChildren:
  1412. for (auto const& [name, navigable] : first_named_children) {
  1413. // 1. Let name be navigable's target name.
  1414. // 2. If navigable's active document's origin is same origin with window's relevant settings object's origin, then append name to names.
  1415. if (navigable->active_document()->origin().is_same_origin(relevant_settings_object(*this).origin()))
  1416. names.set(name, *navigable);
  1417. }
  1418. return names;
  1419. }
  1420. // https://html.spec.whatwg.org/#named-access-on-the-window-object
  1421. Vector<FlyString> Window::supported_property_names() const
  1422. {
  1423. // FIXME: Make the const-correctness of the methods this method calls less cowboy.
  1424. auto& mutable_this = const_cast<Window&>(*this);
  1425. // The Window object supports named properties.
  1426. // The supported property names of a Window object window at any moment consist of the following,
  1427. // in tree order according to the element that contributed them, ignoring later duplicates:
  1428. HashTable<FlyString> property_names;
  1429. // - window's document-tree child navigable target name property set;
  1430. auto child_navigable_property_set = mutable_this.document_tree_child_navigable_target_name_property_set();
  1431. for (auto& entry : child_navigable_property_set)
  1432. property_names.set(entry.key, AK::HashSetExistingEntryBehavior::Keep);
  1433. // - the value of the name content attribute for all embed, form, img, and object elements
  1434. // that have a non-empty name content attribute and are in a document tree with window's associated Document as their root; and
  1435. // - the value of the id content attribute for all HTML elements that have a non-empty id content attribute
  1436. // and are in a document tree with window's associated Document as their root.
  1437. associated_document().for_each_in_subtree_of_type<DOM::Element>([&property_names](auto& element) -> TraversalDecision {
  1438. if (is<HTMLEmbedElement>(element) || is<HTMLFormElement>(element) || is<HTMLImageElement>(element) || is<HTMLObjectElement>(element)) {
  1439. if (element.name().has_value())
  1440. property_names.set(element.name().value(), AK::HashSetExistingEntryBehavior::Keep);
  1441. }
  1442. if (auto const& name = element.id(); name.has_value())
  1443. property_names.set(name.value().to_string(), AK::HashSetExistingEntryBehavior::Keep);
  1444. return TraversalDecision::Continue;
  1445. });
  1446. return property_names.values();
  1447. }
  1448. // https://html.spec.whatwg.org/#named-access-on-the-window-object
  1449. JS::Value Window::named_item_value(FlyString const& name) const
  1450. {
  1451. // FIXME: Make the const-correctness of the methods this method calls less cowboy.
  1452. auto& mutable_this = const_cast<Window&>(*this);
  1453. // To determine the value of a named property name in a Window object window, the user agent must return the value obtained using the following steps:
  1454. // 1. Let objects be the list of named objects of window with the name name.
  1455. // NOTE: There will be at least one such object, since the algorithm would otherwise not have been invoked by Web IDL.
  1456. auto objects = mutable_this.named_objects(name);
  1457. // 2. If objects contains a navigable, then:
  1458. if (!objects.navigables.is_empty()) {
  1459. // 1. Let container be the first navigable container in window's associated Document's descendants whose content navigable is in objects.
  1460. GC::Ptr<NavigableContainer> container = nullptr;
  1461. mutable_this.associated_document().for_each_in_subtree_of_type<HTML::NavigableContainer>([&](HTML::NavigableContainer& navigable_container) {
  1462. if (!navigable_container.content_navigable())
  1463. return TraversalDecision::Continue;
  1464. if (objects.navigables.contains_slow(GC::Ref { *navigable_container.content_navigable() })) {
  1465. container = navigable_container;
  1466. return TraversalDecision::Break;
  1467. }
  1468. return TraversalDecision::Continue;
  1469. });
  1470. // 2. Return container's content navigable's active WindowProxy.
  1471. VERIFY(container);
  1472. return container->content_navigable()->active_window_proxy();
  1473. }
  1474. // 3. Otherwise, if objects has only one element, return that element.
  1475. if (objects.elements.size() == 1)
  1476. return objects.elements[0];
  1477. // 4. Otherwise return an HTMLCollection rooted at window's associated Document,
  1478. // whose filter matches only named objects of window with the name name. (By definition, these will all be elements.)
  1479. return DOM::HTMLCollection::create(mutable_this.associated_document(), DOM::HTMLCollection::Scope::Descendants, [name](auto& element) -> bool {
  1480. if ((is<HTMLEmbedElement>(element) || is<HTMLFormElement>(element) || is<HTMLImageElement>(element) || is<HTMLObjectElement>(element))
  1481. && (element.name() == name))
  1482. return true;
  1483. return element.id() == name;
  1484. });
  1485. }
  1486. // https://html.spec.whatwg.org/#dom-window-nameditem-filter
  1487. Window::NamedObjects Window::named_objects(StringView name)
  1488. {
  1489. // NOTE: Since the Window interface has the [Global] extended attribute, its named properties
  1490. // follow the rules for named properties objects rather than legacy platform objects.
  1491. // Named objects of Window object window with the name name, for the purposes of the above algorithm, consist of the following:
  1492. NamedObjects objects;
  1493. // document-tree child navigables of window's associated Document whose target name is name;
  1494. auto children = associated_document().document_tree_child_navigables();
  1495. for (auto& navigable : children) {
  1496. if (navigable->target_name() == name) {
  1497. objects.navigables.append(*navigable);
  1498. }
  1499. }
  1500. // embed, form, img, or object elements that have a name content attribute whose value is name
  1501. // and are in a document tree with window's associated Document as their root; and
  1502. // HTML elements that have an id content attribute whose value is name and are in a document tree with window's associated Document as their root.
  1503. associated_document().for_each_in_subtree_of_type<DOM::Element>([&objects, &name](auto& element) -> TraversalDecision {
  1504. if ((is<HTMLEmbedElement>(element) || is<HTMLFormElement>(element) || is<HTMLImageElement>(element) || is<HTMLObjectElement>(element))
  1505. && (element.name() == name))
  1506. objects.elements.append(element);
  1507. else if (element.id() == name)
  1508. objects.elements.append(element);
  1509. return TraversalDecision::Continue;
  1510. });
  1511. return objects;
  1512. }
  1513. bool Window::find(String const& string)
  1514. {
  1515. if (string.is_empty())
  1516. return false;
  1517. auto& page = this->page();
  1518. Optional<Page::FindInPageResult> result;
  1519. if (auto last_query = page.last_find_in_page_query(); last_query.has_value() && last_query->string == string) {
  1520. result = page.find_in_page_next_match();
  1521. } else {
  1522. Page::FindInPageQuery query {
  1523. string,
  1524. CaseSensitivity::CaseInsensitive,
  1525. Page::WrapAround::No,
  1526. };
  1527. result = page.find_in_page(query);
  1528. }
  1529. return result.has_value() && result->total_match_count.has_value() && *result->total_match_count > 0;
  1530. }
  1531. }