Window.cpp 62 KB

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