summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibWeb/Bindings/WindowObject.cpp
blob: 24b670ea1d13a7e89e7acedc446ea7daa97c7191 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
/*
 * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
 * Copyright (c) 2021, Sam Atkins <atkinssj@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/Base64.h>
#include <AK/String.h>
#include <AK/Utf8View.h>
#include <LibJS/Runtime/Completion.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibJS/Runtime/Shape.h>
#include <LibTextCodec/Decoder.h>
#include <LibWeb/Bindings/CSSNamespace.h>
#include <LibWeb/Bindings/CSSStyleDeclarationWrapper.h>
#include <LibWeb/Bindings/CryptoWrapper.h>
#include <LibWeb/Bindings/DocumentWrapper.h>
#include <LibWeb/Bindings/ElementWrapper.h>
#include <LibWeb/Bindings/EventTargetConstructor.h>
#include <LibWeb/Bindings/EventTargetPrototype.h>
#include <LibWeb/Bindings/EventWrapper.h>
#include <LibWeb/Bindings/EventWrapperFactory.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/HistoryWrapper.h>
#include <LibWeb/Bindings/LocationObject.h>
#include <LibWeb/Bindings/MediaQueryListWrapper.h>
#include <LibWeb/Bindings/NavigatorObject.h>
#include <LibWeb/Bindings/NodeWrapperFactory.h>
#include <LibWeb/Bindings/PerformanceWrapper.h>
#include <LibWeb/Bindings/Replaceable.h>
#include <LibWeb/Bindings/ScreenWrapper.h>
#include <LibWeb/Bindings/SelectionWrapper.h>
#include <LibWeb/Bindings/WindowObject.h>
#include <LibWeb/Bindings/WindowObjectHelper.h>
#include <LibWeb/Crypto/Crypto.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Event.h>
#include <LibWeb/DOM/Window.h>
#include <LibWeb/HTML/EventHandler.h>
#include <LibWeb/HTML/Scripting/ClassicScript.h>
#include <LibWeb/Origin.h>
#include <LibWeb/Page/BrowsingContext.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/WebAssembly/WebAssemblyObject.h>

namespace Web::Bindings {

WindowObject::WindowObject(DOM::Window& impl)
    : m_impl(impl)
{
    impl.set_wrapper({}, *this);
}

void WindowObject::initialize_global_object()
{
    Base::initialize_global_object();

    Object::set_prototype(&ensure_web_prototype<EventTargetPrototype>("EventTarget"));

    // FIXME: These should be native accessors, not properties
    define_direct_property("window", this, JS::Attribute::Enumerable);
    define_direct_property("frames", this, JS::Attribute::Enumerable);
    define_direct_property("self", this, JS::Attribute::Enumerable);
    define_native_accessor("top", top_getter, nullptr, JS::Attribute::Enumerable);
    define_native_accessor("parent", parent_getter, {}, JS::Attribute::Enumerable);
    define_native_accessor("document", document_getter, {}, JS::Attribute::Enumerable);
    define_native_accessor("history", history_getter, {}, JS::Attribute::Enumerable);
    define_native_accessor("performance", performance_getter, {}, JS::Attribute::Enumerable);
    define_native_accessor("crypto", crypto_getter, {}, JS::Attribute::Enumerable);
    define_native_accessor("screen", screen_getter, {}, JS::Attribute::Enumerable);
    define_native_accessor("innerWidth", inner_width_getter, {}, JS::Attribute::Enumerable);
    define_native_accessor("innerHeight", inner_height_getter, {}, JS::Attribute::Enumerable);
    define_native_accessor("devicePixelRatio", device_pixel_ratio_getter, {}, JS::Attribute::Enumerable | JS::Attribute::Configurable);
    u8 attr = JS::Attribute::Writable | JS::Attribute::Enumerable | JS::Attribute::Configurable;
    define_native_function("alert", alert, 0, attr);
    define_native_function("confirm", confirm, 0, attr);
    define_native_function("prompt", prompt, 0, attr);
    define_native_function("setInterval", set_interval, 1, attr);
    define_native_function("setTimeout", set_timeout, 1, attr);
    define_native_function("clearInterval", clear_interval, 1, attr);
    define_native_function("clearTimeout", clear_timeout, 1, attr);
    define_native_function("requestAnimationFrame", request_animation_frame, 1, attr);
    define_native_function("cancelAnimationFrame", cancel_animation_frame, 1, attr);
    define_native_function("atob", atob, 1, attr);
    define_native_function("btoa", btoa, 1, attr);

    define_native_function("queueMicrotask", queue_microtask, 1, attr);

    define_native_function("getComputedStyle", get_computed_style, 1, attr);
    define_native_function("matchMedia", match_media, 1, attr);
    define_native_function("getSelection", get_selection, 0, attr);

    // FIXME: These properties should be [Replaceable] according to the spec, but [Writable+Configurable] is the closest we have.
    define_native_accessor("scrollX", scroll_x_getter, {}, attr);
    define_native_accessor("pageXOffset", scroll_x_getter, {}, attr);
    define_native_accessor("scrollY", scroll_y_getter, {}, attr);
    define_native_accessor("pageYOffset", scroll_y_getter, {}, attr);

    define_native_function("scroll", scroll, 2, attr);
    define_native_function("scrollTo", scroll, 2, attr);
    define_native_function("scrollBy", scroll_by, 2, attr);

    define_native_accessor("screenX", screen_x_getter, {}, attr);
    define_native_accessor("screenY", screen_y_getter, {}, attr);
    define_native_accessor("screenLeft", screen_left_getter, {}, attr);
    define_native_accessor("screenTop", screen_top_getter, {}, attr);

    define_direct_property("CSS", heap().allocate<CSSNamespace>(*this, *this), 0);

    // Legacy
    define_native_accessor("event", event_getter, event_setter, JS::Attribute::Enumerable);

    m_location_object = heap().allocate<LocationObject>(*this, *this);

    define_direct_property("navigator", heap().allocate<NavigatorObject>(*this, *this), JS::Attribute::Enumerable | JS::Attribute::Configurable);

    // NOTE: location is marked as [LegacyUnforgeable], meaning it isn't configurable.
    define_direct_property("location", m_location_object, JS::Attribute::Enumerable);

    // WebAssembly "namespace"
    define_direct_property("WebAssembly", heap().allocate<WebAssemblyObject>(*this, *this), JS::Attribute::Enumerable | JS::Attribute::Configurable);

    // HTML::GlobalEventHandlers
#define __ENUMERATE(attribute, event_name) \
    define_native_accessor(#attribute, attribute##_getter, attribute##_setter, attr);
    ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE);
#undef __ENUMERATE

    ADD_WINDOW_OBJECT_INTERFACES;
}

WindowObject::~WindowObject()
{
}

void WindowObject::visit_edges(Visitor& visitor)
{
    GlobalObject::visit_edges(visitor);
    visitor.visit(m_location_object);
    for (auto& it : m_prototypes)
        visitor.visit(it.value);
    for (auto& it : m_constructors)
        visitor.visit(it.value);
}

Origin WindowObject::origin() const
{
    return impl().associated_document().origin();
}

// https://webidl.spec.whatwg.org/#platform-object-setprototypeof
JS::ThrowCompletionOr<bool> WindowObject::internal_set_prototype_of(JS::Object* prototype)
{
    // 1. Return ? SetImmutablePrototype(O, V).
    return set_immutable_prototype(prototype);
}

static DOM::Window* impl_from(JS::VM& vm, JS::GlobalObject& global_object)
{
    // Since this is a non built-in function we must treat it as non-strict mode
    // this means that a nullish this_value should be converted to the
    // global_object. Generally this does not matter as we try to convert the
    // this_value to a specific object type in the bindings. But since window is
    // the global object we make an exception here.
    // This allows calls like `setTimeout(f, 10)` to work.
    auto this_value = vm.this_value(global_object);
    if (this_value.is_nullish()) {
        this_value = global_object.value_of();
    }

    auto* this_object = MUST(this_value.to_object(global_object));

    if (StringView("WindowObject") != this_object->class_name()) {
        vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "WindowObject");
        return nullptr;
    }
    return &static_cast<WindowObject*>(this_object)->impl();
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::alert)
{
    // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#simple-dialogs
    // Note: This method is defined using two overloads, instead of using an optional argument,
    //       for historical reasons. The practical impact of this is that alert(undefined) is
    //       treated as alert("undefined"), but alert() is treated as alert("").
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    String message = "";
    if (vm.argument_count())
        message = TRY_OR_DISCARD(vm.argument(0).to_string(global_object));
    impl->alert(message);
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::confirm)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    String message = "";
    if (!vm.argument(0).is_undefined())
        message = TRY_OR_DISCARD(vm.argument(0).to_string(global_object));
    return JS::Value(impl->confirm(message));
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::prompt)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    String message = "";
    String default_ = "";
    if (!vm.argument(0).is_undefined())
        message = TRY_OR_DISCARD(vm.argument(0).to_string(global_object));
    if (!vm.argument(1).is_undefined())
        default_ = TRY_OR_DISCARD(vm.argument(1).to_string(global_object));
    auto response = impl->prompt(message, default_);
    if (response.is_null())
        return JS::js_null();
    return JS::js_string(vm, response);
}

// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
JS_DEFINE_NATIVE_FUNCTION(WindowObject::set_interval)
{
    // FIXME: Ideally this would share more code with setTimeout() using the "timer initialization steps"
    // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    if (!vm.argument_count()) {
        vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::BadArgCountAtLeastOne, "setInterval");
        return {};
    }
    JS::FunctionObject* callback;
    if (vm.argument(0).is_function()) {
        callback = &vm.argument(0).as_function();
    } else {
        auto script_source = TRY_OR_DISCARD(vm.argument(0).to_string(global_object));
        // FIXME: This needs more work once we have a environment settings object.
        // The spec wants us to use a task for the "run function or script string" part,
        // using a NativeFunction for the latter is a workaround so that we can reuse the
        // DOM::Timer API unaltered (always expects a JS::FunctionObject).
        callback = JS::NativeFunction::create(global_object, "", [impl, script_source = move(script_source)](auto&, auto&) mutable {
            auto script = HTML::ClassicScript::create(impl->associated_document().url().to_string(), script_source, impl->associated_document().realm(), AK::URL());
            return script->run();
        });
    }
    i32 interval = 0;
    if (vm.argument_count() >= 2) {
        interval = TRY_OR_DISCARD(vm.argument(1).to_i32(global_object));
        if (interval < 0)
            interval = 0;
    }
    // FIXME: Pass ...arguments to the callback function when it's invoked
    auto timer_id = impl->set_interval(*callback, interval);
    return JS::Value(timer_id);
}

// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
JS_DEFINE_NATIVE_FUNCTION(WindowObject::set_timeout)
{
    // FIXME: Ideally this would share more code with setInterval() using the "timer initialization steps"
    // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    if (!vm.argument_count()) {
        vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::BadArgCountAtLeastOne, "setTimeout");
        return {};
    }
    JS::FunctionObject* callback;
    if (vm.argument(0).is_function()) {
        callback = &vm.argument(0).as_function();
    } else {
        auto script_source = TRY_OR_DISCARD(vm.argument(0).to_string(global_object));
        // FIXME: This needs more work once we have a environment settings object.
        // The spec wants us to use a task for the "run function or script string" part,
        // using a NativeFunction for the latter is a workaround so that we can reuse the
        // DOM::Timer API unaltered (always expects a JS::FunctionObject).
        callback = JS::NativeFunction::create(global_object, "", [impl, script_source = move(script_source)](auto&, auto&) mutable {
            auto script = HTML::ClassicScript::create(impl->associated_document().url().to_string(), script_source, impl->associated_document().realm(), AK::URL());
            return script->run();
        });
    }
    i32 interval = 0;
    if (vm.argument_count() >= 2) {
        interval = TRY_OR_DISCARD(vm.argument(1).to_i32(global_object));
        if (interval < 0)
            interval = 0;
    }
    // FIXME: Pass ...arguments to the callback function when it's invoked
    auto timer_id = impl->set_timeout(*callback, interval);
    return JS::Value(timer_id);
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::clear_timeout)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    if (!vm.argument_count()) {
        vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::BadArgCountAtLeastOne, "clearTimeout");
        return {};
    }
    i32 timer_id = TRY_OR_DISCARD(vm.argument(0).to_i32(global_object));
    impl->clear_timeout(timer_id);
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::clear_interval)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    if (!vm.argument_count()) {
        vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::BadArgCountAtLeastOne, "clearInterval");
        return {};
    }
    i32 timer_id = TRY_OR_DISCARD(vm.argument(0).to_i32(global_object));
    impl->clear_interval(timer_id);
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::request_animation_frame)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    if (!vm.argument_count()) {
        vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::BadArgCountOne, "requestAnimationFrame");
        return {};
    }
    auto* callback_object = TRY_OR_DISCARD(vm.argument(0).to_object(global_object));
    if (!callback_object->is_function()) {
        vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAFunctionNoParam);
        return {};
    }
    return JS::Value(impl->request_animation_frame(*static_cast<JS::FunctionObject*>(callback_object)));
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::cancel_animation_frame)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    if (!vm.argument_count()) {
        vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::BadArgCountOne, "cancelAnimationFrame");
        return {};
    }
    auto id = TRY_OR_DISCARD(vm.argument(0).to_i32(global_object));
    impl->cancel_animation_frame(id);
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::queue_microtask)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    if (!vm.argument_count()) {
        vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::BadArgCountAtLeastOne, "queueMicrotask");
        return {};
    }
    auto* callback_object = TRY_OR_DISCARD(vm.argument(0).to_object(global_object));
    if (!callback_object->is_function()) {
        vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAFunctionNoParam);
        return {};
    }

    impl->queue_microtask(static_cast<JS::FunctionObject&>(*callback_object));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::atob)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    if (!vm.argument_count()) {
        vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::BadArgCountOne, "atob");
        return {};
    }
    auto string = TRY_OR_DISCARD(vm.argument(0).to_string(global_object));
    auto decoded = decode_base64(StringView(string));

    // decode_base64() returns a byte string. LibJS uses UTF-8 for strings. Use Latin1Decoder to convert bytes 128-255 to UTF-8.
    auto decoder = TextCodec::decoder_for("windows-1252");
    VERIFY(decoder);
    return JS::js_string(vm, decoder->to_utf8(decoded));
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::btoa)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    if (!vm.argument_count()) {
        vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::BadArgCountOne, "btoa");
        return {};
    }
    auto string = TRY_OR_DISCARD(vm.argument(0).to_string(global_object));

    Vector<u8> byte_string;
    byte_string.ensure_capacity(string.length());
    for (u32 code_point : Utf8View(string)) {
        if (code_point > 0xff) {
            vm.throw_exception<JS::InvalidCharacterError>(global_object, JS::ErrorType::NotAByteString, "btoa");
            return {};
        }
        byte_string.append(code_point);
    }

    auto encoded = encode_base64(byte_string.span());
    return JS::js_string(vm, move(encoded));
}

// https://html.spec.whatwg.org/multipage/browsers.html#dom-top
JS_DEFINE_NATIVE_FUNCTION(WindowObject::top_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};

    auto* this_browsing_context = impl->associated_document().browsing_context();
    if (!this_browsing_context)
        return JS::js_null();

    VERIFY(this_browsing_context->top_level_browsing_context().active_document());
    auto& top_window = this_browsing_context->top_level_browsing_context().active_document()->window();
    return top_window.wrapper();
}

// https://html.spec.whatwg.org/multipage/browsers.html#dom-parent
JS_DEFINE_NATIVE_FUNCTION(WindowObject::parent_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};

    auto* this_browsing_context = impl->associated_document().browsing_context();
    if (!this_browsing_context)
        return JS::js_null();

    if (this_browsing_context->parent()) {
        VERIFY(this_browsing_context->parent()->active_document());
        auto& parent_window = this_browsing_context->parent()->active_document()->window();
        return parent_window.wrapper();
    }
    VERIFY(this_browsing_context == &this_browsing_context->top_level_browsing_context());
    return impl->wrapper();
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::document_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    return wrap(global_object, impl->associated_document());
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::performance_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    return wrap(global_object, impl->performance());
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::screen_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    return wrap(global_object, impl->screen());
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::event_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    if (!impl->current_event())
        return JS::js_undefined();
    return wrap(global_object, const_cast<DOM::Event&>(*impl->current_event()));
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::event_setter)
{
    REPLACEABLE_PROPERTY_SETTER(WindowObject, event);
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::crypto_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    return wrap(global_object, impl->crypto());
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::inner_width_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    return JS::Value(impl->inner_width());
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::inner_height_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    return JS::Value(impl->inner_height());
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::device_pixel_ratio_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    return JS::Value(impl->device_pixel_ratio());
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::get_computed_style)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    auto* object = TRY_OR_DISCARD(vm.argument(0).to_object(global_object));
    if (!is<ElementWrapper>(object)) {
        vm.throw_exception<JS::TypeError>(global_object, JS::ErrorType::NotAnObjectOfType, "DOM element");
        return {};
    }

    return wrap(global_object, impl->get_computed_style(static_cast<ElementWrapper*>(object)->impl()));
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::get_selection)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    auto* selection = impl->get_selection();
    if (!selection)
        return JS::js_null();
    return wrap(global_object, *selection);
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::match_media)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    auto media = TRY_OR_DISCARD(vm.argument(0).to_string(global_object));
    return wrap(global_object, impl->match_media(move(media)));
}

// https://www.w3.org/TR/cssom-view/#dom-window-scrollx
JS_DEFINE_NATIVE_FUNCTION(WindowObject::scroll_x_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    return JS::Value(impl->scroll_x());
}

// https://www.w3.org/TR/cssom-view/#dom-window-scrolly
JS_DEFINE_NATIVE_FUNCTION(WindowObject::scroll_y_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    return JS::Value(impl->scroll_y());
}

enum class ScrollBehavior {
    Auto,
    Smooth
};

// https://www.w3.org/TR/cssom-view/#perform-a-scroll
static void perform_a_scroll(Page& page, double x, double y, ScrollBehavior)
{
    // FIXME: Stop any existing smooth-scrolls
    // FIXME: Implement smooth-scroll
    page.client().page_did_request_scroll_to({ x, y });
}

// https://www.w3.org/TR/cssom-view/#dom-window-scroll
JS_DEFINE_NATIVE_FUNCTION(WindowObject::scroll)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    if (!impl->page())
        return {};
    auto& page = *impl->page();

    auto viewport_rect = page.top_level_browsing_context().viewport_rect();
    auto x_value = JS::Value(viewport_rect.x());
    auto y_value = JS::Value(viewport_rect.y());
    String behavior_string = "auto";

    if (vm.argument_count() == 1) {
        auto* options = TRY_OR_DISCARD(vm.argument(0).to_object(global_object));
        auto left = TRY_OR_DISCARD(options->get("left"));
        if (!left.is_undefined())
            x_value = left;

        auto top = TRY_OR_DISCARD(options->get("top"));
        if (!top.is_undefined())
            y_value = top;

        auto behavior_string_value = TRY_OR_DISCARD(options->get("behavior"));
        if (!behavior_string_value.is_undefined())
            behavior_string = TRY_OR_DISCARD(behavior_string_value.to_string(global_object));
        if (behavior_string != "smooth" && behavior_string != "auto") {
            vm.throw_exception<JS::TypeError>(global_object, "Behavior is not one of 'smooth' or 'auto'");
            return {};
        }

    } else if (vm.argument_count() >= 2) {
        // We ignore arguments 2+ in line with behavior of Chrome and Firefox
        x_value = vm.argument(0);
        y_value = vm.argument(1);
    }

    ScrollBehavior behavior = (behavior_string == "smooth") ? ScrollBehavior::Smooth : ScrollBehavior::Auto;

    double x = TRY_OR_DISCARD(x_value.to_double(global_object));
    x = JS::Value(x).is_finite_number() ? x : 0.0;

    double y = TRY_OR_DISCARD(y_value.to_double(global_object));
    y = JS::Value(y).is_finite_number() ? y : 0.0;

    // FIXME: Are we calculating the viewport in the way this function expects?
    // FIXME: Handle overflow-directions other than top-left to bottom-right

    perform_a_scroll(page, x, y, behavior);
    return JS::js_undefined();
}

// https://www.w3.org/TR/cssom-view/#dom-window-scrollby
JS_DEFINE_NATIVE_FUNCTION(WindowObject::scroll_by)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    if (!impl->page())
        return {};
    auto& page = *impl->page();

    JS::Object* options = nullptr;

    if (vm.argument_count() == 0) {
        options = JS::Object::create(global_object, nullptr);
    } else if (vm.argument_count() == 1) {
        options = TRY_OR_DISCARD(vm.argument(0).to_object(global_object));
    } else if (vm.argument_count() >= 2) {
        // We ignore arguments 2+ in line with behavior of Chrome and Firefox
        options = JS::Object::create(global_object, nullptr);
        MUST(options->set("left", vm.argument(0), ShouldThrowExceptions::No));
        MUST(options->set("top", vm.argument(1), ShouldThrowExceptions::No));
        MUST(options->set("behavior", JS::js_string(vm, "auto"), ShouldThrowExceptions::No));
    }

    auto left_value = TRY_OR_DISCARD(options->get("left"));
    auto left = TRY_OR_DISCARD(left_value.to_double(global_object));

    auto top_value = TRY_OR_DISCARD(options->get("top"));
    auto top = TRY_OR_DISCARD(top_value.to_double(global_object));

    left = JS::Value(left).is_finite_number() ? left : 0.0;
    top = JS::Value(top).is_finite_number() ? top : 0.0;

    auto current_scroll_position = page.top_level_browsing_context().viewport_scroll_offset();
    left = left + current_scroll_position.x();
    top = top + current_scroll_position.y();

    auto behavior_string_value = TRY_OR_DISCARD(options->get("behavior"));
    auto behavior_string = behavior_string_value.is_undefined() ? "auto" : TRY_OR_DISCARD(behavior_string_value.to_string(global_object));
    if (behavior_string != "smooth" && behavior_string != "auto") {
        vm.throw_exception<JS::TypeError>(global_object, "Behavior is not one of 'smooth' or 'auto'");
        return {};
    }
    ScrollBehavior behavior = (behavior_string == "smooth") ? ScrollBehavior::Smooth : ScrollBehavior::Auto;

    // FIXME: Spec wants us to call scroll(options) here.
    //        The only difference is that would invoke the viewport calculations that scroll()
    //        is not actually doing yet, so this is the same for now.
    perform_a_scroll(page, left, top, behavior);
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::history_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    return wrap(global_object, impl->associated_document().history());
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::screen_left_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    return JS::Value(impl->screen_x());
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::screen_top_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    return JS::Value(impl->screen_y());
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::screen_x_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    return JS::Value(impl->screen_x());
}

JS_DEFINE_NATIVE_FUNCTION(WindowObject::screen_y_getter)
{
    auto* impl = impl_from(vm, global_object);
    if (!impl)
        return {};
    return JS::Value(impl->screen_y());
}

#define __ENUMERATE(attribute, event_name)                                   \
    JS_DEFINE_NATIVE_FUNCTION(WindowObject::attribute##_getter)              \
    {                                                                        \
        auto* impl = impl_from(vm, global_object);                           \
        if (!impl)                                                           \
            return {};                                                       \
        auto retval = impl->attribute();                                     \
        if (retval.callback.is_null())                                       \
            return JS::js_null();                                            \
        return retval.callback.cell();                                       \
    }                                                                        \
    JS_DEFINE_NATIVE_FUNCTION(WindowObject::attribute##_setter)              \
    {                                                                        \
        auto* impl = impl_from(vm, global_object);                           \
        if (!impl)                                                           \
            return {};                                                       \
        auto value = vm.argument(0);                                         \
        HTML::EventHandler cpp_value;                                        \
        if (value.is_function()) {                                           \
            cpp_value.callback = JS::make_handle(&value.as_function());      \
        } else if (value.is_string()) {                                      \
            cpp_value.string = value.as_string().string();                   \
        } else {                                                             \
            return JS::js_undefined();                                       \
        }                                                                    \
        auto result = throw_dom_exception_if_needed(vm, global_object, [&] { \
            return impl->set_##attribute(cpp_value);                         \
        });                                                                  \
        if (should_return_empty(result))                                     \
            return {};                                                       \
        return JS::js_undefined();                                           \
    }
ENUMERATE_GLOBAL_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE

}