Window.cpp 62 KB

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