Window.cpp 74 KB

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