Window.cpp 59 KB

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