Window.cpp 58 KB

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