Window.cpp 80 KB

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