Window.cpp 78 KB

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