Window.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  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/String.h>
  9. #include <AK/Utf8View.h>
  10. #include <LibJS/Runtime/AbstractOperations.h>
  11. #include <LibJS/Runtime/Completion.h>
  12. #include <LibJS/Runtime/Error.h>
  13. #include <LibJS/Runtime/FunctionObject.h>
  14. #include <LibJS/Runtime/GlobalEnvironment.h>
  15. #include <LibJS/Runtime/Shape.h>
  16. #include <LibTextCodec/Decoder.h>
  17. #include <LibWeb/Bindings/CSSNamespace.h>
  18. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  19. #include <LibWeb/Bindings/FetchMethod.h>
  20. #include <LibWeb/Bindings/LocationObject.h>
  21. #include <LibWeb/Bindings/Replaceable.h>
  22. #include <LibWeb/Bindings/WindowExposedInterfaces.h>
  23. #include <LibWeb/Bindings/WindowPrototype.h>
  24. #include <LibWeb/CSS/MediaQueryList.h>
  25. #include <LibWeb/CSS/Parser/Parser.h>
  26. #include <LibWeb/CSS/ResolvedCSSStyleDeclaration.h>
  27. #include <LibWeb/CSS/Screen.h>
  28. #include <LibWeb/Crypto/Crypto.h>
  29. #include <LibWeb/DOM/Document.h>
  30. #include <LibWeb/DOM/Event.h>
  31. #include <LibWeb/DOM/EventDispatcher.h>
  32. #include <LibWeb/HTML/BrowsingContext.h>
  33. #include <LibWeb/HTML/EventHandler.h>
  34. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  35. #include <LibWeb/HTML/MessageEvent.h>
  36. #include <LibWeb/HTML/Navigator.h>
  37. #include <LibWeb/HTML/Origin.h>
  38. #include <LibWeb/HTML/PageTransitionEvent.h>
  39. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  40. #include <LibWeb/HTML/Scripting/Environments.h>
  41. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  42. #include <LibWeb/HTML/Storage.h>
  43. #include <LibWeb/HTML/Timer.h>
  44. #include <LibWeb/HTML/Window.h>
  45. #include <LibWeb/HTML/WindowProxy.h>
  46. #include <LibWeb/HighResolutionTime/Performance.h>
  47. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  48. #include <LibWeb/Layout/InitialContainingBlock.h>
  49. #include <LibWeb/Page/Page.h>
  50. #include <LibWeb/RequestIdleCallback/IdleDeadline.h>
  51. #include <LibWeb/Selection/Selection.h>
  52. #include <LibWeb/WebAssembly/WebAssemblyObject.h>
  53. #include <LibWeb/WebIDL/AbstractOperations.h>
  54. namespace Web::HTML {
  55. // https://html.spec.whatwg.org/#run-the-animation-frame-callbacks
  56. void run_animation_frame_callbacks(DOM::Document& document, double)
  57. {
  58. // FIXME: Bring this closer to the spec.
  59. document.window().animation_frame_callback_driver().run();
  60. }
  61. class IdleCallback : public RefCounted<IdleCallback> {
  62. public:
  63. explicit IdleCallback(Function<JS::Completion(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline>)> handler, u32 handle)
  64. : m_handler(move(handler))
  65. , m_handle(handle)
  66. {
  67. }
  68. ~IdleCallback() = default;
  69. JS::Completion invoke(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline> deadline) { return m_handler(deadline); }
  70. u32 handle() const { return m_handle; }
  71. private:
  72. Function<JS::Completion(JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline>)> m_handler;
  73. u32 m_handle { 0 };
  74. };
  75. JS::NonnullGCPtr<Window> Window::create(JS::Realm& realm)
  76. {
  77. return *realm.heap().allocate<Window>(realm, realm);
  78. }
  79. Window::Window(JS::Realm& realm)
  80. : DOM::EventTarget(realm)
  81. {
  82. }
  83. void Window::visit_edges(JS::Cell::Visitor& visitor)
  84. {
  85. Base::visit_edges(visitor);
  86. visitor.visit(m_associated_document.ptr());
  87. visitor.visit(m_current_event.ptr());
  88. visitor.visit(m_performance.ptr());
  89. visitor.visit(m_screen.ptr());
  90. visitor.visit(m_location_object);
  91. visitor.visit(m_crypto);
  92. visitor.visit(m_navigator);
  93. for (auto& it : m_timers)
  94. visitor.visit(it.value.ptr());
  95. }
  96. Window::~Window() = default;
  97. HighResolutionTime::Performance& Window::performance()
  98. {
  99. if (!m_performance)
  100. m_performance = heap().allocate<HighResolutionTime::Performance>(realm(), *this);
  101. return *m_performance;
  102. }
  103. CSS::Screen& Window::screen()
  104. {
  105. if (!m_screen)
  106. m_screen = heap().allocate<CSS::Screen>(realm(), *this);
  107. return *m_screen;
  108. }
  109. void Window::alert_impl(String const& message)
  110. {
  111. if (auto* page = this->page())
  112. page->client().page_did_request_alert(message);
  113. }
  114. bool Window::confirm_impl(String const& message)
  115. {
  116. if (auto* page = this->page())
  117. return page->client().page_did_request_confirm(message);
  118. return false;
  119. }
  120. String Window::prompt_impl(String const& message, String const& default_)
  121. {
  122. if (auto* page = this->page())
  123. return page->client().page_did_request_prompt(message, default_);
  124. return {};
  125. }
  126. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  127. i32 Window::set_timeout_impl(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  128. {
  129. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::No);
  130. }
  131. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  132. i32 Window::set_interval_impl(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  133. {
  134. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::Yes);
  135. }
  136. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeout
  137. void Window::clear_timeout_impl(i32 id)
  138. {
  139. m_timers.remove(id);
  140. }
  141. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-clearinterval
  142. void Window::clear_interval_impl(i32 id)
  143. {
  144. m_timers.remove(id);
  145. }
  146. void Window::deallocate_timer_id(Badge<Timer>, i32 id)
  147. {
  148. m_timer_id_allocator.deallocate(id);
  149. }
  150. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps
  151. i32 Window::run_timer_initialization_steps(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments, Repeat repeat, Optional<i32> previous_id)
  152. {
  153. // 1. Let thisArg be global if that is a WorkerGlobalScope object; otherwise let thisArg be the WindowProxy that corresponds to global.
  154. // 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.
  155. auto id = previous_id.has_value() ? previous_id.value() : m_timer_id_allocator.allocate();
  156. // 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.
  157. // 4. If timeout is less than 0, then set timeout to 0.
  158. if (timeout < 0)
  159. timeout = 0;
  160. // FIXME: 5. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.
  161. // 6. Let callerRealm be the current Realm Record, and calleeRealm be global's relevant Realm.
  162. // FIXME: Implement this when step 9.2 is implemented.
  163. // 7. Let initiating script be the active script.
  164. // 8. Assert: initiating script is not null, since this algorithm is always called from some script.
  165. // 9. Let task be a task that runs the following substeps:
  166. JS::SafeFunction<void()> task = [this, handler = move(handler), timeout, arguments = move(arguments), repeat, id]() mutable {
  167. // 1. If id does not exist in global's map of active timers, then abort these steps.
  168. if (!m_timers.contains(id))
  169. return;
  170. handler.visit(
  171. // 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.
  172. [&](JS::Handle<WebIDL::CallbackType> callback) {
  173. if (auto result = WebIDL::invoke_callback(*callback, this, arguments); result.is_error())
  174. HTML::report_exception(result, realm());
  175. },
  176. // 3. Otherwise:
  177. [&](String const& source) {
  178. // 1. Assert: handler is a string.
  179. // FIXME: 2. Perform HostEnsureCanCompileStrings(callerRealm, calleeRealm). If this throws an exception, catch it, report the exception, and abort these steps.
  180. // 3. Let settings object be global's relevant settings object.
  181. auto& settings_object = associated_document().relevant_settings_object();
  182. // 4. Let base URL be initiating script's base URL.
  183. auto url = associated_document().url();
  184. // 5. Assert: base URL is not null, as initiating script is a classic script or a JavaScript module script.
  185. // 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.
  186. // 7. Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.
  187. auto script = HTML::ClassicScript::create(url.basename(), source, settings_object, url);
  188. // 8. Run the classic script script.
  189. (void)script->run();
  190. });
  191. // 4. If id does not exist in global's map of active timers, then abort these steps.
  192. if (!m_timers.contains(id))
  193. return;
  194. switch (repeat) {
  195. // 5. If repeat is true, then perform the timer initialization steps again, given global, handler, timeout, arguments, true, and id.
  196. case Repeat::Yes:
  197. run_timer_initialization_steps(handler, timeout, move(arguments), repeat, id);
  198. break;
  199. // 6. Otherwise, remove global's map of active timers[id].
  200. case Repeat::No:
  201. m_timers.remove(id);
  202. break;
  203. }
  204. };
  205. // FIXME: 10. Increment nesting level by one.
  206. // FIXME: 11. Set task's timer nesting level to nesting level.
  207. // 12. Let completionStep be an algorithm step which queues a global task on the timer task source given global to run task.
  208. JS::SafeFunction<void()> completion_step = [this, task = move(task)]() mutable {
  209. HTML::queue_global_task(HTML::Task::Source::TimerTask, *this, move(task));
  210. };
  211. // 13. Run steps after a timeout given global, "setTimeout/setInterval", timeout, completionStep, and id.
  212. auto timer = Timer::create(*this, timeout, move(completion_step), id);
  213. m_timers.set(id, timer);
  214. timer->start();
  215. // 14. Return id.
  216. return id;
  217. }
  218. // https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#run-the-animation-frame-callbacks
  219. i32 Window::request_animation_frame_impl(WebIDL::CallbackType& js_callback)
  220. {
  221. return m_animation_frame_callback_driver.add([this, js_callback = JS::make_handle(js_callback)](auto) mutable {
  222. // 3. Invoke callback, passing now as the only argument,
  223. auto result = WebIDL::invoke_callback(*js_callback, {}, JS::Value(performance().now()));
  224. // and if an exception is thrown, report the exception.
  225. if (result.is_error())
  226. HTML::report_exception(result, realm());
  227. });
  228. }
  229. void Window::cancel_animation_frame_impl(i32 id)
  230. {
  231. m_animation_frame_callback_driver.remove(id);
  232. }
  233. void Window::did_set_location_href(Badge<Bindings::LocationObject>, AK::URL const& new_href)
  234. {
  235. auto* browsing_context = associated_document().browsing_context();
  236. if (!browsing_context)
  237. return;
  238. browsing_context->loader().load(new_href, FrameLoader::Type::Navigation);
  239. }
  240. void Window::did_call_location_reload(Badge<Bindings::LocationObject>)
  241. {
  242. auto* browsing_context = associated_document().browsing_context();
  243. if (!browsing_context)
  244. return;
  245. browsing_context->loader().load(associated_document().url(), FrameLoader::Type::Reload);
  246. }
  247. void Window::did_call_location_replace(Badge<Bindings::LocationObject>, String url)
  248. {
  249. auto* browsing_context = associated_document().browsing_context();
  250. if (!browsing_context)
  251. return;
  252. auto new_url = associated_document().parse_url(url);
  253. browsing_context->loader().load(move(new_url), FrameLoader::Type::Navigation);
  254. }
  255. bool Window::dispatch_event(DOM::Event& event)
  256. {
  257. return DOM::EventDispatcher::dispatch(*this, event, true);
  258. }
  259. // https://www.w3.org/TR/cssom-view-1/#dom-window-innerwidth
  260. int Window::inner_width() const
  261. {
  262. // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar (if any),
  263. // or zero if there is no viewport.
  264. if (auto const* browsing_context = associated_document().browsing_context())
  265. return browsing_context->viewport_rect().width();
  266. return 0;
  267. }
  268. // https://www.w3.org/TR/cssom-view-1/#dom-window-innerheight
  269. int Window::inner_height() const
  270. {
  271. // The innerHeight attribute must return the viewport height including the size of a rendered scroll bar (if any),
  272. // or zero if there is no viewport.
  273. if (auto const* browsing_context = associated_document().browsing_context())
  274. return browsing_context->viewport_rect().height();
  275. return 0;
  276. }
  277. Page* Window::page()
  278. {
  279. return associated_document().page();
  280. }
  281. Page const* Window::page() const
  282. {
  283. return associated_document().page();
  284. }
  285. CSS::CSSStyleDeclaration* Window::get_computed_style_impl(DOM::Element& element) const
  286. {
  287. return CSS::ResolvedCSSStyleDeclaration::create(element);
  288. }
  289. JS::NonnullGCPtr<CSS::MediaQueryList> Window::match_media_impl(String media)
  290. {
  291. auto media_query_list = CSS::MediaQueryList::create(associated_document(), parse_media_query_list(CSS::Parser::ParsingContext(associated_document()), media));
  292. associated_document().add_media_query_list(*media_query_list);
  293. return media_query_list;
  294. }
  295. Optional<CSS::MediaFeatureValue> Window::query_media_feature(CSS::MediaFeatureID media_feature) const
  296. {
  297. // FIXME: Many of these should be dependent on the hardware
  298. // https://www.w3.org/TR/mediaqueries-5/#media-descriptor-table
  299. switch (media_feature) {
  300. case CSS::MediaFeatureID::AnyHover:
  301. return CSS::MediaFeatureValue(CSS::ValueID::Hover);
  302. case CSS::MediaFeatureID::AnyPointer:
  303. return CSS::MediaFeatureValue(CSS::ValueID::Fine);
  304. case CSS::MediaFeatureID::AspectRatio:
  305. return CSS::MediaFeatureValue(CSS::Ratio(inner_width(), inner_height()));
  306. case CSS::MediaFeatureID::Color:
  307. return CSS::MediaFeatureValue(8);
  308. case CSS::MediaFeatureID::ColorGamut:
  309. return CSS::MediaFeatureValue(CSS::ValueID::Srgb);
  310. case CSS::MediaFeatureID::ColorIndex:
  311. return CSS::MediaFeatureValue(0);
  312. // FIXME: device-aspect-ratio
  313. // FIXME: device-height
  314. // FIXME: device-width
  315. case CSS::MediaFeatureID::DisplayMode:
  316. // FIXME: Detect if window is fullscreen
  317. return CSS::MediaFeatureValue(CSS::ValueID::Browser);
  318. case CSS::MediaFeatureID::DynamicRange:
  319. return CSS::MediaFeatureValue(CSS::ValueID::Standard);
  320. case CSS::MediaFeatureID::EnvironmentBlending:
  321. return CSS::MediaFeatureValue(CSS::ValueID::Opaque);
  322. case CSS::MediaFeatureID::ForcedColors:
  323. return CSS::MediaFeatureValue(CSS::ValueID::None);
  324. case CSS::MediaFeatureID::Grid:
  325. return CSS::MediaFeatureValue(0);
  326. case CSS::MediaFeatureID::Height:
  327. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_height()));
  328. case CSS::MediaFeatureID::HorizontalViewportSegments:
  329. return CSS::MediaFeatureValue(1);
  330. case CSS::MediaFeatureID::Hover:
  331. return CSS::MediaFeatureValue(CSS::ValueID::Hover);
  332. case CSS::MediaFeatureID::InvertedColors:
  333. return CSS::MediaFeatureValue(CSS::ValueID::None);
  334. case CSS::MediaFeatureID::Monochrome:
  335. return CSS::MediaFeatureValue(0);
  336. case CSS::MediaFeatureID::NavControls:
  337. return CSS::MediaFeatureValue(CSS::ValueID::Back);
  338. case CSS::MediaFeatureID::Orientation:
  339. return CSS::MediaFeatureValue(inner_height() >= inner_width() ? CSS::ValueID::Portrait : CSS::ValueID::Landscape);
  340. case CSS::MediaFeatureID::OverflowBlock:
  341. return CSS::MediaFeatureValue(CSS::ValueID::Scroll);
  342. case CSS::MediaFeatureID::OverflowInline:
  343. return CSS::MediaFeatureValue(CSS::ValueID::Scroll);
  344. case CSS::MediaFeatureID::Pointer:
  345. return CSS::MediaFeatureValue(CSS::ValueID::Fine);
  346. case CSS::MediaFeatureID::PrefersColorScheme: {
  347. if (auto* page = this->page()) {
  348. switch (page->preferred_color_scheme()) {
  349. case CSS::PreferredColorScheme::Light:
  350. return CSS::MediaFeatureValue(CSS::ValueID::Light);
  351. case CSS::PreferredColorScheme::Dark:
  352. return CSS::MediaFeatureValue(CSS::ValueID::Dark);
  353. case CSS::PreferredColorScheme::Auto:
  354. default:
  355. return CSS::MediaFeatureValue(page->palette().is_dark() ? CSS::ValueID::Dark : CSS::ValueID::Light);
  356. }
  357. }
  358. return CSS::MediaFeatureValue(CSS::ValueID::Light);
  359. }
  360. case CSS::MediaFeatureID::PrefersContrast:
  361. // FIXME: Make this a preference
  362. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  363. case CSS::MediaFeatureID::PrefersReducedData:
  364. // FIXME: Make this a preference
  365. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  366. case CSS::MediaFeatureID::PrefersReducedMotion:
  367. // FIXME: Make this a preference
  368. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  369. case CSS::MediaFeatureID::PrefersReducedTransparency:
  370. // FIXME: Make this a preference
  371. return CSS::MediaFeatureValue(CSS::ValueID::NoPreference);
  372. // FIXME: resolution
  373. case CSS::MediaFeatureID::Scan:
  374. return CSS::MediaFeatureValue(CSS::ValueID::Progressive);
  375. case CSS::MediaFeatureID::Scripting:
  376. if (associated_document().is_scripting_enabled())
  377. return CSS::MediaFeatureValue(CSS::ValueID::Enabled);
  378. return CSS::MediaFeatureValue(CSS::ValueID::None);
  379. case CSS::MediaFeatureID::Update:
  380. return CSS::MediaFeatureValue(CSS::ValueID::Fast);
  381. case CSS::MediaFeatureID::VerticalViewportSegments:
  382. return CSS::MediaFeatureValue(1);
  383. case CSS::MediaFeatureID::VideoColorGamut:
  384. return CSS::MediaFeatureValue(CSS::ValueID::Srgb);
  385. case CSS::MediaFeatureID::VideoDynamicRange:
  386. return CSS::MediaFeatureValue(CSS::ValueID::Standard);
  387. case CSS::MediaFeatureID::Width:
  388. return CSS::MediaFeatureValue(CSS::Length::make_px(inner_width()));
  389. default:
  390. break;
  391. }
  392. return {};
  393. }
  394. // https://www.w3.org/TR/cssom-view/#dom-window-scrollx
  395. float Window::scroll_x() const
  396. {
  397. if (auto* page = this->page())
  398. return page->top_level_browsing_context().viewport_scroll_offset().x();
  399. return 0;
  400. }
  401. // https://www.w3.org/TR/cssom-view/#dom-window-scrolly
  402. float Window::scroll_y() const
  403. {
  404. if (auto* page = this->page())
  405. return page->top_level_browsing_context().viewport_scroll_offset().y();
  406. return 0;
  407. }
  408. // https://html.spec.whatwg.org/#fire-a-page-transition-event
  409. void Window::fire_a_page_transition_event(FlyString const& event_name, bool persisted)
  410. {
  411. // To fire a page transition event named eventName at a Window window with a boolean persisted,
  412. // fire an event named eventName at window, using PageTransitionEvent,
  413. // with the persisted attribute initialized to persisted,
  414. HTML::PageTransitionEventInit event_init {};
  415. event_init.persisted = persisted;
  416. auto event = HTML::PageTransitionEvent::create(associated_document().realm(), event_name, event_init);
  417. // ...the cancelable attribute initialized to true,
  418. event->set_cancelable(true);
  419. // the bubbles attribute initialized to true,
  420. event->set_bubbles(true);
  421. // and legacy target override flag set.
  422. dispatch_event(*event);
  423. }
  424. // https://html.spec.whatwg.org/#dom-queuemicrotask
  425. void Window::queue_microtask_impl(WebIDL::CallbackType& callback)
  426. {
  427. // The queueMicrotask(callback) method must queue a microtask to invoke callback,
  428. HTML::queue_a_microtask(&associated_document(), [this, &callback]() mutable {
  429. auto result = WebIDL::invoke_callback(callback, {});
  430. // and if callback throws an exception, report the exception.
  431. if (result.is_error())
  432. HTML::report_exception(result, realm());
  433. });
  434. }
  435. float Window::device_pixel_ratio() const
  436. {
  437. // FIXME: Return 2.0f if we're in HiDPI mode!
  438. return 1.0f;
  439. }
  440. // https://drafts.csswg.org/cssom-view/#dom-window-screenx
  441. int Window::screen_x() const
  442. {
  443. // The screenX and screenLeft attributes must return the x-coordinate, relative to the origin of the Web-exposed screen area,
  444. // of the left of the client window as number of CSS pixels, or zero if there is no such thing.
  445. return 0;
  446. }
  447. // https://drafts.csswg.org/cssom-view/#dom-window-screeny
  448. int Window::screen_y() const
  449. {
  450. // The screenY and screenTop attributes must return the y-coordinate, relative to the origin of the screen of the Web-exposed screen area,
  451. // of the top of the client window as number of CSS pixels, or zero if there is no such thing.
  452. return 0;
  453. }
  454. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-localstorage
  455. JS::NonnullGCPtr<HTML::Storage> Window::local_storage()
  456. {
  457. // FIXME: Implement according to spec.
  458. static HashMap<Origin, JS::Handle<HTML::Storage>> local_storage_per_origin;
  459. auto storage = local_storage_per_origin.ensure(associated_document().origin(), [this]() -> JS::Handle<HTML::Storage> {
  460. return *HTML::Storage::create(realm());
  461. });
  462. return *storage;
  463. }
  464. // https://html.spec.whatwg.org/multipage/webstorage.html#dom-sessionstorage
  465. JS::NonnullGCPtr<HTML::Storage> Window::session_storage()
  466. {
  467. // FIXME: Implement according to spec.
  468. static HashMap<Origin, JS::Handle<HTML::Storage>> session_storage_per_origin;
  469. auto storage = session_storage_per_origin.ensure(associated_document().origin(), [this]() -> JS::Handle<HTML::Storage> {
  470. return *HTML::Storage::create(realm());
  471. });
  472. return *storage;
  473. }
  474. // https://html.spec.whatwg.org/multipage/browsers.html#dom-parent
  475. WindowProxy* Window::parent()
  476. {
  477. // 1. Let current be this Window object's browsing context.
  478. auto* current = browsing_context();
  479. // 2. If current is null, then return null.
  480. if (!current)
  481. return nullptr;
  482. // 3. If current is a child browsing context of another browsing context parent,
  483. // then return parent's WindowProxy object.
  484. if (current->parent()) {
  485. return current->parent()->window_proxy();
  486. }
  487. // 4. Assert: current is a top-level browsing context.
  488. VERIFY(current->is_top_level());
  489. // 5. Return current's WindowProxy object.
  490. return current->window_proxy();
  491. }
  492. // https://html.spec.whatwg.org/multipage/web-messaging.html#window-post-message-steps
  493. WebIDL::ExceptionOr<void> Window::post_message_impl(JS::Value message, String const&)
  494. {
  495. // FIXME: This is an ad-hoc hack implementation instead, since we don't currently
  496. // have serialization and deserialization of messages.
  497. HTML::queue_global_task(HTML::Task::Source::PostedMessage, *this, [this, message]() mutable {
  498. HTML::MessageEventInit event_init {};
  499. event_init.data = message;
  500. event_init.origin = "<origin>";
  501. dispatch_event(*HTML::MessageEvent::create(realm(), HTML::EventNames::message, event_init));
  502. });
  503. return {};
  504. }
  505. // https://html.spec.whatwg.org/multipage/window-object.html#dom-name
  506. String Window::name() const
  507. {
  508. // 1. If this's browsing context is null, then return the empty string.
  509. if (!browsing_context())
  510. return String::empty();
  511. // 2. Return this's browsing context's name.
  512. return browsing_context()->name();
  513. }
  514. // https://html.spec.whatwg.org/multipage/window-object.html#dom-name
  515. void Window::set_name(String const& name)
  516. {
  517. // 1. If this's browsing context is null, then return.
  518. if (!browsing_context())
  519. return;
  520. // 2. Set this's browsing context's name to the given value.
  521. browsing_context()->set_name(name);
  522. }
  523. // https://html.spec.whatwg.org/multipage/interaction.html#transient-activation
  524. bool Window::has_transient_activation() const
  525. {
  526. // FIXME: Implement this.
  527. return false;
  528. }
  529. // https://w3c.github.io/requestidlecallback/#start-an-idle-period-algorithm
  530. void Window::start_an_idle_period()
  531. {
  532. // 1. Optionally, if the user agent determines the idle period should be delayed, return from this algorithm.
  533. // 2. Let pending_list be window's list of idle request callbacks.
  534. auto& pending_list = m_idle_request_callbacks;
  535. // 3. Let run_list be window's list of runnable idle callbacks.
  536. auto& run_list = m_runnable_idle_callbacks;
  537. run_list.extend(pending_list);
  538. // 4. Clear pending_list.
  539. pending_list.clear();
  540. // FIXME: This might not agree with the spec, but currently we use 100% CPU if we keep queueing tasks
  541. if (run_list.is_empty())
  542. return;
  543. // 5. Queue a task on the queue associated with the idle-task task source,
  544. // which performs the steps defined in the invoke idle callbacks algorithm with window and getDeadline as parameters.
  545. HTML::queue_global_task(HTML::Task::Source::IdleTask, *this, [this]() mutable {
  546. invoke_idle_callbacks();
  547. });
  548. }
  549. // https://w3c.github.io/requestidlecallback/#invoke-idle-callbacks-algorithm
  550. void Window::invoke_idle_callbacks()
  551. {
  552. auto& event_loop = main_thread_event_loop();
  553. // 1. If the user-agent believes it should end the idle period early due to newly scheduled high-priority work, return from the algorithm.
  554. // 2. Let now be the current time.
  555. auto now = HighResolutionTime::unsafe_shared_current_time();
  556. // 3. If now is less than the result of calling getDeadline and the window's list of runnable idle callbacks is not empty:
  557. if (now < event_loop.compute_deadline() && !m_runnable_idle_callbacks.is_empty()) {
  558. // 1. Pop the top callback from window's list of runnable idle callbacks.
  559. auto callback = m_runnable_idle_callbacks.take_first();
  560. // 2. Let deadlineArg be a new IdleDeadline whose [get deadline time algorithm] is getDeadline.
  561. auto deadline_arg = RequestIdleCallback::IdleDeadline::create(realm());
  562. // 3. Call callback with deadlineArg as its argument. If an uncaught runtime script error occurs, then report the exception.
  563. auto result = callback->invoke(deadline_arg);
  564. if (result.is_error())
  565. HTML::report_exception(result, realm());
  566. // 4. If window's list of runnable idle callbacks is not empty, queue a task which performs the steps
  567. // in the invoke idle callbacks algorithm with getDeadline and window as a parameters and return from this algorithm
  568. HTML::queue_global_task(HTML::Task::Source::IdleTask, *this, [this]() mutable {
  569. invoke_idle_callbacks();
  570. });
  571. }
  572. }
  573. // https://w3c.github.io/requestidlecallback/#the-requestidlecallback-method
  574. u32 Window::request_idle_callback_impl(WebIDL::CallbackType& callback)
  575. {
  576. // 1. Let window be this Window object.
  577. auto& window = *this;
  578. // 2. Increment the window's idle callback identifier by one.
  579. window.m_idle_callback_identifier++;
  580. // 3. Let handle be the current value of window's idle callback identifier.
  581. auto handle = window.m_idle_callback_identifier;
  582. // 4. Push callback to the end of window's list of idle request callbacks, associated with handle.
  583. auto handler = [callback = JS::make_handle(callback)](JS::NonnullGCPtr<RequestIdleCallback::IdleDeadline> deadline) -> JS::Completion {
  584. return WebIDL::invoke_callback(const_cast<WebIDL::CallbackType&>(*callback), {}, deadline.ptr());
  585. };
  586. window.m_idle_request_callbacks.append(adopt_ref(*new IdleCallback(move(handler), handle)));
  587. // 5. Return handle and then continue running this algorithm asynchronously.
  588. return handle;
  589. // FIXME: 6. If the timeout property is present in options and has a positive value:
  590. // FIXME: 1. Wait for timeout milliseconds.
  591. // FIXME: 2. Wait until all invocations of this algorithm, whose timeout added to their posted time occurred before this one's, have completed.
  592. // FIXME: 3. Optionally, wait a further user-agent defined length of time.
  593. // 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.
  594. }
  595. // https://w3c.github.io/requestidlecallback/#the-cancelidlecallback-method
  596. void Window::cancel_idle_callback_impl(u32 handle)
  597. {
  598. // 1. Let window be this Window object.
  599. auto& window = *this;
  600. // 2. Find the entry in either the window's list of idle request callbacks or list of runnable idle callbacks
  601. // that is associated with the value handle.
  602. // 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.
  603. window.m_idle_request_callbacks.remove_first_matching([handle](auto& callback) {
  604. return callback->handle() == handle;
  605. });
  606. window.m_runnable_idle_callbacks.remove_first_matching([handle](auto& callback) {
  607. return callback->handle() == handle;
  608. });
  609. }
  610. void Window::set_associated_document(DOM::Document& document)
  611. {
  612. m_associated_document = &document;
  613. }
  614. void Window::set_current_event(DOM::Event* event)
  615. {
  616. m_current_event = event;
  617. }
  618. HTML::BrowsingContext const* Window::browsing_context() const
  619. {
  620. return m_associated_document->browsing_context();
  621. }
  622. HTML::BrowsingContext* Window::browsing_context()
  623. {
  624. return m_associated_document->browsing_context();
  625. }
  626. void Window::initialize_web_interfaces(Badge<WindowEnvironmentSettingsObject>)
  627. {
  628. auto& realm = this->realm();
  629. add_window_exposed_interfaces(*this, realm);
  630. Object::set_prototype(&Bindings::ensure_web_prototype<Bindings::WindowPrototype>(realm, "Window"));
  631. m_crypto = Crypto::Crypto::create(realm);
  632. // FIXME: These should be native accessors, not properties
  633. define_native_accessor(realm, "top", top_getter, nullptr, JS::Attribute::Enumerable);
  634. define_native_accessor(realm, "window", window_getter, {}, JS::Attribute::Enumerable);
  635. define_native_accessor(realm, "frames", frames_getter, {}, JS::Attribute::Enumerable);
  636. define_native_accessor(realm, "self", self_getter, {}, JS::Attribute::Enumerable);
  637. define_native_accessor(realm, "parent", parent_getter, {}, JS::Attribute::Enumerable);
  638. define_native_accessor(realm, "document", document_getter, {}, JS::Attribute::Enumerable);
  639. define_native_accessor(realm, "frameElement", frame_element_getter, {}, JS::Attribute::Enumerable);
  640. define_native_accessor(realm, "name", name_getter, name_setter, JS::Attribute::Enumerable);
  641. define_native_accessor(realm, "history", history_getter, {}, JS::Attribute::Enumerable);
  642. define_native_accessor(realm, "performance", performance_getter, performance_setter, JS::Attribute::Enumerable | JS::Attribute::Configurable);
  643. define_native_accessor(realm, "crypto", crypto_getter, {}, JS::Attribute::Enumerable);
  644. define_native_accessor(realm, "screen", screen_getter, {}, JS::Attribute::Enumerable);
  645. define_native_accessor(realm, "innerWidth", inner_width_getter, {}, JS::Attribute::Enumerable);
  646. define_native_accessor(realm, "innerHeight", inner_height_getter, {}, JS::Attribute::Enumerable);
  647. define_native_accessor(realm, "devicePixelRatio", device_pixel_ratio_getter, {}, JS::Attribute::Enumerable | JS::Attribute::Configurable);
  648. u8 attr = JS::Attribute::Writable | JS::Attribute::Enumerable | JS::Attribute::Configurable;
  649. define_native_function(realm, "alert", alert, 0, attr);
  650. define_native_function(realm, "confirm", confirm, 0, attr);
  651. define_native_function(realm, "prompt", prompt, 0, attr);
  652. define_native_function(realm, "setInterval", set_interval, 1, attr);
  653. define_native_function(realm, "setTimeout", set_timeout, 1, attr);
  654. define_native_function(realm, "clearInterval", clear_interval, 1, attr);
  655. define_native_function(realm, "clearTimeout", clear_timeout, 1, attr);
  656. define_native_function(realm, "requestAnimationFrame", request_animation_frame, 1, attr);
  657. define_native_function(realm, "cancelAnimationFrame", cancel_animation_frame, 1, attr);
  658. define_native_function(realm, "atob", atob, 1, attr);
  659. define_native_function(realm, "btoa", btoa, 1, attr);
  660. define_native_function(realm, "queueMicrotask", queue_microtask, 1, attr);
  661. define_native_function(realm, "requestIdleCallback", request_idle_callback, 1, attr);
  662. define_native_function(realm, "cancelIdleCallback", cancel_idle_callback, 1, attr);
  663. define_native_function(realm, "getComputedStyle", get_computed_style, 1, attr);
  664. define_native_function(realm, "matchMedia", match_media, 1, attr);
  665. define_native_function(realm, "getSelection", get_selection, 0, attr);
  666. define_native_function(realm, "postMessage", post_message, 1, attr);
  667. define_native_function(realm, "fetch", Bindings::fetch, 1, attr);
  668. // FIXME: These properties should be [Replaceable] according to the spec, but [Writable+Configurable] is the closest we have.
  669. define_native_accessor(realm, "scrollX", scroll_x_getter, {}, attr);
  670. define_native_accessor(realm, "pageXOffset", scroll_x_getter, {}, attr);
  671. define_native_accessor(realm, "scrollY", scroll_y_getter, {}, attr);
  672. define_native_accessor(realm, "pageYOffset", scroll_y_getter, {}, attr);
  673. define_native_accessor(realm, "length", length_getter, {}, attr);
  674. define_native_function(realm, "scroll", scroll, 2, attr);
  675. define_native_function(realm, "scrollTo", scroll, 2, attr);
  676. define_native_function(realm, "scrollBy", scroll_by, 2, attr);
  677. define_native_accessor(realm, "screenX", screen_x_getter, {}, attr);
  678. define_native_accessor(realm, "screenY", screen_y_getter, {}, attr);
  679. define_native_accessor(realm, "screenLeft", screen_left_getter, {}, attr);
  680. define_native_accessor(realm, "screenTop", screen_top_getter, {}, attr);
  681. define_direct_property("CSS", heap().allocate<Bindings::CSSNamespace>(realm, realm), 0);
  682. define_native_accessor(realm, "localStorage", local_storage_getter, {}, attr);
  683. define_native_accessor(realm, "sessionStorage", session_storage_getter, {}, attr);
  684. define_native_accessor(realm, "origin", origin_getter, {}, attr);
  685. // Legacy
  686. define_native_accessor(realm, "event", event_getter, event_setter, JS::Attribute::Enumerable);
  687. m_location_object = heap().allocate<Bindings::LocationObject>(realm, realm);
  688. m_navigator = heap().allocate<HTML::Navigator>(realm, realm);
  689. define_direct_property("navigator", m_navigator, JS::Attribute::Enumerable | JS::Attribute::Configurable);
  690. define_direct_property("clientInformation", m_navigator, JS::Attribute::Enumerable | JS::Attribute::Configurable);
  691. // NOTE: location is marked as [LegacyUnforgeable], meaning it isn't configurable.
  692. define_native_accessor(realm, "location", location_getter, location_setter, JS::Attribute::Enumerable);
  693. // WebAssembly "namespace"
  694. define_direct_property("WebAssembly", heap().allocate<Bindings::WebAssemblyObject>(realm, realm), JS::Attribute::Enumerable | JS::Attribute::Configurable);
  695. // HTML::GlobalEventHandlers and HTML::WindowEventHandlers
  696. #define __ENUMERATE(attribute, event_name) \
  697. define_native_accessor(realm, #attribute, attribute##_getter, attribute##_setter, attr);
  698. ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE);
  699. ENUMERATE_WINDOW_EVENT_HANDLERS(__ENUMERATE);
  700. #undef __ENUMERATE
  701. }
  702. HTML::Origin Window::origin() const
  703. {
  704. return associated_document().origin();
  705. }
  706. // https://webidl.spec.whatwg.org/#platform-object-setprototypeof
  707. JS::ThrowCompletionOr<bool> Window::internal_set_prototype_of(JS::Object* prototype)
  708. {
  709. // 1. Return ? SetImmutablePrototype(O, V).
  710. return set_immutable_prototype(prototype);
  711. }
  712. static JS::ThrowCompletionOr<HTML::Window*> impl_from(JS::VM& vm)
  713. {
  714. // Since this is a non built-in function we must treat it as non-strict mode
  715. // this means that a nullish this_value should be converted to the
  716. // global_object. Generally this does not matter as we try to convert the
  717. // this_value to a specific object type in the bindings. But since window is
  718. // the global object we make an exception here.
  719. // This allows calls like `setTimeout(f, 10)` to work.
  720. auto this_value = vm.this_value();
  721. if (this_value.is_nullish())
  722. this_value = &vm.current_realm()->global_object();
  723. auto* this_object = MUST(this_value.to_object(vm));
  724. if (is<WindowProxy>(*this_object))
  725. return static_cast<WindowProxy*>(this_object)->window().ptr();
  726. if (is<Window>(*this_object))
  727. return static_cast<Window*>(this_object);
  728. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Window");
  729. }
  730. JS_DEFINE_NATIVE_FUNCTION(Window::alert)
  731. {
  732. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#simple-dialogs
  733. // Note: This method is defined using two overloads, instead of using an optional argument,
  734. // for historical reasons. The practical impact of this is that alert(undefined) is
  735. // treated as alert("undefined"), but alert() is treated as alert("").
  736. auto* impl = TRY(impl_from(vm));
  737. String message = "";
  738. if (vm.argument_count())
  739. message = TRY(vm.argument(0).to_string(vm));
  740. impl->alert_impl(message);
  741. return JS::js_undefined();
  742. }
  743. JS_DEFINE_NATIVE_FUNCTION(Window::confirm)
  744. {
  745. auto* impl = TRY(impl_from(vm));
  746. String message = "";
  747. if (!vm.argument(0).is_undefined())
  748. message = TRY(vm.argument(0).to_string(vm));
  749. return JS::Value(impl->confirm_impl(message));
  750. }
  751. JS_DEFINE_NATIVE_FUNCTION(Window::prompt)
  752. {
  753. auto* impl = TRY(impl_from(vm));
  754. String message = "";
  755. String default_ = "";
  756. if (!vm.argument(0).is_undefined())
  757. message = TRY(vm.argument(0).to_string(vm));
  758. if (!vm.argument(1).is_undefined())
  759. default_ = TRY(vm.argument(1).to_string(vm));
  760. auto response = impl->prompt_impl(message, default_);
  761. if (response.is_null())
  762. return JS::js_null();
  763. return JS::js_string(vm, response);
  764. }
  765. static JS::ThrowCompletionOr<TimerHandler> make_timer_handler(JS::VM& vm, JS::Value handler)
  766. {
  767. if (handler.is_function())
  768. return JS::make_handle(vm.heap().allocate_without_realm<WebIDL::CallbackType>(handler.as_function(), HTML::incumbent_settings_object()));
  769. return TRY(handler.to_string(vm));
  770. }
  771. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  772. JS_DEFINE_NATIVE_FUNCTION(Window::set_timeout)
  773. {
  774. auto* impl = TRY(impl_from(vm));
  775. if (!vm.argument_count())
  776. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountAtLeastOne, "setTimeout");
  777. auto handler = TRY(make_timer_handler(vm, vm.argument(0)));
  778. i32 timeout = 0;
  779. if (vm.argument_count() >= 2)
  780. timeout = TRY(vm.argument(1).to_i32(vm));
  781. JS::MarkedVector<JS::Value> arguments { vm.heap() };
  782. for (size_t i = 2; i < vm.argument_count(); ++i)
  783. arguments.append(vm.argument(i));
  784. auto id = impl->set_timeout_impl(move(handler), timeout, move(arguments));
  785. return JS::Value(id);
  786. }
  787. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  788. JS_DEFINE_NATIVE_FUNCTION(Window::set_interval)
  789. {
  790. auto* impl = TRY(impl_from(vm));
  791. if (!vm.argument_count())
  792. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountAtLeastOne, "setInterval");
  793. auto handler = TRY(make_timer_handler(vm, vm.argument(0)));
  794. i32 timeout = 0;
  795. if (vm.argument_count() >= 2)
  796. timeout = TRY(vm.argument(1).to_i32(vm));
  797. JS::MarkedVector<JS::Value> arguments { vm.heap() };
  798. for (size_t i = 2; i < vm.argument_count(); ++i)
  799. arguments.append(vm.argument(i));
  800. auto id = impl->set_interval_impl(move(handler), timeout, move(arguments));
  801. return JS::Value(id);
  802. }
  803. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeout
  804. JS_DEFINE_NATIVE_FUNCTION(Window::clear_timeout)
  805. {
  806. auto* impl = TRY(impl_from(vm));
  807. i32 id = 0;
  808. if (vm.argument_count())
  809. id = TRY(vm.argument(0).to_i32(vm));
  810. impl->clear_timeout_impl(id);
  811. return JS::js_undefined();
  812. }
  813. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-clearinterval
  814. JS_DEFINE_NATIVE_FUNCTION(Window::clear_interval)
  815. {
  816. auto* impl = TRY(impl_from(vm));
  817. i32 id = 0;
  818. if (vm.argument_count())
  819. id = TRY(vm.argument(0).to_i32(vm));
  820. impl->clear_interval_impl(id);
  821. return JS::js_undefined();
  822. }
  823. JS_DEFINE_NATIVE_FUNCTION(Window::request_animation_frame)
  824. {
  825. auto* impl = TRY(impl_from(vm));
  826. if (!vm.argument_count())
  827. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "requestAnimationFrame");
  828. auto* callback_object = TRY(vm.argument(0).to_object(vm));
  829. if (!callback_object->is_function())
  830. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam);
  831. auto* callback = vm.heap().allocate_without_realm<WebIDL::CallbackType>(*callback_object, HTML::incumbent_settings_object());
  832. return JS::Value(impl->request_animation_frame_impl(*callback));
  833. }
  834. JS_DEFINE_NATIVE_FUNCTION(Window::cancel_animation_frame)
  835. {
  836. auto* impl = TRY(impl_from(vm));
  837. if (!vm.argument_count())
  838. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "cancelAnimationFrame");
  839. auto id = TRY(vm.argument(0).to_i32(vm));
  840. impl->cancel_animation_frame_impl(id);
  841. return JS::js_undefined();
  842. }
  843. JS_DEFINE_NATIVE_FUNCTION(Window::queue_microtask)
  844. {
  845. auto* impl = TRY(impl_from(vm));
  846. if (!vm.argument_count())
  847. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountAtLeastOne, "queueMicrotask");
  848. auto* callback_object = TRY(vm.argument(0).to_object(vm));
  849. if (!callback_object->is_function())
  850. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam);
  851. auto* callback = vm.heap().allocate_without_realm<WebIDL::CallbackType>(*callback_object, HTML::incumbent_settings_object());
  852. impl->queue_microtask_impl(*callback);
  853. return JS::js_undefined();
  854. }
  855. JS_DEFINE_NATIVE_FUNCTION(Window::request_idle_callback)
  856. {
  857. auto* impl = TRY(impl_from(vm));
  858. if (!vm.argument_count())
  859. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountAtLeastOne, "requestIdleCallback");
  860. auto* callback_object = TRY(vm.argument(0).to_object(vm));
  861. if (!callback_object->is_function())
  862. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAFunctionNoParam);
  863. // FIXME: accept options object
  864. auto* callback = vm.heap().allocate_without_realm<WebIDL::CallbackType>(*callback_object, HTML::incumbent_settings_object());
  865. return JS::Value(impl->request_idle_callback_impl(*callback));
  866. }
  867. JS_DEFINE_NATIVE_FUNCTION(Window::cancel_idle_callback)
  868. {
  869. auto* impl = TRY(impl_from(vm));
  870. if (!vm.argument_count())
  871. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "cancelIdleCallback");
  872. auto id = TRY(vm.argument(0).to_u32(vm));
  873. impl->cancel_idle_callback_impl(id);
  874. return JS::js_undefined();
  875. }
  876. JS_DEFINE_NATIVE_FUNCTION(Window::atob)
  877. {
  878. if (!vm.argument_count())
  879. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "atob");
  880. auto string = TRY(vm.argument(0).to_string(vm));
  881. auto decoded = decode_base64(StringView(string));
  882. if (decoded.is_error())
  883. return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidFormat, "Base64");
  884. // decode_base64() returns a byte string. LibJS uses UTF-8 for strings. Use Latin1Decoder to convert bytes 128-255 to UTF-8.
  885. auto decoder = TextCodec::decoder_for("windows-1252");
  886. VERIFY(decoder);
  887. return JS::js_string(vm, decoder->to_utf8(decoded.value()));
  888. }
  889. JS_DEFINE_NATIVE_FUNCTION(Window::btoa)
  890. {
  891. if (!vm.argument_count())
  892. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "btoa");
  893. auto string = TRY(vm.argument(0).to_string(vm));
  894. Vector<u8> byte_string;
  895. byte_string.ensure_capacity(string.length());
  896. for (u32 code_point : Utf8View(string)) {
  897. if (code_point > 0xff)
  898. return throw_completion(WebIDL::InvalidCharacterError::create(*vm.current_realm(), "Data contains characters outside the range U+0000 and U+00FF"));
  899. byte_string.append(code_point);
  900. }
  901. auto encoded = encode_base64(byte_string.span());
  902. return JS::js_string(vm, move(encoded));
  903. }
  904. // https://html.spec.whatwg.org/multipage/window-object.html#number-of-document-tree-child-browsing-contexts
  905. JS::ThrowCompletionOr<size_t> Window::document_tree_child_browsing_context_count() const
  906. {
  907. // 1. If W's browsing context is null, then return 0.
  908. auto* this_browsing_context = associated_document().browsing_context();
  909. if (!this_browsing_context)
  910. return 0;
  911. // 2. Return the number of document-tree child browsing contexts of W's browsing context.
  912. return this_browsing_context->document_tree_child_browsing_context_count();
  913. }
  914. // https://html.spec.whatwg.org/multipage/window-object.html#dom-length
  915. JS_DEFINE_NATIVE_FUNCTION(Window::length_getter)
  916. {
  917. auto* impl = TRY(impl_from(vm));
  918. // The length getter steps are to return the number of document-tree child browsing contexts of this.
  919. return TRY(impl->document_tree_child_browsing_context_count());
  920. }
  921. // https://html.spec.whatwg.org/multipage/browsers.html#dom-top
  922. JS_DEFINE_NATIVE_FUNCTION(Window::top_getter)
  923. {
  924. auto* impl = TRY(impl_from(vm));
  925. // 1. If this Window object's browsing context is null, then return null.
  926. auto* browsing_context = impl->browsing_context();
  927. if (!browsing_context)
  928. return JS::js_null();
  929. // 2. Return this Window object's browsing context's top-level browsing context's WindowProxy object.
  930. return browsing_context->top_level_browsing_context().window_proxy();
  931. }
  932. // https://html.spec.whatwg.org/multipage/window-object.html#dom-self
  933. JS_DEFINE_NATIVE_FUNCTION(Window::self_getter)
  934. {
  935. auto* impl = TRY(impl_from(vm));
  936. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  937. return &relevant_realm(*impl).global_environment().global_this_value();
  938. }
  939. // https://html.spec.whatwg.org/multipage/window-object.html#dom-window
  940. JS_DEFINE_NATIVE_FUNCTION(Window::window_getter)
  941. {
  942. auto* impl = TRY(impl_from(vm));
  943. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  944. return &relevant_realm(*impl).global_environment().global_this_value();
  945. }
  946. // https://html.spec.whatwg.org/multipage/window-object.html#dom-frames
  947. JS_DEFINE_NATIVE_FUNCTION(Window::frames_getter)
  948. {
  949. auto* impl = TRY(impl_from(vm));
  950. // The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].
  951. return &relevant_realm(*impl).global_environment().global_this_value();
  952. }
  953. JS_DEFINE_NATIVE_FUNCTION(Window::parent_getter)
  954. {
  955. auto* impl = TRY(impl_from(vm));
  956. auto* parent = impl->parent();
  957. if (!parent)
  958. return JS::js_null();
  959. return parent;
  960. }
  961. JS_DEFINE_NATIVE_FUNCTION(Window::document_getter)
  962. {
  963. auto* impl = TRY(impl_from(vm));
  964. return &impl->associated_document();
  965. }
  966. // https://html.spec.whatwg.org/multipage/browsers.html#dom-frameelement
  967. JS_DEFINE_NATIVE_FUNCTION(Window::frame_element_getter)
  968. {
  969. auto* impl = TRY(impl_from(vm));
  970. // 1. Let current be this Window object's browsing context.
  971. auto* current = impl->browsing_context();
  972. // 2. If current is null, then return null.
  973. if (!current)
  974. return JS::js_null();
  975. // 3. Let container be current's container.
  976. auto* container = current->container();
  977. // 4. If container is null, then return null.
  978. if (!container)
  979. return JS::js_null();
  980. // 5. If container's node document's origin is not same origin-domain with the current settings object's origin, then return null.
  981. if (!container->document().origin().is_same_origin(current_settings_object().origin()))
  982. return JS::js_null();
  983. // 6. Return container.
  984. return container;
  985. }
  986. JS_DEFINE_NATIVE_FUNCTION(Window::performance_getter)
  987. {
  988. auto* impl = TRY(impl_from(vm));
  989. return &impl->performance();
  990. }
  991. JS_DEFINE_NATIVE_FUNCTION(Window::performance_setter)
  992. {
  993. // https://webidl.spec.whatwg.org/#dfn-attribute-setter
  994. // 4.1. If no arguments were passed, then throw a TypeError.
  995. if (vm.argument_count() == 0)
  996. return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "set performance");
  997. auto* impl = TRY(impl_from(vm));
  998. // 5. If attribute is declared with the [Replaceable] extended attribute, then:
  999. // 1. Perform ? CreateDataProperty(esValue, id, V).
  1000. TRY(impl->create_data_property("performance", vm.argument(0)));
  1001. // 2. Return undefined.
  1002. return JS::js_undefined();
  1003. }
  1004. JS_DEFINE_NATIVE_FUNCTION(Window::screen_getter)
  1005. {
  1006. auto* impl = TRY(impl_from(vm));
  1007. return &impl->screen();
  1008. }
  1009. JS_DEFINE_NATIVE_FUNCTION(Window::event_getter)
  1010. {
  1011. auto* impl = TRY(impl_from(vm));
  1012. if (!impl->current_event())
  1013. return JS::js_undefined();
  1014. return impl->current_event();
  1015. }
  1016. JS_DEFINE_NATIVE_FUNCTION(Window::event_setter)
  1017. {
  1018. REPLACEABLE_PROPERTY_SETTER(Window, event);
  1019. }
  1020. JS_DEFINE_NATIVE_FUNCTION(Window::location_getter)
  1021. {
  1022. auto* impl = TRY(impl_from(vm));
  1023. return impl->m_location_object;
  1024. }
  1025. JS_DEFINE_NATIVE_FUNCTION(Window::location_setter)
  1026. {
  1027. auto* impl = TRY(impl_from(vm));
  1028. TRY(impl->m_location_object->set(JS::PropertyKey("href"), vm.argument(0), JS::Object::ShouldThrowExceptions::Yes));
  1029. return JS::js_undefined();
  1030. }
  1031. JS_DEFINE_NATIVE_FUNCTION(Window::crypto_getter)
  1032. {
  1033. auto* impl = TRY(impl_from(vm));
  1034. return &impl->crypto();
  1035. }
  1036. JS_DEFINE_NATIVE_FUNCTION(Window::inner_width_getter)
  1037. {
  1038. auto* impl = TRY(impl_from(vm));
  1039. return JS::Value(impl->inner_width());
  1040. }
  1041. JS_DEFINE_NATIVE_FUNCTION(Window::inner_height_getter)
  1042. {
  1043. auto* impl = TRY(impl_from(vm));
  1044. return JS::Value(impl->inner_height());
  1045. }
  1046. JS_DEFINE_NATIVE_FUNCTION(Window::device_pixel_ratio_getter)
  1047. {
  1048. auto* impl = TRY(impl_from(vm));
  1049. return JS::Value(impl->device_pixel_ratio());
  1050. }
  1051. JS_DEFINE_NATIVE_FUNCTION(Window::get_computed_style)
  1052. {
  1053. auto* impl = TRY(impl_from(vm));
  1054. auto* object = TRY(vm.argument(0).to_object(vm));
  1055. if (!is<DOM::Element>(object))
  1056. return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "DOM element");
  1057. return impl->get_computed_style_impl(*static_cast<DOM::Element*>(object));
  1058. }
  1059. // https://w3c.github.io/selection-api/#dom-window-getselection
  1060. JS_DEFINE_NATIVE_FUNCTION(Window::get_selection)
  1061. {
  1062. // The method must invoke and return the result of getSelection() on this's Window.document attribute.
  1063. auto* impl = TRY(impl_from(vm));
  1064. return impl->associated_document().get_selection();
  1065. }
  1066. JS_DEFINE_NATIVE_FUNCTION(Window::match_media)
  1067. {
  1068. auto* impl = TRY(impl_from(vm));
  1069. auto media = TRY(vm.argument(0).to_string(vm));
  1070. return impl->match_media_impl(move(media));
  1071. }
  1072. // https://www.w3.org/TR/cssom-view/#dom-window-scrollx
  1073. JS_DEFINE_NATIVE_FUNCTION(Window::scroll_x_getter)
  1074. {
  1075. auto* impl = TRY(impl_from(vm));
  1076. return JS::Value(impl->scroll_x());
  1077. }
  1078. // https://www.w3.org/TR/cssom-view/#dom-window-scrolly
  1079. JS_DEFINE_NATIVE_FUNCTION(Window::scroll_y_getter)
  1080. {
  1081. auto* impl = TRY(impl_from(vm));
  1082. return JS::Value(impl->scroll_y());
  1083. }
  1084. enum class ScrollBehavior {
  1085. Auto,
  1086. Smooth
  1087. };
  1088. // https://www.w3.org/TR/cssom-view/#perform-a-scroll
  1089. static void perform_a_scroll(Page& page, double x, double y, ScrollBehavior)
  1090. {
  1091. // FIXME: Stop any existing smooth-scrolls
  1092. // FIXME: Implement smooth-scroll
  1093. page.client().page_did_request_scroll_to({ x, y });
  1094. }
  1095. // https://www.w3.org/TR/cssom-view/#dom-window-scroll
  1096. JS_DEFINE_NATIVE_FUNCTION(Window::scroll)
  1097. {
  1098. auto* impl = TRY(impl_from(vm));
  1099. if (!impl->page())
  1100. return JS::js_undefined();
  1101. auto& page = *impl->page();
  1102. auto viewport_rect = page.top_level_browsing_context().viewport_rect();
  1103. auto x_value = JS::Value(viewport_rect.x());
  1104. auto y_value = JS::Value(viewport_rect.y());
  1105. String behavior_string = "auto";
  1106. if (vm.argument_count() == 1) {
  1107. auto* options = TRY(vm.argument(0).to_object(vm));
  1108. auto left = TRY(options->get("left"));
  1109. if (!left.is_undefined())
  1110. x_value = left;
  1111. auto top = TRY(options->get("top"));
  1112. if (!top.is_undefined())
  1113. y_value = top;
  1114. auto behavior_string_value = TRY(options->get("behavior"));
  1115. if (!behavior_string_value.is_undefined())
  1116. behavior_string = TRY(behavior_string_value.to_string(vm));
  1117. if (behavior_string != "smooth" && behavior_string != "auto")
  1118. return vm.throw_completion<JS::TypeError>("Behavior is not one of 'smooth' or 'auto'");
  1119. } else if (vm.argument_count() >= 2) {
  1120. // We ignore arguments 2+ in line with behavior of Chrome and Firefox
  1121. x_value = vm.argument(0);
  1122. y_value = vm.argument(1);
  1123. }
  1124. ScrollBehavior behavior = (behavior_string == "smooth") ? ScrollBehavior::Smooth : ScrollBehavior::Auto;
  1125. double x = TRY(x_value.to_double(vm));
  1126. x = JS::Value(x).is_finite_number() ? x : 0.0;
  1127. double y = TRY(y_value.to_double(vm));
  1128. y = JS::Value(y).is_finite_number() ? y : 0.0;
  1129. // FIXME: Are we calculating the viewport in the way this function expects?
  1130. // FIXME: Handle overflow-directions other than top-left to bottom-right
  1131. perform_a_scroll(page, x, y, behavior);
  1132. return JS::js_undefined();
  1133. }
  1134. // https://www.w3.org/TR/cssom-view/#dom-window-scrollby
  1135. JS_DEFINE_NATIVE_FUNCTION(Window::scroll_by)
  1136. {
  1137. auto& realm = *vm.current_realm();
  1138. auto* impl = TRY(impl_from(vm));
  1139. if (!impl->page())
  1140. return JS::js_undefined();
  1141. auto& page = *impl->page();
  1142. JS::Object* options = nullptr;
  1143. if (vm.argument_count() == 0) {
  1144. options = JS::Object::create(realm, nullptr);
  1145. } else if (vm.argument_count() == 1) {
  1146. options = TRY(vm.argument(0).to_object(vm));
  1147. } else if (vm.argument_count() >= 2) {
  1148. // We ignore arguments 2+ in line with behavior of Chrome and Firefox
  1149. options = JS::Object::create(realm, nullptr);
  1150. MUST(options->set("left", vm.argument(0), ShouldThrowExceptions::No));
  1151. MUST(options->set("top", vm.argument(1), ShouldThrowExceptions::No));
  1152. MUST(options->set("behavior", JS::js_string(vm, "auto"), ShouldThrowExceptions::No));
  1153. }
  1154. auto left_value = TRY(options->get("left"));
  1155. auto left = TRY(left_value.to_double(vm));
  1156. auto top_value = TRY(options->get("top"));
  1157. auto top = TRY(top_value.to_double(vm));
  1158. left = JS::Value(left).is_finite_number() ? left : 0.0;
  1159. top = JS::Value(top).is_finite_number() ? top : 0.0;
  1160. auto current_scroll_position = page.top_level_browsing_context().viewport_scroll_offset();
  1161. left = left + current_scroll_position.x();
  1162. top = top + current_scroll_position.y();
  1163. auto behavior_string_value = TRY(options->get("behavior"));
  1164. auto behavior_string = behavior_string_value.is_undefined() ? "auto" : TRY(behavior_string_value.to_string(vm));
  1165. if (behavior_string != "smooth" && behavior_string != "auto")
  1166. return vm.throw_completion<JS::TypeError>("Behavior is not one of 'smooth' or 'auto'");
  1167. ScrollBehavior behavior = (behavior_string == "smooth") ? ScrollBehavior::Smooth : ScrollBehavior::Auto;
  1168. // FIXME: Spec wants us to call scroll(options) here.
  1169. // The only difference is that would invoke the viewport calculations that scroll()
  1170. // is not actually doing yet, so this is the same for now.
  1171. perform_a_scroll(page, left, top, behavior);
  1172. return JS::js_undefined();
  1173. }
  1174. JS_DEFINE_NATIVE_FUNCTION(Window::history_getter)
  1175. {
  1176. auto* impl = TRY(impl_from(vm));
  1177. return impl->associated_document().history();
  1178. }
  1179. JS_DEFINE_NATIVE_FUNCTION(Window::screen_left_getter)
  1180. {
  1181. auto* impl = TRY(impl_from(vm));
  1182. return JS::Value(impl->screen_x());
  1183. }
  1184. JS_DEFINE_NATIVE_FUNCTION(Window::screen_top_getter)
  1185. {
  1186. auto* impl = TRY(impl_from(vm));
  1187. return JS::Value(impl->screen_y());
  1188. }
  1189. JS_DEFINE_NATIVE_FUNCTION(Window::screen_x_getter)
  1190. {
  1191. auto* impl = TRY(impl_from(vm));
  1192. return JS::Value(impl->screen_x());
  1193. }
  1194. JS_DEFINE_NATIVE_FUNCTION(Window::screen_y_getter)
  1195. {
  1196. auto* impl = TRY(impl_from(vm));
  1197. return JS::Value(impl->screen_y());
  1198. }
  1199. JS_DEFINE_NATIVE_FUNCTION(Window::post_message)
  1200. {
  1201. auto* impl = TRY(impl_from(vm));
  1202. auto target_origin = TRY(vm.argument(1).to_string(vm));
  1203. TRY(Bindings::throw_dom_exception_if_needed(vm, [&] {
  1204. return impl->post_message_impl(vm.argument(0), target_origin);
  1205. }));
  1206. return JS::js_undefined();
  1207. }
  1208. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-origin
  1209. JS_DEFINE_NATIVE_FUNCTION(Window::origin_getter)
  1210. {
  1211. auto* impl = TRY(impl_from(vm));
  1212. return JS::js_string(vm, impl->associated_document().origin().serialize());
  1213. }
  1214. JS_DEFINE_NATIVE_FUNCTION(Window::local_storage_getter)
  1215. {
  1216. auto* impl = TRY(impl_from(vm));
  1217. return impl->local_storage();
  1218. }
  1219. JS_DEFINE_NATIVE_FUNCTION(Window::session_storage_getter)
  1220. {
  1221. auto* impl = TRY(impl_from(vm));
  1222. return impl->session_storage();
  1223. }
  1224. JS_DEFINE_NATIVE_FUNCTION(Window::name_getter)
  1225. {
  1226. auto* impl = TRY(impl_from(vm));
  1227. return JS::js_string(vm, impl->name());
  1228. }
  1229. JS_DEFINE_NATIVE_FUNCTION(Window::name_setter)
  1230. {
  1231. auto* impl = TRY(impl_from(vm));
  1232. impl->set_name(TRY(vm.argument(0).to_string(vm)));
  1233. return JS::js_undefined();
  1234. }
  1235. #define __ENUMERATE(attribute, event_name) \
  1236. JS_DEFINE_NATIVE_FUNCTION(Window::attribute##_getter) \
  1237. { \
  1238. auto* impl = TRY(impl_from(vm)); \
  1239. auto retval = impl->attribute(); \
  1240. if (!retval) \
  1241. return JS::js_null(); \
  1242. return &retval->callback; \
  1243. } \
  1244. JS_DEFINE_NATIVE_FUNCTION(Window::attribute##_setter) \
  1245. { \
  1246. auto* impl = TRY(impl_from(vm)); \
  1247. auto value = vm.argument(0); \
  1248. WebIDL::CallbackType* cpp_value = nullptr; \
  1249. if (value.is_object()) { \
  1250. cpp_value = vm.heap().allocate_without_realm<WebIDL::CallbackType>( \
  1251. value.as_object(), HTML::incumbent_settings_object()); \
  1252. } \
  1253. impl->set_##attribute(cpp_value); \
  1254. return JS::js_undefined(); \
  1255. }
  1256. ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
  1257. ENUMERATE_WINDOW_EVENT_HANDLERS(__ENUMERATE)
  1258. #undef __ENUMERATE
  1259. }