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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::document_loader::{LoadBlocker, LoadType};
use crate::dom::activation::Activatable;
use crate::dom::attr::Attr;
use crate::dom::bindings::cell::{DomRefCell, RefMut};
use crate::dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectBinding::DOMRectMethods;
use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementBinding::ElementMethods;
use crate::dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::{DomRoot, LayoutDom, MutNullableDom};
use crate::dom::bindings::str::{DOMString, USVString};
use crate::dom::document::{determine_policy_for_token, Document};
use crate::dom::element::{cors_setting_for_element, referrer_policy_for_element};
use crate::dom::element::{reflect_cross_origin_attribute, set_cross_origin_attribute};
use crate::dom::element::{
    AttributeMutation, CustomElementCreationMode, Element, ElementCreator, LayoutElementHelpers,
};
use crate::dom::event::Event;
use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlareaelement::HTMLAreaElement;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::htmlformelement::{FormControl, HTMLFormElement};
use crate::dom::htmlmapelement::HTMLMapElement;
use crate::dom::htmlpictureelement::HTMLPictureElement;
use crate::dom::htmlsourceelement::HTMLSourceElement;
use crate::dom::mouseevent::MouseEvent;
use crate::dom::node::UnbindContext;
use crate::dom::node::{
    document_from_node, window_from_node, BindContext, Node, NodeDamage, ShadowIncluding,
};
use crate::dom::performanceresourcetiming::InitiatorType;
use crate::dom::values::UNSIGNED_LONG_MAX;
use crate::dom::virtualmethods::VirtualMethods;
use crate::dom::window::Window;
use crate::fetch::create_a_potential_cors_request;
use crate::image_listener::{generate_cache_listener_for_element, ImageCacheListener};
use crate::microtask::{Microtask, MicrotaskRunnable};
use crate::network_listener::{self, NetworkListener, PreInvoke, ResourceTimingListener};
use crate::script_thread::ScriptThread;
use crate::task_source::TaskSource;
use app_units::{Au, AU_PER_PX};
use cssparser::{Parser, ParserInput};
use dom_struct::dom_struct;
use euclid::Point2D;
use html5ever::{LocalName, Prefix, QualName};
use ipc_channel::ipc;
use ipc_channel::ipc::IpcSender;
use ipc_channel::router::ROUTER;
use mime::{self, Mime};
use msg::constellation_msg::PipelineId;
use net_traits::image::base::{Image, ImageMetadata};
use net_traits::image_cache::{
    CorsStatus, ImageCache, ImageCacheResult, ImageOrMetadataAvailable, ImageResponse,
    PendingImageId, PendingImageResponse, UsePlaceholder,
};
use net_traits::request::{CorsSettings, Destination, Initiator, Referrer, RequestBuilder};
use net_traits::{FetchMetadata, FetchResponseListener, FetchResponseMsg, NetworkError};
use net_traits::{ReferrerPolicy, ResourceFetchTiming, ResourceTimingType};
use num_traits::ToPrimitive;
use servo_url::origin::ImmutableOrigin;
use servo_url::origin::MutableOrigin;
use servo_url::ServoUrl;
use std::cell::Cell;
use std::char;
use std::collections::HashSet;
use std::default::Default;
use std::i32;
use std::mem;
use std::sync::{Arc, Mutex};
use style::attr::{
    parse_double, parse_length, parse_unsigned_integer, AttrValue, LengthOrPercentageOrAuto,
};
use style::context::QuirksMode;
use style::media_queries::MediaList;
use style::parser::ParserContext;
use style::str::is_ascii_digit;
use style::stylesheets::{CssRuleType, Origin};
use style::values::specified::length::{Length, NoCalcLength};
use style::values::specified::{source_size_list::SourceSizeList, AbsoluteLength};
use style_traits::ParsingMode;

enum ParseState {
    InDescriptor,
    InParens,
    AfterDescriptor,
}

pub struct SourceSet {
    image_sources: Vec<ImageSource>,
    source_size: SourceSizeList,
}

impl SourceSet {
    fn new() -> SourceSet {
        SourceSet {
            image_sources: Vec::new(),
            source_size: SourceSizeList::empty(),
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct ImageSource {
    pub url: String,
    pub descriptor: Descriptor,
}

#[derive(Clone, Debug, PartialEq)]
pub struct Descriptor {
    pub wid: Option<u32>,
    pub den: Option<f64>,
}

#[derive(Clone, Copy, JSTraceable, MallocSizeOf)]
#[allow(dead_code)]
enum State {
    Unavailable,
    PartiallyAvailable,
    CompletelyAvailable,
    Broken,
}

#[derive(Clone, Copy, JSTraceable, MallocSizeOf)]
enum ImageRequestPhase {
    Pending,
    Current,
}
#[derive(JSTraceable, MallocSizeOf)]
#[unrooted_must_root_lint::must_root]
struct ImageRequest {
    state: State,
    parsed_url: Option<ServoUrl>,
    source_url: Option<USVString>,
    blocker: Option<LoadBlocker>,
    #[ignore_malloc_size_of = "Arc"]
    image: Option<Arc<Image>>,
    metadata: Option<ImageMetadata>,
    final_url: Option<ServoUrl>,
    current_pixel_density: Option<f64>,
}
#[dom_struct]
pub struct HTMLImageElement {
    htmlelement: HTMLElement,
    image_request: Cell<ImageRequestPhase>,
    current_request: DomRefCell<ImageRequest>,
    pending_request: DomRefCell<ImageRequest>,
    form_owner: MutNullableDom<HTMLFormElement>,
    generation: Cell<u32>,
    #[ignore_malloc_size_of = "SourceSet"]
    source_set: DomRefCell<SourceSet>,
    last_selected_source: DomRefCell<Option<USVString>>,
}

impl HTMLImageElement {
    pub fn get_url(&self) -> Option<ServoUrl> {
        self.current_request.borrow().parsed_url.clone()
    }
    // https://html.spec.whatwg.org/multipage/#check-the-usability-of-the-image-argument
    pub fn is_usable(&self) -> Fallible<bool> {
        // If image has an intrinsic width or intrinsic height (or both) equal to zero, then return bad.
        if let Some(image) = &self.current_request.borrow().image {
            if image.width == 0 || image.height == 0 {
                return Ok(false);
            }
        }

        match self.current_request.borrow().state {
            // If image's current request's state is broken, then throw an "InvalidStateError" DOMException.
            State::Broken => Err(Error::InvalidState),
            State::CompletelyAvailable => Ok(true),
            // If image is not fully decodable, then return bad.
            State::PartiallyAvailable | State::Unavailable => Ok(false),
        }
    }
}

/// The context required for asynchronously loading an external image.
struct ImageContext {
    /// Reference to the script thread image cache.
    image_cache: Arc<dyn ImageCache>,
    /// Indicates whether the request failed, and why
    status: Result<(), NetworkError>,
    /// The cache ID for this request.
    id: PendingImageId,
    /// Used to mark abort
    aborted: bool,
    /// The document associated with this request
    doc: Trusted<Document>,
    /// timing data for this resource
    resource_timing: ResourceFetchTiming,
    url: ServoUrl,
}

impl FetchResponseListener for ImageContext {
    fn process_request_body(&mut self) {}
    fn process_request_eof(&mut self) {}

    fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) {
        debug!("got {:?} for {:?}", metadata.as_ref().map(|_| ()), self.url);
        self.image_cache
            .notify_pending_response(self.id, FetchResponseMsg::ProcessResponse(metadata.clone()));

        let metadata = metadata.ok().map(|meta| match meta {
            FetchMetadata::Unfiltered(m) => m,
            FetchMetadata::Filtered { unsafe_, .. } => unsafe_,
        });

        // Step 14.5 of https://html.spec.whatwg.org/multipage/#img-environment-changes
        if let Some(metadata) = metadata.as_ref() {
            if let Some(ref content_type) = metadata.content_type {
                let mime: Mime = content_type.clone().into_inner().into();
                if mime.type_() == mime::MULTIPART && mime.subtype().as_str() == "x-mixed-replace" {
                    self.aborted = true;
                }
            }
        }

        let status_code = metadata
            .as_ref()
            .and_then(|m| m.status.as_ref().map(|&(code, _)| code))
            .unwrap_or(0);

        self.status = match status_code {
            0 => Err(NetworkError::Internal(
                "No http status code received".to_owned(),
            )),
            200..=299 => Ok(()), // HTTP ok status codes
            _ => Err(NetworkError::Internal(format!(
                "HTTP error code {}",
                status_code
            ))),
        };
    }

    fn process_response_chunk(&mut self, payload: Vec<u8>) {
        if self.status.is_ok() {
            self.image_cache
                .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseChunk(payload));
        }
    }

    fn process_response_eof(&mut self, response: Result<ResourceFetchTiming, NetworkError>) {
        self.image_cache
            .notify_pending_response(self.id, FetchResponseMsg::ProcessResponseEOF(response));
    }

    fn resource_timing_mut(&mut self) -> &mut ResourceFetchTiming {
        &mut self.resource_timing
    }

    fn resource_timing(&self) -> &ResourceFetchTiming {
        &self.resource_timing
    }

    fn submit_resource_timing(&mut self) {
        network_listener::submit_timing(self)
    }
}

impl ResourceTimingListener for ImageContext {
    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
        (
            InitiatorType::LocalName("img".to_string()),
            self.url.clone(),
        )
    }

    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
        self.doc.root().global()
    }
}

impl PreInvoke for ImageContext {
    fn should_invoke(&self) -> bool {
        !self.aborted
    }
}

#[derive(PartialEq)]
pub(crate) enum FromPictureOrSrcSet {
    Yes,
    No,
}

// https://html.spec.whatwg.org/multipage/#update-the-image-data steps 17-20
// This function is also used to prefetch an image in `script::dom::servoparser::prefetch`.
pub(crate) fn image_fetch_request(
    img_url: ServoUrl,
    origin: ImmutableOrigin,
    referrer: Referrer,
    pipeline_id: PipelineId,
    cors_setting: Option<CorsSettings>,
    referrer_policy: Option<ReferrerPolicy>,
    from_picture_or_srcset: FromPictureOrSrcSet,
) -> RequestBuilder {
    let mut request =
        create_a_potential_cors_request(img_url, Destination::Image, cors_setting, None, referrer)
            .origin(origin)
            .pipeline_id(Some(pipeline_id))
            .referrer_policy(referrer_policy);
    if from_picture_or_srcset == FromPictureOrSrcSet::Yes {
        request = request.initiator(Initiator::ImageSet);
    }
    request
}

#[allow(non_snake_case)]
impl HTMLImageElement {
    /// Update the current image with a valid URL.
    fn fetch_image(&self, img_url: &ServoUrl) {
        let window = window_from_node(self);
        let image_cache = window.image_cache();
        let sender = generate_cache_listener_for_element(self);
        let cache_result = image_cache.track_image(
            img_url.clone(),
            window.origin().immutable().clone(),
            cors_setting_for_element(self.upcast()),
            sender,
            UsePlaceholder::Yes,
        );

        match cache_result {
            ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
                image,
                url,
                is_placeholder,
            }) => {
                if is_placeholder {
                    self.process_image_response(ImageResponse::PlaceholderLoaded(image, url))
                } else {
                    self.process_image_response(ImageResponse::Loaded(image, url))
                }
            },
            ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(m)) => {
                self.process_image_response(ImageResponse::MetadataLoaded(m))
            },
            ImageCacheResult::Pending(_) => (),
            ImageCacheResult::ReadyForRequest(id) => self.fetch_request(img_url, id),
            ImageCacheResult::LoadError => self.process_image_response(ImageResponse::None),
        };
    }

    fn fetch_request(&self, img_url: &ServoUrl, id: PendingImageId) {
        let document = document_from_node(self);
        let window = window_from_node(self);

        let context = Arc::new(Mutex::new(ImageContext {
            image_cache: window.image_cache(),
            status: Ok(()),
            id: id,
            aborted: false,
            doc: Trusted::new(&document),
            resource_timing: ResourceFetchTiming::new(ResourceTimingType::Resource),
            url: img_url.clone(),
        }));

        let (action_sender, action_receiver) = ipc::channel().unwrap();
        let (task_source, canceller) = document
            .window()
            .task_manager()
            .networking_task_source_with_canceller();
        let listener = NetworkListener {
            context,
            task_source,
            canceller: Some(canceller),
        };
        ROUTER.add_route(
            action_receiver.to_opaque(),
            Box::new(move |message| {
                listener.notify_fetch(message.to().unwrap());
            }),
        );

        let request = image_fetch_request(
            img_url.clone(),
            document.origin().immutable().clone(),
            document.global().get_referrer(),
            document.global().pipeline_id(),
            cors_setting_for_element(self.upcast()),
            referrer_policy_for_element(self.upcast()),
            if Self::uses_srcset_or_picture(self.upcast()) {
                FromPictureOrSrcSet::Yes
            } else {
                FromPictureOrSrcSet::No
            },
        );

        // This is a background load because the load blocker already fulfills the
        // purpose of delaying the document's load event.
        document
            .loader_mut()
            .fetch_async_background(request, action_sender);
    }

    // Steps common to when an image has been loaded.
    fn handle_loaded_image(&self, image: Arc<Image>, url: ServoUrl) {
        self.current_request.borrow_mut().metadata = Some(ImageMetadata {
            height: image.height,
            width: image.width,
        });
        self.current_request.borrow_mut().final_url = Some(url);
        self.current_request.borrow_mut().image = Some(image);
        self.current_request.borrow_mut().state = State::CompletelyAvailable;
        LoadBlocker::terminate(&mut self.current_request.borrow_mut().blocker);
        // Mark the node dirty
        self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
    }

    /// Step 24 of https://html.spec.whatwg.org/multipage/#update-the-image-data
    fn process_image_response(&self, image: ImageResponse) {
        // TODO: Handle multipart/x-mixed-replace
        let (trigger_image_load, trigger_image_error) = match (image, self.image_request.get()) {
            (ImageResponse::Loaded(image, url), ImageRequestPhase::Current) => {
                self.handle_loaded_image(image, url);
                (true, false)
            },
            (ImageResponse::PlaceholderLoaded(image, url), ImageRequestPhase::Current) => {
                self.handle_loaded_image(image, url);
                (false, true)
            },
            (ImageResponse::Loaded(image, url), ImageRequestPhase::Pending) => {
                self.abort_request(State::Unavailable, ImageRequestPhase::Pending);
                self.image_request.set(ImageRequestPhase::Current);
                self.handle_loaded_image(image, url);
                (true, false)
            },
            (ImageResponse::PlaceholderLoaded(image, url), ImageRequestPhase::Pending) => {
                self.abort_request(State::Unavailable, ImageRequestPhase::Pending);
                self.image_request.set(ImageRequestPhase::Current);
                self.handle_loaded_image(image, url);
                (false, true)
            },
            (ImageResponse::MetadataLoaded(meta), ImageRequestPhase::Current) => {
                self.current_request.borrow_mut().state = State::PartiallyAvailable;
                self.current_request.borrow_mut().metadata = Some(meta);
                (false, false)
            },
            (ImageResponse::MetadataLoaded(_), ImageRequestPhase::Pending) => {
                self.pending_request.borrow_mut().state = State::PartiallyAvailable;
                (false, false)
            },
            (ImageResponse::None, ImageRequestPhase::Current) => {
                self.abort_request(State::Broken, ImageRequestPhase::Current);
                (false, true)
            },
            (ImageResponse::None, ImageRequestPhase::Pending) => {
                self.abort_request(State::Broken, ImageRequestPhase::Current);
                self.abort_request(State::Broken, ImageRequestPhase::Pending);
                self.image_request.set(ImageRequestPhase::Current);
                (false, true)
            },
        };

        // Fire image.onload and loadend
        if trigger_image_load {
            // TODO: https://html.spec.whatwg.org/multipage/#fire-a-progress-event-or-event
            self.upcast::<EventTarget>().fire_event(atom!("load"));
            self.upcast::<EventTarget>().fire_event(atom!("loadend"));
        }

        // Fire image.onerror
        if trigger_image_error {
            self.upcast::<EventTarget>().fire_event(atom!("error"));
            self.upcast::<EventTarget>().fire_event(atom!("loadend"));
        }

        // Trigger reflow
        let window = window_from_node(self);
        window.add_pending_reflow();
    }

    fn process_image_response_for_environment_change(
        &self,
        image: ImageResponse,
        src: USVString,
        generation: u32,
        selected_pixel_density: f64,
    ) {
        match image {
            ImageResponse::Loaded(image, url) | ImageResponse::PlaceholderLoaded(image, url) => {
                self.pending_request.borrow_mut().metadata = Some(ImageMetadata {
                    height: image.height,
                    width: image.width,
                });
                self.pending_request.borrow_mut().final_url = Some(url);
                self.pending_request.borrow_mut().image = Some(image);
                self.finish_reacting_to_environment_change(src, generation, selected_pixel_density);
            },
            ImageResponse::MetadataLoaded(meta) => {
                self.pending_request.borrow_mut().metadata = Some(meta);
            },
            ImageResponse::None => {
                self.abort_request(State::Unavailable, ImageRequestPhase::Pending);
            },
        };
    }

    /// <https://html.spec.whatwg.org/multipage/#abort-the-image-request>
    fn abort_request(&self, state: State, request: ImageRequestPhase) {
        let mut request = match request {
            ImageRequestPhase::Current => self.current_request.borrow_mut(),
            ImageRequestPhase::Pending => self.pending_request.borrow_mut(),
        };
        LoadBlocker::terminate(&mut request.blocker);
        request.state = state;
        request.image = None;
        request.metadata = None;
    }

    /// <https://html.spec.whatwg.org/multipage/#update-the-source-set>
    fn update_source_set(&self) {
        // Step 1
        *self.source_set.borrow_mut() = SourceSet::new();

        // Step 2
        let elem = self.upcast::<Element>();
        let parent = elem.upcast::<Node>().GetParentElement();
        let nodes;
        let elements = match parent.as_ref() {
            Some(p) => {
                if p.is::<HTMLPictureElement>() {
                    nodes = p.upcast::<Node>().children();
                    nodes
                        .filter_map(DomRoot::downcast::<Element>)
                        .map(|n| DomRoot::from_ref(&*n))
                        .collect()
                } else {
                    vec![DomRoot::from_ref(&*elem)]
                }
            },
            None => vec![DomRoot::from_ref(&*elem)],
        };

        // Step 3
        let width = match elem.get_attribute(&ns!(), &local_name!("width")) {
            Some(x) => match parse_length(&x.value()) {
                LengthOrPercentageOrAuto::Length(x) => {
                    let abs_length = AbsoluteLength::Px(x.to_f32_px());
                    Some(Length::NoCalc(NoCalcLength::Absolute(abs_length)))
                },
                _ => None,
            },
            None => None,
        };

        // Step 4
        for element in &elements {
            // Step 4.1
            if *element == DomRoot::from_ref(&*elem) {
                let mut source_set = SourceSet::new();
                // Step 4.1.1
                if let Some(x) = element.get_attribute(&ns!(), &local_name!("srcset")) {
                    source_set.image_sources = parse_a_srcset_attribute(&x.value());
                }

                // Step 4.1.2
                if let Some(x) = element.get_attribute(&ns!(), &local_name!("sizes")) {
                    source_set.source_size =
                        parse_a_sizes_attribute(DOMString::from_string(x.value().to_string()));
                }

                // Step 4.1.3
                let src_attribute = element.get_string_attribute(&local_name!("src"));
                let is_src_empty = src_attribute.is_empty();
                let no_density_source_of_1 = source_set
                    .image_sources
                    .iter()
                    .all(|source| source.descriptor.den != Some(1.));
                let no_width_descriptor = source_set
                    .image_sources
                    .iter()
                    .all(|source| source.descriptor.wid.is_none());
                if !is_src_empty && no_density_source_of_1 && no_width_descriptor {
                    source_set.image_sources.push(ImageSource {
                        url: src_attribute.to_string(),
                        descriptor: Descriptor {
                            wid: None,
                            den: None,
                        },
                    })
                }

                // Step 4.1.4
                self.normalise_source_densities(&mut source_set, width);

                // Step 4.1.5
                *self.source_set.borrow_mut() = source_set;

                // Step 4.1.6
                return;
            }
            // Step 4.2
            if !element.is::<HTMLSourceElement>() {
                continue;
            }

            // Step 4.3 - 4.4
            let mut source_set = SourceSet::new();
            match element.get_attribute(&ns!(), &local_name!("srcset")) {
                Some(x) => {
                    source_set.image_sources = parse_a_srcset_attribute(&x.value());
                },
                _ => continue,
            }

            // Step 4.5
            if source_set.image_sources.is_empty() {
                continue;
            }

            // Step 4.6
            if let Some(x) = element.get_attribute(&ns!(), &local_name!("media")) {
                if !self.matches_environment(x.value().to_string()) {
                    continue;
                }
            }

            // Step 4.7
            if let Some(x) = element.get_attribute(&ns!(), &local_name!("sizes")) {
                source_set.source_size =
                    parse_a_sizes_attribute(DOMString::from_string(x.value().to_string()));
            }

            // Step 4.8
            if let Some(x) = element.get_attribute(&ns!(), &local_name!("type")) {
                // TODO Handle unsupported mime type
                let mime = x.value().parse::<Mime>();
                match mime {
                    Ok(m) => match m.type_() {
                        mime::IMAGE => (),
                        _ => continue,
                    },
                    _ => continue,
                }
            }

            // Step 4.9
            self.normalise_source_densities(&mut source_set, width);

            // Step 4.10
            *self.source_set.borrow_mut() = source_set;
            return;
        }
    }

    fn evaluate_source_size_list(
        &self,
        source_size_list: &mut SourceSizeList,
        _width: Option<Length>,
    ) -> Au {
        let document = document_from_node(self);
        let device = document.device();
        let quirks_mode = document.quirks_mode();
        //FIXME https://github.com/whatwg/html/issues/3832
        source_size_list.evaluate(&device, quirks_mode)
    }

    /// https://html.spec.whatwg.org/multipage/#matches-the-environment
    fn matches_environment(&self, media_query: String) -> bool {
        let document = document_from_node(self);
        let quirks_mode = document.quirks_mode();
        let document_url = &document.url();
        // FIXME(emilio): This should do the same that we do for other media
        // lists regarding the rule type and such, though it doesn't really
        // matter right now...
        //
        // Also, ParsingMode::all() is wrong, and should be DEFAULT.
        let context = ParserContext::new(
            Origin::Author,
            document_url,
            Some(CssRuleType::Style),
            ParsingMode::all(),
            quirks_mode,
            None,
            None,
        );
        let mut parserInput = ParserInput::new(&media_query);
        let mut parser = Parser::new(&mut parserInput);
        let media_list = MediaList::parse(&context, &mut parser);
        media_list.evaluate(&document.device(), quirks_mode)
    }

    /// <https://html.spec.whatwg.org/multipage/#normalise-the-source-densities>
    fn normalise_source_densities(&self, source_set: &mut SourceSet, width: Option<Length>) {
        // Step 1
        let mut source_size = &mut source_set.source_size;

        // Find source_size_length for Step 2.2
        let source_size_length = self.evaluate_source_size_list(&mut source_size, width);

        // Step 2
        for imgsource in &mut source_set.image_sources {
            // Step 2.1
            if imgsource.descriptor.den.is_some() {
                continue;
            }
            // Step 2.2
            if imgsource.descriptor.wid.is_some() {
                let wid = imgsource.descriptor.wid.unwrap();
                imgsource.descriptor.den = Some(wid as f64 / source_size_length.to_f64_px());
            } else {
                //Step 2.3
                imgsource.descriptor.den = Some(1 as f64);
            }
        }
    }

    /// <https://html.spec.whatwg.org/multipage/#select-an-image-source>
    fn select_image_source(&self) -> Option<(USVString, f64)> {
        // Step 1, 3
        self.update_source_set();
        let source_set = &*self.source_set.borrow_mut();
        let len = source_set.image_sources.len();

        // Step 2
        if len == 0 {
            return None;
        }

        // Step 4
        let mut repeat_indices = HashSet::new();
        for outer_index in 0..len {
            if repeat_indices.contains(&outer_index) {
                continue;
            }
            let imgsource = &source_set.image_sources[outer_index];
            let pixel_density = imgsource.descriptor.den.unwrap();
            for inner_index in (outer_index + 1)..len {
                let imgsource2 = &source_set.image_sources[inner_index];
                if pixel_density == imgsource2.descriptor.den.unwrap() {
                    repeat_indices.insert(inner_index);
                }
            }
        }

        let mut max = (0f64, 0);
        let img_sources = &mut vec![];
        for (index, image_source) in source_set.image_sources.iter().enumerate() {
            if repeat_indices.contains(&index) {
                continue;
            }
            let den = image_source.descriptor.den.unwrap();
            if max.0 < den {
                max = (den, img_sources.len());
            }
            img_sources.push(image_source);
        }

        // Step 5
        let mut best_candidate = max;
        let device = document_from_node(self).device();
        let device_den = device.device_pixel_ratio().get() as f64;
        for (index, image_source) in img_sources.iter().enumerate() {
            let current_den = image_source.descriptor.den.unwrap();
            if current_den < best_candidate.0 && current_den >= device_den {
                best_candidate = (current_den, index);
            }
        }
        let selected_source = img_sources.remove(best_candidate.1).clone();
        Some((
            USVString(selected_source.url),
            selected_source.descriptor.den.unwrap() as f64,
        ))
    }

    fn init_image_request(
        &self,
        request: &mut RefMut<ImageRequest>,
        url: &ServoUrl,
        src: &USVString,
    ) {
        request.parsed_url = Some(url.clone());
        request.source_url = Some(src.clone());
        request.image = None;
        request.metadata = None;
        let document = document_from_node(self);
        LoadBlocker::terminate(&mut request.blocker);
        request.blocker = Some(LoadBlocker::new(&*document, LoadType::Image(url.clone())));
    }

    /// Step 13-17 of html.spec.whatwg.org/multipage/#update-the-image-data
    fn prepare_image_request(&self, url: &ServoUrl, src: &USVString, selected_pixel_density: f64) {
        match self.image_request.get() {
            ImageRequestPhase::Pending => {
                if let Some(pending_url) = self.pending_request.borrow().parsed_url.clone() {
                    // Step 13
                    if pending_url == *url {
                        return;
                    }
                }
            },
            ImageRequestPhase::Current => {
                let mut current_request = self.current_request.borrow_mut();
                let mut pending_request = self.pending_request.borrow_mut();
                // step 16, create a new "image_request"
                match (current_request.parsed_url.clone(), current_request.state) {
                    (Some(parsed_url), State::PartiallyAvailable) => {
                        // Step 14
                        if parsed_url == *url {
                            // Step 15 abort pending request
                            pending_request.image = None;
                            pending_request.parsed_url = None;
                            LoadBlocker::terminate(&mut pending_request.blocker);
                            // TODO: queue a task to restart animation, if restart-animation is set
                            return;
                        }
                        pending_request.current_pixel_density = Some(selected_pixel_density);
                        self.image_request.set(ImageRequestPhase::Pending);
                        self.init_image_request(&mut pending_request, &url, &src);
                    },
                    (_, State::Broken) | (_, State::Unavailable) => {
                        // Step 17
                        current_request.current_pixel_density = Some(selected_pixel_density);
                        self.init_image_request(&mut current_request, &url, &src);
                    },
                    (_, _) => {
                        // step 17
                        pending_request.current_pixel_density = Some(selected_pixel_density);
                        self.image_request.set(ImageRequestPhase::Pending);
                        self.init_image_request(&mut pending_request, &url, &src);
                    },
                }
            },
        }
        self.fetch_image(&url);
    }

    /// Step 8-12 of html.spec.whatwg.org/multipage/#update-the-image-data
    fn update_the_image_data_sync_steps(&self) {
        let document = document_from_node(self);
        let window = document.window();
        let task_source = window.task_manager().dom_manipulation_task_source();
        let this = Trusted::new(self);
        let (src, pixel_density) = match self.select_image_source() {
            // Step 8
            Some(data) => data,
            None => {
                self.abort_request(State::Broken, ImageRequestPhase::Current);
                self.abort_request(State::Broken, ImageRequestPhase::Pending);
                // Step 9.
                // FIXME(nox): Why are errors silenced here?
                let _ = task_source.queue(
                    task!(image_null_source_error: move || {
                        let this = this.root();
                        {
                            let mut current_request =
                                this.current_request.borrow_mut();
                            current_request.source_url = None;
                            current_request.parsed_url = None;
                        }
                        let elem = this.upcast::<Element>();
                        let src_present = elem.has_attribute(&local_name!("src"));

                        if src_present || Self::uses_srcset_or_picture(elem) {
                            this.upcast::<EventTarget>().fire_event(atom!("error"));
                        }
                    }),
                    window.upcast(),
                );
                return;
            },
        };

        // Step 11
        let base_url = document.base_url();
        let parsed_url = base_url.join(&src.0);
        match parsed_url {
            Ok(url) => {
                // Step 13-17
                self.prepare_image_request(&url, &src, pixel_density);
            },
            Err(_) => {
                self.abort_request(State::Broken, ImageRequestPhase::Current);
                self.abort_request(State::Broken, ImageRequestPhase::Pending);
                // Step 12.1-12.5.
                let src = src.0;
                // FIXME(nox): Why are errors silenced here?
                let _ = task_source.queue(
                    task!(image_selected_source_error: move || {
                        let this = this.root();
                        {
                            let mut current_request =
                                this.current_request.borrow_mut();
                            current_request.source_url = Some(USVString(src))
                        }
                        this.upcast::<EventTarget>().fire_event(atom!("error"));

                    }),
                    window.upcast(),
                );
            },
        }
    }

    /// <https://html.spec.whatwg.org/multipage/#update-the-image-data>
    pub fn update_the_image_data(&self) {
        let document = document_from_node(self);
        let window = document.window();
        let elem = self.upcast::<Element>();
        let src = elem.get_url_attribute(&local_name!("src"));
        let base_url = document.base_url();

        // https://html.spec.whatwg.org/multipage/#reacting-to-dom-mutations
        // Always first set the current request to unavailable,
        // ensuring img.complete is false.
        {
            let mut current_request = self.current_request.borrow_mut();
            current_request.state = State::Unavailable;
        }

        if !document.is_active() {
            // Step 1 (if the document is inactive)
            // TODO: use GlobalScope::enqueue_microtask,
            // to queue micro task to come back to this algorithm
        }
        // Step 2 abort if user-agent does not supports images
        // NOTE: Servo only supports images, skipping this step

        // Step 3, 4
        let mut selected_source = None;
        let mut pixel_density = None;
        let src_set = elem.get_url_attribute(&local_name!("srcset"));
        let is_parent_picture = elem
            .upcast::<Node>()
            .GetParentElement()
            .map_or(false, |p| p.is::<HTMLPictureElement>());
        if src_set.is_empty() && !is_parent_picture && !src.is_empty() {
            selected_source = Some(src.clone());
            pixel_density = Some(1 as f64);
        };

        // Step 5
        *self.last_selected_source.borrow_mut() = selected_source.clone();

        // Step 6, check the list of available images
        if let Some(src) = selected_source {
            if let Ok(img_url) = base_url.join(&src) {
                let image_cache = window.image_cache();
                let response = image_cache.get_image(
                    img_url.clone(),
                    window.origin().immutable().clone(),
                    cors_setting_for_element(self.upcast()),
                );

                if let Some(image) = response {
                    // Cancel any outstanding tasks that were queued before the src was
                    // set on this element.
                    self.generation.set(self.generation.get() + 1);
                    // Step 6.3
                    let metadata = ImageMetadata {
                        height: image.height,
                        width: image.width,
                    };
                    // Step 6.3.2 abort requests
                    self.abort_request(State::CompletelyAvailable, ImageRequestPhase::Current);
                    self.abort_request(State::Unavailable, ImageRequestPhase::Pending);
                    let mut current_request = self.current_request.borrow_mut();
                    current_request.final_url = Some(img_url.clone());
                    current_request.image = Some(image.clone());
                    current_request.metadata = Some(metadata);
                    // Step 6.3.6
                    current_request.current_pixel_density = pixel_density;
                    let this = Trusted::new(self);
                    let src = src.0;
                    let _ = window.task_manager().dom_manipulation_task_source().queue(
                        task!(image_load_event: move || {
                            let this = this.root();
                            {
                                let mut current_request =
                                    this.current_request.borrow_mut();
                                current_request.parsed_url = Some(img_url);
                                current_request.source_url = Some(USVString(src));
                            }
                            // TODO: restart animation, if set.
                            this.upcast::<EventTarget>().fire_event(atom!("load"));
                        }),
                        window.upcast(),
                    );
                    return;
                }
            }
        }
        // step 7, await a stable state.
        self.generation.set(self.generation.get() + 1);
        let task = ImageElementMicrotask::StableStateUpdateImageDataTask {
            elem: DomRoot::from_ref(self),
            generation: self.generation.get(),
        };
        ScriptThread::await_stable_state(Microtask::ImageElement(task));
    }

    /// <https://html.spec.whatwg.org/multipage/#img-environment-changes>
    pub fn react_to_environment_changes(&self) {
        // Step 1
        let task = ImageElementMicrotask::EnvironmentChangesTask {
            elem: DomRoot::from_ref(self),
            generation: self.generation.get(),
        };
        ScriptThread::await_stable_state(Microtask::ImageElement(task));
    }

    /// Step 2-12 of https://html.spec.whatwg.org/multipage/#img-environment-changes
    fn react_to_environment_changes_sync_steps(&self, generation: u32) {
        // TODO reduce duplicacy of this code

        fn generate_cache_listener_for_element(
            elem: &HTMLImageElement,
            selected_source: String,
            selected_pixel_density: f64,
        ) -> IpcSender<PendingImageResponse> {
            let trusted_node = Trusted::new(elem);
            let (responder_sender, responder_receiver) = ipc::channel().unwrap();

            let window = window_from_node(elem);
            let (task_source, canceller) = window
                .task_manager()
                .networking_task_source_with_canceller();
            let generation = elem.generation.get();
            ROUTER.add_route(
                responder_receiver.to_opaque(),
                Box::new(move |message| {
                    debug!("Got image {:?}", message);
                    // Return the image via a message to the script thread, which marks
                    // the element as dirty and triggers a reflow.
                    let element = trusted_node.clone();
                    let image = message.to().unwrap();
                    let selected_source_clone = selected_source.clone();
                    let _ = task_source.queue_with_canceller(
                        task!(process_image_response_for_environment_change: move || {
                            let element = element.root();
                            // Ignore any image response for a previous request that has been discarded.
                            if generation == element.generation.get() {
                                element.process_image_response_for_environment_change(image,
                                    USVString::from(selected_source_clone), generation, selected_pixel_density);
                            }
                        }),
                        &canceller,
                    );
                }),
            );

            responder_sender
        }

        let elem = self.upcast::<Element>();
        let document = document_from_node(elem);
        let has_pending_request = match self.image_request.get() {
            ImageRequestPhase::Pending => true,
            _ => false,
        };

        // Step 2
        if !document.is_active() || !Self::uses_srcset_or_picture(elem) || has_pending_request {
            return;
        }

        // Steps 3-4
        let (selected_source, selected_pixel_density) = match self.select_image_source() {
            Some(selected) => selected,
            None => return,
        };

        // Step 5
        let same_source = match *self.last_selected_source.borrow() {
            Some(ref last_src) => *last_src == selected_source,
            _ => false,
        };

        let same_selected_pixel_density = match self.current_request.borrow().current_pixel_density
        {
            Some(den) => selected_pixel_density == den,
            _ => false,
        };

        if same_source && same_selected_pixel_density {
            return;
        }

        let base_url = document.base_url();
        // Step 6
        let img_url = match base_url.join(&selected_source.0) {
            Ok(url) => url,
            Err(_) => return,
        };

        // Step 12
        self.image_request.set(ImageRequestPhase::Pending);
        self.init_image_request(
            &mut self.pending_request.borrow_mut(),
            &img_url,
            &selected_source,
        );

        let window = window_from_node(self);
        let image_cache = window.image_cache();

        // Step 14
        let sender = generate_cache_listener_for_element(
            self,
            selected_source.0.clone(),
            selected_pixel_density,
        );
        let cache_result = image_cache.track_image(
            img_url.clone(),
            window.origin().immutable().clone(),
            cors_setting_for_element(self.upcast()),
            sender,
            UsePlaceholder::No,
        );

        match cache_result {
            ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable { .. }) => {
                // Step 15
                self.finish_reacting_to_environment_change(
                    selected_source,
                    generation,
                    selected_pixel_density,
                )
            },
            ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(m)) => {
                self.process_image_response_for_environment_change(
                    ImageResponse::MetadataLoaded(m),
                    selected_source,
                    generation,
                    selected_pixel_density,
                );
            },
            ImageCacheResult::LoadError => {
                self.process_image_response_for_environment_change(
                    ImageResponse::None,
                    selected_source,
                    generation,
                    selected_pixel_density,
                );
            },
            ImageCacheResult::ReadyForRequest(id) => self.fetch_request(&img_url, id),
            ImageCacheResult::Pending(_) => (),
        }
    }

    /// Step 15 for <https://html.spec.whatwg.org/multipage/#img-environment-changes>
    fn finish_reacting_to_environment_change(
        &self,
        src: USVString,
        generation: u32,
        selected_pixel_density: f64,
    ) {
        let this = Trusted::new(self);
        let window = window_from_node(self);
        let src = src.0;
        let _ = window.task_manager().dom_manipulation_task_source().queue(
            task!(image_load_event: move || {
                let this = this.root();
                let relevant_mutation = this.generation.get() != generation;
                // Step 15.1
                if relevant_mutation {
                    this.abort_request(State::Unavailable, ImageRequestPhase::Pending);
                    return;
                }
                // Step 15.2
                *this.last_selected_source.borrow_mut() = Some(USVString(src));

                {
                    let mut pending_request = this.pending_request.borrow_mut();
                    pending_request.current_pixel_density = Some(selected_pixel_density);

                    // Step 15.3
                    pending_request.state = State::CompletelyAvailable;

                    // Step 15.4
                    // Already a part of the list of available images due to Step 14

                    // Step 15.5
                    mem::swap(&mut this.current_request.borrow_mut(), &mut pending_request);
                    this.abort_request(State::Unavailable, ImageRequestPhase::Pending);
                }

                // Step 15.6
                this.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);

                // Step 15.7
                this.upcast::<EventTarget>().fire_event(atom!("load"));
            }),
            window.upcast(),
        );
    }

    fn uses_srcset_or_picture(elem: &Element) -> bool {
        let has_src = elem.has_attribute(&local_name!("srcset"));
        let is_parent_picture = elem
            .upcast::<Node>()
            .GetParentElement()
            .map_or(false, |p| p.is::<HTMLPictureElement>());
        has_src || is_parent_picture
    }

    fn new_inherited(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
    ) -> HTMLImageElement {
        HTMLImageElement {
            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
            image_request: Cell::new(ImageRequestPhase::Current),
            current_request: DomRefCell::new(ImageRequest {
                state: State::Unavailable,
                parsed_url: None,
                source_url: None,
                image: None,
                metadata: None,
                blocker: None,
                final_url: None,
                current_pixel_density: None,
            }),
            pending_request: DomRefCell::new(ImageRequest {
                state: State::Unavailable,
                parsed_url: None,
                source_url: None,
                image: None,
                metadata: None,
                blocker: None,
                final_url: None,
                current_pixel_density: None,
            }),
            form_owner: Default::default(),
            generation: Default::default(),
            source_set: DomRefCell::new(SourceSet::new()),
            last_selected_source: DomRefCell::new(None),
        }
    }

    #[allow(unrooted_must_root)]
    pub fn new(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
    ) -> DomRoot<HTMLImageElement> {
        Node::reflect_node(
            Box::new(HTMLImageElement::new_inherited(
                local_name, prefix, document,
            )),
            document,
        )
    }

    pub fn Image(
        window: &Window,
        width: Option<u32>,
        height: Option<u32>,
    ) -> Fallible<DomRoot<HTMLImageElement>> {
        let element = Element::create(
            QualName::new(None, ns!(html), local_name!("img")),
            None,
            &window.Document(),
            ElementCreator::ScriptCreated,
            CustomElementCreationMode::Synchronous,
        );

        let image = DomRoot::downcast::<HTMLImageElement>(element).unwrap();
        if let Some(w) = width {
            image.SetWidth(w);
        }
        if let Some(h) = height {
            image.SetHeight(h);
        }

        Ok(image)
    }
    pub fn areas(&self) -> Option<Vec<DomRoot<HTMLAreaElement>>> {
        let elem = self.upcast::<Element>();
        let usemap_attr = elem.get_attribute(&ns!(), &local_name!("usemap"))?;

        let value = usemap_attr.value();

        if value.len() == 0 || !value.is_char_boundary(1) {
            return None;
        }

        let (first, last) = value.split_at(1);

        if first != "#" || last.len() == 0 {
            return None;
        }

        let useMapElements = document_from_node(self)
            .upcast::<Node>()
            .traverse_preorder(ShadowIncluding::No)
            .filter_map(DomRoot::downcast::<HTMLMapElement>)
            .find(|n| {
                n.upcast::<Element>()
                    .get_name()
                    .map_or(false, |n| *n == *last)
            });

        useMapElements.map(|mapElem| mapElem.get_area_elements())
    }

    pub fn same_origin(&self, origin: &MutableOrigin) -> bool {
        if let Some(ref image) = self.current_request.borrow().image {
            return image.cors_status == CorsStatus::Safe;
        }

        self.current_request
            .borrow()
            .final_url
            .as_ref()
            .map_or(false, |url| {
                url.scheme() == "data" || url.origin().same_origin(origin)
            })
    }
}

#[derive(JSTraceable, MallocSizeOf)]
pub enum ImageElementMicrotask {
    StableStateUpdateImageDataTask {
        elem: DomRoot<HTMLImageElement>,
        generation: u32,
    },
    EnvironmentChangesTask {
        elem: DomRoot<HTMLImageElement>,
        generation: u32,
    },
}

impl MicrotaskRunnable for ImageElementMicrotask {
    fn handler(&self) {
        match self {
            &ImageElementMicrotask::StableStateUpdateImageDataTask {
                ref elem,
                ref generation,
            } => {
                // Step 7 of https://html.spec.whatwg.org/multipage/#update-the-image-data,
                // stop here if other instances of this algorithm have been scheduled
                if elem.generation.get() == *generation {
                    elem.update_the_image_data_sync_steps();
                }
            },
            &ImageElementMicrotask::EnvironmentChangesTask {
                ref elem,
                ref generation,
            } => {
                elem.react_to_environment_changes_sync_steps(*generation);
            },
        }
    }
}

pub trait LayoutHTMLImageElementHelpers {
    fn image(self) -> Option<Arc<Image>>;
    fn image_url(self) -> Option<ServoUrl>;
    fn image_density(self) -> Option<f64>;
    fn image_data(self) -> (Option<Arc<Image>>, Option<ImageMetadata>);
    fn get_width(self) -> LengthOrPercentageOrAuto;
    fn get_height(self) -> LengthOrPercentageOrAuto;
}

impl<'dom> LayoutDom<'dom, HTMLImageElement> {
    #[allow(unsafe_code)]
    fn current_request(self) -> &'dom ImageRequest {
        unsafe { self.unsafe_get().current_request.borrow_for_layout() }
    }
}

impl LayoutHTMLImageElementHelpers for LayoutDom<'_, HTMLImageElement> {
    fn image(self) -> Option<Arc<Image>> {
        self.current_request().image.clone()
    }

    fn image_url(self) -> Option<ServoUrl> {
        self.current_request().parsed_url.clone()
    }

    fn image_data(self) -> (Option<Arc<Image>>, Option<ImageMetadata>) {
        let current_request = self.current_request();
        (
            current_request.image.clone(),
            current_request.metadata.clone(),
        )
    }

    fn image_density(self) -> Option<f64> {
        self.current_request().current_pixel_density.clone()
    }

    fn get_width(self) -> LengthOrPercentageOrAuto {
        self.upcast::<Element>()
            .get_attr_for_layout(&ns!(), &local_name!("width"))
            .map(AttrValue::as_dimension)
            .cloned()
            .unwrap_or(LengthOrPercentageOrAuto::Auto)
    }

    fn get_height(self) -> LengthOrPercentageOrAuto {
        self.upcast::<Element>()
            .get_attr_for_layout(&ns!(), &local_name!("height"))
            .map(AttrValue::as_dimension)
            .cloned()
            .unwrap_or(LengthOrPercentageOrAuto::Auto)
    }
}

//https://html.spec.whatwg.org/multipage/#parse-a-sizes-attribute
pub fn parse_a_sizes_attribute(value: DOMString) -> SourceSizeList {
    let mut input = ParserInput::new(&value);
    let mut parser = Parser::new(&mut input);
    let url = ServoUrl::parse("about:blank").unwrap();
    let context = ParserContext::new(
        Origin::Author,
        &url,
        Some(CssRuleType::Style),
        // FIXME(emilio): why ::empty() instead of ::DEFAULT? Also, what do
        // browsers do regarding quirks-mode in a media list?
        ParsingMode::empty(),
        QuirksMode::NoQuirks,
        None,
        None,
    );
    SourceSizeList::parse(&context, &mut parser)
}

fn get_correct_referrerpolicy_from_raw_token(token: &DOMString) -> DOMString {
    if token == "" {
        // Empty token is treated as no-referrer inside determine_policy_for_token,
        // while here it should be treated as the default value, so it should remain unchanged.
        DOMString::new()
    } else {
        match determine_policy_for_token(token) {
            Some(policy) => DOMString::from_string(policy.to_string()),
            // If the policy is set to an incorrect value, then it should be
            // treated as an invalid value default (empty string).
            None => DOMString::new(),
        }
    }
}

impl HTMLImageElementMethods for HTMLImageElement {
    // https://html.spec.whatwg.org/multipage/#dom-img-alt
    make_getter!(Alt, "alt");
    // https://html.spec.whatwg.org/multipage/#dom-img-alt
    make_setter!(SetAlt, "alt");

    // https://html.spec.whatwg.org/multipage/#dom-img-src
    make_url_getter!(Src, "src");

    // https://html.spec.whatwg.org/multipage/#dom-img-src
    make_url_setter!(SetSrc, "src");

    // https://html.spec.whatwg.org/multipage/#dom-img-srcset
    make_url_getter!(Srcset, "srcset");
    // https://html.spec.whatwg.org/multipage/#dom-img-src
    make_url_setter!(SetSrcset, "srcset");

    // https://html.spec.whatwg.org/multipage/#dom-img-crossOrigin
    fn GetCrossOrigin(&self) -> Option<DOMString> {
        reflect_cross_origin_attribute(self.upcast::<Element>())
    }

    // https://html.spec.whatwg.org/multipage/#dom-img-crossOrigin
    fn SetCrossOrigin(&self, value: Option<DOMString>) {
        set_cross_origin_attribute(self.upcast::<Element>(), value);
    }

    // https://html.spec.whatwg.org/multipage/#dom-img-usemap
    make_getter!(UseMap, "usemap");
    // https://html.spec.whatwg.org/multipage/#dom-img-usemap
    make_setter!(SetUseMap, "usemap");

    // https://html.spec.whatwg.org/multipage/#dom-img-ismap
    make_bool_getter!(IsMap, "ismap");
    // https://html.spec.whatwg.org/multipage/#dom-img-ismap
    make_bool_setter!(SetIsMap, "ismap");

    // https://html.spec.whatwg.org/multipage/#dom-img-width
    fn Width(&self) -> u32 {
        let node = self.upcast::<Node>();
        match node.bounding_content_box() {
            Some(rect) => rect.size.width.to_px() as u32,
            None => self.NaturalWidth(),
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-img-width
    fn SetWidth(&self, value: u32) {
        image_dimension_setter(self.upcast(), local_name!("width"), value);
    }

    // https://html.spec.whatwg.org/multipage/#dom-img-height
    fn Height(&self) -> u32 {
        let node = self.upcast::<Node>();
        match node.bounding_content_box() {
            Some(rect) => rect.size.height.to_px() as u32,
            None => self.NaturalHeight(),
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-img-height
    fn SetHeight(&self, value: u32) {
        image_dimension_setter(self.upcast(), local_name!("height"), value);
    }

    // https://html.spec.whatwg.org/multipage/#dom-img-naturalwidth
    fn NaturalWidth(&self) -> u32 {
        let request = self.current_request.borrow();
        let pixel_density = request.current_pixel_density.unwrap_or(1f64);

        match request.metadata {
            Some(ref metadata) => (metadata.width as f64 / pixel_density) as u32,
            None => 0,
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-img-naturalheight
    fn NaturalHeight(&self) -> u32 {
        let request = self.current_request.borrow();
        let pixel_density = request.current_pixel_density.unwrap_or(1f64);

        match request.metadata {
            Some(ref metadata) => (metadata.height as f64 / pixel_density) as u32,
            None => 0,
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-img-complete
    fn Complete(&self) -> bool {
        let elem = self.upcast::<Element>();
        let srcset_absent = !elem.has_attribute(&local_name!("srcset"));
        if !elem.has_attribute(&local_name!("src")) && srcset_absent {
            return true;
        }
        let src = elem.get_string_attribute(&local_name!("src"));
        if srcset_absent && src.is_empty() {
            return true;
        }
        let request = self.current_request.borrow();
        let request_state = request.state;
        match request_state {
            State::CompletelyAvailable | State::Broken => return true,
            State::PartiallyAvailable | State::Unavailable => return false,
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-img-currentsrc
    fn CurrentSrc(&self) -> USVString {
        let current_request = self.current_request.borrow();
        let ref url = current_request.parsed_url;
        match *url {
            Some(ref url) => USVString(url.clone().into_string()),
            None => {
                let ref unparsed_url = current_request.source_url;
                match *unparsed_url {
                    Some(ref url) => url.clone(),
                    None => USVString("".to_owned()),
                }
            },
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-img-referrerpolicy
    fn ReferrerPolicy(&self) -> DOMString {
        let element = self.upcast::<Element>();
        let current_policy_value = element.get_string_attribute(&local_name!("referrerpolicy"));
        get_correct_referrerpolicy_from_raw_token(&current_policy_value)
    }

    // https://html.spec.whatwg.org/multipage/#dom-img-referrerpolicy
    fn SetReferrerPolicy(&self, value: DOMString) {
        let referrerpolicy_attr_name = local_name!("referrerpolicy");
        let element = self.upcast::<Element>();
        let previous_correct_attribute_value = get_correct_referrerpolicy_from_raw_token(
            &element.get_string_attribute(&referrerpolicy_attr_name),
        );
        let correct_value_or_empty_string = get_correct_referrerpolicy_from_raw_token(&value);
        if previous_correct_attribute_value != correct_value_or_empty_string {
            // Setting the attribute to the same value will update the image.
            // We don't want to start an update if referrerpolicy is set to the same value.
            element.set_string_attribute(&referrerpolicy_attr_name, correct_value_or_empty_string);
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-img-name
    make_getter!(Name, "name");

    // https://html.spec.whatwg.org/multipage/#dom-img-name
    make_atomic_setter!(SetName, "name");

    // https://html.spec.whatwg.org/multipage/#dom-img-align
    make_getter!(Align, "align");

    // https://html.spec.whatwg.org/multipage/#dom-img-align
    make_setter!(SetAlign, "align");

    // https://html.spec.whatwg.org/multipage/#dom-img-hspace
    make_uint_getter!(Hspace, "hspace");

    // https://html.spec.whatwg.org/multipage/#dom-img-hspace
    make_uint_setter!(SetHspace, "hspace");

    // https://html.spec.whatwg.org/multipage/#dom-img-vspace
    make_uint_getter!(Vspace, "vspace");

    // https://html.spec.whatwg.org/multipage/#dom-img-vspace
    make_uint_setter!(SetVspace, "vspace");

    // https://html.spec.whatwg.org/multipage/#dom-img-longdesc
    make_getter!(LongDesc, "longdesc");

    // https://html.spec.whatwg.org/multipage/#dom-img-longdesc
    make_setter!(SetLongDesc, "longdesc");

    // https://html.spec.whatwg.org/multipage/#dom-img-border
    make_getter!(Border, "border");

    // https://html.spec.whatwg.org/multipage/#dom-img-border
    make_setter!(SetBorder, "border");
}

impl VirtualMethods for HTMLImageElement {
    fn super_type(&self) -> Option<&dyn VirtualMethods> {
        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
    }

    fn adopting_steps(&self, old_doc: &Document) {
        self.super_type().unwrap().adopting_steps(old_doc);
        self.update_the_image_data();
    }

    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
        self.super_type().unwrap().attribute_mutated(attr, mutation);
        match attr.local_name() {
            &local_name!("src") |
            &local_name!("srcset") |
            &local_name!("width") |
            &local_name!("crossorigin") |
            &local_name!("sizes") |
            &local_name!("referrerpolicy") => self.update_the_image_data(),
            _ => {},
        }
    }

    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
        match name {
            &local_name!("width") | &local_name!("height") => {
                AttrValue::from_dimension(value.into())
            },
            &local_name!("hspace") | &local_name!("vspace") => AttrValue::from_u32(value.into(), 0),
            _ => self
                .super_type()
                .unwrap()
                .parse_plain_attribute(name, value),
        }
    }

    fn handle_event(&self, event: &Event) {
        if event.type_() != atom!("click") {
            return;
        }

        let area_elements = self.areas();
        let elements = match area_elements {
            Some(x) => x,
            None => return,
        };

        // Fetch click coordinates
        let mouse_event = match event.downcast::<MouseEvent>() {
            Some(x) => x,
            None => return,
        };

        let point = Point2D::new(
            mouse_event.ClientX().to_f32().unwrap(),
            mouse_event.ClientY().to_f32().unwrap(),
        );
        let bcr = self.upcast::<Element>().GetBoundingClientRect();
        let bcr_p = Point2D::new(bcr.X() as f32, bcr.Y() as f32);

        // Walk HTMLAreaElements
        for element in elements {
            let shape = element.get_shape_from_coords();
            let shp = match shape {
                Some(x) => x.absolute_coords(bcr_p),
                None => return,
            };
            if shp.hit_test(&point) {
                element.activation_behavior(event, self.upcast());
                return;
            }
        }
    }

    fn bind_to_tree(&self, context: &BindContext) {
        if let Some(ref s) = self.super_type() {
            s.bind_to_tree(context);
        }
        let document = document_from_node(self);
        if context.tree_connected {
            document.register_responsive_image(self);
        }

        // The element is inserted into a picture parent element
        // https://html.spec.whatwg.org/multipage/#relevant-mutations
        if let Some(parent) = self.upcast::<Node>().GetParentElement() {
            if parent.is::<HTMLPictureElement>() {
                self.update_the_image_data();
            }
        }
    }

    fn unbind_from_tree(&self, context: &UnbindContext) {
        self.super_type().unwrap().unbind_from_tree(context);
        let document = document_from_node(self);
        document.unregister_responsive_image(self);

        // The element is removed from a picture parent element
        // https://html.spec.whatwg.org/multipage/#relevant-mutations
        if context.parent.is::<HTMLPictureElement>() {
            self.update_the_image_data();
        }
    }
}

impl FormControl for HTMLImageElement {
    fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
        self.form_owner.get()
    }

    fn set_form_owner(&self, form: Option<&HTMLFormElement>) {
        self.form_owner.set(form);
    }

    fn to_element<'a>(&'a self) -> &'a Element {
        self.upcast::<Element>()
    }

    fn is_listed(&self) -> bool {
        false
    }
}

impl ImageCacheListener for HTMLImageElement {
    fn generation_id(&self) -> u32 {
        self.generation.get()
    }

    fn process_image_response(&self, response: ImageResponse) {
        self.process_image_response(response);
    }
}

fn image_dimension_setter(element: &Element, attr: LocalName, value: u32) {
    // This setter is a bit weird: the IDL type is unsigned long, but it's parsed as
    // a dimension for rendering.
    let value = if value > UNSIGNED_LONG_MAX { 0 } else { value };

    // FIXME: There are probably quite a few more cases of this. This is the
    // only overflow that was hitting on automation, but we should consider what
    // to do in the general case case.
    //
    // See <https://github.com/servo/app_units/issues/22>
    let pixel_value = if value > (i32::MAX / AU_PER_PX) as u32 {
        0
    } else {
        value
    };

    let dim = LengthOrPercentageOrAuto::Length(Au::from_px(pixel_value as i32));
    let value = AttrValue::Dimension(value.to_string(), dim);
    element.set_attribute(&attr, value);
}

/// Collect sequence of code points
pub fn collect_sequence_characters<F>(s: &str, predicate: F) -> (&str, &str)
where
    F: Fn(&char) -> bool,
{
    for (i, ch) in s.chars().enumerate() {
        if !predicate(&ch) {
            return (&s[0..i], &s[i..]);
        }
    }

    return (s, "");
}

/// Parse an `srcset` attribute - https://html.spec.whatwg.org/multipage/#parsing-a-srcset-attribute.
pub fn parse_a_srcset_attribute(input: &str) -> Vec<ImageSource> {
    let mut url_len = 0;
    let mut candidates: Vec<ImageSource> = vec![];
    while url_len < input.len() {
        let position = &input[url_len..];
        let (spaces, position) =
            collect_sequence_characters(position, |c| *c == ',' || char::is_whitespace(*c));
        // add the length of the url that we parse to advance the start index
        let space_len = spaces.char_indices().count();
        url_len += space_len;
        if position.is_empty() {
            return candidates;
        }
        let (url, spaces) = collect_sequence_characters(position, |c| !char::is_whitespace(*c));
        // add the counts of urls that we parse to advance the start index
        url_len += url.chars().count();
        let comma_count = url.chars().rev().take_while(|c| *c == ',').count();
        let url: String = url
            .chars()
            .take(url.chars().count() - comma_count)
            .collect();
        // add 1 to start index, for the comma
        url_len += comma_count + 1;
        let (space, position) = collect_sequence_characters(spaces, |c| char::is_whitespace(*c));
        let space_len = space.len();
        url_len += space_len;
        let mut descriptors = Vec::new();
        let mut current_descriptor = String::new();
        let mut state = ParseState::InDescriptor;
        let mut char_stream = position.chars().enumerate();
        let mut buffered: Option<(usize, char)> = None;
        loop {
            let next_char = buffered.take().or_else(|| char_stream.next());
            if next_char.is_some() {
                url_len += 1;
            }
            match state {
                ParseState::InDescriptor => match next_char {
                    Some((_, ' ')) => {
                        if !current_descriptor.is_empty() {
                            descriptors.push(current_descriptor.clone());
                            current_descriptor = String::new();
                            state = ParseState::AfterDescriptor;
                        }
                        continue;
                    },
                    Some((_, ',')) => {
                        if !current_descriptor.is_empty() {
                            descriptors.push(current_descriptor.clone());
                        }
                        break;
                    },
                    Some((_, c @ '(')) => {
                        current_descriptor.push(c);
                        state = ParseState::InParens;
                        continue;
                    },
                    Some((_, c)) => {
                        current_descriptor.push(c);
                    },
                    None => {
                        if !current_descriptor.is_empty() {
                            descriptors.push(current_descriptor.clone());
                        }
                        break;
                    },
                },
                ParseState::InParens => match next_char {
                    Some((_, c @ ')')) => {
                        current_descriptor.push(c);
                        state = ParseState::InDescriptor;
                        continue;
                    },
                    Some((_, c)) => {
                        current_descriptor.push(c);
                        continue;
                    },
                    None => {
                        if !current_descriptor.is_empty() {
                            descriptors.push(current_descriptor.clone());
                        }
                        break;
                    },
                },
                ParseState::AfterDescriptor => match next_char {
                    Some((_, ' ')) => {
                        state = ParseState::AfterDescriptor;
                        continue;
                    },
                    Some((idx, c)) => {
                        state = ParseState::InDescriptor;
                        buffered = Some((idx, c));
                        continue;
                    },
                    None => {
                        if !current_descriptor.is_empty() {
                            descriptors.push(current_descriptor.clone());
                        }
                        break;
                    },
                },
            }
        }

        let mut error = false;
        let mut width: Option<u32> = None;
        let mut density: Option<f64> = None;
        let mut future_compat_h: Option<u32> = None;
        for descriptor in descriptors {
            let (digits, remaining) =
                collect_sequence_characters(&descriptor, |c| is_ascii_digit(c) || *c == '.');
            let valid_non_negative_integer = parse_unsigned_integer(digits.chars());
            let has_w = remaining == "w";
            let valid_floating_point = parse_double(digits);
            let has_x = remaining == "x";
            let has_h = remaining == "h";
            if valid_non_negative_integer.is_ok() && has_w {
                let result = valid_non_negative_integer;
                error = result.is_err();
                if width.is_some() || density.is_some() {
                    error = true;
                }
                if let Ok(w) = result {
                    width = Some(w);
                }
            } else if valid_floating_point.is_ok() && has_x {
                let result = valid_floating_point;
                error = result.is_err();
                if width.is_some() || density.is_some() || future_compat_h.is_some() {
                    error = true;
                }
                if let Ok(x) = result {
                    density = Some(x);
                }
            } else if valid_non_negative_integer.is_ok() && has_h {
                let result = valid_non_negative_integer;
                error = result.is_err();
                if density.is_some() || future_compat_h.is_some() {
                    error = true;
                }
                if let Ok(h) = result {
                    future_compat_h = Some(h);
                }
            } else {
                error = true;
            }
        }
        if future_compat_h.is_some() && width.is_none() {
            error = true;
        }
        if !error {
            let descriptor = Descriptor {
                wid: width,
                den: density,
            };
            let image_source = ImageSource {
                url: url,
                descriptor: descriptor,
            };
            candidates.push(image_source);
        }
    }
    candidates
}