Window.cpp 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901
  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/Completion.h>
  14. #include <LibJS/Runtime/Error.h>
  15. #include <LibJS/Runtime/FunctionObject.h>
  16. #include <LibJS/Runtime/GlobalEnvironment.h>
  17. #include <LibJS/Runtime/Shape.h>
  18. #include <LibTextCodec/Decoder.h>
  19. #include <LibWeb/Bindings/CSSNamespace.h>
  20. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  21. #include <LibWeb/Bindings/FetchMethod.h>
  22. #include <LibWeb/Bindings/Replaceable.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/ClassicScript.h>
  44. #include <LibWeb/HTML/Scripting/Environments.h>
  45. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  46. #include <LibWeb/HTML/Storage.h>
  47. #include <LibWeb/HTML/StructuredSerialize.h>
  48. #include <LibWeb/HTML/Timer.h>
  49. #include <LibWeb/HTML/Window.h>
  50. #include <LibWeb/HTML/WindowProxy.h>
  51. #include <LibWeb/HighResolutionTime/Performance.h>
  52. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  53. #include <LibWeb/Infra/Base64.h>
  54. #include <LibWeb/Infra/CharacterTypes.h>
  55. #include <LibWeb/Layout/Viewport.h>
  56. #include <LibWeb/Page/Page.h>
  57. #include <LibWeb/RequestIdleCallback/IdleDeadline.h>
  58. #include <LibWeb/Selection/Selection.h>
  59. #include <LibWeb/WebAssembly/WebAssemblyObject.h>
  60. #include <LibWeb/WebIDL/AbstractOperations.h>
  61. namespace Web::HTML {
  62. // https://html.spec.whatwg.org/#run-the-animation-frame-callbacks
  63. void run_animation_frame_callbacks(DOM::Document& document, double)
  64. {
  65. // FIXME: Bring this closer to the spec.
  66. document.window().animation_frame_callback_driver().run();
  67. }
  68. class IdleCallback : public RefCounted<IdleCallback> {
  69. public:
  70. explicit IdleCallback(Function<JS::Completion(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline>)> handler, u32 handle)
  71. : m_handler(move(handler))
  72. , m_handle(handle)
  73. {
  74. }
  75. ~IdleCallback() = default;
  76. JS::Completion invoke(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline> deadline) { return m_handler(deadline); }
  77. u32 handle() const { return m_handle; }
  78. private:
  79. Function<JS::Completion(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline>)> m_handler;
  80. u32 m_handle { 0 };
  81. };
  82. WebIDL::ExceptionOr<JS::NonnullGCPtr<Window>> Window::create(JS::Realm& realm)
  83. {
  84. return MUST_OR_THROW_OOM(realm.heap().allocate<Window>(realm, realm));
  85. }
  86. Window::Window(JS::Realm& realm)
  87. : DOM::EventTarget(realm)
  88. {
  89. }
  90. void Window::visit_edges(JS::Cell::Visitor& visitor)
  91. {
  92. Base::visit_edges(visitor);
  93. visitor.visit(m_associated_document.ptr());
  94. visitor.visit(m_current_event.ptr());
  95. visitor.visit(m_performance.ptr());
  96. visitor.visit(m_screen.ptr());
  97. visitor.visit(m_location);
  98. visitor.visit(m_crypto);
  99. visitor.visit(m_navigator);
  100. for (auto& it : m_timers)
  101. visitor.visit(it.value.ptr());
  102. for (auto& plugin_object : m_pdf_viewer_plugin_objects)
  103. visitor.visit(plugin_object);
  104. for (auto& mime_type_object : m_pdf_viewer_mime_type_objects)
  105. visitor.visit(mime_type_object);
  106. }
  107. Window::~Window() = default;
  108. HighResolutionTime::Performance& Window::performance()
  109. {
  110. if (!m_performance)
  111. m_performance = heap().allocate<HighResolutionTime::Performance>(realm(), *this).release_allocated_value_but_fixme_should_propagate_errors();
  112. return *m_performance;
  113. }
  114. CSS::Screen& Window::screen()
  115. {
  116. if (!m_screen)
  117. m_screen = heap().allocate<CSS::Screen>(realm(), *this).release_allocated_value_but_fixme_should_propagate_errors();
  118. return *m_screen;
  119. }
  120. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#normalizing-the-feature-name
  121. static StringView normalize_feature_name(StringView name)
  122. {
  123. // For legacy reasons, there are some aliases of some feature names. To normalize a feature name name, switch on name:
  124. // "screenx"
  125. if (name == "screenx"sv) {
  126. // Return "left".
  127. return "left"sv;
  128. }
  129. // "screeny"
  130. else if (name == "screeny"sv) {
  131. // Return "top".
  132. return "top"sv;
  133. }
  134. // "innerwidth"
  135. else if (name == "innerwidth"sv) {
  136. // Return "width".
  137. return "width"sv;
  138. }
  139. // "innerheight"
  140. else if (name == "innerheight") {
  141. // Return "height".
  142. return "height"sv;
  143. }
  144. // Anything else
  145. else {
  146. // Return name.
  147. return name;
  148. }
  149. }
  150. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#concept-window-open-features-tokenize
  151. static OrderedHashMap<DeprecatedString, DeprecatedString> tokenize_open_features(StringView features)
  152. {
  153. // 1. Let tokenizedFeatures be a new ordered map.
  154. OrderedHashMap<DeprecatedString, DeprecatedString> tokenized_features;
  155. // 2. Let position point at the first code point of features.
  156. GenericLexer lexer(features);
  157. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#feature-separator
  158. auto is_feature_separator = [](auto character) {
  159. return Infra::is_ascii_whitespace(character) || character == '=' || character == ',';
  160. };
  161. // 3. While position is not past the end of features:
  162. while (!lexer.is_eof()) {
  163. // 1. Let name be the empty string.
  164. DeprecatedString name;
  165. // 2. Let value be the empty string.
  166. DeprecatedString value;
  167. // 3. Collect a sequence of code points that are feature separators from features given position. This skips past leading separators before the name.
  168. lexer.ignore_while(is_feature_separator);
  169. // 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.
  170. name = lexer.consume_until(is_feature_separator).to_lowercase_string();
  171. // 5. Set name to the result of normalizing the feature name name.
  172. name = normalize_feature_name(name);
  173. // 6. While position is not past the end of features and the code point at position in features is not U+003D (=):
  174. // 1. If the code point at position in features is U+002C (,), or if it is not a feature separator, then break.
  175. // 2. Advance position by 1.
  176. lexer.ignore_while(Infra::is_ascii_whitespace);
  177. // 7. If the code point at position in features is a feature separator:
  178. // 1. While position is not past the end of features and the code point at position in features is a feature separator:
  179. // 1. If the code point at position in features is U+002C (,), then break.
  180. // 2. Advance position by 1.
  181. lexer.ignore_while([](auto character) { return Infra::is_ascii_whitespace(character) || character == '='; });
  182. // 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.
  183. value = lexer.consume_until(is_feature_separator).to_lowercase_string();
  184. // 8. If name is not the empty string, then set tokenizedFeatures[name] to value.
  185. if (!name.is_empty())
  186. tokenized_features.set(move(name), move(value));
  187. }
  188. // 4. Return tokenizedFeatures.
  189. return tokenized_features;
  190. }
  191. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#concept-window-open-features-parse-boolean
  192. static bool parse_boolean_feature(StringView value)
  193. {
  194. // 1. If value is the empty string, then return true.
  195. if (value.is_empty())
  196. return true;
  197. // 2. If value is "yes", then return true.
  198. if (value == "yes"sv)
  199. return true;
  200. // 3. If value is "true", then return true.
  201. if (value == "true"sv)
  202. return true;
  203. // 4. Let parsed be the result of parsing value as an integer.
  204. auto parsed = value.to_int<i64>();
  205. // 5. If parsed is an error, then set it to 0.
  206. if (!parsed.has_value())
  207. parsed = 0;
  208. // 6. Return false if parsed is 0, and true otherwise.
  209. return *parsed != 0;
  210. }
  211. // https://html.spec.whatwg.org/multipage/window-object.html#popup-window-is-requested
  212. static bool check_if_a_popup_window_is_requested(OrderedHashMap<DeprecatedString, DeprecatedString> const& tokenized_features)
  213. {
  214. // 1. If tokenizedFeatures is empty, then return false.
  215. if (tokenized_features.is_empty())
  216. return false;
  217. // 2. If tokenizedFeatures["popup"] exists, then return the result of parsing tokenizedFeatures["popup"] as a boolean feature.
  218. if (auto popup_feature = tokenized_features.get("popup"sv); popup_feature.has_value())
  219. return parse_boolean_feature(*popup_feature);
  220. // https://html.spec.whatwg.org/multipage/window-object.html#window-feature-is-set
  221. auto check_if_a_window_feature_is_set = [&](StringView feature_name, bool default_value) {
  222. // 1. If tokenizedFeatures[featureName] exists, then return the result of parsing tokenizedFeatures[featureName] as a boolean feature.
  223. if (auto feature = tokenized_features.get(feature_name); feature.has_value())
  224. return parse_boolean_feature(*feature);
  225. // 2. Return defaultValue.
  226. return default_value;
  227. };
  228. // 3. Let location be the result of checking if a window feature is set, given tokenizedFeatures, "location", and false.
  229. auto location = check_if_a_window_feature_is_set("location"sv, false);
  230. // 4. Let toolbar be the result of checking if a window feature is set, given tokenizedFeatures, "toolbar", and false.
  231. auto toolbar = check_if_a_window_feature_is_set("toolbar"sv, false);
  232. // 5. If location and toolbar are both false, then return true.
  233. if (!location && !toolbar)
  234. return true;
  235. // 6. Let menubar be the result of checking if a window feature is set, given tokenizedFeatures, menubar", and false.
  236. auto menubar = check_if_a_window_feature_is_set("menubar"sv, false);
  237. // 7. If menubar is false, then return true.
  238. if (!menubar)
  239. return true;
  240. // 8. Let resizable be the result of checking if a window feature is set, given tokenizedFeatures, "resizable", and true.
  241. auto resizable = check_if_a_window_feature_is_set("resizable"sv, true);
  242. // 9. If resizable is false, then return true.
  243. if (!resizable)
  244. return true;
  245. // 10. Let scrollbars be the result of checking if a window feature is set, given tokenizedFeatures, "scrollbars", and false.
  246. auto scrollbars = check_if_a_window_feature_is_set("scrollbars"sv, false);
  247. // 11. If scrollbars is false, then return true.
  248. if (!scrollbars)
  249. return true;
  250. // 12. Let status be the result of checking if a window feature is set, given tokenizedFeatures, "status", and false.
  251. auto status = check_if_a_window_feature_is_set("status"sv, false);
  252. // 13. If status is false, then return true.
  253. if (!status)
  254. return true;
  255. // 14. Return false.
  256. return false;
  257. }
  258. // FIXME: This is based on the old 'browsing context' concept, which was replaced with 'navigable'
  259. // https://html.spec.whatwg.org/multipage/window-object.html#window-open-steps
  260. WebIDL::ExceptionOr<JS::GCPtr<HTML::WindowProxy>> Window::open_impl(StringView url, StringView target, StringView features)
  261. {
  262. auto& vm = this->vm();
  263. // 1. If the event loop's termination nesting level is nonzero, return null.
  264. if (HTML::main_thread_event_loop().termination_nesting_level() != 0)
  265. return nullptr;
  266. // 2. Let source browsing context be the entry global object's browsing context.
  267. auto* source_browsing_context = verify_cast<Window>(entry_global_object()).browsing_context();
  268. // 3. If target is the empty string, then set target to "_blank".
  269. if (target.is_empty())
  270. target = "_blank"sv;
  271. // 4. Let tokenizedFeatures be the result of tokenizing features.
  272. auto tokenized_features = tokenize_open_features(features);
  273. // 5. Let noopener and noreferrer be false.
  274. auto no_opener = false;
  275. auto no_referrer = false;
  276. // 6. If tokenizedFeatures["noopener"] exists, then:
  277. if (auto no_opener_feature = tokenized_features.get("noopener"sv); no_opener_feature.has_value()) {
  278. // 1. Set noopener to the result of parsing tokenizedFeatures["noopener"] as a boolean feature.
  279. no_opener = parse_boolean_feature(*no_opener_feature);
  280. // 2. Remove tokenizedFeatures["noopener"].
  281. tokenized_features.remove("noopener"sv);
  282. }
  283. // 7. If tokenizedFeatures["noreferrer"] exists, then:
  284. if (auto no_referrer_feature = tokenized_features.get("noreferrer"sv); no_referrer_feature.has_value()) {
  285. // 1. Set noreferrer to the result of parsing tokenizedFeatures["noreferrer"] as a boolean feature.
  286. no_referrer = parse_boolean_feature(*no_referrer_feature);
  287. // 2. Remove tokenizedFeatures["noreferrer"].
  288. tokenized_features.remove("noreferrer"sv);
  289. }
  290. // 8. If noreferrer is true, then set noopener to true.
  291. if (no_referrer)
  292. no_opener = true;
  293. // 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.
  294. auto [target_browsing_context, window_type] = source_browsing_context->choose_a_browsing_context(target, no_opener);
  295. // 10. If target browsing context is null, then return null.
  296. if (target_browsing_context == nullptr)
  297. return nullptr;
  298. // 11. If windowType is either "new and unrestricted" or "new with no opener", then:
  299. if (window_type == BrowsingContext::WindowType::NewAndUnrestricted || window_type == BrowsingContext::WindowType::NewWithNoOpener) {
  300. // 1. Set the target browsing context's is popup to the result of checking if a popup window is requested, given tokenizedFeatures.
  301. target_browsing_context->set_is_popup(check_if_a_popup_window_is_requested(tokenized_features));
  302. // FIXME: 2. Set up browsing context features for target browsing context given tokenizedFeatures. [CSSOMVIEW]
  303. // NOTE: While this is not implemented yet, all of observable actions taken by this operation are optional (implementation-defined).
  304. // 3. Let urlRecord be the URL record about:blank.
  305. auto url_record = AK::URL("about:blank"sv);
  306. // 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.
  307. if (!url.is_empty()) {
  308. url_record = entry_settings_object().parse_url(url);
  309. if (!url_record.is_valid())
  310. return WebIDL::SyntaxError::create(realm(), "URL is not valid");
  311. }
  312. // FIXME: 5. If urlRecord matches about:blank, then perform the URL and history update steps given target browsing context's active document and urlRecord.
  313. // 6. Otherwise:
  314. else {
  315. // 1. Let request be a new request whose URL is urlRecord.
  316. auto request = Fetch::Infrastructure::Request::create(vm);
  317. request->set_url(url_record);
  318. // 2. If noreferrer is true, then set request's referrer to "no-referrer".
  319. if (no_referrer)
  320. request->set_referrer(Fetch::Infrastructure::Request::Referrer::NoReferrer);
  321. // 3. Navigate target browsing context to request, with exceptionsEnabled set to true and the source browsing context set to source browsing context.
  322. TRY(target_browsing_context->navigate(request, *source_browsing_context, true));
  323. }
  324. }
  325. // 12. Otherwise:
  326. else {
  327. // 1. If url is not the empty string, then:
  328. if (!url.is_empty()) {
  329. // 1. Let urlRecord be the URL record about:blank.
  330. auto url_record = AK::URL("about:blank"sv);
  331. // 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.
  332. url_record = entry_settings_object().parse_url(url);
  333. if (!url_record.is_valid())
  334. return WebIDL::SyntaxError::create(realm(), "URL is not valid");
  335. // 3. Let request be a new request whose URL is urlRecord.
  336. auto request = Fetch::Infrastructure::Request::create(vm);
  337. request->set_url(url_record);
  338. // 4. If noreferrer is true, then set request's referrer to "noreferrer".
  339. if (no_referrer)
  340. request->set_referrer(Fetch::Infrastructure::Request::Referrer::NoReferrer);
  341. // 5. Navigate target browsing context to request, with exceptionsEnabled set to true and the source browsing context set to source browsing context.
  342. TRY(target_browsing_context->navigate(request, *source_browsing_context, true));
  343. }
  344. // 2. If noopener is false, then set target browsing context's opener browsing context to source browsing context.
  345. if (!no_opener)
  346. target_browsing_context->set_opener_browsing_context(source_browsing_context);
  347. }
  348. // 13. If noopener is true or windowType is "new with no opener", then return null.
  349. if (no_opener || window_type == BrowsingContext::WindowType::NewWithNoOpener)
  350. return nullptr;
  351. // 14. Return target browsing context's WindowProxy object.
  352. return target_browsing_context->window_proxy();
  353. }
  354. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  355. i32 Window::set_timeout_impl(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  356. {
  357. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::No);
  358. }
  359. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  360. i32 Window::set_interval_impl(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  361. {
  362. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::Yes);
  363. }
  364. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeout
  365. void Window::clear_timeout_impl(i32 id)
  366. {
  367. m_timers.remove(id);
  368. }
  369. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-clearinterval
  370. void Window::clear_interval_impl(i32 id)
  371. {
  372. m_timers.remove(id);
  373. }
  374. void Window::deallocate_timer_id(Badge<Timer>, i32 id)
  375. {
  376. m_timer_id_allocator.deallocate(id);
  377. }
  378. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps
  379. i32 Window::run_timer_initialization_steps(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments, Repeat repeat, Optional<i32> previous_id)
  380. {
  381. // 1. Let thisArg be global if that is a WorkerGlobalScope object; otherwise let thisArg be the WindowProxy that corresponds to global.
  382. // 2. If previousId was given, let id be previousId; otherwise, let id be an implementation-defined integer that is greater than zero and does not already exist in global's map of active timers.
  383. auto id = previous_id.has_value() ? previous_id.value() : m_timer_id_allocator.allocate();
  384. // FIXME: 3. If the surrounding agent's event loop's currently running task is a task that was created by this algorithm, then let nesting level be the task's timer nesting level. Otherwise, let nesting level be zero.
  385. // 4. If timeout is less than 0, then set timeout to 0.
  386. if (timeout < 0)
  387. timeout = 0;
  388. // FIXME: 5. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.
  389. // 6. Let callerRealm be the current Realm Record, and calleeRealm be global's relevant Realm.
  390. // FIXME: Implement this when step 9.2 is implemented.
  391. // 7. Let initiating script be the active script.
  392. // 8. Assert: initiating script is not null, since this algorithm is always called from some script.
  393. // 9. Let task be a task that runs the following substeps:
  394. JS::SafeFunction<void()> task = [this, handler = move(handler), timeout, arguments = move(arguments), repeat, id] {
  395. // 1. If id does not exist in global's map of active timers, then abort these steps.
  396. if (!m_timers.contains(id))
  397. return;
  398. handler.visit(
  399. // 2. If handler is a Function, then invoke handler given arguments with the callback this value set to thisArg. If this throws an exception, catch it, and report the exception.
  400. [&](JS::Handle<WebIDL::CallbackType> callback) {
  401. if (auto result = WebIDL::invoke_callback(*callback, this, arguments); result.is_error())
  402. HTML::report_exception(result, realm());
  403. },
  404. // 3. Otherwise:
  405. [&](DeprecatedString const& source) {
  406. // 1. Assert: handler is a string.
  407. // FIXME: 2. Perform HostEnsureCanCompileStrings(callerRealm, calleeRealm). If this throws an exception, catch it, report the exception, and abort these steps.
  408. // 3. Let settings object be global's relevant settings object.
  409. auto& settings_object = associated_document().relevant_settings_object();
  410. // 4. Let base URL be initiating script's base URL.
  411. auto url = associated_document().url();
  412. // 5. Assert: base URL is not null, as initiating script is a classic script or a JavaScript module script.
  413. // 6. Let fetch options be a script fetch options whose cryptographic nonce is initiating script's fetch options's cryptographic nonce, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is initiating script's fetch options's credentials mode, and referrer policy is initiating script's fetch options's referrer policy.
  414. // 7. Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.
  415. auto script = HTML::ClassicScript::create(url.basename(), source, settings_object, url);
  416. // 8. Run the classic script script.
  417. (void)script->run();
  418. });
  419. // 4. If id does not exist in global's map of active timers, then abort these steps.
  420. if (!m_timers.contains(id))
  421. return;
  422. switch (repeat) {
  423. // 5. If repeat is true, then perform the timer initialization steps again, given global, handler, timeout, arguments, true, and id.
  424. case Repeat::Yes:
  425. run_timer_initialization_steps(handler, timeout, move(arguments), repeat, id);
  426. break;
  427. // 6. Otherwise, remove global's map of active timers[id].
  428. case Repeat::No:
  429. m_timers.remove(id);
  430. break;
  431. }
  432. };
  433. // FIXME: 10. Increment nesting level by one.
  434. // FIXME: 11. Set task's timer nesting level to nesting level.
  435. // 12. Let completionStep be an algorithm step which queues a global task on the timer task source given global to run task.
  436. JS::SafeFunction<void()> completion_step = [this, task = move(task)]() mutable {
  437. HTML::queue_global_task(HTML::Task::Source::TimerTask, *this, move(task));
  438. };
  439. // 13. Run steps after a timeout given global, "setTimeout/setInterval", timeout, completionStep, and id.
  440. auto timer = Timer::create(*this, timeout, move(completion_step), id);
  441. m_timers.set(id, timer);
  442. timer->start();
  443. // 14. Return id.
  444. return id;
  445. }
  446. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#run-the-animation-frame-callbacks
  447. i32 Window::request_animation_frame_impl(WebIDL::CallbackType& js_callback)
  448. {
  449. return m_animation_frame_callback_driver.add([this, js_callback = JS::make_handle(js_callback)](auto) {
  450. // 3. Invoke callback, passing now as the only argument,
  451. auto result = WebIDL::invoke_callback(*js_callback, {}, JS::Value(performance().now()));
  452. // and if an exception is thrown, report the exception.
  453. if (result.is_error())
  454. HTML::report_exception(result, realm());
  455. });
  456. }
  457. void Window::cancel_animation_frame_impl(i32 id)
  458. {
  459. m_animation_frame_callback_driver.remove(id);
  460. }
  461. void Window::did_set_location_href(Badge<HTML::Location>, AK::URL const& new_href)
  462. {
  463. auto* browsing_context = associated_document().browsing_context();
  464. if (!browsing_context)
  465. return;
  466. browsing_context->loader().load(new_href, FrameLoader::Type::Navigation);
  467. }
  468. void Window::did_call_location_reload(Badge<HTML::Location>)
  469. {
  470. auto* browsing_context = associated_document().browsing_context();
  471. if (!browsing_context)
  472. return;
  473. browsing_context->loader().load(associated_document().url(), FrameLoader::Type::Reload);
  474. }
  475. void Window::did_call_location_replace(Badge<HTML::Location>, DeprecatedString url)
  476. {
  477. auto* browsing_context = associated_document().browsing_context();
  478. if (!browsing_context)
  479. return;
  480. auto new_url = associated_document().parse_url(url);
  481. browsing_context->loader().load(move(new_url), FrameLoader::Type::Navigation);
  482. }
  483. bool Window::dispatch_event(DOM::Event& event)
  484. {
  485. return DOM::EventDispatcher::dispatch(*this, event, true);
  486. }
  487. // https://www.w3.org/TR/cssom-view-1/#dom-window-innerwidth
  488. int Window::inner_width() const
  489. {
  490. // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar (if any),
  491. // or zero if there is no viewport.
  492. if (auto const* browsing_context = associated_document().browsing_context())
  493. return browsing_context->viewport_rect().width().value();
  494. return 0;
  495. }
  496. // https://www.w3.org/TR/cssom-view-1/#dom-window-innerheight
  497. int Window::inner_height() const
  498. {
  499. // The innerHeight attribute must return the viewport height including the size of a rendered scroll bar (if any),
  500. // or zero if there is no viewport.
  501. if (auto const* browsing_context = associated_document().browsing_context())
  502. return browsing_context->viewport_rect().height().value();
  503. return 0;
  504. }
  505. Page* Window::page()
  506. {
  507. return associated_document().page();
  508. }
  509. Page const* Window::page() const
  510. {
  511. return associated_document().page();
  512. }
  513. CSS::CSSStyleDeclaration* Window::get_computed_style_impl(DOM::Element& element) const
  514. {
  515. return CSS::ResolvedCSSStyleDeclaration::create(element).release_value_but_fixme_should_propagate_errors().ptr();
  516. }
  517. JS::NonnullGCPtr<CSS::MediaQueryList> Window::match_media_impl(DeprecatedString media)
  518. {
  519. auto media_query_list = CSS::MediaQueryList::create(associated_document(), parse_media_query_list(CSS::Parser::ParsingContext(associated_document()), media)).release_value_but_fixme_should_propagate_errors();
  520. associated_document().add_media_query_list(*media_query_list);
  521. return media_query_list;
  522. }
  523. Optional<CSS::MediaFeatureValue> Window::query_media_feature(CSS::MediaFeatureID media_feature) const
  524. {
  525. // FIXME: Many of these should be dependent on the hardware
  526. // https://www.w3.org/TR/mediaqueries-5/#media-descriptor-table
  527. switch (media_feature) {
  528. case CSS::MediaFeatureID::AnyHover:
  529. return CSS::MediaFeatureValue(CSS::ValueID::Hover);
  530. case CSS::MediaFeatureID::AnyPointer:
  531. return CSS::MediaFeatureValue(CSS::ValueID::Fine);
  532. case CSS::MediaFeatureID::AspectRatio:
  533. return CSS::MediaFeatureValue(CSS::Ratio(inner_width(), inner_height()));
  534. case CSS::MediaFeatureID::Color:
  535. return CSS::MediaFeatureValue(8);
  536. case CSS::MediaFeatureID::ColorGamut:
  537. return CSS::MediaFeatureValue(CSS::ValueID::Srgb);
  538. case CSS::MediaFeatureID::ColorIndex:
  539. return CSS::MediaFeatureValue(0);
  540. // FIXME: device-aspect-ratio
  541. case CSS::MediaFeatureID::DeviceHeight:
  542. if (auto* page = this->page()) {
  543. return CSS::MediaFeatureValue(CSS::Length::make_px(page->web_exposed_screen_area().height().value()));
  544. }
  545. return CSS::MediaFeatureValue(0);
  546. case CSS::MediaFeatureID::DeviceWidth:
  547. if (auto* page = this->page()) {
  548. return CSS::MediaFeatureValue(CSS::Length::make_px(page->web_exposed_screen_area().width().value()));
  549. }
  550. return CSS::MediaFeatureValue(0);
  551. case CSS::MediaFeatureID::DisplayMode:
  552. // FIXME: Detect if window is fullscreen
  553. return CSS::MediaFeatureValue(CSS::ValueID::Browser);
  554. case CSS::MediaFeatureID::DynamicRange:
  555. return CSS::MediaFeatureValue(CSS::ValueID::Standard);
  556. case CSS::MediaFeatureID::EnvironmentBlending:
  557. return CSS::MediaFeatureValue(CSS::ValueID::Opaque);
  558. case CSS::MediaFeatureID::ForcedColors:
  559. return CSS::MediaFeatureValue(CSS::ValueID::None);
  560. case CSS::MediaFeatureID::Grid:
  561. return CSS::MediaFeatureValue(0);
  562. case CSS::MediaFeatureID::Height:
  563. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_height()));
  564. case CSS::MediaFeatureID::HorizontalViewportSegments:
  565. return CSS::MediaFeatureValue(1);
  566. case CSS::MediaFeatureID::Hover:
  567. return CSS::MediaFeatureValue(CSS::ValueID::Hover);
  568. case CSS::MediaFeatureID::InvertedColors:
  569. return CSS::MediaFeatureValue(CSS::ValueID::None);
  570. case CSS::MediaFeatureID::Monochrome:
  571. return CSS::MediaFeatureValue(0);
  572. case CSS::MediaFeatureID::NavControls:
  573. return CSS::MediaFeatureValue(CSS::ValueID::Back);
  574. case CSS::MediaFeatureID::Orientation:
  575. return CSS::MediaFeatureValue(inner_height() >= inner_width() ? CSS::ValueID::Portrait : CSS::ValueID::Landscape);
  576. case CSS::MediaFeatureID::OverflowBlock:
  577. return CSS::MediaFeatureValue(CSS::ValueID::Scroll);
  578. case CSS::MediaFeatureID::OverflowInline:
  579. return CSS::MediaFeatureValue(CSS::ValueID::Scroll);
  580. case CSS::MediaFeatureID::Pointer:
  581. return CSS::MediaFeatureValue(CSS::ValueID::Fine);
  582. case CSS::MediaFeatureID::PrefersColorScheme: {
  583. if (auto* page = this->page()) {
  584. switch (page->preferred_color_scheme()) {
  585. case CSS::PreferredColorScheme::Light:
  586. return CSS::MediaFeatureValue(CSS::ValueID::Light);
  587. case CSS::PreferredColorScheme::Dark:
  588. return CSS::MediaFeatureValue(CSS::ValueID::Dark);
  589. case CSS::PreferredColorScheme::Auto:
  590. default:
  591. return CSS::MediaFeatureValue(page->palette().is_dark() ? CSS::ValueID::Dark : CSS::ValueID::Light);
  592. }
  593. }
  594. return CSS::MediaFeatureValue(CSS::ValueID::Light);
  595. }
  596. case CSS::MediaFeatureID::PrefersContrast:
  597. // FIXME: Make this a preference
  598. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  599. case CSS::MediaFeatureID::PrefersReducedData:
  600. // FIXME: Make this a preference
  601. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  602. case CSS::MediaFeatureID::PrefersReducedMotion:
  603. // FIXME: Make this a preference
  604. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  605. case CSS::MediaFeatureID::PrefersReducedTransparency:
  606. // FIXME: Make this a preference
  607. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  608. // FIXME: resolution
  609. case CSS::MediaFeatureID::Scan:
  610. return CSS::MediaFeatureValue(CSS::ValueID::Progressive);
  611. case CSS::MediaFeatureID::Scripting:
  612. if (associated_document().is_scripting_enabled())
  613. return CSS::MediaFeatureValue(CSS::ValueID::Enabled);
  614. return CSS::MediaFeatureValue(CSS::ValueID::None);
  615. case CSS::MediaFeatureID::Update:
  616. return CSS::MediaFeatureValue(CSS::ValueID::Fast);
  617. case CSS::MediaFeatureID::VerticalViewportSegments:
  618. return CSS::MediaFeatureValue(1);
  619. case CSS::MediaFeatureID::VideoColorGamut:
  620. return CSS::MediaFeatureValue(CSS::ValueID::Srgb);
  621. case CSS::MediaFeatureID::VideoDynamicRange:
  622. return CSS::MediaFeatureValue(CSS::ValueID::Standard);
  623. case CSS::MediaFeatureID::Width:
  624. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_width()));
  625. default:
  626. break;
  627. }
  628. return {};
  629. }
  630. // https://www.w3.org/TR/cssom-view/#dom-window-scrollx
  631. float Window::scroll_x() const
  632. {
  633. if (auto* page = this->page())
  634. return page->top_level_browsing_context().viewport_scroll_offset().x().value();
  635. return 0;
  636. }
  637. // https://www.w3.org/TR/cssom-view/#dom-window-scrolly
  638. float Window::scroll_y() const
  639. {
  640. if (auto* page = this->page())
  641. return page->top_level_browsing_context().viewport_scroll_offset().y().value();
  642. return 0;
  643. }
  644. // https://html.spec.whatwg.org/#fire-a-page-transition-event
  645. void Window::fire_a_page_transition_event(DeprecatedFlyString const& event_name, bool persisted)
  646. {
  647. // To fire a page transition event named eventName at a Window window with a boolean persisted,
  648. // fire an event named eventName at window, using PageTransitionEvent,
  649. // with the persisted attribute initialized to persisted,
  650. HTML::PageTransitionEventInit event_init {};
  651. event_init.persisted = persisted;
  652. auto event = HTML::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();
  653. // ...the cancelable attribute initialized to true,
  654. event->set_cancelable(true);
  655. // the bubbles attribute initialized to true,
  656. event->set_bubbles(true);
  657. // and legacy target override flag set.
  658. dispatch_event(event);
  659. }
  660. // https://html.spec.whatwg.org/#dom-queuemicrotask
  661. void Window::queue_microtask_impl(WebIDL::CallbackType& callback)
  662. {
  663. // The queueMicrotask(callback) method must queue a microtask to invoke callback,
  664. HTML::queue_a_microtask(&associated_document(), [this, &callback] {
  665. auto result = WebIDL::invoke_callback(callback, {});
  666. // and if callback throws an exception, report the exception.
  667. if (result.is_error())
  668. HTML::report_exception(result, realm());
  669. });
  670. }
  671. float Window::device_pixel_ratio() const
  672. {
  673. // FIXME: Return 2.0f if we're in HiDPI mode!
  674. return 1.0f;
  675. }
  676. // https://drafts.csswg.org/cssom-view/#dom-window-screenx
  677. int Window::screen_x() const
  678. {
  679. // The screenX and screenLeft attributes must return the x-coordinate, relative to the origin of the Web-exposed screen area,
  680. // of the left of the client window as number of CSS pixels, or zero if there is no such thing.
  681. if (auto* page = this->page())
  682. return page->window_position().x().value();
  683. return 0;
  684. }
  685. // https://drafts.csswg.org/cssom-view/#dom-window-screeny
  686. int Window::screen_y() const
  687. {
  688. // The screenY and screenTop attributes must return the y-coordinate, relative to the origin of the screen of the Web-exposed screen area,
  689. // of the top of the client window as number of CSS pixels, or zero if there is no such thing.
  690. if (auto* page = this->page())
  691. return page->window_position().y().value();
  692. return 0;
  693. }
  694. // https://drafts.csswg.org/cssom-view/#dom-window-outerwidth
  695. int Window::outer_width() const
  696. {
  697. // The outerWidth attribute must return the width of the client window. If there is no client window this attribute must return zero.
  698. if (auto* page = this->page())
  699. return page->window_size().width().value();
  700. return 0;
  701. }
  702. // https://drafts.csswg.org/cssom-view/#dom-window-screeny
  703. int Window::outer_height() const
  704. {
  705. // The outerHeight attribute must return the height of the client window. If there is no client window this attribute must return zero.
  706. if (auto* page = this->page())
  707. return page->window_size().height().value();
  708. return 0;
  709. }
  710. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-localstorage
  711. JS::NonnullGCPtr<HTML::Storage> Window::local_storage()
  712. {
  713. // FIXME: Implement according to spec.
  714. static HashMap<Origin, JS::Handle<HTML::Storage>> local_storage_per_origin;
  715. auto storage = local_storage_per_origin.ensure(associated_document().origin(), [this]() -> JS::Handle<HTML::Storage> {
  716. return *HTML::Storage::create(realm()).release_value_but_fixme_should_propagate_errors();
  717. });
  718. return *storage;
  719. }
  720. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-sessionstorage
  721. JS::NonnullGCPtr<HTML::Storage> Window::session_storage()
  722. {
  723. // FIXME: Implement according to spec.
  724. static HashMap<Origin, JS::Handle<HTML::Storage>> session_storage_per_origin;
  725. auto storage = session_storage_per_origin.ensure(associated_document().origin(), [this]() -> JS::Handle<HTML::Storage> {
  726. return *HTML::Storage::create(realm()).release_value_but_fixme_should_propagate_errors();
  727. });
  728. return *storage;
  729. }
  730. // https://html.spec.whatwg.org/multipage/browsers.html#dom-parent
  731. WindowProxy* Window::parent()
  732. {
  733. // 1. Let current be this Window object's browsing context.
  734. auto* current = browsing_context();
  735. // 2. If current is null, then return null.
  736. if (!current)
  737. return nullptr;
  738. // 3. If current is a child browsing context of another browsing context parent,
  739. // then return parent's WindowProxy object.
  740. if (current->parent()) {
  741. return current->parent()->window_proxy();
  742. }
  743. // 4. Assert: current is a top-level browsing context.
  744. VERIFY(current->is_top_level());
  745. // 5. Return current's WindowProxy object.
  746. return current->window_proxy();
  747. }
  748. // https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone
  749. WebIDL::ExceptionOr<JS::Value> Window::structured_clone_impl(JS::VM& vm, JS::Value message)
  750. {
  751. auto serialized = TRY(structured_serialize(vm, message));
  752. return MUST(structured_deserialize(vm, serialized, *vm.current_realm(), {}));
  753. }
  754. // https://html.spec.whatwg.org/multipage/interaction.html#transient-activation
  755. bool Window::has_transient_activation() const
  756. {
  757. // FIXME: Implement this.
  758. return false;
  759. }
  760. // https://w3c.github.io/requestidlecallback/#start-an-idle-period-algorithm
  761. void Window::start_an_idle_period()
  762. {
  763. // 1. Optionally, if the user agent determines the idle period should be delayed, return from this algorithm.
  764. // 2. Let pending_list be window's list of idle request callbacks.
  765. auto& pending_list = m_idle_request_callbacks;
  766. // 3. Let run_list be window's list of runnable idle callbacks.
  767. auto& run_list = m_runnable_idle_callbacks;
  768. run_list.extend(pending_list);
  769. // 4. Clear pending_list.
  770. pending_list.clear();
  771. // FIXME: This might not agree with the spec, but currently we use 100% CPU if we keep queueing tasks
  772. if (run_list.is_empty())
  773. return;
  774. // 5. Queue a task on the queue associated with the idle-task task source,
  775. // which performs the steps defined in the invoke idle callbacks algorithm with window and getDeadline as parameters.
  776. HTML::queue_global_task(HTML::Task::Source::IdleTask, *this, [this] {
  777. invoke_idle_callbacks();
  778. });
  779. }
  780. // https://w3c.github.io/requestidlecallback/#invoke-idle-callbacks-algorithm
  781. void Window::invoke_idle_callbacks()
  782. {
  783. auto& event_loop = main_thread_event_loop();
  784. // 1. If the user-agent believes it should end the idle period early due to newly scheduled high-priority work, return from the algorithm.
  785. // 2. Let now be the current time.
  786. auto now = HighResolutionTime::unsafe_shared_current_time();
  787. // 3. If now is less than the result of calling getDeadline and the window's list of runnable idle callbacks is not empty:
  788. if (now < event_loop.compute_deadline() && !m_runnable_idle_callbacks.is_empty()) {
  789. // 1. Pop the top callback from window's list of runnable idle callbacks.
  790. auto callback = m_runnable_idle_callbacks.take_first();
  791. // 2. Let deadlineArg be a new IdleDeadline whose [get deadline time algorithm] is getDeadline.
  792. auto deadline_arg = RequestIdleCallback::IdleDeadline::create(realm()).release_value_but_fixme_should_propagate_errors();
  793. // 3. Call callback with deadlineArg as its argument. If an uncaught runtime script error occurs, then report the exception.
  794. auto result = callback->invoke(deadline_arg);
  795. if (result.is_error())
  796. HTML::report_exception(result, realm());
  797. // 4. If window's list of runnable idle callbacks is not empty, queue a task which performs the steps
  798. // in the invoke idle callbacks algorithm with getDeadline and window as a parameters and return from this algorithm
  799. HTML::queue_global_task(HTML::Task::Source::IdleTask, *this, [this] {
  800. invoke_idle_callbacks();
  801. });
  802. }
  803. }
  804. // https://w3c.github.io/requestidlecallback/#the-requestidlecallback-method
  805. u32 Window::request_idle_callback_impl(WebIDL::CallbackType& callback)
  806. {
  807. // 1. Let window be this Window object.
  808. auto& window = *this;
  809. // 2. Increment the window's idle callback identifier by one.
  810. window.m_idle_callback_identifier++;
  811. // 3. Let handle be the current value of window's idle callback identifier.
  812. auto handle = window.m_idle_callback_identifier;
  813. // 4. Push callback to the end of window's list of idle request callbacks, associated with handle.
  814. auto handler = [callback = JS::make_handle(callback)](JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline> deadline) -> JS::Completion {
  815. return WebIDL::invoke_callback(const_cast<WebIDL::CallbackType&>(*callback), {}, deadline.ptr());
  816. };
  817. window.m_idle_request_callbacks.append(adopt_ref(*new IdleCallback(move(handler), handle)));
  818. // 5. Return handle and then continue running this algorithm asynchronously.
  819. return handle;
  820. // FIXME: 6. If the timeout property is present in options and has a positive value:
  821. // FIXME: 1. Wait for timeout milliseconds.
  822. // FIXME: 2. Wait until all invocations of this algorithm, whose timeout added to their posted time occurred before this one's, have completed.
  823. // FIXME: 3. Optionally, wait a further user-agent defined length of time.
  824. // 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.
  825. }
  826. // https://w3c.github.io/requestidlecallback/#the-cancelidlecallback-method
  827. void Window::cancel_idle_callback_impl(u32 handle)
  828. {
  829. // 1. Let window be this Window object.
  830. auto& window = *this;
  831. // 2. Find the entry in either the window's list of idle request callbacks or list of runnable idle callbacks
  832. // that is associated with the value handle.
  833. // 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.
  834. window.m_idle_request_callbacks.remove_first_matching([handle](auto& callback) {
  835. return callback->handle() == handle;
  836. });
  837. window.m_runnable_idle_callbacks.remove_first_matching([handle](auto& callback) {
  838. return callback->handle() == handle;
  839. });
  840. }
  841. void Window::set_associated_document(DOM::Document& document)
  842. {
  843. m_associated_document = &document;
  844. }
  845. void Window::set_current_event(DOM::Event* event)
  846. {
  847. m_current_event = event;
  848. }
  849. HTML::BrowsingContext const* Window::browsing_context() const
  850. {
  851. return m_associated_document->browsing_context();
  852. }
  853. HTML::BrowsingContext* Window::browsing_context()
  854. {
  855. return m_associated_document->browsing_context();
  856. }
  857. // https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-plugin-objects
  858. Vector<JS::NonnullGCPtr<Plugin>> Window::pdf_viewer_plugin_objects()
  859. {
  860. // 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.
  861. // Otherwise, it is a list containing five Plugin objects, whose names are, respectively:
  862. // 0. "PDF Viewer"
  863. // 1. "Chrome PDF Viewer"
  864. // 2. "Chromium PDF Viewer"
  865. // 3. "Microsoft Edge PDF Viewer"
  866. // 4. "WebKit built-in PDF"
  867. // 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
  868. VERIFY(page());
  869. if (!page()->pdf_viewer_supported())
  870. return {};
  871. if (m_pdf_viewer_plugin_objects.is_empty()) {
  872. // FIXME: Propagate errors.
  873. 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());
  874. 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());
  875. 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());
  876. 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());
  877. 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());
  878. }
  879. return m_pdf_viewer_plugin_objects;
  880. }
  881. // https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-mime-type-objects
  882. Vector<JS::NonnullGCPtr<MimeType>> Window::pdf_viewer_mime_type_objects()
  883. {
  884. // 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.
  885. // Otherwise, it is a list containing two MimeType objects, whose types are, respectively:
  886. // 0. "application/pdf"
  887. // 1. "text/pdf"
  888. // 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
  889. VERIFY(page());
  890. if (!page()->pdf_viewer_supported())
  891. return {};
  892. if (m_pdf_viewer_mime_type_objects.is_empty()) {
  893. 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());
  894. 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());
  895. }
  896. return m_pdf_viewer_mime_type_objects;
  897. }
  898. WebIDL::ExceptionOr<void> Window::initialize_web_interfaces(Badge<WindowEnvironmentSettingsObject>)
  899. {
  900. auto& realm = this->realm();
  901. add_window_exposed_interfaces(*this);
  902. Object::set_prototype(&Bindings::ensure_web_prototype<Bindings::WindowPrototype>(realm, "Window"));
  903. m_crypto = MUST_OR_THROW_OOM(heap().allocate<Crypto::Crypto>(realm, realm));
  904. m_location = MUST_OR_THROW_OOM(heap().allocate<Location>(realm, realm));
  905. m_navigator = MUST_OR_THROW_OOM(heap().allocate<Navigator>(realm, realm));
  906. MUST_OR_THROW_OOM(Bindings::WindowGlobalMixin::initialize(realm, *this));
  907. // FIXME: These should be native accessors, not properties
  908. define_native_accessor(realm, "top", top_getter, nullptr, JS::Attribute::Enumerable);
  909. define_native_accessor(realm, "parent", parent_getter, {}, JS::Attribute::Enumerable);
  910. define_native_accessor(realm, "frameElement", frame_element_getter, {}, JS::Attribute::Enumerable);
  911. define_native_accessor(realm, "history", history_getter, {}, JS::Attribute::Enumerable);
  912. define_native_accessor(realm, "performance", performance_getter, performance_setter, JS::Attribute::Enumerable | JS::Attribute::Configurable);
  913. define_native_accessor(realm, "crypto", crypto_getter, {}, JS::Attribute::Enumerable);
  914. define_native_accessor(realm, "screen", screen_getter, screen_setter, JS::Attribute::Enumerable | JS::Attribute::Configurable);
  915. define_native_accessor(realm, "innerWidth", inner_width_getter, {}, JS::Attribute::Enumerable);
  916. define_native_accessor(realm, "innerHeight", inner_height_getter, {}, JS::Attribute::Enumerable);
  917. define_native_accessor(realm, "devicePixelRatio", device_pixel_ratio_getter, {}, JS::Attribute::Enumerable | JS::Attribute::Configurable);
  918. u8 attr = JS::Attribute::Writable | JS::Attribute::Enumerable | JS::Attribute::Configurable;
  919. define_native_function(realm, "open", open, 0, attr);
  920. define_native_function(realm, "setInterval", set_interval, 1, attr);
  921. define_native_function(realm, "setTimeout", set_timeout, 1, attr);
  922. define_native_function(realm, "clearInterval", clear_interval, 1, attr);
  923. define_native_function(realm, "clearTimeout", clear_timeout, 1, attr);
  924. define_native_function(realm, "requestAnimationFrame", request_animation_frame, 1, attr);
  925. define_native_function(realm, "cancelAnimationFrame", cancel_animation_frame, 1, attr);
  926. define_native_function(realm, "atob", atob, 1, attr);
  927. define_native_function(realm, "btoa", btoa, 1, attr);
  928. define_native_function(realm, "focus", focus, 0, attr);
  929. define_native_function(realm, "queueMicrotask", queue_microtask, 1, attr);
  930. define_native_function(realm, "requestIdleCallback", request_idle_callback, 1, attr);
  931. define_native_function(realm, "cancelIdleCallback", cancel_idle_callback, 1, attr);
  932. define_native_function(realm, "getComputedStyle", get_computed_style, 1, attr);
  933. define_native_function(realm, "matchMedia", match_media, 1, attr);
  934. define_native_function(realm, "getSelection", get_selection, 0, attr);
  935. define_native_function(realm, "structuredClone", structured_clone, 1, attr);
  936. define_native_function(realm, "fetch", Bindings::fetch, 1, attr);
  937. // FIXME: These properties should be [Replaceable] according to the spec, but [Writable+Configurable] is the closest we have.
  938. define_native_accessor(realm, "scrollX", scroll_x_getter, {}, attr);
  939. define_native_accessor(realm, "pageXOffset", scroll_x_getter, {}, attr);
  940. define_native_accessor(realm, "scrollY", scroll_y_getter, {}, attr);
  941. define_native_accessor(realm, "pageYOffset", scroll_y_getter, {}, attr);
  942. define_native_accessor(realm, "length", length_getter, {}, attr);
  943. define_native_function(realm, "scroll", scroll, 2, attr);
  944. define_native_function(realm, "scrollTo", scroll, 2, attr);
  945. define_native_function(realm, "scrollBy", scroll_by, 2, attr);
  946. define_native_accessor(realm, "screenX", screen_x_getter, {}, attr);
  947. define_native_accessor(realm, "screenY", screen_y_getter, {}, attr);
  948. define_native_accessor(realm, "screenLeft", screen_left_getter, {}, attr);
  949. define_native_accessor(realm, "screenTop", screen_top_getter, {}, attr);
  950. define_native_accessor(realm, "outerWidth", outer_width_getter, {}, attr);
  951. define_native_accessor(realm, "outerHeight", outer_height_getter, {}, attr);
  952. define_direct_property("CSS", MUST_OR_THROW_OOM(heap().allocate<Bindings::CSSNamespace>(realm, realm)), 0);
  953. define_native_accessor(realm, "localStorage", local_storage_getter, {}, attr);
  954. define_native_accessor(realm, "sessionStorage", session_storage_getter, {}, attr);
  955. define_native_accessor(realm, "origin", origin_getter, {}, attr);
  956. define_native_accessor(realm, "isSecureContext", is_secure_context_getter, {}, attr);
  957. // Legacy
  958. define_native_accessor(realm, "event", event_getter, event_setter, JS::Attribute::Enumerable);
  959. // NOTE: location is marked as [LegacyUnforgeable], meaning it isn't configurable.
  960. define_native_accessor(realm, "location", location_getter, location_setter, JS::Attribute::Enumerable);
  961. // WebAssembly "namespace"
  962. define_direct_property("WebAssembly", MUST_OR_THROW_OOM(heap().allocate<Bindings::WebAssemblyObject>(realm, realm)), JS::Attribute::Enumerable | JS::Attribute::Configurable);
  963. return {};
  964. }
  965. HTML::Origin Window::origin() const
  966. {
  967. return associated_document().origin();
  968. }
  969. // https://webidl.spec.whatwg.org/#platform-object-setprototypeof
  970. JS::ThrowCompletionOr<bool> Window::internal_set_prototype_of(JS::Object* prototype)
  971. {
  972. // 1. Return ? SetImmutablePrototype(O, V).
  973. return set_immutable_prototype(prototype);
  974. }
  975. static JS::ThrowCompletionOr<HTML::Window*> impl_from(JS::VM& vm)
  976. {
  977. // Since this is a non built-in function we must treat it as non-strict mode
  978. // this means that a nullish this_value should be converted to the
  979. // global_object. Generally this does not matter as we try to convert the
  980. // this_value to a specific object type in the bindings. But since window is
  981. // the global object we make an exception here.
  982. // This allows calls like `setTimeout(f, 10)` to work.
  983. auto this_value = vm.this_value();
  984. if (this_value.is_nullish())
  985. this_value = &vm.current_realm()->global_object();
  986. auto* this_object = MUST(this_value.to_object(vm));
  987. if (is<WindowProxy>(*this_object))
  988. return static_cast<WindowProxy*>(this_object)->window().ptr();
  989. if (is<Window>(*this_object))
  990. return static_cast<Window*>(this_object);
  991. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Window");
  992. }
  993. // https://html.spec.whatwg.org/multipage/window-object.html#dom-window
  994. JS::NonnullGCPtr<WindowProxy> Window::window() const
  995. {
  996. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  997. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  998. }
  999. // https://html.spec.whatwg.org/multipage/window-object.html#dom-self
  1000. JS::NonnullGCPtr<WindowProxy> Window::self() const
  1001. {
  1002. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  1003. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  1004. }
  1005. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-document-2
  1006. JS::NonnullGCPtr<DOM::Document const> Window::document() const
  1007. {
  1008. // The document getter steps are to return this's associated Document.
  1009. return associated_document();
  1010. }
  1011. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#dom-name
  1012. String Window::name() const
  1013. {
  1014. // 1. If this's navigable is null, then return the empty string.
  1015. if (!browsing_context())
  1016. return String {};
  1017. // 2. Return this's navigable's target name.
  1018. return String::from_deprecated_string(browsing_context()->name()).release_value_but_fixme_should_propagate_errors();
  1019. }
  1020. // https://html.spec.whatwg.org/multipage/nav-history-apis.html#apis-for-creating-and-navigating-browsing-contexts-by-name:dom-name
  1021. void Window::set_name(String const& name)
  1022. {
  1023. // 1. If this's navigable is null, then return.
  1024. if (!browsing_context())
  1025. return;
  1026. // 2. Set this's navigable's active session history entry's document state's navigable target name to the given value.
  1027. browsing_context()->set_name(name.to_deprecated_string());
  1028. }
  1029. // https://html.spec.whatwg.org/multipage/window-object.html#dom-frames
  1030. JS::NonnullGCPtr<WindowProxy> Window::frames() const
  1031. {
  1032. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  1033. return verify_cast<WindowProxy>(relevant_realm(*this).global_environment().global_this_value());
  1034. }
  1035. // https://html.spec.whatwg.org/multipage/system-state.html#dom-navigator
  1036. JS::NonnullGCPtr<Navigator> Window::navigator() const
  1037. {
  1038. // The navigator and clientInformation getter steps are to return this's associated Navigator.
  1039. return *m_navigator;
  1040. }
  1041. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-alert
  1042. void Window::alert(String const& message)
  1043. {
  1044. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#simple-dialogs
  1045. // Note: This method is defined using two overloads, instead of using an optional argument,
  1046. // for historical reasons. The practical impact of this is that alert(undefined) is
  1047. // treated as alert("undefined"), but alert() is treated as alert("").
  1048. // FIXME: Make this fully spec compliant.
  1049. if (auto* page = this->page())
  1050. page->did_request_alert(message.to_deprecated_string());
  1051. }
  1052. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-confirm
  1053. bool Window::confirm(Optional<String> const& message)
  1054. {
  1055. // FIXME: Make this fully spec compliant.
  1056. // NOTE: `message` has an IDL-provided default value and is never empty.
  1057. if (auto* page = this->page())
  1058. return page->did_request_confirm(message->to_deprecated_string());
  1059. return false;
  1060. }
  1061. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-prompt
  1062. Optional<String> Window::prompt(Optional<String> const& message, Optional<String> const& default_)
  1063. {
  1064. // FIXME: Make this fully spec compliant.
  1065. if (auto* page = this->page()) {
  1066. auto response = page->did_request_prompt(message->to_deprecated_string(), default_->to_deprecated_string());
  1067. if (response.is_null())
  1068. return {};
  1069. return String::from_deprecated_string(response).release_value_but_fixme_should_propagate_errors();
  1070. }
  1071. return {};
  1072. }
  1073. // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-window-postmessage
  1074. void Window::post_message(JS::Value message, String const&)
  1075. {
  1076. // FIXME: This is an ad-hoc hack implementation instead, since we don't currently
  1077. // have serialization and deserialization of messages.
  1078. HTML::queue_global_task(HTML::Task::Source::PostedMessage, *this, [this, message] {
  1079. HTML::MessageEventInit event_init {};
  1080. event_init.data = message;
  1081. event_init.origin = "<origin>"_string.release_value_but_fixme_should_propagate_errors();
  1082. dispatch_event(HTML::MessageEvent::create(realm(), String::from_deprecated_string(HTML::EventNames::message).release_value_but_fixme_should_propagate_errors(), event_init).release_value_but_fixme_should_propagate_errors());
  1083. });
  1084. }
  1085. JS_DEFINE_NATIVE_FUNCTION(Window::open)
  1086. {
  1087. auto* impl = TRY(impl_from(vm));
  1088. // optional USVString url = ""
  1089. DeprecatedString url = "";
  1090. if (!vm.argument(0).is_undefined())
  1091. url = TRY(vm.argument(0).to_deprecated_string(vm));
  1092. // optional DOMString target = "_blank"
  1093. DeprecatedString target = "_blank";
  1094. if (!vm.argument(1).is_undefined())
  1095. target = TRY(vm.argument(1).to_deprecated_string(vm));
  1096. // optional [LegacyNullToEmptyString] DOMString features = "")
  1097. DeprecatedString features = "";
  1098. if (!vm.argument(2).is_nullish())
  1099. features = TRY(vm.argument(2).to_deprecated_string(vm));
  1100. return TRY(Bindings::throw_dom_exception_if_needed(vm, [&] { return impl->open_impl(url, target, features); }));
  1101. }
  1102. static JS::ThrowCompletionOr<TimerHandler> make_timer_handler(JS::VM& vm, JS::Value handler)
  1103. {
  1104. if (handler.is_function())
  1105. return JS::make_handle(vm.heap().allocate_without_realm<WebIDL::CallbackType>(handler.as_function(), HTML::incumbent_settings_object()));
  1106. return TRY(handler.to_deprecated_string(vm));
  1107. }
  1108. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  1109. JS_DEFINE_NATIVE_FUNCTION(Window::set_timeout)
  1110. {
  1111. auto* impl = TRY(impl_from(vm));
  1112. if (!vm.argument_count())
  1113. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountAtLeastOne, "setTimeout");
  1114. auto handler = TRY(make_timer_handler(vm, vm.argument(0)));
  1115. i32 timeout = 0;
  1116. if (vm.argument_count() >= 2)
  1117. timeout = TRY(vm.argument(1).to_i32(vm));
  1118. JS::MarkedVector<JS::Value> arguments { vm.heap() };
  1119. for (size_t i = 2; i < vm.argument_count(); ++i)
  1120. arguments.append(vm.argument(i));
  1121. auto id = impl->set_timeout_impl(move(handler), timeout, move(arguments));
  1122. return JS::Value(id);
  1123. }
  1124. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  1125. JS_DEFINE_NATIVE_FUNCTION(Window::set_interval)
  1126. {
  1127. auto* impl = TRY(impl_from(vm));
  1128. if (!vm.argument_count())
  1129. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountAtLeastOne, "setInterval");
  1130. auto handler = TRY(make_timer_handler(vm, vm.argument(0)));
  1131. i32 timeout = 0;
  1132. if (vm.argument_count() >= 2)
  1133. timeout = TRY(vm.argument(1).to_i32(vm));
  1134. JS::MarkedVector<JS::Value> arguments { vm.heap() };
  1135. for (size_t i = 2; i < vm.argument_count(); ++i)
  1136. arguments.append(vm.argument(i));
  1137. auto id = impl->set_interval_impl(move(handler), timeout, move(arguments));
  1138. return JS::Value(id);
  1139. }
  1140. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeout
  1141. JS_DEFINE_NATIVE_FUNCTION(Window::clear_timeout)
  1142. {
  1143. auto* impl = TRY(impl_from(vm));
  1144. i32 id = 0;
  1145. if (vm.argument_count())
  1146. id = TRY(vm.argument(0).to_i32(vm));
  1147. impl->clear_timeout_impl(id);
  1148. return JS::js_undefined();
  1149. }
  1150. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-clearinterval
  1151. JS_DEFINE_NATIVE_FUNCTION(Window::clear_interval)
  1152. {
  1153. auto* impl = TRY(impl_from(vm));
  1154. i32 id = 0;
  1155. if (vm.argument_count())
  1156. id = TRY(vm.argument(0).to_i32(vm));
  1157. impl->clear_interval_impl(id);
  1158. return JS::js_undefined();
  1159. }
  1160. JS_DEFINE_NATIVE_FUNCTION(Window::request_animation_frame)
  1161. {
  1162. auto* impl = TRY(impl_from(vm));
  1163. if (!vm.argument_count())
  1164. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "requestAnimationFrame");
  1165. auto* callback_object = TRY(vm.argument(0).to_object(vm));
  1166. if (!callback_object->is_function())
  1167. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam);
  1168. auto callback = vm.heap().allocate_without_realm<WebIDL::CallbackType>(*callback_object, HTML::incumbent_settings_object());
  1169. return JS::Value(impl->request_animation_frame_impl(*callback));
  1170. }
  1171. JS_DEFINE_NATIVE_FUNCTION(Window::cancel_animation_frame)
  1172. {
  1173. auto* impl = TRY(impl_from(vm));
  1174. if (!vm.argument_count())
  1175. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "cancelAnimationFrame");
  1176. auto id = TRY(vm.argument(0).to_i32(vm));
  1177. impl->cancel_animation_frame_impl(id);
  1178. return JS::js_undefined();
  1179. }
  1180. JS_DEFINE_NATIVE_FUNCTION(Window::queue_microtask)
  1181. {
  1182. auto* impl = TRY(impl_from(vm));
  1183. if (!vm.argument_count())
  1184. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountAtLeastOne, "queueMicrotask");
  1185. auto* callback_object = TRY(vm.argument(0).to_object(vm));
  1186. if (!callback_object->is_function())
  1187. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam);
  1188. auto callback = vm.heap().allocate_without_realm<WebIDL::CallbackType>(*callback_object, HTML::incumbent_settings_object());
  1189. impl->queue_microtask_impl(*callback);
  1190. return JS::js_undefined();
  1191. }
  1192. JS_DEFINE_NATIVE_FUNCTION(Window::request_idle_callback)
  1193. {
  1194. auto* impl = TRY(impl_from(vm));
  1195. if (!vm.argument_count())
  1196. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountAtLeastOne, "requestIdleCallback");
  1197. auto* callback_object = TRY(vm.argument(0).to_object(vm));
  1198. if (!callback_object->is_function())
  1199. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam);
  1200. // FIXME: accept options object
  1201. auto callback = vm.heap().allocate_without_realm<WebIDL::CallbackType>(*callback_object, HTML::incumbent_settings_object());
  1202. return JS::Value(impl->request_idle_callback_impl(*callback));
  1203. }
  1204. JS_DEFINE_NATIVE_FUNCTION(Window::cancel_idle_callback)
  1205. {
  1206. auto* impl = TRY(impl_from(vm));
  1207. if (!vm.argument_count())
  1208. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "cancelIdleCallback");
  1209. auto id = TRY(vm.argument(0).to_u32(vm));
  1210. impl->cancel_idle_callback_impl(id);
  1211. return JS::js_undefined();
  1212. }
  1213. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob-dev
  1214. JS_DEFINE_NATIVE_FUNCTION(Window::atob)
  1215. {
  1216. if (!vm.argument_count())
  1217. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "atob");
  1218. auto deprecated_string = TRY(vm.argument(0).to_deprecated_string(vm));
  1219. auto string = String::from_utf8(deprecated_string).release_value_but_fixme_should_propagate_errors();
  1220. // must throw an "InvalidCharacterError" DOMException if data contains any character whose code point is greater than U+00FF
  1221. for (auto code_point : string.code_points()) {
  1222. if (code_point > 0x00FF)
  1223. return throw_completion(WebIDL::InvalidCharacterError::create(*vm.current_realm(), "Data contains characters outside the range U+0000 and U+00FF"));
  1224. }
  1225. // Otherwise, the user agent must convert data to a byte sequence whose nth byte is the eight-bit representation of the nth code point of data
  1226. // and then must apply forgiving-base64 encode to that byte sequence and return the result.
  1227. auto decoded = Infra::decode_forgiving_base64(StringView(deprecated_string));
  1228. if (decoded.is_error())
  1229. return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidFormat, "Base64");
  1230. // The bytes object might contain bytes greater than 128, encode them in UTF8
  1231. // NOTE: Any 8-bit encoding -> utf-8 decoder will work for this
  1232. auto text_decoder = TextCodec::decoder_for("windows-1252"sv);
  1233. VERIFY(text_decoder.has_value());
  1234. auto text = TRY_OR_THROW_OOM(vm, text_decoder->to_utf8(decoded.release_value()));
  1235. return JS::PrimitiveString::create(vm, text);
  1236. }
  1237. JS_DEFINE_NATIVE_FUNCTION(Window::btoa)
  1238. {
  1239. if (!vm.argument_count())
  1240. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "btoa");
  1241. auto string = TRY(vm.argument(0).to_deprecated_string(vm));
  1242. Vector<u8> byte_string;
  1243. byte_string.ensure_capacity(string.length());
  1244. for (u32 code_point : Utf8View(string)) {
  1245. if (code_point > 0xff)
  1246. return throw_completion(WebIDL::InvalidCharacterError::create(*vm.current_realm(), "Data contains characters outside the range U+0000 and U+00FF"));
  1247. byte_string.append(code_point);
  1248. }
  1249. auto encoded = MUST(encode_base64(byte_string.span()));
  1250. return JS::PrimitiveString::create(vm, encoded.to_deprecated_string());
  1251. }
  1252. // https://html.spec.whatwg.org/multipage/interaction.html#dom-window-focus
  1253. JS_DEFINE_NATIVE_FUNCTION(Window::focus)
  1254. {
  1255. auto* impl = TRY(impl_from(vm));
  1256. // 1. Let current be this Window object's browsing context.
  1257. auto* current = impl->browsing_context();
  1258. // 2. If current is null, then return.
  1259. if (!current)
  1260. return JS::js_undefined();
  1261. // 3. Run the focusing steps with current.
  1262. // FIXME: We should pass in the browsing context itself instead of the active document, however the focusing steps don't currently accept browsing contexts.
  1263. // Passing in a browsing context always makes it resolve to its active document for focus, so this is fine for now.
  1264. run_focusing_steps(current->active_document());
  1265. // FIXME: 4. If current is a top-level browsing context, user agents are encouraged to trigger some sort of notification to indicate to the user that the page is attempting to gain focus.
  1266. return JS::js_undefined();
  1267. }
  1268. // https://html.spec.whatwg.org/multipage/window-object.html#number-of-document-tree-child-browsing-contexts
  1269. JS::ThrowCompletionOr<size_t> Window::document_tree_child_browsing_context_count() const
  1270. {
  1271. // 1. If W's browsing context is null, then return 0.
  1272. auto* this_browsing_context = associated_document().browsing_context();
  1273. if (!this_browsing_context)
  1274. return 0;
  1275. // 2. Return the number of document-tree child browsing contexts of W's browsing context.
  1276. return this_browsing_context->document_tree_child_browsing_context_count();
  1277. }
  1278. // https://html.spec.whatwg.org/multipage/window-object.html#dom-length
  1279. JS_DEFINE_NATIVE_FUNCTION(Window::length_getter)
  1280. {
  1281. auto* impl = TRY(impl_from(vm));
  1282. // The length getter steps are to return the number of document-tree child browsing contexts of this.
  1283. return TRY(impl->document_tree_child_browsing_context_count());
  1284. }
  1285. // https://html.spec.whatwg.org/multipage/browsers.html#dom-top
  1286. JS_DEFINE_NATIVE_FUNCTION(Window::top_getter)
  1287. {
  1288. auto* impl = TRY(impl_from(vm));
  1289. // 1. If this Window object's browsing context is null, then return null.
  1290. auto* browsing_context = impl->browsing_context();
  1291. if (!browsing_context)
  1292. return JS::js_null();
  1293. // 2. Return this Window object's browsing context's top-level browsing context's WindowProxy object.
  1294. return browsing_context->top_level_browsing_context().window_proxy();
  1295. }
  1296. JS_DEFINE_NATIVE_FUNCTION(Window::parent_getter)
  1297. {
  1298. auto* impl = TRY(impl_from(vm));
  1299. auto* parent = impl->parent();
  1300. if (!parent)
  1301. return JS::js_null();
  1302. return parent;
  1303. }
  1304. // https://html.spec.whatwg.org/multipage/browsers.html#dom-frameelement
  1305. JS_DEFINE_NATIVE_FUNCTION(Window::frame_element_getter)
  1306. {
  1307. auto* impl = TRY(impl_from(vm));
  1308. // 1. Let current be this Window object's browsing context.
  1309. auto* current = impl->browsing_context();
  1310. // 2. If current is null, then return null.
  1311. if (!current)
  1312. return JS::js_null();
  1313. // 3. Let container be current's container.
  1314. auto* container = current->container();
  1315. // 4. If container is null, then return null.
  1316. if (!container)
  1317. return JS::js_null();
  1318. // 5. If container's node document's origin is not same origin-domain with the current settings object's origin, then return null.
  1319. if (!container->document().origin().is_same_origin(current_settings_object().origin()))
  1320. return JS::js_null();
  1321. // 6. Return container.
  1322. return container;
  1323. }
  1324. JS_DEFINE_NATIVE_FUNCTION(Window::performance_getter)
  1325. {
  1326. auto* impl = TRY(impl_from(vm));
  1327. return &impl->performance();
  1328. }
  1329. JS_DEFINE_NATIVE_FUNCTION(Window::performance_setter)
  1330. {
  1331. // https://webidl.spec.whatwg.org/#dfn-attribute-setter
  1332. // 4.1. If no arguments were passed, then throw a TypeError.
  1333. if (vm.argument_count() == 0)
  1334. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "set performance");
  1335. auto* impl = TRY(impl_from(vm));
  1336. // 5. If attribute is declared with the [Replaceable] extended attribute, then:
  1337. // 1. Perform ? CreateDataProperty(esValue, id, V).
  1338. TRY(impl->create_data_property("performance", vm.argument(0)));
  1339. // 2. Return undefined.
  1340. return JS::js_undefined();
  1341. }
  1342. JS_DEFINE_NATIVE_FUNCTION(Window::screen_getter)
  1343. {
  1344. auto* impl = TRY(impl_from(vm));
  1345. return &impl->screen();
  1346. }
  1347. JS_DEFINE_NATIVE_FUNCTION(Window::screen_setter)
  1348. {
  1349. REPLACEABLE_PROPERTY_SETTER(Window, screen);
  1350. }
  1351. JS_DEFINE_NATIVE_FUNCTION(Window::event_getter)
  1352. {
  1353. auto* impl = TRY(impl_from(vm));
  1354. if (!impl->current_event())
  1355. return JS::js_undefined();
  1356. return impl->current_event();
  1357. }
  1358. JS_DEFINE_NATIVE_FUNCTION(Window::event_setter)
  1359. {
  1360. REPLACEABLE_PROPERTY_SETTER(Window, event);
  1361. }
  1362. JS_DEFINE_NATIVE_FUNCTION(Window::location_getter)
  1363. {
  1364. auto* impl = TRY(impl_from(vm));
  1365. return impl->m_location;
  1366. }
  1367. JS_DEFINE_NATIVE_FUNCTION(Window::location_setter)
  1368. {
  1369. auto* impl = TRY(impl_from(vm));
  1370. TRY(impl->m_location->set(JS::PropertyKey("href"), vm.argument(0), JS::Object::ShouldThrowExceptions::Yes));
  1371. return JS::js_undefined();
  1372. }
  1373. JS_DEFINE_NATIVE_FUNCTION(Window::crypto_getter)
  1374. {
  1375. auto* impl = TRY(impl_from(vm));
  1376. return &impl->crypto();
  1377. }
  1378. JS_DEFINE_NATIVE_FUNCTION(Window::inner_width_getter)
  1379. {
  1380. auto* impl = TRY(impl_from(vm));
  1381. return JS::Value(impl->inner_width());
  1382. }
  1383. JS_DEFINE_NATIVE_FUNCTION(Window::inner_height_getter)
  1384. {
  1385. auto* impl = TRY(impl_from(vm));
  1386. return JS::Value(impl->inner_height());
  1387. }
  1388. JS_DEFINE_NATIVE_FUNCTION(Window::device_pixel_ratio_getter)
  1389. {
  1390. auto* impl = TRY(impl_from(vm));
  1391. return JS::Value(impl->device_pixel_ratio());
  1392. }
  1393. JS_DEFINE_NATIVE_FUNCTION(Window::get_computed_style)
  1394. {
  1395. auto* impl = TRY(impl_from(vm));
  1396. auto* object = TRY(vm.argument(0).to_object(vm));
  1397. if (!is<DOM::Element>(object))
  1398. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "DOM element");
  1399. return impl->get_computed_style_impl(*static_cast<DOM::Element*>(object));
  1400. }
  1401. // https://w3c.github.io/selection-api/#dom-window-getselection
  1402. JS_DEFINE_NATIVE_FUNCTION(Window::get_selection)
  1403. {
  1404. // The method must invoke and return the result of getSelection() on this's Window.document attribute.
  1405. auto* impl = TRY(impl_from(vm));
  1406. return impl->associated_document().get_selection();
  1407. }
  1408. JS_DEFINE_NATIVE_FUNCTION(Window::match_media)
  1409. {
  1410. auto* impl = TRY(impl_from(vm));
  1411. auto media = TRY(vm.argument(0).to_deprecated_string(vm));
  1412. return impl->match_media_impl(move(media));
  1413. }
  1414. // https://www.w3.org/TR/cssom-view/#dom-window-scrollx
  1415. JS_DEFINE_NATIVE_FUNCTION(Window::scroll_x_getter)
  1416. {
  1417. auto* impl = TRY(impl_from(vm));
  1418. return JS::Value(impl->scroll_x());
  1419. }
  1420. // https://www.w3.org/TR/cssom-view/#dom-window-scrolly
  1421. JS_DEFINE_NATIVE_FUNCTION(Window::scroll_y_getter)
  1422. {
  1423. auto* impl = TRY(impl_from(vm));
  1424. return JS::Value(impl->scroll_y());
  1425. }
  1426. enum class ScrollBehavior {
  1427. Auto,
  1428. Smooth
  1429. };
  1430. // https://www.w3.org/TR/cssom-view/#perform-a-scroll
  1431. static void perform_a_scroll(Page& page, double x, double y, ScrollBehavior)
  1432. {
  1433. // FIXME: Stop any existing smooth-scrolls
  1434. // FIXME: Implement smooth-scroll
  1435. page.client().page_did_request_scroll_to({ x, y });
  1436. }
  1437. // https://www.w3.org/TR/cssom-view/#dom-window-scroll
  1438. JS_DEFINE_NATIVE_FUNCTION(Window::scroll)
  1439. {
  1440. auto* impl = TRY(impl_from(vm));
  1441. if (!impl->page())
  1442. return JS::js_undefined();
  1443. auto& page = *impl->page();
  1444. auto viewport_rect = page.top_level_browsing_context().viewport_rect().to_type<float>();
  1445. auto x_value = JS::Value(viewport_rect.x());
  1446. auto y_value = JS::Value(viewport_rect.y());
  1447. DeprecatedString behavior_string = "auto";
  1448. if (vm.argument_count() == 1) {
  1449. auto* options = TRY(vm.argument(0).to_object(vm));
  1450. auto left = TRY(options->get("left"));
  1451. if (!left.is_undefined())
  1452. x_value = left;
  1453. auto top = TRY(options->get("top"));
  1454. if (!top.is_undefined())
  1455. y_value = top;
  1456. auto behavior_string_value = TRY(options->get("behavior"));
  1457. if (!behavior_string_value.is_undefined())
  1458. behavior_string = TRY(behavior_string_value.to_deprecated_string(vm));
  1459. if (behavior_string != "smooth" && behavior_string != "auto")
  1460. return vm.throw_completion<JS::TypeError>("Behavior is not one of 'smooth' or 'auto'"sv);
  1461. } else if (vm.argument_count() >= 2) {
  1462. // We ignore arguments 2+ in line with behavior of Chrome and Firefox
  1463. x_value = vm.argument(0);
  1464. y_value = vm.argument(1);
  1465. }
  1466. ScrollBehavior behavior = (behavior_string == "smooth") ? ScrollBehavior::Smooth : ScrollBehavior::Auto;
  1467. double x = TRY(x_value.to_double(vm));
  1468. x = JS::Value(x).is_finite_number() ? x : 0.0;
  1469. double y = TRY(y_value.to_double(vm));
  1470. y = JS::Value(y).is_finite_number() ? y : 0.0;
  1471. // FIXME: Are we calculating the viewport in the way this function expects?
  1472. // FIXME: Handle overflow-directions other than top-left to bottom-right
  1473. perform_a_scroll(page, x, y, behavior);
  1474. return JS::js_undefined();
  1475. }
  1476. // https://www.w3.org/TR/cssom-view/#dom-window-scrollby
  1477. JS_DEFINE_NATIVE_FUNCTION(Window::scroll_by)
  1478. {
  1479. auto& realm = *vm.current_realm();
  1480. auto* impl = TRY(impl_from(vm));
  1481. if (!impl->page())
  1482. return JS::js_undefined();
  1483. auto& page = *impl->page();
  1484. JS::Object* options = nullptr;
  1485. if (vm.argument_count() == 0) {
  1486. options = JS::Object::create(realm, nullptr);
  1487. } else if (vm.argument_count() == 1) {
  1488. options = TRY(vm.argument(0).to_object(vm));
  1489. } else if (vm.argument_count() >= 2) {
  1490. // We ignore arguments 2+ in line with behavior of Chrome and Firefox
  1491. options = JS::Object::create(realm, nullptr);
  1492. MUST(options->set("left", vm.argument(0), ShouldThrowExceptions::No));
  1493. MUST(options->set("top", vm.argument(1), ShouldThrowExceptions::No));
  1494. MUST(options->set("behavior", MUST_OR_THROW_OOM(JS::PrimitiveString::create(vm, "auto"sv)), ShouldThrowExceptions::No));
  1495. }
  1496. auto left_value = TRY(options->get("left"));
  1497. auto left = TRY(left_value.to_double(vm));
  1498. auto top_value = TRY(options->get("top"));
  1499. auto top = TRY(top_value.to_double(vm));
  1500. left = JS::Value(left).is_finite_number() ? left : 0.0;
  1501. top = JS::Value(top).is_finite_number() ? top : 0.0;
  1502. auto current_scroll_position = page.top_level_browsing_context().viewport_scroll_offset().to_type<float>();
  1503. left = left + static_cast<double>(current_scroll_position.x());
  1504. top = top + static_cast<double>(current_scroll_position.y());
  1505. auto behavior_string_value = TRY(options->get("behavior"));
  1506. auto behavior_string = behavior_string_value.is_undefined() ? "auto" : TRY(behavior_string_value.to_deprecated_string(vm));
  1507. if (behavior_string != "smooth" && behavior_string != "auto")
  1508. return vm.throw_completion<JS::TypeError>("Behavior is not one of 'smooth' or 'auto'"sv);
  1509. ScrollBehavior behavior = (behavior_string == "smooth") ? ScrollBehavior::Smooth : ScrollBehavior::Auto;
  1510. // FIXME: Spec wants us to call scroll(options) here.
  1511. // The only difference is that would invoke the viewport calculations that scroll()
  1512. // is not actually doing yet, so this is the same for now.
  1513. perform_a_scroll(page, left, top, behavior);
  1514. return JS::js_undefined();
  1515. }
  1516. JS_DEFINE_NATIVE_FUNCTION(Window::history_getter)
  1517. {
  1518. auto* impl = TRY(impl_from(vm));
  1519. return impl->associated_document().history();
  1520. }
  1521. JS_DEFINE_NATIVE_FUNCTION(Window::screen_left_getter)
  1522. {
  1523. auto* impl = TRY(impl_from(vm));
  1524. return JS::Value(impl->screen_x());
  1525. }
  1526. JS_DEFINE_NATIVE_FUNCTION(Window::screen_top_getter)
  1527. {
  1528. auto* impl = TRY(impl_from(vm));
  1529. return JS::Value(impl->screen_y());
  1530. }
  1531. JS_DEFINE_NATIVE_FUNCTION(Window::screen_x_getter)
  1532. {
  1533. auto* impl = TRY(impl_from(vm));
  1534. return JS::Value(impl->screen_x());
  1535. }
  1536. JS_DEFINE_NATIVE_FUNCTION(Window::screen_y_getter)
  1537. {
  1538. auto* impl = TRY(impl_from(vm));
  1539. return JS::Value(impl->screen_y());
  1540. }
  1541. JS_DEFINE_NATIVE_FUNCTION(Window::outer_width_getter)
  1542. {
  1543. auto* impl = TRY(impl_from(vm));
  1544. return JS::Value(impl->outer_width());
  1545. }
  1546. JS_DEFINE_NATIVE_FUNCTION(Window::outer_height_getter)
  1547. {
  1548. auto* impl = TRY(impl_from(vm));
  1549. return JS::Value(impl->outer_height());
  1550. }
  1551. JS_DEFINE_NATIVE_FUNCTION(Window::structured_clone)
  1552. {
  1553. auto* impl = TRY(impl_from(vm));
  1554. return TRY(Bindings::throw_dom_exception_if_needed(vm, [&] {
  1555. return impl->structured_clone_impl(vm, vm.argument(0));
  1556. }));
  1557. }
  1558. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-origin
  1559. JS_DEFINE_NATIVE_FUNCTION(Window::origin_getter)
  1560. {
  1561. auto* impl = TRY(impl_from(vm));
  1562. return JS::PrimitiveString::create(vm, impl->associated_document().origin().serialize());
  1563. }
  1564. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-issecurecontext
  1565. JS_DEFINE_NATIVE_FUNCTION(Window::is_secure_context_getter)
  1566. {
  1567. auto* impl = TRY(impl_from(vm));
  1568. // The isSecureContext getter steps are to return true if this's relevant settings object is a secure context, or false otherwise.
  1569. return JS::Value(is_secure_context(impl->associated_document().relevant_settings_object()));
  1570. }
  1571. JS_DEFINE_NATIVE_FUNCTION(Window::local_storage_getter)
  1572. {
  1573. auto* impl = TRY(impl_from(vm));
  1574. return impl->local_storage();
  1575. }
  1576. JS_DEFINE_NATIVE_FUNCTION(Window::session_storage_getter)
  1577. {
  1578. auto* impl = TRY(impl_from(vm));
  1579. return impl->session_storage();
  1580. }
  1581. }