Window.cpp 57 KB

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