Coverage Report

Created: 2025-12-18 07:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/serenity/Userland/Libraries/LibWeb/HTML/HTMLImageElement.cpp
Line
Count
Source
1
/*
2
 * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
3
 *
4
 * SPDX-License-Identifier: BSD-2-Clause
5
 */
6
7
#include <LibCore/Timer.h>
8
#include <LibGfx/Bitmap.h>
9
#include <LibWeb/ARIA/Roles.h>
10
#include <LibWeb/Bindings/HTMLImageElementPrototype.h>
11
#include <LibWeb/CSS/Parser/Parser.h>
12
#include <LibWeb/CSS/StyleComputer.h>
13
#include <LibWeb/DOM/Document.h>
14
#include <LibWeb/DOM/Event.h>
15
#include <LibWeb/Fetch/Fetching/Fetching.h>
16
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
17
#include <LibWeb/Fetch/Response.h>
18
#include <LibWeb/HTML/AnimatedBitmapDecodedImageData.h>
19
#include <LibWeb/HTML/CORSSettingAttribute.h>
20
#include <LibWeb/HTML/EventNames.h>
21
#include <LibWeb/HTML/HTMLImageElement.h>
22
#include <LibWeb/HTML/HTMLLinkElement.h>
23
#include <LibWeb/HTML/HTMLPictureElement.h>
24
#include <LibWeb/HTML/HTMLSourceElement.h>
25
#include <LibWeb/HTML/ImageRequest.h>
26
#include <LibWeb/HTML/ListOfAvailableImages.h>
27
#include <LibWeb/HTML/Parser/HTMLParser.h>
28
#include <LibWeb/HTML/PotentialCORSRequest.h>
29
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
30
#include <LibWeb/Layout/ImageBox.h>
31
#include <LibWeb/Loader/ResourceLoader.h>
32
#include <LibWeb/Painting/PaintableBox.h>
33
#include <LibWeb/Platform/EventLoopPlugin.h>
34
#include <LibWeb/Platform/ImageCodecPlugin.h>
35
#include <LibWeb/SVG/SVGDecodedImageData.h>
36
37
namespace Web::HTML {
38
39
JS_DEFINE_ALLOCATOR(HTMLImageElement);
40
41
HTMLImageElement::HTMLImageElement(DOM::Document& document, DOM::QualifiedName qualified_name)
42
0
    : HTMLElement(document, move(qualified_name))
43
0
{
44
0
    m_animation_timer = Core::Timer::try_create().release_value_but_fixme_should_propagate_errors();
45
0
    m_animation_timer->on_timeout = [this] { animate(); };
46
47
0
    document.register_viewport_client(*this);
48
0
}
49
50
0
HTMLImageElement::~HTMLImageElement() = default;
51
52
void HTMLImageElement::finalize()
53
0
{
54
0
    Base::finalize();
55
0
    document().unregister_viewport_client(*this);
56
0
}
57
58
void HTMLImageElement::initialize(JS::Realm& realm)
59
0
{
60
0
    Base::initialize(realm);
61
0
    WEB_SET_PROTOTYPE_FOR_INTERFACE(HTMLImageElement);
62
63
0
    m_current_request = ImageRequest::create(realm, document().page());
64
0
}
65
66
void HTMLImageElement::adopted_from(DOM::Document& old_document)
67
0
{
68
0
    old_document.unregister_viewport_client(*this);
69
0
    document().register_viewport_client(*this);
70
0
}
71
72
void HTMLImageElement::visit_edges(Cell::Visitor& visitor)
73
0
{
74
0
    Base::visit_edges(visitor);
75
0
    visitor.visit(m_current_request);
76
0
    visitor.visit(m_pending_request);
77
0
    visit_lazy_loading_element(visitor);
78
0
}
79
80
void HTMLImageElement::apply_presentational_hints(CSS::StyleProperties& style) const
81
0
{
82
0
    for_each_attribute([&](auto& name, auto& value) {
83
0
        if (name == HTML::AttributeNames::hspace) {
84
0
            if (auto parsed_value = parse_dimension_value(value)) {
85
0
                style.set_property(CSS::PropertyID::MarginLeft, *parsed_value);
86
0
                style.set_property(CSS::PropertyID::MarginRight, *parsed_value);
87
0
            }
88
0
        } else if (name == HTML::AttributeNames::vspace) {
89
0
            if (auto parsed_value = parse_dimension_value(value)) {
90
0
                style.set_property(CSS::PropertyID::MarginTop, *parsed_value);
91
0
                style.set_property(CSS::PropertyID::MarginBottom, *parsed_value);
92
0
            }
93
0
        }
94
0
    });
95
0
}
96
97
void HTMLImageElement::form_associated_element_attribute_changed(FlyString const& name, Optional<String> const& value)
98
0
{
99
0
    if (name == HTML::AttributeNames::crossorigin) {
100
0
        m_cors_setting = cors_setting_attribute_from_keyword(value);
101
0
    }
102
103
0
    if (name.is_one_of(HTML::AttributeNames::src, HTML::AttributeNames::srcset)) {
104
0
        update_the_image_data(true).release_value_but_fixme_should_propagate_errors();
105
0
    }
106
107
0
    if (name == HTML::AttributeNames::alt) {
108
0
        if (layout_node())
109
0
            did_update_alt_text(verify_cast<Layout::ImageBox>(*layout_node()));
110
0
    }
111
0
}
112
113
JS::GCPtr<Layout::Node> HTMLImageElement::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style)
114
0
{
115
0
    return heap().allocate_without_realm<Layout::ImageBox>(document(), *this, move(style), *this);
116
0
}
117
118
RefPtr<Gfx::ImmutableBitmap> HTMLImageElement::immutable_bitmap() const
119
0
{
120
0
    return current_image_bitmap();
121
0
}
122
123
RefPtr<Gfx::Bitmap const> HTMLImageElement::bitmap() const
124
0
{
125
0
    if (auto immutable_bitmap = this->immutable_bitmap())
126
0
        return immutable_bitmap->bitmap();
127
0
    return {};
128
0
}
129
130
bool HTMLImageElement::is_image_available() const
131
0
{
132
0
    return m_current_request && m_current_request->is_available();
133
0
}
134
135
Optional<CSSPixels> HTMLImageElement::intrinsic_width() const
136
0
{
137
0
    if (auto image_data = m_current_request->image_data())
138
0
        return image_data->intrinsic_width();
139
0
    return {};
140
0
}
141
142
Optional<CSSPixels> HTMLImageElement::intrinsic_height() const
143
0
{
144
0
    if (auto image_data = m_current_request->image_data())
145
0
        return image_data->intrinsic_height();
146
0
    return {};
147
0
}
148
149
Optional<CSSPixelFraction> HTMLImageElement::intrinsic_aspect_ratio() const
150
0
{
151
0
    if (auto image_data = m_current_request->image_data())
152
0
        return image_data->intrinsic_aspect_ratio();
153
0
    return {};
154
0
}
155
156
RefPtr<Gfx::ImmutableBitmap> HTMLImageElement::current_image_bitmap(Gfx::IntSize size) const
157
0
{
158
0
    if (auto data = m_current_request->image_data())
159
0
        return data->bitmap(m_current_frame_index, size);
160
0
    return nullptr;
161
0
}
162
163
void HTMLImageElement::set_visible_in_viewport(bool)
164
0
{
165
    // FIXME: Loosen grip on image data when it's not visible, e.g via volatile memory.
166
0
}
167
168
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-width
169
unsigned HTMLImageElement::width() const
170
0
{
171
0
    const_cast<DOM::Document&>(document()).update_layout();
172
173
    // Return the rendered width of the image, in CSS pixels, if the image is being rendered.
174
0
    if (auto* paintable_box = this->paintable_box())
175
0
        return paintable_box->content_width().to_int();
176
177
    // NOTE: This step seems to not be in the spec, but all browsers do it.
178
0
    if (auto width_attr = get_attribute(HTML::AttributeNames::width); width_attr.has_value()) {
179
0
        if (auto converted = width_attr->to_number<unsigned>(); converted.has_value())
180
0
            return *converted;
181
0
    }
182
183
    // ...or else the density-corrected intrinsic width and height of the image, in CSS pixels,
184
    // if the image has intrinsic dimensions and is available but not being rendered.
185
0
    if (auto bitmap = current_image_bitmap())
186
0
        return bitmap->width();
187
188
    // ...or else 0, if the image is not available or does not have intrinsic dimensions.
189
0
    return 0;
190
0
}
191
192
WebIDL::ExceptionOr<void> HTMLImageElement::set_width(unsigned width)
193
0
{
194
0
    return set_attribute(HTML::AttributeNames::width, String::number(width));
195
0
}
196
197
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-height
198
unsigned HTMLImageElement::height() const
199
0
{
200
0
    const_cast<DOM::Document&>(document()).update_layout();
201
202
    // Return the rendered height of the image, in CSS pixels, if the image is being rendered.
203
0
    if (auto* paintable_box = this->paintable_box())
204
0
        return paintable_box->content_height().to_int();
205
206
    // NOTE: This step seems to not be in the spec, but all browsers do it.
207
0
    if (auto height_attr = get_attribute(HTML::AttributeNames::height); height_attr.has_value()) {
208
0
        if (auto converted = height_attr->to_number<unsigned>(); converted.has_value())
209
0
            return *converted;
210
0
    }
211
212
    // ...or else the density-corrected intrinsic height and height of the image, in CSS pixels,
213
    // if the image has intrinsic dimensions and is available but not being rendered.
214
0
    if (auto bitmap = current_image_bitmap())
215
0
        return bitmap->height();
216
217
    // ...or else 0, if the image is not available or does not have intrinsic dimensions.
218
0
    return 0;
219
0
}
220
221
WebIDL::ExceptionOr<void> HTMLImageElement::set_height(unsigned height)
222
0
{
223
0
    return set_attribute(HTML::AttributeNames::height, String::number(height));
224
0
}
225
226
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-naturalwidth
227
unsigned HTMLImageElement::natural_width() const
228
0
{
229
    // Return the density-corrected intrinsic width of the image, in CSS pixels,
230
    // if the image has intrinsic dimensions and is available.
231
0
    if (auto bitmap = current_image_bitmap())
232
0
        return bitmap->width();
233
234
    // ...or else 0.
235
0
    return 0;
236
0
}
237
238
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-naturalheight
239
unsigned HTMLImageElement::natural_height() const
240
0
{
241
    // Return the density-corrected intrinsic height of the image, in CSS pixels,
242
    // if the image has intrinsic dimensions and is available.
243
0
    if (auto bitmap = current_image_bitmap())
244
0
        return bitmap->height();
245
246
    // ...or else 0.
247
0
    return 0;
248
0
}
249
250
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-complete
251
bool HTMLImageElement::complete() const
252
0
{
253
    // The IDL attribute complete must return true if any of the following conditions is true:
254
255
    // - Both the src attribute and the srcset attribute are omitted.
256
0
    if (!has_attribute(HTML::AttributeNames::src) && !has_attribute(HTML::AttributeNames::srcset))
257
0
        return true;
258
259
    // - The srcset attribute is omitted and the src attribute's value is the empty string.
260
0
    if (!has_attribute(HTML::AttributeNames::srcset) && attribute(HTML::AttributeNames::src).value().is_empty())
261
0
        return true;
262
263
    // - The img element's current request's state is completely available and its pending request is null.
264
0
    if (m_current_request->state() == ImageRequest::State::CompletelyAvailable && !m_pending_request)
265
0
        return true;
266
267
    // - The img element's current request's state is broken and its pending request is null.
268
0
    if (m_current_request->state() == ImageRequest::State::Broken && !m_pending_request)
269
0
        return true;
270
271
0
    return false;
272
0
}
273
274
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-currentsrc
275
String HTMLImageElement::current_src() const
276
0
{
277
    // The currentSrc IDL attribute must return the img element's current request's current URL.
278
0
    auto current_url = m_current_request->current_url();
279
0
    if (!current_url.is_valid())
280
0
        return {};
281
0
    return MUST(current_url.to_string());
282
0
}
283
284
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-decode
285
WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> HTMLImageElement::decode() const
286
0
{
287
0
    auto& realm = this->realm();
288
289
    // 1. Let promise be a new promise.
290
0
    auto promise = WebIDL::create_promise(realm);
291
292
    // 2. Queue a microtask to perform the following steps:
293
0
    queue_a_microtask(&document(), JS::create_heap_function(realm.heap(), [this, promise, &realm]() mutable {
294
0
        auto reject_if_document_not_fully_active = [this, promise, &realm]() -> bool {
295
0
            if (this->document().is_fully_active())
296
0
                return false;
297
298
0
            auto exception = WebIDL::EncodingError::create(realm, "Node document not fully active"_string);
299
0
            HTML::TemporaryExecutionContext context(HTML::relevant_settings_object(*this));
300
0
            WebIDL::reject_promise(realm, promise, exception);
301
0
            return true;
302
0
        };
303
304
0
        auto reject_if_current_request_state_broken = [this, promise, &realm]() {
305
0
            if (this->current_request().state() != ImageRequest::State::Broken)
306
0
                return false;
307
308
0
            auto exception = WebIDL::EncodingError::create(realm, "Current request state is broken"_string);
309
0
            HTML::TemporaryExecutionContext context(HTML::relevant_settings_object(*this));
310
0
            WebIDL::reject_promise(realm, promise, exception);
311
0
            return true;
312
0
        };
313
314
        // 2.1 If any of the following are true:
315
        // 2.1.1 this's node document is not fully active;
316
        // 2.1.1 then reject promise with an "EncodingError" DOMException.
317
0
        if (reject_if_document_not_fully_active())
318
0
            return;
319
320
        // 2.1.2  or this's current request's state is broken,
321
        // 2.1.2 then reject promise with an "EncodingError" DOMException.
322
0
        if (reject_if_current_request_state_broken())
323
0
            return;
324
325
        // 2.2 Otherwise, in parallel wait for one of the following cases to occur, and perform the corresponding actions:
326
0
        Platform::EventLoopPlugin::the().deferred_invoke([this, promise, &realm, reject_if_document_not_fully_active, reject_if_current_request_state_broken] {
327
0
            Platform::EventLoopPlugin::the().spin_until([&] {
328
0
                auto state = this->current_request().state();
329
330
0
                return !this->document().is_fully_active() || state == ImageRequest::State::Broken || state == ImageRequest::State::CompletelyAvailable;
331
0
            });
332
333
            // 2.2.1 This img element's node document stops being fully active
334
            // 2.2.1 Reject promise with an "EncodingError" DOMException.
335
0
            if (reject_if_document_not_fully_active())
336
0
                return;
337
338
            // FIXME: 2.2.2 This img element's current request changes or is mutated
339
            // FIXME: 2.2.2 Reject promise with an "EncodingError" DOMException.
340
341
            // 2.2.3 This img element's current request's state becomes broken
342
            // 2.2.3 Reject promise with an "EncodingError" DOMException.
343
0
            if (reject_if_current_request_state_broken())
344
0
                return;
345
346
            // 2.2.4 This img element's current request's state becomes completely available
347
0
            if (this->current_request().state() == ImageRequest::State::CompletelyAvailable) {
348
                // 2.2.4.1 FIXME: Decode the image.
349
                // 2.2.4.2 FIXME: If decoding does not need to be performed for this image (for example because it is a vector graphic), resolve promise with undefined.
350
                // 2.2.4.3 FIXME: If decoding fails (for example due to invalid image data), reject promise with an "EncodingError" DOMException.
351
                // 2.2.4.4 FIXME: If the decoding process completes successfully, resolve promise with undefined.
352
                // 2.2.4.5 FIXME: User agents should ensure that the decoded media data stays readily available until at least the end of the next successful update
353
                // the rendering step in the event loop. This is an important part of the API contract, and should not be broken if at all possible.
354
                // (Typically, this would only be violated in low-memory situations that require evicting decoded image data, or when the image is too large
355
                // to keep in decoded form for this period of time.)
356
357
0
                HTML::TemporaryExecutionContext context(HTML::relevant_settings_object(*this));
358
0
                WebIDL::resolve_promise(realm, promise, JS::js_undefined());
359
0
            }
360
0
        });
361
0
    }));
362
363
0
    return JS::NonnullGCPtr { verify_cast<JS::Promise>(*promise->promise()) };
364
0
}
365
366
Optional<ARIA::Role> HTMLImageElement::default_role() const
367
0
{
368
    // https://www.w3.org/TR/html-aria/#el-img
369
    // https://www.w3.org/TR/html-aria/#el-img-no-alt
370
0
    if (!alt().is_empty())
371
0
        return ARIA::Role::img;
372
    // https://www.w3.org/TR/html-aria/#el-img-empty-alt
373
0
    return ARIA::Role::presentation;
374
0
}
375
376
// https://html.spec.whatwg.org/multipage/images.html#use-srcset-or-picture
377
bool HTMLImageElement::uses_srcset_or_picture() const
378
0
{
379
    // An img element is said to use srcset or picture if it has a srcset attribute specified
380
    // or if it has a parent that is a picture element.
381
0
    return has_attribute(HTML::AttributeNames::srcset) || (parent() && is<HTMLPictureElement>(*parent()));
382
0
}
383
384
// We batch handling of successfully fetched images to avoid interleaving 1 image, 1 layout, 1 image, 1 layout, etc.
385
// The processing timer is 1ms instead of 0ms, since layout is driven by a 0ms timer, and if we use 0ms here,
386
// the event loop will process them in insertion order. This is a bit of a hack, but it works.
387
struct BatchingDispatcher {
388
public:
389
    BatchingDispatcher()
390
0
        : m_timer(Core::Timer::create_single_shot(1, [this] { process(); }))
391
0
    {
392
0
    }
393
394
    void enqueue(JS::Handle<JS::HeapFunction<void()>> callback)
395
0
    {
396
        // NOTE: We don't want to flush the queue on every image load, since that would be slow.
397
        //       However, we don't want to keep growing the batch forever either.
398
0
        static constexpr size_t max_loads_to_batch_before_flushing = 16;
399
400
0
        m_queue.append(move(callback));
401
0
        if (m_queue.size() < max_loads_to_batch_before_flushing)
402
0
            m_timer->restart();
403
0
    }
404
405
private:
406
    void process()
407
0
    {
408
0
        auto queue = move(m_queue);
409
0
        for (auto& callback : queue)
410
0
            callback->function()();
411
0
    }
412
413
    NonnullRefPtr<Core::Timer> m_timer;
414
    Vector<JS::Handle<JS::HeapFunction<void()>>> m_queue;
415
};
416
417
static BatchingDispatcher& batching_dispatcher()
418
0
{
419
0
    static BatchingDispatcher dispatcher;
420
0
    return dispatcher;
421
0
}
422
423
// https://html.spec.whatwg.org/multipage/images.html#update-the-image-data
424
ErrorOr<void> HTMLImageElement::update_the_image_data(bool restart_animations, bool maybe_omit_events)
425
0
{
426
    // 1. If the element's node document is not fully active, then:
427
0
    if (!document().is_fully_active()) {
428
        // FIXME: 1. Continue running this algorithm in parallel.
429
        // FIXME: 2. Wait until the element's node document is fully active.
430
        // FIXME: 3. If another instance of this algorithm for this img element was started after this instance
431
        //           (even if it aborted and is no longer running), then return.
432
        // FIXME: 4. Queue a microtask to continue this algorithm.
433
0
    }
434
435
    // 2. FIXME: If the user agent cannot support images, or its support for images has been disabled,
436
    //           then abort the image request for the current request and the pending request,
437
    //           set current request's state to unavailable, set pending request to null, and return.
438
439
    // 3. Let previous URL be the current request's current URL.
440
0
    auto previous_url = m_current_request->current_url();
441
442
    // 4. Let selected source be null and selected pixel density be undefined.
443
0
    Optional<String> selected_source;
444
0
    Optional<float> selected_pixel_density;
445
446
    // 5. If the element does not use srcset or picture
447
    //    and it has a src attribute specified whose value is not the empty string,
448
    //    then set selected source to the value of the element's src attribute
449
    //    and set selected pixel density to 1.0.
450
0
    auto maybe_src_attribute = attribute(HTML::AttributeNames::src);
451
0
    if (!uses_srcset_or_picture() && maybe_src_attribute.has_value() && !maybe_src_attribute.value().is_empty()) {
452
0
        selected_source = maybe_src_attribute.release_value();
453
0
        selected_pixel_density = 1.0f;
454
0
    }
455
456
    // 6. Set the element's last selected source to selected source.
457
0
    m_last_selected_source = selected_source;
458
459
    // 7. If selected source is not null, then:
460
0
    if (selected_source.has_value()) {
461
        // 1. Parse selected source, relative to the element's node document.
462
        //    If that is not successful, then abort this inner set of steps.
463
        //    Otherwise, let urlString be the resulting URL string.
464
0
        auto url_string = document().parse_url(selected_source.value());
465
0
        if (!url_string.is_valid())
466
0
            goto after_step_7;
467
468
        // 2. Let key be a tuple consisting of urlString, the img element's crossorigin attribute's mode,
469
        //    and, if that mode is not No CORS, the node document's origin.
470
0
        ListOfAvailableImages::Key key;
471
0
        key.url = url_string;
472
0
        key.mode = m_cors_setting;
473
0
        key.origin = document().origin();
474
475
        // 3. If the list of available images contains an entry for key, then:
476
0
        if (auto* entry = document().list_of_available_images().get(key)) {
477
            // 1. Set the ignore higher-layer caching flag for that entry.
478
0
            entry->ignore_higher_layer_caching = true;
479
480
            // 2. Abort the image request for the current request and the pending request.
481
0
            abort_the_image_request(realm(), m_current_request);
482
0
            abort_the_image_request(realm(), m_pending_request);
483
484
            // 3. Set pending request to null.
485
0
            m_pending_request = nullptr;
486
487
            // 4. Let current request be a new image request whose image data is that of the entry and whose state is completely available.
488
0
            m_current_request = ImageRequest::create(realm(), document().page());
489
0
            m_current_request->set_image_data(entry->image_data);
490
0
            m_current_request->set_state(ImageRequest::State::CompletelyAvailable);
491
492
            // 5. Prepare current request for presentation given img.
493
0
            m_current_request->prepare_for_presentation(*this);
494
495
            // 6. Set current request's current pixel density to selected pixel density.
496
            // FIXME: Spec bug! `selected_pixel_density` can be undefined here, per the spec.
497
            //        That's why we value_or(1.0f) it.
498
0
            m_current_request->set_current_pixel_density(selected_pixel_density.value_or(1.0f));
499
500
            // 7. Queue an element task on the DOM manipulation task source given the img element and following steps:
501
0
            queue_an_element_task(HTML::Task::Source::DOMManipulation, [this, restart_animations, maybe_omit_events, url_string, previous_url] {
502
                // 1. If restart animation is set, then restart the animation.
503
0
                if (restart_animations)
504
0
                    restart_the_animation();
505
506
                // 2. Set current request's current URL to urlString.
507
0
                m_current_request->set_current_url(realm(), url_string);
508
509
                // 3. If maybe omit events is not set or previousURL is not equal to urlString, then fire an event named load at the img element.
510
0
                if (!maybe_omit_events || previous_url != url_string)
511
0
                    dispatch_event(DOM::Event::create(realm(), HTML::EventNames::load));
512
0
            });
513
514
            // 8. Abort the update the image data algorithm.
515
0
            return {};
516
0
        }
517
0
    }
518
0
after_step_7:
519
    // 8. Queue a microtask to perform the rest of this algorithm, allowing the task that invoked this algorithm to continue.
520
0
    queue_a_microtask(&document(), JS::create_heap_function(this->heap(), [this, restart_animations, maybe_omit_events, previous_url]() mutable {
521
        // FIXME: 9. If another instance of this algorithm for this img element was started after this instance
522
        //           (even if it aborted and is no longer running), then return.
523
524
        // 10. Let selected source and selected pixel density be
525
        //    the URL and pixel density that results from selecting an image source, respectively.
526
0
        Optional<ImageSource> selected_source;
527
0
        Optional<float> pixel_density;
528
0
        if (auto result = select_an_image_source(); result.has_value()) {
529
0
            selected_source = result.value().source;
530
0
            pixel_density = result.value().pixel_density;
531
0
        }
532
533
        // 11. If selected source is null, then:
534
0
        if (!selected_source.has_value()) {
535
            // 1. Set the current request's state to broken,
536
            //    abort the image request for the current request and the pending request,
537
            //    and set pending request to null.
538
0
            m_current_request->set_state(ImageRequest::State::Broken);
539
0
            abort_the_image_request(realm(), m_current_request);
540
0
            abort_the_image_request(realm(), m_pending_request);
541
0
            m_pending_request = nullptr;
542
543
            // 2. Queue an element task on the DOM manipulation task source given the img element and the following steps:
544
0
            queue_an_element_task(HTML::Task::Source::DOMManipulation, [this, maybe_omit_events, previous_url] {
545
                // 1. Change the current request's current URL to the empty string.
546
0
                m_current_request->set_current_url(realm(), ""sv);
547
548
                // 2. If all of the following conditions are true:
549
                //    - the element has a src attribute or it uses srcset or picture; and
550
                //    - maybe omit events is not set or previousURL is not the empty string
551
0
                if (
552
0
                    (has_attribute(HTML::AttributeNames::src) || uses_srcset_or_picture())
553
0
                    && (!maybe_omit_events || m_current_request->current_url() != ""sv)) {
554
0
                    dispatch_event(DOM::Event::create(realm(), HTML::EventNames::error));
555
0
                }
556
0
            });
557
558
            // 3. Return.
559
0
            return;
560
0
        }
561
562
        // 12. Parse selected source, relative to the element's node document, and let urlString be the resulting URL string.
563
0
        auto url_string = document().parse_url(selected_source.value().url.to_byte_string());
564
        // If that is not successful, then:
565
0
        if (!url_string.is_valid()) {
566
            // 1. Abort the image request for the current request and the pending request.
567
0
            abort_the_image_request(realm(), m_current_request);
568
0
            abort_the_image_request(realm(), m_pending_request);
569
570
            // 2. Set the current request's state to broken.
571
0
            m_current_request->set_state(ImageRequest::State::Broken);
572
573
            // 3. Set pending request to null.
574
0
            m_pending_request = nullptr;
575
576
            // 4. Queue an element task on the DOM manipulation task source given the img element and the following steps:
577
0
            queue_an_element_task(HTML::Task::Source::DOMManipulation, [this, selected_source, maybe_omit_events, previous_url] {
578
                // 1. Change the current request's current URL to selected source.
579
0
                m_current_request->set_current_url(realm(), selected_source.value().url);
580
581
                // 2. If maybe omit events is not set or previousURL is not equal to selected source, then fire an event named error at the img element.
582
0
                if (!maybe_omit_events || previous_url != selected_source.value().url)
583
0
                    dispatch_event(DOM::Event::create(realm(), HTML::EventNames::error));
584
0
            });
585
586
            // 5. Return.
587
0
            return;
588
0
        }
589
590
        // 13. If the pending request is not null and urlString is the same as the pending request's current URL, then return.
591
0
        if (m_pending_request && url_string == m_pending_request->current_url())
592
0
            return;
593
594
        // 14. If urlString is the same as the current request's current URL and current request's state is partially available,
595
        //     then abort the image request for the pending request,
596
        //     queue an element task on the DOM manipulation task source given the img element
597
        //     to restart the animation if restart animation is set, and return.
598
0
        if (url_string == m_current_request->current_url() && m_current_request->state() == ImageRequest::State::PartiallyAvailable) {
599
0
            abort_the_image_request(realm(), m_pending_request);
600
0
            if (restart_animations) {
601
0
                queue_an_element_task(HTML::Task::Source::DOMManipulation, [this] {
602
0
                    restart_the_animation();
603
0
                });
604
0
            }
605
0
            return;
606
0
        }
607
608
        // 15. If the pending request is not null, then abort the image request for the pending request.
609
0
        abort_the_image_request(realm(), m_pending_request);
610
611
        // AD-HOC: At this point we start deviating from the spec in order to allow sharing ImageRequest between
612
        //         multiple image elements (as well as CSS background-images, etc.)
613
614
        // 16. Set image request to a new image request whose current URL is urlString.
615
0
        auto image_request = ImageRequest::create(realm(), document().page());
616
0
        image_request->set_current_url(realm(), url_string);
617
618
        // 17. If current request's state is unavailable or broken, then set the current request to image request.
619
        //     Otherwise, set the pending request to image request.
620
0
        if (m_current_request->state() == ImageRequest::State::Unavailable || m_current_request->state() == ImageRequest::State::Broken)
621
0
            m_current_request = image_request;
622
0
        else
623
0
            m_pending_request = image_request;
624
625
        // 23. Let delay load event be true if the img's lazy loading attribute is in the Eager state, or if scripting is disabled for the img, and false otherwise.
626
0
        auto delay_load_event = lazy_loading_attribute() == LazyLoading::Eager;
627
628
        // When delay load event is true, fetching the image must delay the load event of the element's node document
629
        // until the task that is queued by the networking task source once the resource has been fetched (defined below) has been run.
630
0
        if (delay_load_event)
631
0
            m_load_event_delayer.emplace(document());
632
633
0
        add_callbacks_to_image_request(*image_request, maybe_omit_events, url_string, previous_url);
634
635
        // AD-HOC: If the image request is already available or fetching, no need to start another fetch.
636
0
        if (image_request->is_available() || image_request->is_fetching())
637
0
            return;
638
639
        // 18. Let request be the result of creating a potential-CORS request given urlString, "image",
640
        //     and the current state of the element's crossorigin content attribute.
641
0
        auto request = create_potential_CORS_request(vm(), url_string, Fetch::Infrastructure::Request::Destination::Image, m_cors_setting);
642
643
        // 19. Set request's client to the element's node document's relevant settings object.
644
0
        request->set_client(&document().relevant_settings_object());
645
646
        // 20. If the element uses srcset or picture, set request's initiator to "imageset".
647
0
        if (uses_srcset_or_picture())
648
0
            request->set_initiator(Fetch::Infrastructure::Request::Initiator::ImageSet);
649
650
        // 21. Set request's referrer policy to the current state of the element's referrerpolicy attribute.
651
0
        request->set_referrer_policy(ReferrerPolicy::from_string(get_attribute_value(HTML::AttributeNames::referrerpolicy)).value_or(ReferrerPolicy::ReferrerPolicy::EmptyString));
652
653
        // 22. Set request's priority to the current state of the element's fetchpriority attribute.
654
0
        request->set_priority(Fetch::Infrastructure::request_priority_from_string(get_attribute_value(HTML::AttributeNames::fetchpriority)).value_or(Fetch::Infrastructure::Request::Priority::Auto));
655
656
        // 24. If the will lazy load element steps given the img return true, then:
657
0
        if (will_lazy_load_element()) {
658
            // 1. Set the img's lazy load resumption steps to the rest of this algorithm starting with the step labeled fetch the image.
659
0
            set_lazy_load_resumption_steps([this, request, image_request]() {
660
0
                image_request->fetch_image(realm(), request);
661
0
            });
662
663
            // 2. Start intersection-observing a lazy loading element for the img element.
664
0
            document().start_intersection_observing_a_lazy_loading_element(*this);
665
666
            // 3. Return.
667
0
            return;
668
0
        }
669
670
0
        image_request->fetch_image(realm(), request);
671
0
    }));
672
0
    return {};
673
0
}
674
675
void HTMLImageElement::add_callbacks_to_image_request(JS::NonnullGCPtr<ImageRequest> image_request, bool maybe_omit_events, URL::URL const& url_string, URL::URL const& previous_url)
676
0
{
677
0
    image_request->add_callbacks(
678
0
        [this, image_request, maybe_omit_events, url_string, previous_url]() {
679
0
            batching_dispatcher().enqueue(JS::create_heap_function(realm().heap(), [this, image_request, maybe_omit_events, url_string, previous_url] {
680
0
                VERIFY(image_request->shared_resource_request());
681
0
                auto image_data = image_request->shared_resource_request()->image_data();
682
0
                image_request->set_image_data(image_data);
683
684
0
                ListOfAvailableImages::Key key;
685
0
                key.url = url_string;
686
0
                key.mode = m_cors_setting;
687
0
                key.origin = document().origin();
688
689
                // 1. If image request is the pending request, abort the image request for the current request,
690
                //    upgrade the pending request to the current request
691
                //    and prepare image request for presentation given the img element.
692
0
                if (image_request == m_pending_request) {
693
0
                    abort_the_image_request(realm(), m_current_request);
694
0
                    upgrade_pending_request_to_current_request();
695
0
                    image_request->prepare_for_presentation(*this);
696
0
                }
697
698
                // 2. Set image request to the completely available state.
699
0
                image_request->set_state(ImageRequest::State::CompletelyAvailable);
700
701
                // 3. Add the image to the list of available images using the key key, with the ignore higher-layer caching flag set.
702
0
                document().list_of_available_images().add(key, *image_data, true);
703
704
0
                set_needs_style_update(true);
705
0
                document().set_needs_layout();
706
707
                // 4. If maybe omit events is not set or previousURL is not equal to urlString, then fire an event named load at the img element.
708
0
                if (!maybe_omit_events || previous_url != url_string)
709
0
                    dispatch_event(DOM::Event::create(realm(), HTML::EventNames::load));
710
711
0
                if (image_data->is_animated() && image_data->frame_count() > 1) {
712
0
                    m_current_frame_index = 0;
713
0
                    m_animation_timer->set_interval(image_data->frame_duration(0));
714
0
                    m_animation_timer->start();
715
0
                }
716
717
0
                m_load_event_delayer.clear();
718
0
            }));
719
0
        },
720
0
        [this, image_request, maybe_omit_events, url_string, previous_url]() {
721
            // The image data is not in a supported file format;
722
723
            // the user agent must set image request's state to broken,
724
0
            image_request->set_state(ImageRequest::State::Broken);
725
726
            // abort the image request for the current request and the pending request,
727
0
            abort_the_image_request(realm(), m_current_request);
728
0
            abort_the_image_request(realm(), m_pending_request);
729
730
            // upgrade the pending request to the current request if image request is the pending request,
731
0
            if (image_request == m_pending_request)
732
0
                upgrade_pending_request_to_current_request();
733
734
            // and then, if maybe omit events is not set or previousURL is not equal to urlString,
735
            // queue an element task on the DOM manipulation task source given the img element
736
            // to fire an event named error at the img element.
737
0
            if (!maybe_omit_events || previous_url != url_string)
738
0
                dispatch_event(DOM::Event::create(realm(), HTML::EventNames::error));
739
740
0
            m_load_event_delayer.clear();
741
0
        });
742
0
}
743
744
void HTMLImageElement::did_set_viewport_rect(CSSPixelRect const& viewport_rect)
745
0
{
746
0
    if (viewport_rect.size() == m_last_seen_viewport_size)
747
0
        return;
748
0
    m_last_seen_viewport_size = viewport_rect.size();
749
0
    batching_dispatcher().enqueue(JS::create_heap_function(realm().heap(), [this] {
750
0
        react_to_changes_in_the_environment();
751
0
    }));
752
0
}
753
754
// https://html.spec.whatwg.org/multipage/images.html#img-environment-changes
755
void HTMLImageElement::react_to_changes_in_the_environment()
756
0
{
757
    // FIXME: 1. Await a stable state.
758
    //           The synchronous section consists of all the remaining steps of this algorithm
759
    //           until the algorithm says the synchronous section has ended.
760
    //           (Steps in synchronous sections are marked with ⌛.)
761
762
    // 2. ⌛ If the img element does not use srcset or picture,
763
    //       its node document is not fully active,
764
    //       FIXME: has image data whose resource type is multipart/x-mixed-replace,
765
    //       or the pending request is not null,
766
    //       then return.
767
0
    if (!uses_srcset_or_picture() || !document().is_fully_active() || m_pending_request)
768
0
        return;
769
770
    // 3. ⌛ Let selected source and selected pixel density be the URL and pixel density
771
    //       that results from selecting an image source, respectively.
772
0
    Optional<String> selected_source;
773
0
    Optional<float> pixel_density;
774
0
    if (auto result = select_an_image_source(); result.has_value()) {
775
0
        selected_source = result.value().source.url;
776
0
        pixel_density = result.value().pixel_density;
777
0
    }
778
779
    // 4. ⌛ If selected source is null, then return.
780
0
    if (!selected_source.has_value())
781
0
        return;
782
783
    // 5. ⌛ If selected source and selected pixel density are the same
784
    //       as the element's last selected source and current pixel density, then return.
785
0
    if (selected_source == m_last_selected_source && pixel_density == m_current_request->current_pixel_density())
786
0
        return;
787
788
    // 6. ⌛ Parse selected source, relative to the element's node document,
789
    //       and let urlString be the resulting URL string. If that is not successful, then return.
790
0
    auto url_string = document().parse_url(selected_source.value());
791
0
    if (!url_string.is_valid())
792
0
        return;
793
794
    // 7. ⌛ Let corsAttributeState be the state of the element's crossorigin content attribute.
795
0
    auto cors_attribute_state = m_cors_setting;
796
797
    // 8. ⌛ Let origin be the img element's node document's origin.
798
0
    auto origin = document().origin();
799
800
    // 9. ⌛ Let client be the img element's node document's relevant settings object.
801
0
    auto& client = document().relevant_settings_object();
802
803
    // 10. ⌛ Let key be a tuple consisting of urlString, corsAttributeState, and, if corsAttributeState is not No CORS, origin.
804
0
    ListOfAvailableImages::Key key;
805
0
    key.url = url_string;
806
0
    key.mode = m_cors_setting;
807
0
    if (cors_attribute_state != CORSSettingAttribute::NoCORS)
808
0
        key.origin = document().origin();
809
810
    // 11. ⌛ Let image request be a new image request whose current URL is urlString
811
0
    auto image_request = ImageRequest::create(realm(), document().page());
812
0
    image_request->set_current_url(realm(), url_string);
813
814
    // 12. ⌛ Let the element's pending request be image request.
815
0
    m_pending_request = image_request;
816
817
    // FIXME: 13. End the synchronous section, continuing the remaining steps in parallel.
818
819
0
    auto step_15 = [this](String const& selected_source, JS::NonnullGCPtr<ImageRequest> image_request, ListOfAvailableImages::Key const& key, JS::NonnullGCPtr<DecodedImageData> image_data) {
820
        // 15. Queue an element task on the DOM manipulation task source given the img element and the following steps:
821
0
        queue_an_element_task(HTML::Task::Source::DOMManipulation, [this, selected_source, image_request, key, image_data] {
822
            // 1. FIXME: If the img element has experienced relevant mutations since this algorithm started, then let pending request be null and abort these steps.
823
            // AD-HOC: Check if we have a pending request still, otherwise we will crash when upgrading the request. This will happen if the image has experienced mutations,
824
            //        but since the pending request may be set by another task soon after it is cleared, this check is probably not sufficient.
825
0
            if (!m_pending_request)
826
0
                return;
827
828
            // 2. Let the img element's last selected source be selected source and the img element's current pixel density be selected pixel density.
829
0
            m_last_selected_source = selected_source;
830
831
            // 3. Set the image request's state to completely available.
832
0
            image_request->set_state(ImageRequest::State::CompletelyAvailable);
833
834
            // 4. Add the image to the list of available images using the key key, with the ignore higher-layer caching flag set.
835
0
            document().list_of_available_images().add(key, image_data, true);
836
837
            // 5. Upgrade the pending request to the current request.
838
0
            upgrade_pending_request_to_current_request();
839
840
            // 6. Prepare image request for presentation given the img element.
841
0
            image_request->prepare_for_presentation(*this);
842
            // FIXME: This is ad-hoc, updating the layout here should probably be handled by prepare_for_presentation().
843
0
            set_needs_style_update(true);
844
0
            document().set_needs_layout();
845
846
            // 7. Fire an event named load at the img element.
847
0
            dispatch_event(DOM::Event::create(realm(), HTML::EventNames::load));
848
0
        });
849
0
    };
850
851
    // 14. If the list of available images contains an entry for key, then set image request's image data to that of the entry.
852
    //     Continue to the next step.
853
0
    if (auto* entry = document().list_of_available_images().get(key)) {
854
0
        image_request->set_image_data(entry->image_data);
855
0
        step_15(selected_source.value(), *image_request, key, entry->image_data);
856
0
    }
857
    // Otherwise:
858
0
    else {
859
        // 1. Let request be the result of creating a potential-CORS request given urlString, "image", and corsAttributeState.
860
0
        auto request = create_potential_CORS_request(vm(), url_string, Fetch::Infrastructure::Request::Destination::Image, m_cors_setting);
861
862
        // 2. Set request's client to client, initiator to "imageset", and set request's synchronous flag.
863
0
        request->set_client(&client);
864
0
        request->set_initiator(Fetch::Infrastructure::Request::Initiator::ImageSet);
865
866
        // 3. Set request's referrer policy to the current state of the element's referrerpolicy attribute.
867
0
        request->set_referrer_policy(ReferrerPolicy::from_string(get_attribute_value(HTML::AttributeNames::referrerpolicy)).value_or(ReferrerPolicy::ReferrerPolicy::EmptyString));
868
869
        // FIXME: 4. Set request's priority to the current state of the element's fetchpriority attribute.
870
871
        // Set the callbacks to handle steps 6 and 7 before starting the fetch request.
872
0
        image_request->add_callbacks(
873
0
            [this, step_15, selected_source = selected_source.value(), image_request, key]() mutable {
874
                // 6. If response's unsafe response is a network error
875
                // NOTE: This is handled in the second callback below.
876
877
                // FIXME: or if the image format is unsupported (as determined by applying the image sniffing rules, again as mentioned earlier),
878
879
                // or if the user agent is able to determine that image request's image is corrupted in some
880
                // fatal way such that the image dimensions cannot be obtained,
881
                // NOTE: This is also handled in the other callback.
882
883
                // FIXME: or if the resource type is multipart/x-mixed-replace,
884
885
                // then let pending request be null and abort these steps.
886
887
0
                batching_dispatcher().enqueue(JS::create_heap_function(realm().heap(), [step_15, selected_source = move(selected_source), image_request, key] {
888
                    // 7. Otherwise, response's unsafe response is image request's image data. It can be either CORS-same-origin
889
                    //    or CORS-cross-origin; this affects the image's interaction with other APIs (e.g., when used on a canvas).
890
0
                    VERIFY(image_request->shared_resource_request());
891
0
                    auto image_data = image_request->shared_resource_request()->image_data();
892
0
                    image_request->set_image_data(image_data);
893
0
                    step_15(selected_source, image_request, key, *image_data);
894
0
                }));
895
0
            },
896
0
            [this]() {
897
                // 6. If response's unsafe response is a network error
898
                //    or if the image format is unsupported (as determined by applying the image sniffing rules, again as mentioned earlier),
899
                //    ...
900
                //    or if the user agent is able to determine that image request's image is corrupted in some
901
                //    fatal way such that the image dimensions cannot be obtained,
902
0
                m_pending_request = nullptr;
903
0
            });
904
905
        // 5. Let response be the result of fetching request.
906
0
        image_request->fetch_image(realm(), request);
907
0
    }
908
0
}
909
910
// https://html.spec.whatwg.org/multipage/images.html#upgrade-the-pending-request-to-the-current-request
911
void HTMLImageElement::upgrade_pending_request_to_current_request()
912
0
{
913
    // 1. Let the img element's current request be the pending request.
914
0
    VERIFY(m_pending_request);
915
0
    m_current_request = m_pending_request;
916
917
    // 2. Let the img element's pending request be null.
918
0
    m_pending_request = nullptr;
919
0
}
920
921
void HTMLImageElement::handle_failed_fetch()
922
0
{
923
    // AD-HOC
924
0
    dispatch_event(DOM::Event::create(realm(), HTML::EventNames::error));
925
0
}
926
927
// https://html.spec.whatwg.org/multipage/rendering.html#restart-the-animation
928
void HTMLImageElement::restart_the_animation()
929
0
{
930
0
    m_current_frame_index = 0;
931
932
0
    auto image_data = m_current_request->image_data();
933
0
    if (image_data && image_data->frame_count() > 1) {
934
0
        m_animation_timer->start();
935
0
    } else {
936
0
        m_animation_timer->stop();
937
0
    }
938
0
}
939
940
// https://html.spec.whatwg.org/multipage/images.html#update-the-source-set
941
static void update_the_source_set(DOM::Element& element)
942
0
{
943
    // When asked to update the source set for a given img or link element el, user agents must do the following:
944
0
    VERIFY(is<HTMLImageElement>(element) || is<HTMLLinkElement>(element));
945
946
    // 1. Set el's source set to an empty source set.
947
0
    if (is<HTMLImageElement>(element))
948
0
        static_cast<HTMLImageElement&>(element).set_source_set(SourceSet {});
949
0
    else if (is<HTMLLinkElement>(element))
950
0
        TODO();
951
952
    // 2. Let elements be « el ».
953
0
    JS::MarkedVector<DOM::Element*> elements(element.heap());
954
0
    elements.append(&element);
955
956
    // 3. If el is an img element whose parent node is a picture element,
957
    //    then replace the contents of elements with el's parent node's child elements, retaining relative order.
958
0
    if (is<HTMLImageElement>(element) && element.parent() && is<HTMLPictureElement>(*element.parent())) {
959
0
        elements.clear();
960
0
        element.parent()->for_each_child_of_type<DOM::Element>([&](auto& child) {
961
0
            elements.append(&child);
962
0
            return IterationDecision::Continue;
963
0
        });
964
0
    }
965
966
    // 4. For each child in elements:
967
0
    for (auto child : elements) {
968
        // 1. If child is el:
969
0
        if (child == &element) {
970
            // 1. Let default source be the empty string.
971
0
            String default_source;
972
973
            // 2. Let srcset be the empty string.
974
0
            String srcset;
975
976
            // 3. Let sizes be the empty string.
977
0
            String sizes;
978
979
            // 4. If el is an img element that has a srcset attribute, then set srcset to that attribute's value.
980
0
            if (is<HTMLImageElement>(element)) {
981
0
                if (auto srcset_value = element.attribute(HTML::AttributeNames::srcset); srcset_value.has_value())
982
0
                    srcset = srcset_value.release_value();
983
0
            }
984
985
            // 5. Otherwise, if el is a link element that has an imagesrcset attribute, then set srcset to that attribute's value.
986
0
            else if (is<HTMLLinkElement>(element)) {
987
0
                if (auto imagesrcset_value = element.attribute(HTML::AttributeNames::imagesrcset); imagesrcset_value.has_value())
988
0
                    srcset = imagesrcset_value.release_value();
989
0
            }
990
991
            // 6. If el is an img element that has a sizes attribute, then set sizes to that attribute's value.
992
0
            if (is<HTMLImageElement>(element)) {
993
0
                if (auto sizes_value = element.attribute(HTML::AttributeNames::sizes); sizes_value.has_value())
994
0
                    sizes = sizes_value.release_value();
995
0
            }
996
997
            // 7. Otherwise, if el is a link element that has an imagesizes attribute, then set sizes to that attribute's value.
998
0
            else if (is<HTMLLinkElement>(element)) {
999
0
                if (auto imagesizes_value = element.attribute(HTML::AttributeNames::imagesizes); imagesizes_value.has_value())
1000
0
                    sizes = imagesizes_value.release_value();
1001
0
            }
1002
1003
            // 8. If el is an img element that has a src attribute, then set default source to that attribute's value.
1004
0
            if (is<HTMLImageElement>(element)) {
1005
0
                if (auto src_value = element.attribute(HTML::AttributeNames::src); src_value.has_value())
1006
0
                    default_source = src_value.release_value();
1007
0
            }
1008
1009
            // 9. Otherwise, if el is a link element that has an href attribute, then set default source to that attribute's value.
1010
0
            else if (is<HTMLLinkElement>(element)) {
1011
0
                if (auto href_value = element.attribute(HTML::AttributeNames::href); href_value.has_value())
1012
0
                    default_source = href_value.release_value();
1013
0
            }
1014
1015
            // 10. Let el's source set be the result of creating a source set given default source, srcset, and sizes.
1016
0
            if (is<HTMLImageElement>(element))
1017
0
                static_cast<HTMLImageElement&>(element).set_source_set(SourceSet::create(element, default_source, srcset, sizes));
1018
0
            else if (is<HTMLLinkElement>(element))
1019
0
                TODO();
1020
0
            return;
1021
0
        }
1022
        // 2. If child is not a source element, then continue.
1023
0
        if (!is<HTMLSourceElement>(child))
1024
0
            continue;
1025
1026
        // 3. If child does not have a srcset attribute, continue to the next child.
1027
0
        if (!child->has_attribute(HTML::AttributeNames::srcset))
1028
0
            continue;
1029
1030
        // 4. Parse child's srcset attribute and let the returned source set be source set.
1031
0
        auto source_set = parse_a_srcset_attribute(child->get_attribute_value(HTML::AttributeNames::srcset));
1032
1033
        // 5. If source set has zero image sources, continue to the next child.
1034
0
        if (source_set.is_empty())
1035
0
            continue;
1036
1037
        // 6. If child has a media attribute, and its value does not match the environment, continue to the next child.
1038
0
        if (child->has_attribute(HTML::AttributeNames::media)) {
1039
0
            auto media_query = parse_media_query(CSS::Parser::ParsingContext { element.document() },
1040
0
                child->get_attribute_value(HTML::AttributeNames::media));
1041
0
            if (!media_query || !element.document().window() || !media_query->evaluate(*element.document().window())) {
1042
0
                continue;
1043
0
            }
1044
0
        }
1045
1046
        // 7. Parse child's sizes attribute, and let source set's source size be the returned value.
1047
0
        source_set.m_source_size = parse_a_sizes_attribute(element.document(), child->get_attribute_value(HTML::AttributeNames::sizes));
1048
1049
        // FIXME: 8. If child has a type attribute, and its value is an unknown or unsupported MIME type, continue to the next child.
1050
0
        if (child->has_attribute(HTML::AttributeNames::type)) {
1051
0
        }
1052
1053
        // FIXME: 9. If child has width or height attributes, set el's dimension attribute source to child.
1054
        //           Otherwise, set el's dimension attribute source to el.
1055
1056
        // 10. Normalize the source densities of source set.
1057
0
        source_set.normalize_source_densities(element);
1058
1059
        // 11. Let el's source set be source set.
1060
0
        if (is<HTMLImageElement>(element))
1061
0
            static_cast<HTMLImageElement&>(element).set_source_set(move(source_set));
1062
0
        else if (is<HTMLLinkElement>(element))
1063
0
            TODO();
1064
1065
        // 12. Return.
1066
0
        return;
1067
0
    }
1068
0
}
1069
1070
// https://html.spec.whatwg.org/multipage/images.html#select-an-image-source
1071
Optional<ImageSourceAndPixelDensity> HTMLImageElement::select_an_image_source()
1072
0
{
1073
    // 1. Update the source set for el.
1074
0
    update_the_source_set(*this);
1075
1076
    // 2. If el's source set is empty, return null as the URL and undefined as the pixel density.
1077
0
    if (m_source_set.is_empty())
1078
0
        return {};
1079
1080
    // 3. Return the result of selecting an image from el's source set.
1081
0
    return m_source_set.select_an_image_source();
1082
0
}
1083
1084
void HTMLImageElement::set_source_set(SourceSet source_set)
1085
0
{
1086
0
    m_source_set = move(source_set);
1087
0
}
1088
1089
void HTMLImageElement::animate()
1090
0
{
1091
0
    auto image_data = m_current_request->image_data();
1092
0
    if (!image_data) {
1093
0
        return;
1094
0
    }
1095
1096
0
    m_current_frame_index = (m_current_frame_index + 1) % image_data->frame_count();
1097
0
    auto current_frame_duration = image_data->frame_duration(m_current_frame_index);
1098
1099
0
    if (current_frame_duration != m_animation_timer->interval()) {
1100
0
        m_animation_timer->restart(current_frame_duration);
1101
0
    }
1102
1103
0
    if (m_current_frame_index == image_data->frame_count() - 1) {
1104
0
        ++m_loops_completed;
1105
0
        if (m_loops_completed > 0 && m_loops_completed == image_data->loop_count()) {
1106
0
            m_animation_timer->stop();
1107
0
        }
1108
0
    }
1109
1110
0
    if (paintable())
1111
0
        paintable()->set_needs_display();
1112
0
}
1113
1114
StringView HTMLImageElement::decoding() const
1115
0
{
1116
0
    switch (m_decoding_hint) {
1117
0
    case ImageDecodingHint::Sync:
1118
0
        return "sync"sv;
1119
0
    case ImageDecodingHint::Async:
1120
0
        return "async"sv;
1121
0
    case ImageDecodingHint::Auto:
1122
0
        return "auto"sv;
1123
0
    default:
1124
0
        VERIFY_NOT_REACHED();
1125
0
    }
1126
0
}
1127
1128
void HTMLImageElement::set_decoding(String decoding)
1129
0
{
1130
0
    if (decoding == "sync"sv) {
1131
0
        dbgln("FIXME: HTMLImageElement.decoding = 'sync' is not implemented yet");
1132
0
        m_decoding_hint = ImageDecodingHint::Sync;
1133
0
    } else if (decoding == "async"sv) {
1134
0
        dbgln("FIXME: HTMLImageElement.decoding = 'async' is not implemented yet");
1135
0
        m_decoding_hint = ImageDecodingHint::Async;
1136
0
    } else
1137
0
        m_decoding_hint = ImageDecodingHint::Auto;
1138
0
}
1139
1140
}