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

#include "mozilla/dom/ResponsiveImageSelector.h"
#include "nsIURI.h"
#include "nsIDocument.h"
#include "nsContentUtils.h"
#include "nsPresContext.h"

#include "nsCSSParser.h"
#include "nsCSSProps.h"
#include "nsIMediaList.h"
#include "nsRuleNode.h"
#include "nsRuleData.h"

using namespace mozilla;
using namespace mozilla::dom;

namespace mozilla {
namespace dom {

NS_IMPL_CYCLE_COLLECTION(ResponsiveImageSelector, mOwnerNode)

NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(ResponsiveImageSelector, AddRef)
NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(ResponsiveImageSelector, Release)

static bool
ParseInteger(const nsAString& aString, int32_t& aInt)
{
  nsContentUtils::ParseHTMLIntegerResultFlags parseResult;
  aInt = nsContentUtils::ParseHTMLInteger(aString, &parseResult);
  return !(parseResult &
           ( nsContentUtils::eParseHTMLInteger_Error |
             nsContentUtils::eParseHTMLInteger_DidNotConsumeAllInput |
             nsContentUtils::eParseHTMLInteger_IsPercent |
             nsContentUtils::eParseHTMLInteger_NonStandard ));
}

static bool
ParseFloat(const nsAString& aString, double& aDouble)
{
  // Check if it is a valid floating-point number first since the result of
  // nsString.ToDouble() is more lenient than the spec,
  // https://html.spec.whatwg.org/#valid-floating-point-number
  nsAString::const_iterator iter, end;
  aString.BeginReading(iter);
  aString.EndReading(end);

  if (iter == end) {
    return false;
  }

  if (*iter == char16_t('-') && ++iter == end) {
    return false;
  }

  if (nsCRT::IsAsciiDigit(*iter)) {
    for (; iter != end && nsCRT::IsAsciiDigit(*iter) ; ++iter);
  } else if (*iter == char16_t('.')) {
    // Do nothing, jumps to fraction part
  } else {
    return false;
  }

  // Fraction
  if (*iter == char16_t('.')) {
    ++iter;
    if (iter == end || !nsCRT::IsAsciiDigit(*iter)) {
      // U+002E FULL STOP character (.) must be followed by one or more ASCII digits
      return false;
    }

    for (; iter != end && nsCRT::IsAsciiDigit(*iter) ; ++iter);
  }

  if (iter != end && (*iter == char16_t('e') || *iter == char16_t('E'))) {
    ++iter;
    if (*iter == char16_t('-') || *iter == char16_t('+')) {
      ++iter;
    }

    if (iter == end || !nsCRT::IsAsciiDigit(*iter)) {
      // Should have one or more ASCII digits
      return false;
    }

    for (; iter != end && nsCRT::IsAsciiDigit(*iter) ; ++iter);
  }

  if (iter != end) {
    return false;
  }

  nsresult rv;
  aDouble = PromiseFlatString(aString).ToDouble(&rv);
  return NS_SUCCEEDED(rv);
}

ResponsiveImageSelector::ResponsiveImageSelector(nsIContent *aContent)
  : mOwnerNode(aContent),
    mSelectedCandidateIndex(-1)
{
}

ResponsiveImageSelector::ResponsiveImageSelector(nsIDocument *aDocument)
  : mOwnerNode(aDocument),
    mSelectedCandidateIndex(-1)
{
}

ResponsiveImageSelector::~ResponsiveImageSelector()
{}

// http://www.whatwg.org/specs/web-apps/current-work/#processing-the-image-candidates
bool
ResponsiveImageSelector::SetCandidatesFromSourceSet(const nsAString & aSrcSet)
{
  ClearSelectedCandidate();

  nsCOMPtr<nsIURI> docBaseURI = mOwnerNode ? mOwnerNode->GetBaseURI() : nullptr;

  if (!docBaseURI) {
    MOZ_ASSERT(false,
               "Should not be parsing SourceSet without a document");
    return false;
  }

  mCandidates.Clear();

  nsAString::const_iterator iter, end;
  aSrcSet.BeginReading(iter);
  aSrcSet.EndReading(end);

  // Read URL / descriptor pairs
  while (iter != end) {
    nsAString::const_iterator url, urlEnd, descriptor;

    // Skip whitespace and commas.
    // Extra commas at this point are a non-fatal syntax error.
    for (; iter != end && (nsContentUtils::IsHTMLWhitespace(*iter) ||
                           *iter == char16_t(',')); ++iter);

    if (iter == end) {
      break;
    }

    url = iter;

    // Find end of url
    for (;iter != end && !nsContentUtils::IsHTMLWhitespace(*iter); ++iter);

    // Omit trailing commas from URL.
    // Multiple commas are a non-fatal error.
    while (iter != url) {
      if (*(--iter) != char16_t(',')) {
        iter++;
        break;
      }
    }

    const nsDependentSubstring &urlStr = Substring(url, iter);

    MOZ_ASSERT(url != iter, "Shouldn't have empty URL at this point");

    ResponsiveImageCandidate candidate;
    if (candidate.ConsumeDescriptors(iter, end)) {
      candidate.SetURLSpec(urlStr);
      AppendCandidateIfUnique(candidate);
    }
  }

  bool parsedCandidates = mCandidates.Length() > 0;

  // Re-add default to end of list
  MaybeAppendDefaultCandidate();

  return parsedCandidates;
}

uint32_t
ResponsiveImageSelector::NumCandidates(bool aIncludeDefault)
{
  uint32_t candidates = mCandidates.Length();

  // If present, the default candidate is the last item
  if (!aIncludeDefault && candidates &&
      (mCandidates[candidates - 1].Type() ==
       ResponsiveImageCandidate::eCandidateType_Default)) {
    candidates--;
  }

  return candidates;
}

nsIContent*
ResponsiveImageSelector::Content()
{
  return mOwnerNode->IsContent() ? mOwnerNode->AsContent() : nullptr;
}

nsIDocument*
ResponsiveImageSelector::Document()
{
  return mOwnerNode->OwnerDoc();
}

void
ResponsiveImageSelector::SetDefaultSource(const nsAString& aURLString)
{
  ClearSelectedCandidate();

  // Check if the last element of our candidates is a default
  int32_t candidates = mCandidates.Length();
  if (candidates && (mCandidates[candidates - 1].Type() ==
                     ResponsiveImageCandidate::eCandidateType_Default)) {
    mCandidates.RemoveElementAt(candidates - 1);
  }

  mDefaultSourceURL = aURLString;

  // Add new default to end of list
  MaybeAppendDefaultCandidate();
}

void
ResponsiveImageSelector::ClearSelectedCandidate()
{
  mSelectedCandidateIndex = -1;
  mSelectedCandidateURL = nullptr;
}

bool
ResponsiveImageSelector::SetSizesFromDescriptor(const nsAString & aSizes)
{
  ClearSelectedCandidate();
  mSizeQueries.Clear();
  mSizeValues.Clear();

  nsCSSParser cssParser;

  return cssParser.ParseSourceSizeList(aSizes, nullptr, 0,
                                       mSizeQueries, mSizeValues, true);
}

void
ResponsiveImageSelector::AppendCandidateIfUnique(const ResponsiveImageCandidate & aCandidate)
{
  int numCandidates = mCandidates.Length();

  // With the exception of Default, which should not be added until we are done
  // building the list.
  if (aCandidate.Type() == ResponsiveImageCandidate::eCandidateType_Default) {
    return;
  }

  // Discard candidates with identical parameters, they will never match
  for (int i = 0; i < numCandidates; i++) {
    if (mCandidates[i].HasSameParameter(aCandidate)) {
      return;
    }
  }

  mCandidates.AppendElement(aCandidate);
}

void
ResponsiveImageSelector::MaybeAppendDefaultCandidate()
{
  if (mDefaultSourceURL.IsEmpty()) {
    return;
  }

  int numCandidates = mCandidates.Length();

  // https://html.spec.whatwg.org/multipage/embedded-content.html#update-the-source-set
  // step 4.1.3:
  // If child has a src attribute whose value is not the empty string and source
  // set does not contain an image source with a density descriptor value of 1,
  // and no image source with a width descriptor, append child's src attribute
  // value to source set.
  for (int i = 0; i < numCandidates; i++) {
    if (mCandidates[i].IsComputedFromWidth()) {
      return;
    } else if (mCandidates[i].Density(this) == 1.0) {
      return;
    }
  }

  ResponsiveImageCandidate defaultCandidate;
  defaultCandidate.SetParameterDefault();
  defaultCandidate.SetURLSpec(mDefaultSourceURL);
  // We don't use MaybeAppend since we want to keep this even if it can never
  // match, as it may if the source set changes.
  mCandidates.AppendElement(defaultCandidate);
}

already_AddRefed<nsIURI>
ResponsiveImageSelector::GetSelectedImageURL()
{
  SelectImage();

  nsCOMPtr<nsIURI> url = mSelectedCandidateURL;
  return url.forget();
}

bool
ResponsiveImageSelector::GetSelectedImageURLSpec(nsAString& aResult)
{
  SelectImage();

  if (mSelectedCandidateIndex == -1) {
    return false;
  }

  aResult.Assign(mCandidates[mSelectedCandidateIndex].URLString());
  return true;
}

double
ResponsiveImageSelector::GetSelectedImageDensity()
{
  int bestIndex = GetSelectedCandidateIndex();
  if (bestIndex < 0) {
    return 1.0;
  }

  return mCandidates[bestIndex].Density(this);
}

bool
ResponsiveImageSelector::SelectImage(bool aReselect)
{
  if (!aReselect && mSelectedCandidateIndex != -1) {
    // Already have selection
    return false;
  }

  int oldBest = mSelectedCandidateIndex;
  ClearSelectedCandidate();

  int numCandidates = mCandidates.Length();
  if (!numCandidates) {
    return oldBest != -1;
  }

  nsIDocument* doc = Document();
  nsIPresShell *shell = doc ? doc->GetShell() : nullptr;
  nsPresContext *pctx = shell ? shell->GetPresContext() : nullptr;
  nsCOMPtr<nsIURI> baseURI = mOwnerNode ? mOwnerNode->GetBaseURI() : nullptr;

  if (!pctx || !doc || !baseURI) {
    return oldBest != -1;
  }

  double displayDensity = pctx->CSSPixelsToDevPixels(1.0f);

  // Per spec, "In a UA-specific manner, choose one image source"
  // - For now, select the lowest density greater than displayDensity, otherwise
  //   the greatest density available

  // If the list contains computed width candidates, compute the current
  // effective image width.
  double computedWidth = -1;
  for (int i = 0; i < numCandidates; i++) {
    if (mCandidates[i].IsComputedFromWidth()) {
      DebugOnly<bool> computeResult = \
        ComputeFinalWidthForCurrentViewport(&computedWidth);
      MOZ_ASSERT(computeResult,
                 "Computed candidates not allowed without sizes data");
      break;
    }
  }

  int bestIndex = -1;
  double bestDensity = -1.0;
  for (int i = 0; i < numCandidates; i++) {
    double candidateDensity = \
      (computedWidth == -1) ? mCandidates[i].Density(this)
                            : mCandidates[i].Density(computedWidth);
    // - If bestIndex is below display density, pick anything larger.
    // - Otherwise, prefer if less dense than bestDensity but still above
    //   displayDensity.
    if (bestIndex == -1 ||
        (bestDensity < displayDensity && candidateDensity > bestDensity) ||
        (candidateDensity >= displayDensity && candidateDensity < bestDensity)) {
      bestIndex = i;
      bestDensity = candidateDensity;
    }
  }

  MOZ_ASSERT(bestIndex >= 0 && bestIndex < numCandidates);

  // Resolve URL
  nsresult rv;
  const nsAString& urlStr = mCandidates[bestIndex].URLString();
  nsCOMPtr<nsIURI> candidateURL;
  rv = nsContentUtils::NewURIWithDocumentCharset(getter_AddRefs(candidateURL),
                                                 urlStr, doc, baseURI);

  mSelectedCandidateURL = NS_SUCCEEDED(rv) ? candidateURL : nullptr;
  mSelectedCandidateIndex = bestIndex;

  return mSelectedCandidateIndex != oldBest;
}

int
ResponsiveImageSelector::GetSelectedCandidateIndex()
{
  SelectImage();

  return mSelectedCandidateIndex;
}

bool
ResponsiveImageSelector::ComputeFinalWidthForCurrentViewport(double *aWidth)
{
  unsigned int numSizes = mSizeQueries.Length();
  nsIDocument* doc = Document();
  nsIPresShell *presShell = doc ? doc->GetShell() : nullptr;
  nsPresContext *pctx = presShell ? presShell->GetPresContext() : nullptr;

  if (!pctx) {
    return false;
  }

  MOZ_ASSERT(numSizes == mSizeValues.Length(),
             "mSizeValues length differs from mSizeQueries");

  unsigned int i;
  for (i = 0; i < numSizes; i++) {
    if (mSizeQueries[i]->Matches(pctx, nullptr)) {
      break;
    }
  }

  nscoord effectiveWidth;
  if (i == numSizes) {
    // No match defaults to 100% viewport
    nsCSSValue defaultWidth(100.0f, eCSSUnit_ViewportWidth);
    effectiveWidth = nsRuleNode::CalcLengthWithInitialFont(pctx,
                                                           defaultWidth);
  } else {
    effectiveWidth = nsRuleNode::CalcLengthWithInitialFont(pctx,
                                                           mSizeValues[i]);
  }

  *aWidth = nsPresContext::AppUnitsToDoubleCSSPixels(std::max(effectiveWidth, 0));
  return true;
}

ResponsiveImageCandidate::ResponsiveImageCandidate()
{
  mType = eCandidateType_Invalid;
  mValue.mDensity = 1.0;
}

ResponsiveImageCandidate::ResponsiveImageCandidate(const nsAString& aURLString,
                                                   double aDensity)
  : mURLString(aURLString)
{
  mType = eCandidateType_Density;
  mValue.mDensity = aDensity;
}


void
ResponsiveImageCandidate::SetURLSpec(const nsAString& aURLString)
{
  mURLString = aURLString;
}

void
ResponsiveImageCandidate::SetParameterAsComputedWidth(int32_t aWidth)
{
  mType = eCandidateType_ComputedFromWidth;
  mValue.mWidth = aWidth;
}

void
ResponsiveImageCandidate::SetParameterDefault()
{
  MOZ_ASSERT(mType == eCandidateType_Invalid, "double setting candidate type");

  mType = eCandidateType_Default;
  // mValue shouldn't actually be used for this type, but set it to default
  // anyway
  mValue.mDensity = 1.0;
}

void
ResponsiveImageCandidate::SetParameterInvalid()
{
  mType = eCandidateType_Invalid;
  // mValue shouldn't actually be used for this type, but set it to default
  // anyway
  mValue.mDensity = 1.0;
}

void
ResponsiveImageCandidate::SetParameterAsDensity(double aDensity)
{
  MOZ_ASSERT(mType == eCandidateType_Invalid, "double setting candidate type");

  mType = eCandidateType_Density;
  mValue.mDensity = aDensity;
}

// Represents all supported descriptors for a ResponsiveImageCandidate, though
// there is no candidate type that uses all of these. This should generally
// match the mValue union of ResponsiveImageCandidate.
struct ResponsiveImageDescriptors {
  ResponsiveImageDescriptors()
    : mInvalid(false) {};

  Maybe<double> mDensity;
  Maybe<int32_t> mWidth;
  // We don't support "h" descriptors yet and they are not spec'd, but the
  // current spec does specify that they can be silently ignored (whereas
  // entirely unknown descriptors cause us to invalidate the candidate)
  Maybe<int32_t> mFutureCompatHeight;
  // If this descriptor set is bogus, e.g. a value was added twice (and thus
  // dropped) or an unknown descriptor was added.
  bool mInvalid;

  void AddDescriptor(const nsAString& aDescriptor);
  bool Valid();
  // Use the current set of descriptors to configure a candidate
  void FillCandidate(ResponsiveImageCandidate &aCandidate);
};

// Try to parse a single descriptor from a string. If value already set or
// unknown, sets invalid flag.
// This corresponds to the descriptor "Descriptor parser" step in:
// https://html.spec.whatwg.org/#parse-a-srcset-attribute
void
ResponsiveImageDescriptors::AddDescriptor(const nsAString& aDescriptor)
{
  if (aDescriptor.IsEmpty()) {
    return;
  }

  // All currently supported descriptors end with an identifying character.
  nsAString::const_iterator descStart, descType;
  aDescriptor.BeginReading(descStart);
  aDescriptor.EndReading(descType);
  descType--;
  const nsDependentSubstring& valueStr = Substring(descStart, descType);
  if (*descType == char16_t('w')) {
    int32_t possibleWidth;
    // If the value is not a valid non-negative integer, it doesn't match this
    // descriptor, fall through.
    if (ParseInteger(valueStr, possibleWidth) && possibleWidth >= 0) {
      if (possibleWidth != 0 && mWidth.isNothing() && mDensity.isNothing()) {
        mWidth.emplace(possibleWidth);
      } else {
        // Valid width descriptor, but width or density were already seen, sizes
        // support isn't enabled, or it parsed to 0, which is an error per spec
        mInvalid = true;
      }

      return;
    }
  } else if (*descType == char16_t('h')) {
    int32_t possibleHeight;
    // If the value is not a valid non-negative integer, it doesn't match this
    // descriptor, fall through.
    if (ParseInteger(valueStr, possibleHeight) && possibleHeight >= 0) {
      if (possibleHeight != 0 && mFutureCompatHeight.isNothing() &&
          mDensity.isNothing()) {
        mFutureCompatHeight.emplace(possibleHeight);
      } else {
        // Valid height descriptor, but height or density were already seen, or
        // it parsed to zero, which is an error per spec
        mInvalid = true;
      }

      return;
    }
  } else if (*descType == char16_t('x')) {
    // If the value is not a valid floating point number, it doesn't match this
    // descriptor, fall through.
    double possibleDensity = 0.0;
    if (ParseFloat(valueStr, possibleDensity)) {
      if (possibleDensity >= 0.0 &&
          mWidth.isNothing() &&
          mDensity.isNothing() &&
          mFutureCompatHeight.isNothing()) {
        mDensity.emplace(possibleDensity);
      } else {
        // Valid density descriptor, but height or width or density were already
        // seen, or it parsed to less than zero, which is an error per spec
        mInvalid = true;
      }

      return;
    }
  }

  // Matched no known descriptor, mark this descriptor set invalid
  mInvalid = true;
}

bool
ResponsiveImageDescriptors::Valid()
{
  return !mInvalid && !(mFutureCompatHeight.isSome() && mWidth.isNothing());
}

void
ResponsiveImageDescriptors::FillCandidate(ResponsiveImageCandidate &aCandidate)
{
  if (!Valid()) {
    aCandidate.SetParameterInvalid();
  } else if (mWidth.isSome()) {
    MOZ_ASSERT(mDensity.isNothing()); // Shouldn't be valid

    aCandidate.SetParameterAsComputedWidth(*mWidth);
  } else if (mDensity.isSome()) {
    MOZ_ASSERT(mWidth.isNothing()); // Shouldn't be valid

    aCandidate.SetParameterAsDensity(*mDensity);
  } else {
    // A valid set of descriptors with no density nor width (e.g. an empty set)
    // becomes 1.0 density, per spec
    aCandidate.SetParameterAsDensity(1.0);
  }
}

bool
ResponsiveImageCandidate::ConsumeDescriptors(nsAString::const_iterator& aIter,
                                             const nsAString::const_iterator& aIterEnd)
{
  nsAString::const_iterator &iter = aIter;
  const nsAString::const_iterator &end  = aIterEnd;

  bool inParens = false;

  ResponsiveImageDescriptors descriptors;

  // Parse descriptor list.
  // This corresponds to the descriptor parsing loop from:
  // https://html.spec.whatwg.org/#parse-a-srcset-attribute

  // Skip initial whitespace
  for (; iter != end && nsContentUtils::IsHTMLWhitespace(*iter); ++iter);

  nsAString::const_iterator currentDescriptor = iter;

  for (;; iter++) {
    if (iter == end) {
      descriptors.AddDescriptor(Substring(currentDescriptor, iter));
      break;
    } else if (inParens) {
      if (*iter == char16_t(')')) {
        inParens = false;
      }
    } else {
      if (*iter == char16_t(',')) {
        // End of descriptors, flush current descriptor and advance past comma
        // before breaking
        descriptors.AddDescriptor(Substring(currentDescriptor, iter));
        iter++;
        break;
      } else if (nsContentUtils::IsHTMLWhitespace(*iter)) {
        // End of current descriptor, consume it, skip spaces
        // ("After descriptor" state in spec) before continuing
        descriptors.AddDescriptor(Substring(currentDescriptor, iter));
        for (; iter != end && nsContentUtils::IsHTMLWhitespace(*iter); ++iter);
        if (iter == end) {
          break;
        }
        currentDescriptor = iter;
        // Leave one whitespace so the loop advances to this position next iteration
        iter--;
      } else if (*iter == char16_t('(')) {
        inParens = true;
      }
    }
  }

  descriptors.FillCandidate(*this);

  return Type() != eCandidateType_Invalid;
}

bool
ResponsiveImageCandidate::HasSameParameter(const ResponsiveImageCandidate & aOther) const
{
  if (aOther.mType != mType) {
    return false;
  }

  if (mType == eCandidateType_Default) {
    return true;
  }

  if (mType == eCandidateType_Density) {
    return aOther.mValue.mDensity == mValue.mDensity;
  }

  if (mType == eCandidateType_Invalid) {
    MOZ_ASSERT(false, "Comparing invalid candidates?");
    return true;
  } else if (mType == eCandidateType_ComputedFromWidth) {
    return aOther.mValue.mWidth == mValue.mWidth;
  }

  MOZ_ASSERT(false, "Somebody forgot to check for all uses of this enum");
  return false;
}

const nsAString&
ResponsiveImageCandidate::URLString() const
{
  return mURLString;
}

double
ResponsiveImageCandidate::Density(ResponsiveImageSelector *aSelector) const
{
  if (mType == eCandidateType_ComputedFromWidth) {
    double width;
    if (!aSelector->ComputeFinalWidthForCurrentViewport(&width)) {
      return 1.0;
    }
    return Density(width);
  }

  // Other types don't need matching width
  MOZ_ASSERT(mType == eCandidateType_Default || mType == eCandidateType_Density,
             "unhandled candidate type");
  return Density(-1);
}

double
ResponsiveImageCandidate::Density(double aMatchingWidth) const
{
  if (mType == eCandidateType_Invalid) {
    MOZ_ASSERT(false, "Getting density for uninitialized candidate");
    return 1.0;
  }

  if (mType == eCandidateType_Default) {
    return 1.0;
  }

  if (mType == eCandidateType_Density) {
    return mValue.mDensity;
  } else if (mType == eCandidateType_ComputedFromWidth) {
    if (aMatchingWidth < 0) {
      MOZ_ASSERT(false, "Don't expect to have a negative matching width at this point");
      return 1.0;
    }
    double density = double(mValue.mWidth) / aMatchingWidth;
    MOZ_ASSERT(density > 0.0);
    return density;
  }

  MOZ_ASSERT(false, "Unknown candidate type");
  return 1.0;
}

bool
ResponsiveImageCandidate::IsComputedFromWidth() const
{
  if (mType == eCandidateType_ComputedFromWidth) {
    return true;
  }

  MOZ_ASSERT(mType == eCandidateType_Default || mType == eCandidateType_Density,
             "Unknown candidate type");
  return false;
}

} // namespace dom
} // namespace mozilla