Window.cpp 79 KB

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