Window.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  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/CSSNamespace.h>
  22. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  23. #include <LibWeb/Bindings/WindowExposedInterfaces.h>
  24. #include <LibWeb/Bindings/WindowPrototype.h>
  25. #include <LibWeb/CSS/MediaQueryList.h>
  26. #include <LibWeb/CSS/Parser/Parser.h>
  27. #include <LibWeb/CSS/ResolvedCSSStyleDeclaration.h>
  28. #include <LibWeb/CSS/Screen.h>
  29. #include <LibWeb/Crypto/Crypto.h>
  30. #include <LibWeb/DOM/Document.h>
  31. #include <LibWeb/DOM/Event.h>
  32. #include <LibWeb/DOM/EventDispatcher.h>
  33. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  34. #include <LibWeb/HTML/BrowsingContext.h>
  35. #include <LibWeb/HTML/EventHandler.h>
  36. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  37. #include <LibWeb/HTML/Focus.h>
  38. #include <LibWeb/HTML/Location.h>
  39. #include <LibWeb/HTML/MessageEvent.h>
  40. #include <LibWeb/HTML/Navigator.h>
  41. #include <LibWeb/HTML/Origin.h>
  42. #include <LibWeb/HTML/PageTransitionEvent.h>
  43. #include <LibWeb/HTML/Scripting/Environments.h>
  44. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  45. #include <LibWeb/HTML/Storage.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/WebAssembly/WebAssemblyObject.h>
  57. #include <LibWeb/WebIDL/AbstractOperations.h>
  58. namespace Web::HTML {
  59. // https://html.spec.whatwg.org/#run-the-animation-frame-callbacks
  60. void run_animation_frame_callbacks(DOM::Document& document, double)
  61. {
  62. // FIXME: Bring this closer to the spec.
  63. document.window().animation_frame_callback_driver().run();
  64. }
  65. class IdleCallback : public RefCounted<IdleCallback> {
  66. public:
  67. explicit IdleCallback(Function<JS::Completion(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline>)> handler, u32 handle)
  68. : m_handler(move(handler))
  69. , m_handle(handle)
  70. {
  71. }
  72. ~IdleCallback() = default;
  73. JS::Completion invoke(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline> deadline) { return m_handler(deadline); }
  74. u32 handle() const { return m_handle; }
  75. private:
  76. Function<JS::Completion(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline>)> m_handler;
  77. u32 m_handle { 0 };
  78. };
  79. WebIDL::ExceptionOr<JS::NonnullGCPtr<Window>> Window::create(JS::Realm& realm)
  80. {
  81. return MUST_OR_THROW_OOM(realm.heap().allocate<Window>(realm, realm));
  82. }
  83. Window::Window(JS::Realm& realm)
  84. : DOM::EventTarget(realm)
  85. {
  86. }
  87. void Window::visit_edges(JS::Cell::Visitor& visitor)
  88. {
  89. Base::visit_edges(visitor);
  90. WindowOrWorkerGlobalScopeMixin::visit_edges(visitor);
  91. visitor.visit(m_associated_document.ptr());
  92. visitor.visit(m_current_event.ptr());
  93. visitor.visit(m_performance.ptr());
  94. visitor.visit(m_screen.ptr());
  95. visitor.visit(m_location);
  96. visitor.visit(m_crypto);
  97. visitor.visit(m_navigator);
  98. for (auto& plugin_object : m_pdf_viewer_plugin_objects)
  99. visitor.visit(plugin_object);
  100. for (auto& mime_type_object : m_pdf_viewer_mime_type_objects)
  101. visitor.visit(mime_type_object);
  102. }
  103. Window::~Window() = default;
  104. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#normalizing-the-feature-name
  105. static StringView normalize_feature_name(StringView name)
  106. {
  107. // For legacy reasons, there are some aliases of some feature names. To normalize a feature name name, switch on name:
  108. // "screenx"
  109. if (name == "screenx"sv) {
  110. // Return "left".
  111. return "left"sv;
  112. }
  113. // "screeny"
  114. else if (name == "screeny"sv) {
  115. // Return "top".
  116. return "top"sv;
  117. }
  118. // "innerwidth"
  119. else if (name == "innerwidth"sv) {
  120. // Return "width".
  121. return "width"sv;
  122. }
  123. // "innerheight"
  124. else if (name == "innerheight") {
  125. // Return "height".
  126. return "height"sv;
  127. }
  128. // Anything else
  129. else {
  130. // Return name.
  131. return name;
  132. }
  133. }
  134. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#concept-window-open-features-tokenize
  135. static OrderedHashMap<DeprecatedString, DeprecatedString> tokenize_open_features(StringView features)
  136. {
  137. // 1. Let tokenizedFeatures be a new ordered map.
  138. OrderedHashMap<DeprecatedString, DeprecatedString> tokenized_features;
  139. // 2. Let position point at the first code point of features.
  140. GenericLexer lexer(features);
  141. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#feature-separator
  142. auto is_feature_separator = [](auto character) {
  143. return Infra::is_ascii_whitespace(character) || character == '=' || character == ',';
  144. };
  145. // 3. While position is not past the end of features:
  146. while (!lexer.is_eof()) {
  147. // 1. Let name be the empty string.
  148. DeprecatedString name;
  149. // 2. Let value be the empty string.
  150. DeprecatedString value;
  151. // 3. Collect a sequence of code points that are feature separators from features given position. This skips past leading separators before the name.
  152. lexer.ignore_while(is_feature_separator);
  153. // 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.
  154. name = lexer.consume_until(is_feature_separator).to_lowercase_string();
  155. // 5. Set name to the result of normalizing the feature name name.
  156. name = normalize_feature_name(name);
  157. // 6. While position is not past the end of features and the code point at position in features is not U+003D (=):
  158. // 1. If the code point at position in features is U+002C (,), or if it is not a feature separator, then break.
  159. // 2. Advance position by 1.
  160. lexer.ignore_while(Infra::is_ascii_whitespace);
  161. // 7. If the code point at position in features is a feature separator:
  162. // 1. While position is not past the end of features and the code point at position in features is a feature separator:
  163. // 1. If the code point at position in features is U+002C (,), then break.
  164. // 2. Advance position by 1.
  165. lexer.ignore_while([](auto character) { return Infra::is_ascii_whitespace(character) || character == '='; });
  166. // 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.
  167. value = lexer.consume_until(is_feature_separator).to_lowercase_string();
  168. // 8. If name is not the empty string, then set tokenizedFeatures[name] to value.
  169. if (!name.is_empty())
  170. tokenized_features.set(move(name), move(value));
  171. }
  172. // 4. Return tokenizedFeatures.
  173. return tokenized_features;
  174. }
  175. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#concept-window-open-features-parse-boolean
  176. static bool parse_boolean_feature(StringView value)
  177. {
  178. // 1. If value is the empty string, then return true.
  179. if (value.is_empty())
  180. return true;
  181. // 2. If value is "yes", then return true.
  182. if (value == "yes"sv)
  183. return true;
  184. // 3. If value is "true", then return true.
  185. if (value == "true"sv)
  186. return true;
  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;
  194. }
  195. // https://html.spec.whatwg.org/multipage/window-object.html#popup-window-is-requested
  196. static bool 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 false;
  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(*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 = [&](StringView feature_name, bool 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(*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, false);
  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, false);
  216. // 5. If location and toolbar are both false, then return true.
  217. if (!location && !toolbar)
  218. return true;
  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, false);
  221. // 7. If menubar is false, then return true.
  222. if (!menubar)
  223. return true;
  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, true);
  226. // 9. If resizable is false, then return true.
  227. if (!resizable)
  228. return true;
  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, false);
  231. // 11. If scrollbars is false, then return true.
  232. if (!scrollbars)
  233. return true;
  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, false);
  236. // 13. If status is false, then return true.
  237. if (!status)
  238. return true;
  239. // 14. Return false.
  240. return false;
  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 = false;
  259. auto no_referrer = false;
  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(*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(*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)
  276. no_opener = true;
  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)
  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)
  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)
  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 || 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. // FIXME: These should be native accessors, not properties
  637. u8 attr = JS::Attribute::Writable | JS::Attribute::Enumerable | JS::Attribute::Configurable;
  638. define_native_function(realm, "setInterval", set_interval, 1, attr);
  639. define_native_function(realm, "setTimeout", set_timeout, 1, attr);
  640. define_native_function(realm, "clearInterval", clear_interval, 1, attr);
  641. define_native_function(realm, "clearTimeout", clear_timeout, 1, attr);
  642. // https://webidl.spec.whatwg.org/#define-the-global-property-references
  643. // 5. For every namespace namespace that is exposed in realm:
  644. // 1. Let id be namespace’s identifier.
  645. // 3. Let namespaceObject be the result of creating a namespace object for namespace in realm.
  646. // 3. Perform CreateMethodProperty(target, id, namespaceObject).
  647. create_method_property("CSS", MUST_OR_THROW_OOM(heap().allocate<Bindings::CSSNamespace>(realm, realm)));
  648. create_method_property("WebAssembly", MUST_OR_THROW_OOM(heap().allocate<Bindings::WebAssemblyObject>(realm, realm)));
  649. // FIXME: Implement codegen for readonly properties with [PutForwards]
  650. auto& location_accessor = storage_get("location")->value.as_accessor();
  651. location_accessor.set_setter(JS::NativeFunction::create(realm, location_setter, 1, "location", &realm, {}, "set"sv));
  652. return {};
  653. }
  654. // https://webidl.spec.whatwg.org/#platform-object-setprototypeof
  655. JS::ThrowCompletionOr<bool> Window::internal_set_prototype_of(JS::Object* prototype)
  656. {
  657. // 1. Return ? SetImmutablePrototype(O, V).
  658. return set_immutable_prototype(prototype);
  659. }
  660. static JS::ThrowCompletionOr<Window*> impl_from(JS::VM& vm)
  661. {
  662. // Since this is a non built-in function we must treat it as non-strict mode
  663. // this means that a nullish this_value should be converted to the
  664. // global_object. Generally this does not matter as we try to convert the
  665. // this_value to a specific object type in the bindings. But since window is
  666. // the global object we make an exception here.
  667. // This allows calls like `setTimeout(f, 10)` to work.
  668. auto this_value = vm.this_value();
  669. if (this_value.is_nullish())
  670. this_value = &vm.current_realm()->global_object();
  671. auto* this_object = MUST(this_value.to_object(vm));
  672. if (is<WindowProxy>(*this_object))
  673. return static_cast<WindowProxy*>(this_object)->window().ptr();
  674. if (is<Window>(*this_object))
  675. return static_cast<Window*>(this_object);
  676. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Window");
  677. }
  678. // https://html.spec.whatwg.org/multipage/window-object.html#dom-window
  679. JS::NonnullGCPtr<WindowProxy> Window::window() const
  680. {
  681. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  682. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  683. }
  684. // https://html.spec.whatwg.org/multipage/window-object.html#dom-self
  685. JS::NonnullGCPtr<WindowProxy> Window::self() const
  686. {
  687. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  688. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  689. }
  690. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-document-2
  691. JS::NonnullGCPtr<DOM::Document const> Window::document() const
  692. {
  693. // The document getter steps are to return this's associated Document.
  694. return associated_document();
  695. }
  696. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-name
  697. String Window::name() const
  698. {
  699. // 1. If this's navigable is null, then return the empty string.
  700. if (!browsing_context())
  701. return String {};
  702. // 2. Return this's navigable's target name.
  703. return String::from_deprecated_string(browsing_context()->name()).release_value_but_fixme_should_propagate_errors();
  704. }
  705. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#apis-for-creating-and-navigating-browsing-contexts-by-name:dom-name
  706. void Window::set_name(String const& name)
  707. {
  708. // 1. If this's navigable is null, then return.
  709. if (!browsing_context())
  710. return;
  711. // 2. Set this's navigable's active session history entry's document state's navigable target name to the given value.
  712. browsing_context()->set_name(name.to_deprecated_string());
  713. }
  714. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-location
  715. WebIDL::ExceptionOr<JS::NonnullGCPtr<Location>> Window::location()
  716. {
  717. auto& realm = this->realm();
  718. // The Window object's location getter steps are to return this's Location object.
  719. if (!m_location)
  720. m_location = MUST_OR_THROW_OOM(heap().allocate<Location>(realm, realm));
  721. return JS::NonnullGCPtr { *m_location };
  722. }
  723. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-history
  724. JS::NonnullGCPtr<History> Window::history() const
  725. {
  726. // The history getter steps are to return this's associated Document's history object.
  727. return associated_document().history();
  728. }
  729. // https://html.spec.whatwg.org/multipage/interaction.html#dom-window-focus
  730. void Window::focus()
  731. {
  732. // 1. Let current be this Window object's navigable.
  733. auto* current = browsing_context();
  734. // 2. If current is null, then return.
  735. if (!current)
  736. return;
  737. // 3. Run the focusing steps with current.
  738. // FIXME: We should pass in the browsing context itself instead of the active document, however the focusing steps don't currently accept browsing contexts.
  739. // Passing in a browsing context always makes it resolve to its active document for focus, so this is fine for now.
  740. run_focusing_steps(current->active_document());
  741. // FIXME: 4. If current is a top-level traversable, user agents are encouraged to trigger some sort of notification to
  742. // indicate to the user that the page is attempting to gain focus.
  743. }
  744. // https://html.spec.whatwg.org/multipage/window-object.html#dom-frames
  745. JS::NonnullGCPtr<WindowProxy> Window::frames() const
  746. {
  747. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  748. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  749. }
  750. // https://html.spec.whatwg.org/multipage/window-object.html#dom-length
  751. u32 Window::length() const
  752. {
  753. // The length getter steps are to return this's associated Document's document-tree child navigables's size.
  754. return static_cast<u32>(document_tree_child_browsing_context_count());
  755. }
  756. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-top
  757. JS::GCPtr<WindowProxy const> Window::top() const
  758. {
  759. // 1. If this's navigable is null, then return null.
  760. auto const* browsing_context = this->browsing_context();
  761. if (!browsing_context)
  762. return {};
  763. // 2. Return this's navigable's top-level traversable's active WindowProxy.
  764. return browsing_context->top_level_browsing_context().window_proxy();
  765. }
  766. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-parent
  767. JS::GCPtr<WindowProxy const> Window::parent() const
  768. {
  769. // 1. Let navigable be this's navigable.
  770. auto* navigable = browsing_context();
  771. // 2. If navigable is null, then return null.
  772. if (!navigable)
  773. return {};
  774. // 3. If navigable's parent is not null, then set navigable to navigable's parent.
  775. if (auto parent = navigable->parent())
  776. navigable = parent;
  777. // 4. Return navigable's active WindowProxy.
  778. return navigable->window_proxy();
  779. }
  780. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-frameelement
  781. JS::GCPtr<DOM::Element const> Window::frame_element() const
  782. {
  783. // 1. Let current be this's node navigable.
  784. auto* current = browsing_context();
  785. // 2. If current is null, then return null.
  786. if (!current)
  787. return {};
  788. // 3. Let container be current's container.
  789. auto* container = current->container();
  790. // 4. If container is null, then return null.
  791. if (!container)
  792. return {};
  793. // 5. If container's node document's origin is not same origin-domain with the current settings object's origin, then return null.
  794. if (!container->document().origin().is_same_origin_domain(current_settings_object().origin()))
  795. return {};
  796. // 6. Return container.
  797. return container;
  798. }
  799. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-open
  800. WebIDL::ExceptionOr<JS::GCPtr<WindowProxy>> Window::open(Optional<String> const& url, Optional<String> const& target, Optional<String> const& features)
  801. {
  802. // The open(url, target, features) method steps are to run the window open steps with url, target, and features.
  803. return open_impl(*url, *target, *features);
  804. }
  805. // https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator
  806. WebIDL::ExceptionOr<JS::NonnullGCPtr<Navigator>> Window::navigator()
  807. {
  808. auto& realm = this->realm();
  809. // The navigator and clientInformation getter steps are to return this's associated Navigator.
  810. if (!m_navigator)
  811. m_navigator = MUST_OR_THROW_OOM(heap().allocate<Navigator>(realm, realm));
  812. return JS::NonnullGCPtr { *m_navigator };
  813. }
  814. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-alert
  815. void Window::alert(String const& message)
  816. {
  817. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#simple-dialogs
  818. // Note: This method is defined using two overloads, instead of using an optional argument,
  819. // for historical reasons. The practical impact of this is that alert(undefined) is
  820. // treated as alert("undefined"), but alert() is treated as alert("").
  821. // FIXME: Make this fully spec compliant.
  822. if (auto* page = this->page())
  823. page->did_request_alert(message);
  824. }
  825. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-confirm
  826. bool Window::confirm(Optional<String> const& message)
  827. {
  828. // FIXME: Make this fully spec compliant.
  829. // NOTE: `message` has an IDL-provided default value and is never empty.
  830. if (auto* page = this->page())
  831. return page->did_request_confirm(*message);
  832. return false;
  833. }
  834. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-prompt
  835. Optional<String> Window::prompt(Optional<String> const& message, Optional<String> const& default_)
  836. {
  837. // FIXME: Make this fully spec compliant.
  838. if (auto* page = this->page())
  839. return page->did_request_prompt(*message, *default_);
  840. return {};
  841. }
  842. // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-window-postmessage
  843. void Window::post_message(JS::Value message, String const&)
  844. {
  845. // FIXME: This is an ad-hoc hack implementation instead, since we don't currently
  846. // have serialization and deserialization of messages.
  847. queue_global_task(Task::Source::PostedMessage, *this, [this, message] {
  848. MessageEventInit event_init {};
  849. event_init.data = message;
  850. event_init.origin = "<origin>"_string.release_value_but_fixme_should_propagate_errors();
  851. 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());
  852. });
  853. }
  854. // https://dom.spec.whatwg.org/#dom-window-event
  855. Variant<JS::Handle<DOM::Event>, JS::Value> Window::event() const
  856. {
  857. // The event getter steps are to return this’s current event.
  858. if (auto* current_event = this->current_event())
  859. return make_handle(const_cast<DOM::Event&>(*current_event));
  860. return JS::js_undefined();
  861. }
  862. // https://w3c.github.io/csswg-drafts/cssom/#dom-window-getcomputedstyle
  863. WebIDL::ExceptionOr<JS::NonnullGCPtr<CSS::CSSStyleDeclaration>> Window::get_computed_style(DOM::Element& element, Optional<String> const& pseudo_element) const
  864. {
  865. // FIXME: Make this fully spec compliant.
  866. (void)pseudo_element;
  867. return MUST_OR_THROW_OOM(heap().allocate<CSS::ResolvedCSSStyleDeclaration>(realm(), element));
  868. }
  869. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-matchmedia
  870. WebIDL::ExceptionOr<JS::NonnullGCPtr<CSS::MediaQueryList>> Window::match_media(String const& query)
  871. {
  872. // 1. Let parsed media query list be the result of parsing query.
  873. auto parsed_media_query_list = parse_media_query_list(CSS::Parser::ParsingContext(associated_document()), query);
  874. // 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.
  875. auto media_query_list = MUST_OR_THROW_OOM(heap().allocate<CSS::MediaQueryList>(realm(), associated_document(), move(parsed_media_query_list)));
  876. associated_document().add_media_query_list(media_query_list);
  877. return media_query_list;
  878. }
  879. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screen
  880. WebIDL::ExceptionOr<JS::NonnullGCPtr<CSS::Screen>> Window::screen()
  881. {
  882. // The screen attribute must return the Screen object associated with the Window object.
  883. if (!m_screen)
  884. m_screen = MUST_OR_THROW_OOM(heap().allocate<CSS::Screen>(realm(), *this));
  885. return JS::NonnullGCPtr { *m_screen };
  886. }
  887. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-innerwidth
  888. i32 Window::inner_width() const
  889. {
  890. // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar (if any),
  891. // or zero if there is no viewport.
  892. if (auto const* browsing_context = associated_document().browsing_context())
  893. return browsing_context->viewport_rect().width().value();
  894. return 0;
  895. }
  896. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-innerheight
  897. i32 Window::inner_height() const
  898. {
  899. // The innerHeight attribute must return the viewport height including the size of a rendered scroll bar (if any),
  900. // or zero if there is no viewport.
  901. if (auto const* browsing_context = associated_document().browsing_context())
  902. return browsing_context->viewport_rect().height().value();
  903. return 0;
  904. }
  905. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrollx
  906. double Window::scroll_x() const
  907. {
  908. // The scrollX attribute must return the x-coordinate, relative to the initial containing block origin,
  909. // of the left of the viewport, or zero if there is no viewport.
  910. if (auto* page = this->page())
  911. return page->top_level_browsing_context().viewport_scroll_offset().x().value();
  912. return 0;
  913. }
  914. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrolly
  915. double Window::scroll_y() const
  916. {
  917. // The scrollY attribute must return the y-coordinate, relative to the initial containing block origin,
  918. // of the top of the viewport, or zero if there is no viewport.
  919. if (auto* page = this->page())
  920. return page->top_level_browsing_context().viewport_scroll_offset().y().value();
  921. return 0;
  922. }
  923. // https://w3c.github.io/csswg-drafts/cssom-view/#perform-a-scroll
  924. static void perform_a_scroll(Page& page, double x, double y, JS::GCPtr<DOM::Node const> element, Bindings::ScrollBehavior behavior)
  925. {
  926. // FIXME: 1. Abort any ongoing smooth scroll for box.
  927. // 2. If the user agent honors the scroll-behavior property and one of the following are true:
  928. // - behavior is "auto" and element is not null and its computed value of the scroll-behavior property is smooth
  929. // - behavior is smooth
  930. // ...then perform a smooth scroll of box to position. Once the position has finished updating, emit the scrollend
  931. // event. Otherwise, perform an instant scroll of box to position. After an instant scroll emit the scrollend event.
  932. // FIXME: Support smooth scrolling.
  933. (void)element;
  934. (void)behavior;
  935. page.client().page_did_request_scroll_to({ x, y });
  936. }
  937. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scroll
  938. void Window::scroll(ScrollToOptions const& options)
  939. {
  940. // 4. If there is no viewport, abort these steps.
  941. auto* page = this->page();
  942. if (!page)
  943. return;
  944. auto const& top_level_browsing_context = page->top_level_browsing_context();
  945. // 1. If invoked with one argument, follow these substeps:
  946. // 1. Let options be the argument.
  947. auto viewport_rect = top_level_browsing_context.viewport_rect().to_type<float>();
  948. // 2. Let x be the value of the left dictionary member of options, if present, or the viewport’s current scroll
  949. // position on the x axis otherwise.
  950. auto x = options.left.value_or(viewport_rect.x());
  951. // 3. Let y be the value of the top dictionary member of options, if present, or the viewport’s current scroll
  952. // position on the y axis otherwise.
  953. auto y = options.top.value_or(viewport_rect.y());
  954. // 3. Normalize non-finite values for x and y.
  955. x = JS::Value(x).is_finite_number() ? x : 0;
  956. y = JS::Value(y).is_finite_number() ? y : 0;
  957. // 5. Let viewport width be the width of the viewport excluding the width of the scroll bar, if any.
  958. auto viewport_width = viewport_rect.width();
  959. // 6. Let viewport height be the height of the viewport excluding the height of the scroll bar, if any.
  960. auto viewport_height = viewport_rect.height();
  961. (void)viewport_width;
  962. (void)viewport_height;
  963. // FIXME: 7.
  964. // -> If the viewport has rightward overflow direction
  965. // Let x be max(0, min(x, viewport scrolling area width - viewport width)).
  966. // -> If the viewport has leftward overflow direction
  967. // Let x be min(0, max(x, viewport width - viewport scrolling area width)).
  968. // FIXME: 8.
  969. // -> If the viewport has downward overflow direction
  970. // Let y be max(0, min(y, viewport scrolling area height - viewport height)).
  971. // -> If the viewport has upward overflow direction
  972. // Let y be min(0, max(y, viewport height - viewport scrolling area height)).
  973. // FIXME: 9. Let position be the scroll position the viewport would have by aligning the x-coordinate x of the viewport
  974. // scrolling area with the left of the viewport and aligning the y-coordinate y of the viewport scrolling area
  975. // with the top of the viewport.
  976. // FIXME: 10. If position is the same as the viewport’s current scroll position, and the viewport does not have an ongoing
  977. // smooth scroll, abort these steps.
  978. // 11. Let document be the viewport’s associated Document.
  979. auto const* document = top_level_browsing_context.active_document();
  980. // 12. Perform a scroll of the viewport to position, document’s root element as the associated element, if there is
  981. // one, or null otherwise, and the scroll behavior being the value of the behavior dictionary member of options.
  982. auto element = JS::GCPtr<DOM::Node const> { document ? &document->root() : nullptr };
  983. perform_a_scroll(*page, x, y, element, options.behavior);
  984. }
  985. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scroll
  986. void Window::scroll(double x, double y)
  987. {
  988. // 2. If invoked with two arguments, follow these substeps:
  989. // 1. Let options be null converted to a ScrollToOptions dictionary. [WEBIDL]
  990. auto options = ScrollToOptions {};
  991. // 2. Let x and y be the arguments, respectively.
  992. options.left = x;
  993. options.top = y;
  994. scroll(options);
  995. }
  996. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrollby
  997. void Window::scroll_by(ScrollToOptions options)
  998. {
  999. // 2. Normalize non-finite values for the left and top dictionary members of options.
  1000. auto x = options.left.value_or(0);
  1001. auto y = options.top.value_or(0);
  1002. x = JS::Value(x).is_finite_number() ? x : 0;
  1003. y = JS::Value(y).is_finite_number() ? y : 0;
  1004. // 3. Add the value of scrollX to the left dictionary member.
  1005. options.left = x + scroll_x();
  1006. // 4. Add the value of scrollY to the top dictionary member.
  1007. options.top = y + scroll_y();
  1008. // 5. Act as if the scroll() method was invoked with options as the only argument.
  1009. scroll(options);
  1010. }
  1011. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-scrollby
  1012. void Window::scroll_by(double x, double y)
  1013. {
  1014. // 1. If invoked with two arguments, follow these substeps:
  1015. // 1. Let options be null converted to a ScrollToOptions dictionary. [WEBIDL]
  1016. auto options = ScrollToOptions {};
  1017. // 2. Let x and y be the arguments, respectively.
  1018. // 3. Let the left dictionary member of options have the value x.
  1019. options.left = x;
  1020. // 4. Let the top dictionary member of options have the value y.
  1021. options.top = y;
  1022. scroll_by(options);
  1023. }
  1024. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screenx
  1025. i32 Window::screen_x() const
  1026. {
  1027. // The screenX and screenLeft attributes must return the x-coordinate, relative to the origin of the Web-exposed
  1028. // screen area, of the left of the client window as number of CSS pixels, or zero if there is no such thing.
  1029. if (auto* page = this->page())
  1030. return page->window_position().x().value();
  1031. return 0;
  1032. }
  1033. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-screeny
  1034. i32 Window::screen_y() const
  1035. {
  1036. // The screenY and screenTop attributes must return the y-coordinate, relative to the origin of the screen of the
  1037. // Web-exposed screen area, of the top of the client window as number of CSS pixels, or zero if there is no such thing.
  1038. if (auto* page = this->page())
  1039. return page->window_position().y().value();
  1040. return 0;
  1041. }
  1042. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-outerwidth
  1043. i32 Window::outer_width() const
  1044. {
  1045. // The outerWidth attribute must return the width of the client window. If there is no client window this
  1046. // attribute must return zero.
  1047. if (auto* page = this->page())
  1048. return page->window_size().width().value();
  1049. return 0;
  1050. }
  1051. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-outerheight
  1052. i32 Window::outer_height() const
  1053. {
  1054. // The outerHeight attribute must return the height of the client window. If there is no client window this
  1055. // attribute must return zero.
  1056. if (auto* page = this->page())
  1057. return page->window_size().height().value();
  1058. return 0;
  1059. }
  1060. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-window-devicepixelratio
  1061. double Window::device_pixel_ratio() const
  1062. {
  1063. // 1. If there is no output device, return 1 and abort these steps.
  1064. // 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.
  1065. // 3. Let device pixel size be the vertical size of a device pixel of the output device.
  1066. // 4. Return the result of dividing CSS pixel size by device pixel size.
  1067. if (auto* page = this->page())
  1068. return page->client().device_pixels_per_css_pixel();
  1069. return 1;
  1070. }
  1071. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-animationframeprovider-requestanimationframe
  1072. i32 Window::request_animation_frame(WebIDL::CallbackType& callback)
  1073. {
  1074. // FIXME: Make this fully spec compliant. Currently implements a mix of 'requestAnimationFrame()' and 'run the animation frame callbacks'.
  1075. auto now = HighResolutionTime::unsafe_shared_current_time();
  1076. return m_animation_frame_callback_driver.add([this, now, callback = JS::make_handle(callback)](auto) {
  1077. // 3. Invoke callback, passing now as the only argument, and if an exception is thrown, report the exception.
  1078. auto result = WebIDL::invoke_callback(*callback, {}, JS::Value(now));
  1079. if (result.is_error())
  1080. report_exception(result, realm());
  1081. });
  1082. }
  1083. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#animationframeprovider-cancelanimationframe
  1084. void Window::cancel_animation_frame(i32 handle)
  1085. {
  1086. // 1. If this is not supported, then throw a "NotSupportedError" DOMException.
  1087. // NOTE: Doesn't apply in this Window-specific implementation.
  1088. // 2. Let callbacks be this's target object's map of animation frame callbacks.
  1089. // 3. Remove callbacks[handle].
  1090. m_animation_frame_callback_driver.remove(handle);
  1091. }
  1092. // https://w3c.github.io/requestidlecallback/#dom-window-requestidlecallback
  1093. u32 Window::request_idle_callback(WebIDL::CallbackType& callback, RequestIdleCallback::IdleRequestOptions const& options)
  1094. {
  1095. // 1. Let window be this Window object.
  1096. // 2. Increment the window's idle callback identifier by one.
  1097. m_idle_callback_identifier++;
  1098. // 3. Let handle be the current value of window's idle callback identifier.
  1099. auto handle = m_idle_callback_identifier;
  1100. // 4. Push callback to the end of window's list of idle request callbacks, associated with handle.
  1101. auto handler = [callback = JS::make_handle(callback)](JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline> deadline) -> JS::Completion {
  1102. return WebIDL::invoke_callback(*callback, {}, deadline.ptr());
  1103. };
  1104. m_idle_request_callbacks.append(adopt_ref(*new IdleCallback(move(handler), handle)));
  1105. // 5. Return handle and then continue running this algorithm asynchronously.
  1106. return handle;
  1107. // FIXME: 6. If the timeout property is present in options and has a positive value:
  1108. // FIXME: 1. Wait for timeout milliseconds.
  1109. // FIXME: 2. Wait until all invocations of this algorithm, whose timeout added to their posted time occurred before this one's, have completed.
  1110. // FIXME: 3. Optionally, wait a further user-agent defined length of time.
  1111. // 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.
  1112. (void)options;
  1113. }
  1114. // https://w3c.github.io/requestidlecallback/#dom-window-cancelidlecallback
  1115. void Window::cancel_idle_callback(u32 handle)
  1116. {
  1117. // 1. Let window be this Window object.
  1118. // 2. Find the entry in either the window's list of idle request callbacks or list of runnable idle callbacks
  1119. // that is associated with the value handle.
  1120. // 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.
  1121. m_idle_request_callbacks.remove_first_matching([&](auto& callback) {
  1122. return callback->handle() == handle;
  1123. });
  1124. m_runnable_idle_callbacks.remove_first_matching([&](auto& callback) {
  1125. return callback->handle() == handle;
  1126. });
  1127. }
  1128. // https://w3c.github.io/selection-api/#dom-window-getselection
  1129. JS::GCPtr<Selection::Selection> Window::get_selection() const
  1130. {
  1131. // The method must invoke and return the result of getSelection() on this's Window.document attribute.
  1132. return associated_document().get_selection();
  1133. }
  1134. // https://w3c.github.io/hr-time/#dom-windoworworkerglobalscope-performance
  1135. WebIDL::ExceptionOr<JS::NonnullGCPtr<HighResolutionTime::Performance>> Window::performance()
  1136. {
  1137. if (!m_performance)
  1138. m_performance = MUST_OR_THROW_OOM(heap().allocate<HighResolutionTime::Performance>(realm(), *this));
  1139. return JS::NonnullGCPtr { *m_performance };
  1140. }
  1141. // https://w3c.github.io/webcrypto/#dom-windoworworkerglobalscope-crypto
  1142. WebIDL::ExceptionOr<JS::NonnullGCPtr<Crypto::Crypto>> Window::crypto()
  1143. {
  1144. auto& realm = this->realm();
  1145. if (!m_crypto)
  1146. m_crypto = MUST_OR_THROW_OOM(heap().allocate<Crypto::Crypto>(realm, realm));
  1147. return JS::NonnullGCPtr { *m_crypto };
  1148. }
  1149. static JS::ThrowCompletionOr<TimerHandler> make_timer_handler(JS::VM& vm, JS::Value handler)
  1150. {
  1151. if (handler.is_function())
  1152. return JS::make_handle(vm.heap().allocate_without_realm<WebIDL::CallbackType>(handler.as_function(), incumbent_settings_object()));
  1153. return TRY(handler.to_string(vm));
  1154. }
  1155. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  1156. JS_DEFINE_NATIVE_FUNCTION(Window::set_timeout)
  1157. {
  1158. auto* impl = TRY(impl_from(vm));
  1159. if (!vm.argument_count())
  1160. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountAtLeastOne, "setTimeout");
  1161. auto handler = TRY(make_timer_handler(vm, vm.argument(0)));
  1162. i32 timeout = 0;
  1163. if (vm.argument_count() >= 2)
  1164. timeout = TRY(vm.argument(1).to_i32(vm));
  1165. JS::MarkedVector<JS::Value> arguments { vm.heap() };
  1166. for (size_t i = 2; i < vm.argument_count(); ++i)
  1167. arguments.append(vm.argument(i));
  1168. auto id = static_cast<WindowOrWorkerGlobalScopeMixin*>(impl)->set_timeout(move(handler), timeout, move(arguments));
  1169. return JS::Value(id);
  1170. }
  1171. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  1172. JS_DEFINE_NATIVE_FUNCTION(Window::set_interval)
  1173. {
  1174. auto* impl = TRY(impl_from(vm));
  1175. if (!vm.argument_count())
  1176. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountAtLeastOne, "setInterval");
  1177. auto handler = TRY(make_timer_handler(vm, vm.argument(0)));
  1178. i32 timeout = 0;
  1179. if (vm.argument_count() >= 2)
  1180. timeout = TRY(vm.argument(1).to_i32(vm));
  1181. JS::MarkedVector<JS::Value> arguments { vm.heap() };
  1182. for (size_t i = 2; i < vm.argument_count(); ++i)
  1183. arguments.append(vm.argument(i));
  1184. auto id = static_cast<WindowOrWorkerGlobalScopeMixin*>(impl)->set_interval(move(handler), timeout, move(arguments));
  1185. return JS::Value(id);
  1186. }
  1187. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeout
  1188. JS_DEFINE_NATIVE_FUNCTION(Window::clear_timeout)
  1189. {
  1190. auto* impl = TRY(impl_from(vm));
  1191. i32 id = 0;
  1192. if (vm.argument_count())
  1193. id = TRY(vm.argument(0).to_i32(vm));
  1194. static_cast<WindowOrWorkerGlobalScopeMixin*>(impl)->clear_timeout(id);
  1195. return JS::js_undefined();
  1196. }
  1197. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-clearinterval
  1198. JS_DEFINE_NATIVE_FUNCTION(Window::clear_interval)
  1199. {
  1200. auto* impl = TRY(impl_from(vm));
  1201. i32 id = 0;
  1202. if (vm.argument_count())
  1203. id = TRY(vm.argument(0).to_i32(vm));
  1204. static_cast<WindowOrWorkerGlobalScopeMixin*>(impl)->clear_interval(id);
  1205. return JS::js_undefined();
  1206. }
  1207. // https://html.spec.whatwg.org/multipage/window-object.html#number-of-document-tree-child-browsing-contexts
  1208. size_t Window::document_tree_child_browsing_context_count() const
  1209. {
  1210. // 1. If W's browsing context is null, then return 0.
  1211. auto* this_browsing_context = associated_document().browsing_context();
  1212. if (!this_browsing_context)
  1213. return 0;
  1214. // 2. Return the number of document-tree child browsing contexts of W's browsing context.
  1215. return this_browsing_context->document_tree_child_browsing_context_count();
  1216. }
  1217. JS_DEFINE_NATIVE_FUNCTION(Window::location_setter)
  1218. {
  1219. auto* impl = TRY(impl_from(vm));
  1220. auto location = TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return impl->location(); }));
  1221. TRY(location->set(JS::PropertyKey("href"), vm.argument(0), JS::Object::ShouldThrowExceptions::Yes));
  1222. return JS::js_undefined();
  1223. }
  1224. }