Window.cpp 59 KB

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