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