Window.cpp 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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_reload(Badge<Location>)
  354. {
  355. auto* browsing_context = associated_document().browsing_context();
  356. if (!browsing_context)
  357. return;
  358. browsing_context->loader().load(associated_document().url(), FrameLoader::Type::Reload);
  359. }
  360. void Window::did_call_location_replace(Badge<Location>, DeprecatedString url)
  361. {
  362. auto* browsing_context = associated_document().browsing_context();
  363. if (!browsing_context)
  364. return;
  365. auto new_url = associated_document().parse_url(url);
  366. browsing_context->loader().load(move(new_url), FrameLoader::Type::Navigation);
  367. }
  368. bool Window::dispatch_event(DOM::Event& event)
  369. {
  370. return DOM::EventDispatcher::dispatch(*this, event, true);
  371. }
  372. Page* Window::page()
  373. {
  374. return associated_document().page();
  375. }
  376. Page const* Window::page() const
  377. {
  378. return associated_document().page();
  379. }
  380. Optional<CSS::MediaFeatureValue> Window::query_media_feature(CSS::MediaFeatureID media_feature) const
  381. {
  382. // FIXME: Many of these should be dependent on the hardware
  383. // https://www.w3.org/TR/mediaqueries-5/#media-descriptor-table
  384. switch (media_feature) {
  385. case CSS::MediaFeatureID::AnyHover:
  386. return CSS::MediaFeatureValue(CSS::ValueID::Hover);
  387. case CSS::MediaFeatureID::AnyPointer:
  388. return CSS::MediaFeatureValue(CSS::ValueID::Fine);
  389. case CSS::MediaFeatureID::AspectRatio:
  390. return CSS::MediaFeatureValue(CSS::Ratio(inner_width(), inner_height()));
  391. case CSS::MediaFeatureID::Color:
  392. return CSS::MediaFeatureValue(8);
  393. case CSS::MediaFeatureID::ColorGamut:
  394. return CSS::MediaFeatureValue(CSS::ValueID::Srgb);
  395. case CSS::MediaFeatureID::ColorIndex:
  396. return CSS::MediaFeatureValue(0);
  397. // FIXME: device-aspect-ratio
  398. case CSS::MediaFeatureID::DeviceHeight:
  399. if (auto* page = this->page()) {
  400. return CSS::MediaFeatureValue(CSS::Length::make_px(page->web_exposed_screen_area().height()));
  401. }
  402. return CSS::MediaFeatureValue(0);
  403. case CSS::MediaFeatureID::DeviceWidth:
  404. if (auto* page = this->page()) {
  405. return CSS::MediaFeatureValue(CSS::Length::make_px(page->web_exposed_screen_area().width()));
  406. }
  407. return CSS::MediaFeatureValue(0);
  408. case CSS::MediaFeatureID::DisplayMode:
  409. // FIXME: Detect if window is fullscreen
  410. return CSS::MediaFeatureValue(CSS::ValueID::Browser);
  411. case CSS::MediaFeatureID::DynamicRange:
  412. return CSS::MediaFeatureValue(CSS::ValueID::Standard);
  413. case CSS::MediaFeatureID::EnvironmentBlending:
  414. return CSS::MediaFeatureValue(CSS::ValueID::Opaque);
  415. case CSS::MediaFeatureID::ForcedColors:
  416. return CSS::MediaFeatureValue(CSS::ValueID::None);
  417. case CSS::MediaFeatureID::Grid:
  418. return CSS::MediaFeatureValue(0);
  419. case CSS::MediaFeatureID::Height:
  420. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_height()));
  421. case CSS::MediaFeatureID::HorizontalViewportSegments:
  422. return CSS::MediaFeatureValue(1);
  423. case CSS::MediaFeatureID::Hover:
  424. return CSS::MediaFeatureValue(CSS::ValueID::Hover);
  425. case CSS::MediaFeatureID::InvertedColors:
  426. return CSS::MediaFeatureValue(CSS::ValueID::None);
  427. case CSS::MediaFeatureID::Monochrome:
  428. return CSS::MediaFeatureValue(0);
  429. case CSS::MediaFeatureID::NavControls:
  430. return CSS::MediaFeatureValue(CSS::ValueID::Back);
  431. case CSS::MediaFeatureID::Orientation:
  432. return CSS::MediaFeatureValue(inner_height() >= inner_width() ? CSS::ValueID::Portrait : CSS::ValueID::Landscape);
  433. case CSS::MediaFeatureID::OverflowBlock:
  434. return CSS::MediaFeatureValue(CSS::ValueID::Scroll);
  435. case CSS::MediaFeatureID::OverflowInline:
  436. return CSS::MediaFeatureValue(CSS::ValueID::Scroll);
  437. case CSS::MediaFeatureID::Pointer:
  438. return CSS::MediaFeatureValue(CSS::ValueID::Fine);
  439. case CSS::MediaFeatureID::PrefersColorScheme: {
  440. if (auto* page = this->page()) {
  441. switch (page->preferred_color_scheme()) {
  442. case CSS::PreferredColorScheme::Light:
  443. return CSS::MediaFeatureValue(CSS::ValueID::Light);
  444. case CSS::PreferredColorScheme::Dark:
  445. return CSS::MediaFeatureValue(CSS::ValueID::Dark);
  446. case CSS::PreferredColorScheme::Auto:
  447. default:
  448. return CSS::MediaFeatureValue(page->palette().is_dark() ? CSS::ValueID::Dark : CSS::ValueID::Light);
  449. }
  450. }
  451. return CSS::MediaFeatureValue(CSS::ValueID::Light);
  452. }
  453. case CSS::MediaFeatureID::PrefersContrast:
  454. // FIXME: Make this a preference
  455. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  456. case CSS::MediaFeatureID::PrefersReducedData:
  457. // FIXME: Make this a preference
  458. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  459. case CSS::MediaFeatureID::PrefersReducedMotion:
  460. // FIXME: Make this a preference
  461. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  462. case CSS::MediaFeatureID::PrefersReducedTransparency:
  463. // FIXME: Make this a preference
  464. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  465. case CSS::MediaFeatureID::Resolution:
  466. return CSS::MediaFeatureValue(CSS::Resolution(device_pixel_ratio(), CSS::Resolution::Type::Dppx));
  467. case CSS::MediaFeatureID::Scan:
  468. return CSS::MediaFeatureValue(CSS::ValueID::Progressive);
  469. case CSS::MediaFeatureID::Scripting:
  470. if (associated_document().is_scripting_enabled())
  471. return CSS::MediaFeatureValue(CSS::ValueID::Enabled);
  472. return CSS::MediaFeatureValue(CSS::ValueID::None);
  473. case CSS::MediaFeatureID::Update:
  474. return CSS::MediaFeatureValue(CSS::ValueID::Fast);
  475. case CSS::MediaFeatureID::VerticalViewportSegments:
  476. return CSS::MediaFeatureValue(1);
  477. case CSS::MediaFeatureID::VideoColorGamut:
  478. return CSS::MediaFeatureValue(CSS::ValueID::Srgb);
  479. case CSS::MediaFeatureID::VideoDynamicRange:
  480. return CSS::MediaFeatureValue(CSS::ValueID::Standard);
  481. case CSS::MediaFeatureID::Width:
  482. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_width()));
  483. default:
  484. break;
  485. }
  486. return {};
  487. }
  488. // https://html.spec.whatwg.org/#fire-a-page-transition-event
  489. void Window::fire_a_page_transition_event(FlyString const& event_name, bool persisted)
  490. {
  491. // To fire a page transition event named eventName at a Window window with a boolean persisted,
  492. // fire an event named eventName at window, using PageTransitionEvent,
  493. // with the persisted attribute initialized to persisted,
  494. PageTransitionEventInit event_init {};
  495. event_init.persisted = persisted;
  496. auto event = PageTransitionEvent::create(associated_document().realm(), event_name, event_init);
  497. // ...the cancelable attribute initialized to true,
  498. event->set_cancelable(true);
  499. // the bubbles attribute initialized to true,
  500. event->set_bubbles(true);
  501. // and legacy target override flag set.
  502. dispatch_event(event);
  503. }
  504. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-localstorage
  505. WebIDL::ExceptionOr<JS::NonnullGCPtr<Storage>> Window::local_storage()
  506. {
  507. // FIXME: Implement according to spec.
  508. static HashMap<Origin, JS::Handle<Storage>> local_storage_per_origin;
  509. auto storage = local_storage_per_origin.ensure(associated_document().origin(), [this]() -> JS::Handle<Storage> {
  510. return Storage::create(realm());
  511. });
  512. return JS::NonnullGCPtr { *storage };
  513. }
  514. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-sessionstorage
  515. WebIDL::ExceptionOr<JS::NonnullGCPtr<Storage>> Window::session_storage()
  516. {
  517. // FIXME: Implement according to spec.
  518. static HashMap<Origin, JS::Handle<Storage>> session_storage_per_origin;
  519. auto storage = session_storage_per_origin.ensure(associated_document().origin(), [this]() -> JS::Handle<Storage> {
  520. return Storage::create(realm());
  521. });
  522. return JS::NonnullGCPtr { *storage };
  523. }
  524. // https://html.spec.whatwg.org/multipage/interaction.html#transient-activation
  525. bool Window::has_transient_activation() const
  526. {
  527. // The transient activation duration is expected be at most a few seconds, so that the user can possibly
  528. // perceive the link between an interaction with the page and the page calling the activation-gated API.
  529. auto transient_activation_duration = 5;
  530. // When the current high resolution time given W
  531. auto unsafe_shared_time = HighResolutionTime::unsafe_shared_current_time();
  532. auto current_time = HighResolutionTime::relative_high_resolution_time(unsafe_shared_time, realm().global_object());
  533. // is greater than or equal to the last activation timestamp in W
  534. if (current_time >= m_last_activation_timestamp) {
  535. // and less than the last activation timestamp in W plus the transient activation duration
  536. if (current_time < m_last_activation_timestamp + transient_activation_duration) {
  537. // then W is said to have transient activation.
  538. return true;
  539. }
  540. }
  541. return false;
  542. }
  543. // https://w3c.github.io/requestidlecallback/#start-an-idle-period-algorithm
  544. void Window::start_an_idle_period()
  545. {
  546. // 1. Optionally, if the user agent determines the idle period should be delayed, return from this algorithm.
  547. // 2. Let pending_list be window's list of idle request callbacks.
  548. auto& pending_list = m_idle_request_callbacks;
  549. // 3. Let run_list be window's list of runnable idle callbacks.
  550. auto& run_list = m_runnable_idle_callbacks;
  551. run_list.extend(pending_list);
  552. // 4. Clear pending_list.
  553. pending_list.clear();
  554. // FIXME: This might not agree with the spec, but currently we use 100% CPU if we keep queueing tasks
  555. if (run_list.is_empty())
  556. return;
  557. // 5. Queue a task on the queue associated with the idle-task task source,
  558. // which performs the steps defined in the invoke idle callbacks algorithm with window and getDeadline as parameters.
  559. queue_global_task(Task::Source::IdleTask, *this, [this] {
  560. invoke_idle_callbacks();
  561. });
  562. }
  563. // https://w3c.github.io/requestidlecallback/#invoke-idle-callbacks-algorithm
  564. void Window::invoke_idle_callbacks()
  565. {
  566. auto& event_loop = main_thread_event_loop();
  567. // 1. If the user-agent believes it should end the idle period early due to newly scheduled high-priority work, return from the algorithm.
  568. // 2. Let now be the current time.
  569. auto now = HighResolutionTime::unsafe_shared_current_time();
  570. // 3. If now is less than the result of calling getDeadline and the window's list of runnable idle callbacks is not empty:
  571. if (now < event_loop.compute_deadline() && !m_runnable_idle_callbacks.is_empty()) {
  572. // 1. Pop the top callback from window's list of runnable idle callbacks.
  573. auto callback = m_runnable_idle_callbacks.take_first();
  574. // 2. Let deadlineArg be a new IdleDeadline whose [get deadline time algorithm] is getDeadline.
  575. auto deadline_arg = RequestIdleCallback::IdleDeadline::create(realm());
  576. // 3. Call callback with deadlineArg as its argument. If an uncaught runtime script error occurs, then report the exception.
  577. auto result = callback->invoke(deadline_arg);
  578. if (result.is_error())
  579. report_exception(result, realm());
  580. // 4. If window's list of runnable idle callbacks is not empty, queue a task which performs the steps
  581. // in the invoke idle callbacks algorithm with getDeadline and window as a parameters and return from this algorithm
  582. queue_global_task(Task::Source::IdleTask, *this, [this] {
  583. invoke_idle_callbacks();
  584. });
  585. }
  586. }
  587. void Window::set_associated_document(DOM::Document& document)
  588. {
  589. m_associated_document = &document;
  590. }
  591. void Window::set_current_event(DOM::Event* event)
  592. {
  593. m_current_event = event;
  594. }
  595. BrowsingContext const* Window::browsing_context() const
  596. {
  597. return m_associated_document->browsing_context();
  598. }
  599. BrowsingContext* Window::browsing_context()
  600. {
  601. return m_associated_document->browsing_context();
  602. }
  603. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#window-navigable
  604. JS::GCPtr<Navigable> Window::navigable() const
  605. {
  606. // 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.
  607. return Navigable::navigable_with_active_document(*m_associated_document);
  608. }
  609. // https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-plugin-objects
  610. Vector<JS::NonnullGCPtr<Plugin>> Window::pdf_viewer_plugin_objects()
  611. {
  612. // 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.
  613. // Otherwise, it is a list containing five Plugin objects, whose names are, respectively:
  614. // 0. "PDF Viewer"
  615. // 1. "Chrome PDF Viewer"
  616. // 2. "Chromium PDF Viewer"
  617. // 3. "Microsoft Edge PDF Viewer"
  618. // 4. "WebKit built-in PDF"
  619. // 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
  620. VERIFY(page());
  621. if (!page()->pdf_viewer_supported())
  622. return {};
  623. if (m_pdf_viewer_plugin_objects.is_empty()) {
  624. // FIXME: Propagate errors.
  625. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "PDF Viewer"_string));
  626. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "Chrome PDF Viewer"_string));
  627. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "Chromium PDF Viewer"_string));
  628. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "Microsoft Edge PDF Viewer"_string));
  629. m_pdf_viewer_plugin_objects.append(realm().heap().allocate<Plugin>(realm(), realm(), "WebKit built-in PDF"_string));
  630. }
  631. return m_pdf_viewer_plugin_objects;
  632. }
  633. // https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-mime-type-objects
  634. Vector<JS::NonnullGCPtr<MimeType>> Window::pdf_viewer_mime_type_objects()
  635. {
  636. // 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.
  637. // Otherwise, it is a list containing two MimeType objects, whose types are, respectively:
  638. // 0. "application/pdf"
  639. // 1. "text/pdf"
  640. // 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
  641. VERIFY(page());
  642. if (!page()->pdf_viewer_supported())
  643. return {};
  644. if (m_pdf_viewer_mime_type_objects.is_empty()) {
  645. m_pdf_viewer_mime_type_objects.append(realm().heap().allocate<MimeType>(realm(), realm(), "application/pdf"_string));
  646. m_pdf_viewer_mime_type_objects.append(realm().heap().allocate<MimeType>(realm(), realm(), "text/pdf"_string));
  647. }
  648. return m_pdf_viewer_mime_type_objects;
  649. }
  650. // https://streams.spec.whatwg.org/#count-queuing-strategy-size-function
  651. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::CallbackType>> Window::count_queuing_strategy_size_function()
  652. {
  653. auto& realm = this->realm();
  654. if (!m_count_queuing_strategy_size_function) {
  655. // 1. Let steps be the following steps:
  656. auto steps = [](auto const&) {
  657. // 1. Return 1.
  658. return 1.0;
  659. };
  660. // 2. Let F be ! CreateBuiltinFunction(steps, 0, "size", « », globalObject’s relevant Realm).
  661. auto function = JS::NativeFunction::create(realm, move(steps), 0, "size", &realm);
  662. // 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.
  663. m_count_queuing_strategy_size_function = heap().allocate<WebIDL::CallbackType>(realm, *function, relevant_settings_object(*this));
  664. }
  665. return JS::NonnullGCPtr { *m_count_queuing_strategy_size_function };
  666. }
  667. // https://streams.spec.whatwg.org/#byte-length-queuing-strategy-size-function
  668. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::CallbackType>> Window::byte_length_queuing_strategy_size_function()
  669. {
  670. auto& realm = this->realm();
  671. if (!m_byte_length_queuing_strategy_size_function) {
  672. // 1. Let steps be the following steps, given chunk:
  673. auto steps = [](JS::VM& vm) {
  674. auto chunk = vm.argument(0);
  675. // 1. Return ? GetV(chunk, "byteLength").
  676. return chunk.get(vm, vm.names.byteLength);
  677. };
  678. // 2. Let F be ! CreateBuiltinFunction(steps, 1, "size", « », globalObject’s relevant Realm).
  679. auto function = JS::NativeFunction::create(realm, move(steps), 1, "size", &realm);
  680. // 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.
  681. m_byte_length_queuing_strategy_size_function = heap().allocate<WebIDL::CallbackType>(realm, *function, relevant_settings_object(*this));
  682. }
  683. return JS::NonnullGCPtr { *m_byte_length_queuing_strategy_size_function };
  684. }
  685. static bool s_internals_object_exposed = false;
  686. void Window::set_internals_object_exposed(bool exposed)
  687. {
  688. s_internals_object_exposed = exposed;
  689. }
  690. WebIDL::ExceptionOr<void> Window::initialize_web_interfaces(Badge<WindowEnvironmentSettingsObject>)
  691. {
  692. auto& realm = this->realm();
  693. add_window_exposed_interfaces(*this);
  694. Object::set_prototype(&Bindings::ensure_web_prototype<Bindings::WindowPrototype>(realm, "Window"));
  695. Bindings::WindowGlobalMixin::initialize(realm, *this);
  696. WindowOrWorkerGlobalScopeMixin::initialize(realm);
  697. if (s_internals_object_exposed)
  698. define_direct_property("internals", heap().allocate<Internals::Internals>(realm, realm), JS::default_attributes);
  699. return {};
  700. }
  701. // https://webidl.spec.whatwg.org/#platform-object-setprototypeof
  702. JS::ThrowCompletionOr<bool> Window::internal_set_prototype_of(JS::Object* prototype)
  703. {
  704. // 1. Return ? SetImmutablePrototype(O, V).
  705. return set_immutable_prototype(prototype);
  706. }
  707. // https://html.spec.whatwg.org/multipage/window-object.html#dom-window
  708. JS::NonnullGCPtr<WindowProxy> Window::window() const
  709. {
  710. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  711. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  712. }
  713. // https://html.spec.whatwg.org/multipage/window-object.html#dom-self
  714. JS::NonnullGCPtr<WindowProxy> Window::self() const
  715. {
  716. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  717. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  718. }
  719. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-document-2
  720. JS::NonnullGCPtr<DOM::Document const> Window::document() const
  721. {
  722. // The document getter steps are to return this's associated Document.
  723. return associated_document();
  724. }
  725. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-name
  726. String Window::name() const
  727. {
  728. // 1. If this's navigable is null, then return the empty string.
  729. if (!browsing_context())
  730. return String {};
  731. // 2. Return this's navigable's target name.
  732. return browsing_context()->name();
  733. }
  734. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#apis-for-creating-and-navigating-browsing-contexts-by-name:dom-name
  735. void Window::set_name(String const& name)
  736. {
  737. // 1. If this's navigable is null, then return.
  738. if (!browsing_context())
  739. return;
  740. // 2. Set this's navigable's active session history entry's document state's navigable target name to the given value.
  741. browsing_context()->set_name(name);
  742. }
  743. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-location
  744. JS::NonnullGCPtr<Location> Window::location()
  745. {
  746. auto& realm = this->realm();
  747. // The Window object's location getter steps are to return this's Location object.
  748. if (!m_location)
  749. m_location = heap().allocate<Location>(realm, realm);
  750. return JS::NonnullGCPtr { *m_location };
  751. }
  752. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-history
  753. JS::NonnullGCPtr<History> Window::history() const
  754. {
  755. // The history getter steps are to return this's associated Document's history object.
  756. return associated_document().history();
  757. }
  758. // https://html.spec.whatwg.org/multipage/interaction.html#dom-window-focus
  759. void Window::focus()
  760. {
  761. // 1. Let current be this Window object's navigable.
  762. auto* current = browsing_context();
  763. // 2. If current is null, then return.
  764. if (!current)
  765. return;
  766. // 3. Run the focusing steps with current.
  767. // FIXME: We should pass in the browsing context itself instead of the active document, however the focusing steps don't currently accept browsing contexts.
  768. // Passing in a browsing context always makes it resolve to its active document for focus, so this is fine for now.
  769. run_focusing_steps(current->active_document());
  770. // FIXME: 4. If current is a top-level traversable, user agents are encouraged to trigger some sort of notification to
  771. // indicate to the user that the page is attempting to gain focus.
  772. }
  773. // https://html.spec.whatwg.org/multipage/window-object.html#dom-frames
  774. JS::NonnullGCPtr<WindowProxy> Window::frames() const
  775. {
  776. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  777. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  778. }
  779. // https://html.spec.whatwg.org/multipage/window-object.html#dom-length
  780. u32 Window::length() const
  781. {
  782. // The length getter steps are to return this's associated Document's document-tree child navigables's size.
  783. return static_cast<u32>(document_tree_child_browsing_context_count());
  784. }
  785. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-top
  786. JS::GCPtr<WindowProxy const> Window::top() const
  787. {
  788. // 1. If this's navigable is null, then return null.
  789. auto const* browsing_context = this->browsing_context();
  790. if (!browsing_context)
  791. return {};
  792. // 2. Return this's navigable's top-level traversable's active WindowProxy.
  793. return browsing_context->top_level_browsing_context().window_proxy();
  794. }
  795. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-parent
  796. JS::GCPtr<WindowProxy const> Window::parent() const
  797. {
  798. // 1. Let navigable be this's navigable.
  799. auto* navigable = browsing_context();
  800. // 2. If navigable is null, then return null.
  801. if (!navigable)
  802. return {};
  803. // 3. If navigable's parent is not null, then set navigable to navigable's parent.
  804. if (auto parent = navigable->parent())
  805. navigable = parent;
  806. // 4. Return navigable's active WindowProxy.
  807. return navigable->window_proxy();
  808. }
  809. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-frameelement
  810. JS::GCPtr<DOM::Element const> Window::frame_element() const
  811. {
  812. // 1. Let current be this's node navigable.
  813. auto* current = browsing_context();
  814. // 2. If current is null, then return null.
  815. if (!current)
  816. return {};
  817. // 3. Let container be current's container.
  818. auto* container = current->container();
  819. // 4. If container is null, then return null.
  820. if (!container)
  821. return {};
  822. // 5. If container's node document's origin is not same origin-domain with the current settings object's origin, then return null.
  823. if (!container->document().origin().is_same_origin_domain(current_settings_object().origin()))
  824. return {};
  825. // 6. Return container.
  826. return container;
  827. }
  828. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-open
  829. WebIDL::ExceptionOr<JS::GCPtr<WindowProxy>> Window::open(Optional<String> const& url, Optional<String> const& target, Optional<String> const& features)
  830. {
  831. // The open(url, target, features) method steps are to run the window open steps with url, target, and features.
  832. return open_impl(*url, *target, *features);
  833. }
  834. // https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator
  835. JS::NonnullGCPtr<Navigator> Window::navigator()
  836. {
  837. auto& realm = this->realm();
  838. // The navigator and clientInformation getter steps are to return this's associated Navigator.
  839. if (!m_navigator)
  840. m_navigator = heap().allocate<Navigator>(realm, realm);
  841. return JS::NonnullGCPtr { *m_navigator };
  842. }
  843. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-alert
  844. void Window::alert(String const& message)
  845. {
  846. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#simple-dialogs
  847. // Note: This method is defined using two overloads, instead of using an optional argument,
  848. // for historical reasons. The practical impact of this is that alert(undefined) is
  849. // treated as alert("undefined"), but alert() is treated as alert("").
  850. // FIXME: Make this fully spec compliant.
  851. if (auto* page = this->page())
  852. page->did_request_alert(message);
  853. }
  854. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-confirm
  855. bool Window::confirm(Optional<String> const& message)
  856. {
  857. // FIXME: Make this fully spec compliant.
  858. // NOTE: `message` has an IDL-provided default value and is never empty.
  859. if (auto* page = this->page())
  860. return page->did_request_confirm(*message);
  861. return false;
  862. }
  863. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-prompt
  864. Optional<String> Window::prompt(Optional<String> const& message, Optional<String> const& default_)
  865. {
  866. // FIXME: Make this fully spec compliant.
  867. if (auto* page = this->page())
  868. return page->did_request_prompt(*message, *default_);
  869. return {};
  870. }
  871. // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-window-postmessage
  872. void Window::post_message(JS::Value message, String const&)
  873. {
  874. // FIXME: This is an ad-hoc hack implementation instead, since we don't currently
  875. // have serialization and deserialization of messages.
  876. queue_global_task(Task::Source::PostedMessage, *this, [this, message] {
  877. MessageEventInit event_init {};
  878. event_init.data = message;
  879. event_init.origin = "<origin>"_string;
  880. dispatch_event(MessageEvent::create(realm(), EventNames::message, event_init));
  881. });
  882. }
  883. // https://dom.spec.whatwg.org/#dom-window-event
  884. Variant<JS::Handle<DOM::Event>, JS::Value> Window::event() const
  885. {
  886. // The event getter steps are to return this’s current event.
  887. if (auto* current_event = this->current_event())
  888. return make_handle(const_cast<DOM::Event&>(*current_event));
  889. return JS::js_undefined();
  890. }
  891. // https://w3c.github.io/csswg-drafts/cssom/#dom-window-getcomputedstyle
  892. JS::NonnullGCPtr<CSS::CSSStyleDeclaration> Window::get_computed_style(DOM::Element& element, Optional<String> const& pseudo_element) const
  893. {
  894. // FIXME: Make this fully spec compliant.
  895. (void)pseudo_element;
  896. return heap().allocate<CSS::ResolvedCSSStyleDeclaration>(realm(), element);
  897. }
  898. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-matchmedia
  899. WebIDL::ExceptionOr<JS::NonnullGCPtr<CSS::MediaQueryList>> Window::match_media(String const& query)
  900. {
  901. // 1. Let parsed media query list be the result of parsing query.
  902. auto parsed_media_query_list = parse_media_query_list(CSS::Parser::ParsingContext(associated_document()), query);
  903. // 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.
  904. auto media_query_list = heap().allocate<CSS::MediaQueryList>(realm(), associated_document(), move(parsed_media_query_list));
  905. associated_document().add_media_query_list(media_query_list);
  906. return media_query_list;
  907. }
  908. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screen
  909. JS::NonnullGCPtr<CSS::Screen> Window::screen()
  910. {
  911. // The screen attribute must return the Screen object associated with the Window object.
  912. if (!m_screen)
  913. m_screen = heap().allocate<CSS::Screen>(realm(), *this);
  914. return JS::NonnullGCPtr { *m_screen };
  915. }
  916. JS::GCPtr<CSS::VisualViewport> Window::visual_viewport()
  917. {
  918. // If the associated document is fully active, the visualViewport attribute must return
  919. // the VisualViewport object associated with the Window object’s associated document.
  920. if (associated_document().is_fully_active())
  921. return associated_document().visual_viewport();
  922. // Otherwise, it must return null.
  923. return nullptr;
  924. }
  925. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-innerwidth
  926. i32 Window::inner_width() const
  927. {
  928. // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar (if any),
  929. // or zero if there is no viewport.
  930. if (auto const navigable = associated_document().navigable())
  931. return navigable->viewport_rect().width().to_int();
  932. return 0;
  933. }
  934. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-innerheight
  935. i32 Window::inner_height() const
  936. {
  937. // The innerHeight attribute must return the viewport height including the size of a rendered scroll bar (if any),
  938. // or zero if there is no viewport.
  939. if (auto const navigable = associated_document().navigable())
  940. return navigable->viewport_rect().height().to_int();
  941. return 0;
  942. }
  943. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrollx
  944. double Window::scroll_x() const
  945. {
  946. // The scrollX attribute must return the x-coordinate, relative to the initial containing block origin,
  947. // of the left of the viewport, or zero if there is no viewport.
  948. if (auto* page = this->page())
  949. return page->top_level_traversable()->viewport_scroll_offset().x().to_double();
  950. return 0;
  951. }
  952. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrolly
  953. double Window::scroll_y() const
  954. {
  955. // The scrollY attribute must return the y-coordinate, relative to the initial containing block origin,
  956. // of the top of the viewport, or zero if there is no viewport.
  957. if (auto* page = this->page())
  958. return page->top_level_traversable()->viewport_scroll_offset().y().to_double();
  959. return 0;
  960. }
  961. // https://w3c.github.io/csswg-drafts/cssom-view/#perform-a-scroll
  962. static void perform_a_scroll(Page& page, double x, double y, JS::GCPtr<DOM::Node const> element, Bindings::ScrollBehavior behavior)
  963. {
  964. // FIXME: 1. Abort any ongoing smooth scroll for box.
  965. // 2. If the user agent honors the scroll-behavior property and one of the following are true:
  966. // - behavior is "auto" and element is not null and its computed value of the scroll-behavior property is smooth
  967. // - behavior is smooth
  968. // ...then perform a smooth scroll of box to position. Once the position has finished updating, emit the scrollend
  969. // event. Otherwise, perform an instant scroll of box to position. After an instant scroll emit the scrollend event.
  970. // FIXME: Support smooth scrolling.
  971. (void)element;
  972. (void)behavior;
  973. page.client().page_did_request_scroll_to({ x, y });
  974. }
  975. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scroll
  976. void Window::scroll(ScrollToOptions const& options)
  977. {
  978. // 4. If there is no viewport, abort these steps.
  979. auto* page = this->page();
  980. if (!page)
  981. return;
  982. auto top_level_traversable = page->top_level_traversable();
  983. // 1. If invoked with one argument, follow these substeps:
  984. // 1. Let options be the argument.
  985. auto viewport_rect = top_level_traversable->viewport_rect().to_type<float>();
  986. // 2. Let x be the value of the left dictionary member of options, if present, or the viewport’s current scroll
  987. // position on the x axis otherwise.
  988. auto x = options.left.value_or(viewport_rect.x());
  989. // 3. Let y be the value of the top dictionary member of options, if present, or the viewport’s current scroll
  990. // position on the y axis otherwise.
  991. auto y = options.top.value_or(viewport_rect.y());
  992. // 3. Normalize non-finite values for x and y.
  993. x = JS::Value(x).is_finite_number() ? x : 0;
  994. y = JS::Value(y).is_finite_number() ? y : 0;
  995. // 5. Let viewport width be the width of the viewport excluding the width of the scroll bar, if any.
  996. auto viewport_width = viewport_rect.width();
  997. // 6. Let viewport height be the height of the viewport excluding the height of the scroll bar, if any.
  998. auto viewport_height = viewport_rect.height();
  999. (void)viewport_width;
  1000. (void)viewport_height;
  1001. // FIXME: 7.
  1002. // -> If the viewport has rightward overflow direction
  1003. // Let x be max(0, min(x, viewport scrolling area width - viewport width)).
  1004. // -> If the viewport has leftward overflow direction
  1005. // Let x be min(0, max(x, viewport width - viewport scrolling area width)).
  1006. // FIXME: 8.
  1007. // -> If the viewport has downward overflow direction
  1008. // Let y be max(0, min(y, viewport scrolling area height - viewport height)).
  1009. // -> If the viewport has upward overflow direction
  1010. // Let y be min(0, max(y, viewport height - viewport scrolling area height)).
  1011. // FIXME: 9. Let position be the scroll position the viewport would have by aligning the x-coordinate x of the viewport
  1012. // scrolling area with the left of the viewport and aligning the y-coordinate y of the viewport scrolling area
  1013. // with the top of the viewport.
  1014. // FIXME: 10. If position is the same as the viewport’s current scroll position, and the viewport does not have an ongoing
  1015. // smooth scroll, abort these steps.
  1016. // 11. Let document be the viewport’s associated Document.
  1017. auto const document = top_level_traversable->active_document();
  1018. // 12. Perform a scroll of the viewport to position, document’s root element as the associated element, if there is
  1019. // one, or null otherwise, and the scroll behavior being the value of the behavior dictionary member of options.
  1020. auto element = JS::GCPtr<DOM::Node const> { document ? &document->root() : nullptr };
  1021. perform_a_scroll(*page, x, y, element, options.behavior);
  1022. }
  1023. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scroll
  1024. void Window::scroll(double x, double y)
  1025. {
  1026. // 2. If invoked with two arguments, follow these substeps:
  1027. // 1. Let options be null converted to a ScrollToOptions dictionary. [WEBIDL]
  1028. auto options = ScrollToOptions {};
  1029. // 2. Let x and y be the arguments, respectively.
  1030. options.left = x;
  1031. options.top = y;
  1032. scroll(options);
  1033. }
  1034. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrollby
  1035. void Window::scroll_by(ScrollToOptions options)
  1036. {
  1037. // 2. Normalize non-finite values for the left and top dictionary members of options.
  1038. auto x = options.left.value_or(0);
  1039. auto y = options.top.value_or(0);
  1040. x = JS::Value(x).is_finite_number() ? x : 0;
  1041. y = JS::Value(y).is_finite_number() ? y : 0;
  1042. // 3. Add the value of scrollX to the left dictionary member.
  1043. options.left = x + scroll_x();
  1044. // 4. Add the value of scrollY to the top dictionary member.
  1045. options.top = y + scroll_y();
  1046. // 5. Act as if the scroll() method was invoked with options as the only argument.
  1047. scroll(options);
  1048. }
  1049. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrollby
  1050. void Window::scroll_by(double x, double y)
  1051. {
  1052. // 1. If invoked with two arguments, follow these substeps:
  1053. // 1. Let options be null converted to a ScrollToOptions dictionary. [WEBIDL]
  1054. auto options = ScrollToOptions {};
  1055. // 2. Let x and y be the arguments, respectively.
  1056. // 3. Let the left dictionary member of options have the value x.
  1057. options.left = x;
  1058. // 4. Let the top dictionary member of options have the value y.
  1059. options.top = y;
  1060. scroll_by(options);
  1061. }
  1062. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screenx
  1063. i32 Window::screen_x() const
  1064. {
  1065. // The screenX and screenLeft attributes must return the x-coordinate, relative to the origin of the Web-exposed
  1066. // screen area, of the left of the client window as number of CSS pixels, or zero if there is no such thing.
  1067. if (auto* page = this->page())
  1068. return page->window_position().x().value();
  1069. return 0;
  1070. }
  1071. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screeny
  1072. i32 Window::screen_y() const
  1073. {
  1074. // The screenY and screenTop attributes must return the y-coordinate, relative to the origin of the screen of the
  1075. // Web-exposed screen area, of the top of the client window as number of CSS pixels, or zero if there is no such thing.
  1076. if (auto* page = this->page())
  1077. return page->window_position().y().value();
  1078. return 0;
  1079. }
  1080. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-outerwidth
  1081. i32 Window::outer_width() const
  1082. {
  1083. // The outerWidth attribute must return the width of the client window. If there is no client window this
  1084. // attribute must return zero.
  1085. if (auto* page = this->page())
  1086. return page->window_size().width().value();
  1087. return 0;
  1088. }
  1089. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-outerheight
  1090. i32 Window::outer_height() const
  1091. {
  1092. // The outerHeight attribute must return the height of the client window. If there is no client window this
  1093. // attribute must return zero.
  1094. if (auto* page = this->page())
  1095. return page->window_size().height().value();
  1096. return 0;
  1097. }
  1098. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-devicepixelratio
  1099. double Window::device_pixel_ratio() const
  1100. {
  1101. // 1. If there is no output device, return 1 and abort these steps.
  1102. // 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.
  1103. // 3. Let device pixel size be the vertical size of a device pixel of the output device.
  1104. // 4. Return the result of dividing CSS pixel size by device pixel size.
  1105. if (auto* page = this->page())
  1106. return page->client().device_pixels_per_css_pixel();
  1107. return 1;
  1108. }
  1109. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-animationframeprovider-requestanimationframe
  1110. i32 Window::request_animation_frame(WebIDL::CallbackType& callback)
  1111. {
  1112. // FIXME: Make this fully spec compliant. Currently implements a mix of 'requestAnimationFrame()' and 'run the animation frame callbacks'.
  1113. auto now = HighResolutionTime::unsafe_shared_current_time();
  1114. return m_animation_frame_callback_driver.add([this, now, callback = JS::make_handle(callback)](auto) {
  1115. // 3. Invoke callback, passing now as the only argument, and if an exception is thrown, report the exception.
  1116. auto result = WebIDL::invoke_callback(*callback, {}, JS::Value(now));
  1117. if (result.is_error())
  1118. report_exception(result, realm());
  1119. });
  1120. }
  1121. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#animationframeprovider-cancelanimationframe
  1122. void Window::cancel_animation_frame(i32 handle)
  1123. {
  1124. // 1. If this is not supported, then throw a "NotSupportedError" DOMException.
  1125. // NOTE: Doesn't apply in this Window-specific implementation.
  1126. // 2. Let callbacks be this's target object's map of animation frame callbacks.
  1127. // 3. Remove callbacks[handle].
  1128. m_animation_frame_callback_driver.remove(handle);
  1129. }
  1130. // https://w3c.github.io/requestidlecallback/#dom-window-requestidlecallback
  1131. u32 Window::request_idle_callback(WebIDL::CallbackType& callback, RequestIdleCallback::IdleRequestOptions const& options)
  1132. {
  1133. // 1. Let window be this Window object.
  1134. // 2. Increment the window's idle callback identifier by one.
  1135. m_idle_callback_identifier++;
  1136. // 3. Let handle be the current value of window's idle callback identifier.
  1137. auto handle = m_idle_callback_identifier;
  1138. // 4. Push callback to the end of window's list of idle request callbacks, associated with handle.
  1139. auto handler = [callback = JS::make_handle(callback)](JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline> deadline) -> JS::Completion {
  1140. return WebIDL::invoke_callback(*callback, {}, deadline.ptr());
  1141. };
  1142. m_idle_request_callbacks.append(adopt_ref(*new IdleCallback(move(handler), handle)));
  1143. // 5. Return handle and then continue running this algorithm asynchronously.
  1144. return handle;
  1145. // FIXME: 6. If the timeout property is present in options and has a positive value:
  1146. // FIXME: 1. Wait for timeout milliseconds.
  1147. // FIXME: 2. Wait until all invocations of this algorithm, whose timeout added to their posted time occurred before this one's, have completed.
  1148. // FIXME: 3. Optionally, wait a further user-agent defined length of time.
  1149. // 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.
  1150. (void)options;
  1151. }
  1152. // https://w3c.github.io/requestidlecallback/#dom-window-cancelidlecallback
  1153. void Window::cancel_idle_callback(u32 handle)
  1154. {
  1155. // 1. Let window be this Window object.
  1156. // 2. Find the entry in either the window's list of idle request callbacks or list of runnable idle callbacks
  1157. // that is associated with the value handle.
  1158. // 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.
  1159. m_idle_request_callbacks.remove_first_matching([&](auto& callback) {
  1160. return callback->handle() == handle;
  1161. });
  1162. m_runnable_idle_callbacks.remove_first_matching([&](auto& callback) {
  1163. return callback->handle() == handle;
  1164. });
  1165. }
  1166. // https://w3c.github.io/selection-api/#dom-window-getselection
  1167. JS::GCPtr<Selection::Selection> Window::get_selection() const
  1168. {
  1169. // The method must invoke and return the result of getSelection() on this's Window.document attribute.
  1170. return associated_document().get_selection();
  1171. }
  1172. // https://w3c.github.io/hr-time/#dom-windoworworkerglobalscope-performance
  1173. JS::NonnullGCPtr<HighResolutionTime::Performance> Window::performance()
  1174. {
  1175. if (!m_performance)
  1176. m_performance = heap().allocate<HighResolutionTime::Performance>(realm(), *this);
  1177. return JS::NonnullGCPtr { *m_performance };
  1178. }
  1179. // https://w3c.github.io/webcrypto/#dom-windoworworkerglobalscope-crypto
  1180. JS::NonnullGCPtr<Crypto::Crypto> Window::crypto()
  1181. {
  1182. auto& realm = this->realm();
  1183. if (!m_crypto)
  1184. m_crypto = heap().allocate<Crypto::Crypto>(realm, realm);
  1185. return JS::NonnullGCPtr { *m_crypto };
  1186. }
  1187. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-navigation
  1188. JS::NonnullGCPtr<Navigation> Window::navigation()
  1189. {
  1190. // Upon creation of the Window object, its navigation API must be set
  1191. // to a new Navigation object created in the Window object's relevant realm.
  1192. if (!m_navigation) {
  1193. auto& realm = relevant_realm(*this);
  1194. m_navigation = heap().allocate<Navigation>(realm, realm);
  1195. }
  1196. // The navigation getter steps are to return this's navigation API.
  1197. return *m_navigation;
  1198. }
  1199. // https://html.spec.whatwg.org/multipage/custom-elements.html#dom-window-customelements
  1200. JS::NonnullGCPtr<CustomElementRegistry> Window::custom_elements()
  1201. {
  1202. auto& realm = this->realm();
  1203. // The customElements attribute of the Window interface must return the CustomElementRegistry object for that Window object.
  1204. if (!m_custom_element_registry)
  1205. m_custom_element_registry = heap().allocate<CustomElementRegistry>(realm, realm);
  1206. return JS::NonnullGCPtr { *m_custom_element_registry };
  1207. }
  1208. // https://html.spec.whatwg.org/multipage/window-object.html#number-of-document-tree-child-browsing-contexts
  1209. size_t Window::document_tree_child_browsing_context_count() const
  1210. {
  1211. // 1. If W's browsing context is null, then return 0.
  1212. auto* this_browsing_context = associated_document().browsing_context();
  1213. if (!this_browsing_context)
  1214. return 0;
  1215. // 2. Return the number of document-tree child browsing contexts of W's browsing context.
  1216. return this_browsing_context->document_tree_child_browsing_context_count();
  1217. }
  1218. }