Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / html / track / vtt / VTTCue.cpp
1 /*
2  * Copyright (c) 2013, Opera Software ASA. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  * 3. Neither the name of Opera Software ASA nor the names of its
13  *    contributors may be used to endorse or promote products derived
14  *    from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
19  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
20  * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
21  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
25  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
27  * OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "config.h"
31 #include "core/html/track/vtt/VTTCue.h"
32
33 #include "CSSPropertyNames.h"
34 #include "CSSValueKeywords.h"
35 #include "RuntimeEnabledFeatures.h"
36 #include "bindings/v8/ExceptionMessages.h"
37 #include "bindings/v8/ExceptionStatePlaceholder.h"
38 #include "core/dom/DocumentFragment.h"
39 #include "core/dom/NodeTraversal.h"
40 #include "core/events/Event.h"
41 #include "core/frame/UseCounter.h"
42 #include "core/html/HTMLDivElement.h"
43 #include "core/html/track/TextTrack.h"
44 #include "core/html/track/TextTrackCueList.h"
45 #include "core/html/track/vtt/VTTElement.h"
46 #include "core/html/track/vtt/VTTParser.h"
47 #include "core/html/track/vtt/VTTRegionList.h"
48 #include "core/html/track/vtt/VTTScanner.h"
49 #include "core/rendering/RenderVTTCue.h"
50 #include "platform/text/BidiResolver.h"
51 #include "platform/text/TextRunIterator.h"
52 #include "wtf/MathExtras.h"
53 #include "wtf/text/StringBuilder.h"
54
55 namespace WebCore {
56
57 static const int undefinedPosition = -1;
58 static const int undefinedSize = -1;
59
60 static const CSSValueID displayWritingModeMap[] = {
61     CSSValueHorizontalTb, CSSValueVerticalRl, CSSValueVerticalLr
62 };
63 COMPILE_ASSERT(WTF_ARRAY_LENGTH(displayWritingModeMap) == VTTCue::NumberOfWritingDirections,
64     displayWritingModeMap_has_wrong_size);
65
66 static const CSSValueID displayAlignmentMap[] = {
67     CSSValueStart, CSSValueCenter, CSSValueEnd, CSSValueLeft, CSSValueRight
68 };
69 COMPILE_ASSERT(WTF_ARRAY_LENGTH(displayAlignmentMap) == VTTCue::NumberOfAlignments,
70     displayAlignmentMap_has_wrong_size);
71
72 static const String& startKeyword()
73 {
74     DEFINE_STATIC_LOCAL(const String, start, ("start"));
75     return start;
76 }
77
78 static const String& middleKeyword()
79 {
80     DEFINE_STATIC_LOCAL(const String, middle, ("middle"));
81     return middle;
82 }
83
84 static const String& endKeyword()
85 {
86     DEFINE_STATIC_LOCAL(const String, end, ("end"));
87     return end;
88 }
89
90 static const String& leftKeyword()
91 {
92     DEFINE_STATIC_LOCAL(const String, left, ("left"));
93     return left;
94 }
95
96 static const String& rightKeyword()
97 {
98     DEFINE_STATIC_LOCAL(const String, right, ("right"));
99     return right;
100 }
101
102 static const String& horizontalKeyword()
103 {
104     return emptyString();
105 }
106
107 static const String& verticalGrowingLeftKeyword()
108 {
109     DEFINE_STATIC_LOCAL(const String, verticalrl, ("rl"));
110     return verticalrl;
111 }
112
113 static const String& verticalGrowingRightKeyword()
114 {
115     DEFINE_STATIC_LOCAL(const String, verticallr, ("lr"));
116     return verticallr;
117 }
118
119 static bool isInvalidPercentage(int value, ExceptionState& exceptionState)
120 {
121     if (value < 0 || value > 100) {
122         exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexOutsideRange("value", value, 0, ExceptionMessages::InclusiveBound, 100, ExceptionMessages::InclusiveBound));
123         return true;
124     }
125     return false;
126 }
127
128 VTTCueBox::VTTCueBox(Document& document, VTTCue* cue)
129     : HTMLDivElement(document)
130     , m_cue(cue)
131 {
132     setShadowPseudoId(AtomicString("-webkit-media-text-track-display", AtomicString::ConstructFromLiteral));
133 }
134
135 void VTTCueBox::applyCSSProperties(const IntSize&)
136 {
137     // FIXME: Apply all the initial CSS positioning properties. http://wkb.ug/79916
138     if (!m_cue->regionId().isEmpty()) {
139         setInlineStyleProperty(CSSPropertyPosition, CSSValueRelative);
140         return;
141     }
142
143     // 3.5.1 On the (root) List of WebVTT Node Objects:
144
145     // the 'position' property must be set to 'absolute'
146     setInlineStyleProperty(CSSPropertyPosition, CSSValueAbsolute);
147
148     //  the 'unicode-bidi' property must be set to 'plaintext'
149     setInlineStyleProperty(CSSPropertyUnicodeBidi, CSSValueWebkitPlaintext);
150
151     // the 'direction' property must be set to direction
152     setInlineStyleProperty(CSSPropertyDirection, m_cue->getCSSWritingDirection());
153
154     // the 'writing-mode' property must be set to writing-mode
155     setInlineStyleProperty(CSSPropertyWebkitWritingMode, m_cue->getCSSWritingMode());
156
157     std::pair<float, float> position = m_cue->getCSSPosition();
158
159     // the 'top' property must be set to top,
160     setInlineStyleProperty(CSSPropertyTop, position.second, CSSPrimitiveValue::CSS_PERCENTAGE);
161
162     // the 'left' property must be set to left
163     setInlineStyleProperty(CSSPropertyLeft, position.first, CSSPrimitiveValue::CSS_PERCENTAGE);
164
165     // the 'width' property must be set to width, and the 'height' property  must be set to height
166     if (m_cue->vertical() == horizontalKeyword()) {
167         setInlineStyleProperty(CSSPropertyWidth, static_cast<double>(m_cue->getCSSSize()), CSSPrimitiveValue::CSS_PERCENTAGE);
168         setInlineStyleProperty(CSSPropertyHeight, CSSValueAuto);
169     } else {
170         setInlineStyleProperty(CSSPropertyWidth, CSSValueAuto);
171         setInlineStyleProperty(CSSPropertyHeight, static_cast<double>(m_cue->getCSSSize()),  CSSPrimitiveValue::CSS_PERCENTAGE);
172     }
173
174     // The 'text-align' property on the (root) List of WebVTT Node Objects must
175     // be set to the value in the second cell of the row of the table below
176     // whose first cell is the value of the corresponding cue's text track cue
177     // alignment:
178     setInlineStyleProperty(CSSPropertyTextAlign, m_cue->getCSSAlignment());
179
180     if (!m_cue->snapToLines()) {
181         // 10.13.1 Set up x and y:
182         // Note: x and y are set through the CSS left and top above.
183
184         // 10.13.2 Position the boxes in boxes such that the point x% along the
185         // width of the bounding box of the boxes in boxes is x% of the way
186         // across the width of the video's rendering area, and the point y%
187         // along the height of the bounding box of the boxes in boxes is y%
188         // of the way across the height of the video's rendering area, while
189         // maintaining the relative positions of the boxes in boxes to each
190         // other.
191         setInlineStyleProperty(CSSPropertyWebkitTransform,
192             String::format("translate(-%.2f%%, -%.2f%%)", position.first, position.second));
193
194         setInlineStyleProperty(CSSPropertyWhiteSpace, CSSValuePre);
195     }
196 }
197
198 RenderObject* VTTCueBox::createRenderer(RenderStyle*)
199 {
200     return new RenderVTTCue(this);
201 }
202
203 void VTTCueBox::trace(Visitor* visitor)
204 {
205     visitor->trace(m_cue);
206     HTMLDivElement::trace(visitor);
207 }
208
209 VTTCue::VTTCue(Document& document, double startTime, double endTime, const String& text)
210     : TextTrackCue(startTime, endTime)
211     , m_text(text)
212     , m_linePosition(undefinedPosition)
213     , m_computedLinePosition(undefinedPosition)
214     , m_textPosition(50)
215     , m_cueSize(100)
216     , m_writingDirection(Horizontal)
217     , m_cueAlignment(Middle)
218     , m_vttNodeTree(nullptr)
219     , m_cueBackgroundBox(HTMLDivElement::create(document))
220     , m_displayDirection(CSSValueLtr)
221     , m_displaySize(undefinedSize)
222     , m_snapToLines(true)
223     , m_displayTreeShouldChange(true)
224     , m_notifyRegion(true)
225 {
226     ScriptWrappable::init(this);
227     UseCounter::count(document, UseCounter::VTTCue);
228 }
229
230 VTTCue::~VTTCue()
231 {
232     // Using oilpan, if m_displayTree is in the document it will strongly keep
233     // the cue alive. Thus, if the cue is dead, either m_displayTree is not in
234     // the document or the entire document is dead too.
235 #if !ENABLE(OILPAN)
236     // FIXME: This is scary, we should make the life cycle smarter so the destructor
237     // doesn't need to do DOM mutations.
238     if (m_displayTree)
239         m_displayTree->remove(ASSERT_NO_EXCEPTION);
240 #endif
241 }
242
243 #ifndef NDEBUG
244 String VTTCue::toString() const
245 {
246     return String::format("%p id=%s interval=%f-->%f cue=%s)", this, id().utf8().data(), startTime(), endTime(), text().utf8().data());
247 }
248 #endif
249
250 VTTCueBox& VTTCue::ensureDisplayTree()
251 {
252     if (!m_displayTree)
253         m_displayTree = VTTCueBox::create(document(), this);
254     return *m_displayTree;
255 }
256
257 void VTTCue::cueDidChange()
258 {
259     TextTrackCue::cueDidChange();
260     m_displayTreeShouldChange = true;
261 }
262
263 const String& VTTCue::vertical() const
264 {
265     switch (m_writingDirection) {
266     case Horizontal:
267         return horizontalKeyword();
268     case VerticalGrowingLeft:
269         return verticalGrowingLeftKeyword();
270     case VerticalGrowingRight:
271         return verticalGrowingRightKeyword();
272     default:
273         ASSERT_NOT_REACHED();
274         return emptyString();
275     }
276 }
277
278 void VTTCue::setVertical(const String& value)
279 {
280     WritingDirection direction = m_writingDirection;
281     if (value == horizontalKeyword())
282         direction = Horizontal;
283     else if (value == verticalGrowingLeftKeyword())
284         direction = VerticalGrowingLeft;
285     else if (value == verticalGrowingRightKeyword())
286         direction = VerticalGrowingRight;
287     else
288         ASSERT_NOT_REACHED();
289
290     if (direction == m_writingDirection)
291         return;
292
293     cueWillChange();
294     m_writingDirection = direction;
295     cueDidChange();
296 }
297
298 void VTTCue::setSnapToLines(bool value)
299 {
300     if (m_snapToLines == value)
301         return;
302
303     cueWillChange();
304     m_snapToLines = value;
305     cueDidChange();
306 }
307
308 void VTTCue::setLine(int position, ExceptionState& exceptionState)
309 {
310     // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-line
311     // On setting, if the text track cue snap-to-lines flag is not set, and the new
312     // value is negative or greater than 100, then throw an IndexSizeError exception.
313     if (!m_snapToLines && (position < 0 || position > 100)) {
314         exceptionState.throwDOMException(IndexSizeError, "The snap-to-lines flag is not set, and the value provided (" + String::number(position) + ") is not between 0 and 100.");
315         return;
316     }
317
318     // Otherwise, set the text track cue line position to the new value.
319     if (m_linePosition == position)
320         return;
321
322     cueWillChange();
323     m_linePosition = position;
324     m_computedLinePosition = calculateComputedLinePosition();
325     cueDidChange();
326 }
327
328 void VTTCue::setPosition(int position, ExceptionState& exceptionState)
329 {
330     // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-position
331     // On setting, if the new value is negative or greater than 100, then throw an IndexSizeError exception.
332     // Otherwise, set the text track cue text position to the new value.
333     if (isInvalidPercentage(position, exceptionState))
334         return;
335
336     // Otherwise, set the text track cue line position to the new value.
337     if (m_textPosition == position)
338         return;
339
340     cueWillChange();
341     m_textPosition = position;
342     cueDidChange();
343 }
344
345 void VTTCue::setSize(int size, ExceptionState& exceptionState)
346 {
347     // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-size
348     // On setting, if the new value is negative or greater than 100, then throw an IndexSizeError
349     // exception. Otherwise, set the text track cue size to the new value.
350     if (isInvalidPercentage(size, exceptionState))
351         return;
352
353     // Otherwise, set the text track cue line position to the new value.
354     if (m_cueSize == size)
355         return;
356
357     cueWillChange();
358     m_cueSize = size;
359     cueDidChange();
360 }
361
362 const String& VTTCue::align() const
363 {
364     switch (m_cueAlignment) {
365     case Start:
366         return startKeyword();
367     case Middle:
368         return middleKeyword();
369     case End:
370         return endKeyword();
371     case Left:
372         return leftKeyword();
373     case Right:
374         return rightKeyword();
375     default:
376         ASSERT_NOT_REACHED();
377         return emptyString();
378     }
379 }
380
381 void VTTCue::setAlign(const String& value)
382 {
383     CueAlignment alignment = m_cueAlignment;
384     if (value == startKeyword())
385         alignment = Start;
386     else if (value == middleKeyword())
387         alignment = Middle;
388     else if (value == endKeyword())
389         alignment = End;
390     else if (value == leftKeyword())
391         alignment = Left;
392     else if (value == rightKeyword())
393         alignment = Right;
394     else
395         ASSERT_NOT_REACHED();
396
397     if (alignment == m_cueAlignment)
398         return;
399
400     cueWillChange();
401     m_cueAlignment = alignment;
402     cueDidChange();
403 }
404
405 void VTTCue::setText(const String& text)
406 {
407     if (m_text == text)
408         return;
409
410     cueWillChange();
411     // Clear the document fragment but don't bother to create it again just yet as we can do that
412     // when it is requested.
413     m_vttNodeTree = nullptr;
414     m_text = text;
415     cueDidChange();
416 }
417
418 void VTTCue::createVTTNodeTree()
419 {
420     if (!m_vttNodeTree)
421         m_vttNodeTree = VTTParser::createDocumentFragmentFromCueText(document(), m_text);
422 }
423
424 void VTTCue::copyVTTNodeToDOMTree(ContainerNode* vttNode, ContainerNode* parent)
425 {
426     for (Node* node = vttNode->firstChild(); node; node = node->nextSibling()) {
427         RefPtr<Node> clonedNode;
428         if (node->isVTTElement())
429             clonedNode = toVTTElement(node)->createEquivalentHTMLElement(document());
430         else
431             clonedNode = node->cloneNode(false);
432         parent->appendChild(clonedNode);
433         if (node->isContainerNode())
434             copyVTTNodeToDOMTree(toContainerNode(node), toContainerNode(clonedNode));
435     }
436 }
437
438 PassRefPtr<DocumentFragment> VTTCue::getCueAsHTML()
439 {
440     createVTTNodeTree();
441     RefPtr<DocumentFragment> clonedFragment = DocumentFragment::create(document());
442     copyVTTNodeToDOMTree(m_vttNodeTree.get(), clonedFragment.get());
443     return clonedFragment.release();
444 }
445
446 PassRefPtr<DocumentFragment> VTTCue::createCueRenderingTree()
447 {
448     RefPtr<DocumentFragment> clonedFragment;
449     createVTTNodeTree();
450     clonedFragment = DocumentFragment::create(document());
451     m_vttNodeTree->cloneChildNodes(clonedFragment.get());
452     return clonedFragment.release();
453 }
454
455 void VTTCue::setRegionId(const String& regionId)
456 {
457     if (m_regionId == regionId)
458         return;
459
460     cueWillChange();
461     m_regionId = regionId;
462     cueDidChange();
463 }
464
465 void VTTCue::notifyRegionWhenRemovingDisplayTree(bool notifyRegion)
466 {
467     m_notifyRegion = notifyRegion;
468 }
469
470 int VTTCue::calculateComputedLinePosition()
471 {
472     // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-computed-line-position
473
474     // If the text track cue line position is numeric, then that is the text
475     // track cue computed line position.
476     if (m_linePosition != undefinedPosition)
477         return m_linePosition;
478
479     // If the text track cue snap-to-lines flag of the text track cue is not
480     // set, the text track cue computed line position is the value 100;
481     if (!m_snapToLines)
482         return 100;
483
484     // Otherwise, it is the value returned by the following algorithm:
485
486     // If cue is not associated with a text track, return -1 and abort these
487     // steps.
488     if (!track())
489         return -1;
490
491     // Let n be the number of text tracks whose text track mode is showing or
492     // showing by default and that are in the media element's list of text
493     // tracks before track.
494     int n = track()->trackIndexRelativeToRenderedTracks();
495
496     // Increment n by one.
497     n++;
498
499     // Negate n.
500     n = -n;
501
502     return n;
503 }
504
505 class VTTTextRunIterator : public TextRunIterator {
506 public:
507     VTTTextRunIterator() { }
508     VTTTextRunIterator(const TextRun* textRun, unsigned offset) : TextRunIterator(textRun, offset) { }
509
510     bool atParagraphSeparator() const
511     {
512         // Within a cue, paragraph boundaries are only denoted by Type B characters,
513         // such as U+000A LINE FEED (LF), U+0085 NEXT LINE (NEL), and U+2029 PARAGRAPH SEPARATOR.
514         return WTF::Unicode::category(current()) & WTF::Unicode::Separator_Paragraph;
515     }
516 };
517
518 // Almost the same as determineDirectionality in core/html/HTMLElement.cpp, but
519 // that one uses a "plain" TextRunIterator (which only checks for '\n').
520 static TextDirection determineDirectionality(const String& value, bool& hasStrongDirectionality)
521 {
522     TextRun run(value);
523     BidiResolver<VTTTextRunIterator, BidiCharacterRun> bidiResolver;
524     bidiResolver.setStatus(BidiStatus(LTR, false));
525     bidiResolver.setPositionIgnoringNestedIsolates(VTTTextRunIterator(&run, 0));
526     return bidiResolver.determineParagraphDirectionality(&hasStrongDirectionality);
527 }
528
529 static CSSValueID determineTextDirection(DocumentFragment* vttRoot)
530 {
531     DEFINE_STATIC_LOCAL(const String, rtTag, ("rt"));
532     ASSERT(vttRoot);
533
534     // Apply the Unicode Bidirectional Algorithm's Paragraph Level steps to the
535     // concatenation of the values of each WebVTT Text Object in nodes, in a
536     // pre-order, depth-first traversal, excluding WebVTT Ruby Text Objects and
537     // their descendants.
538     TextDirection textDirection = LTR;
539     for (Node* node = vttRoot->firstChild(); node; node = NodeTraversal::next(*node, vttRoot)) {
540         if (!node->isTextNode() || node->localName() == rtTag)
541             continue;
542
543         bool hasStrongDirectionality;
544         textDirection = determineDirectionality(node->nodeValue(), hasStrongDirectionality);
545         if (hasStrongDirectionality)
546             break;
547     }
548     return isLeftToRightDirection(textDirection) ? CSSValueLtr : CSSValueRtl;
549 }
550
551 void VTTCue::calculateDisplayParameters()
552 {
553     createVTTNodeTree();
554
555     // Steps 10.2, 10.3
556     m_displayDirection = determineTextDirection(m_vttNodeTree.get());
557
558     // 10.4 If the text track cue writing direction is horizontal, then let
559     // block-flow be 'tb'. Otherwise, if the text track cue writing direction is
560     // vertical growing left, then let block-flow be 'lr'. Otherwise, the text
561     // track cue writing direction is vertical growing right; let block-flow be
562     // 'rl'.
563
564     // The above step is done through the writing direction static map.
565
566     // 10.5 Determine the value of maximum size for cue as per the appropriate
567     // rules from the following list:
568     int maximumSize = m_textPosition;
569     if ((m_writingDirection == Horizontal && m_cueAlignment == Start && m_displayDirection == CSSValueLtr)
570         || (m_writingDirection == Horizontal && m_cueAlignment == End && m_displayDirection == CSSValueRtl)
571         || (m_writingDirection == Horizontal && m_cueAlignment == Left)
572         || (m_writingDirection == VerticalGrowingLeft && (m_cueAlignment == Start || m_cueAlignment == Left))
573         || (m_writingDirection == VerticalGrowingRight && (m_cueAlignment == Start || m_cueAlignment == Left))) {
574         maximumSize = 100 - m_textPosition;
575     } else if ((m_writingDirection == Horizontal && m_cueAlignment == End && m_displayDirection == CSSValueLtr)
576         || (m_writingDirection == Horizontal && m_cueAlignment == Start && m_displayDirection == CSSValueRtl)
577         || (m_writingDirection == Horizontal && m_cueAlignment == Right)
578         || (m_writingDirection == VerticalGrowingLeft && (m_cueAlignment == End || m_cueAlignment == Right))
579         || (m_writingDirection == VerticalGrowingRight && (m_cueAlignment == End || m_cueAlignment == Right))) {
580         maximumSize = m_textPosition;
581     } else if (m_cueAlignment == Middle) {
582         maximumSize = m_textPosition <= 50 ? m_textPosition : (100 - m_textPosition);
583         maximumSize = maximumSize * 2;
584     } else {
585         ASSERT_NOT_REACHED();
586     }
587
588     // 10.6 If the text track cue size is less than maximum size, then let size
589     // be text track cue size. Otherwise, let size be maximum size.
590     m_displaySize = std::min(m_cueSize, maximumSize);
591
592     // FIXME: Understand why step 10.7 is missing (just a copy/paste error?)
593     // Could be done within a spec implementation check - http://crbug.com/301580
594
595     // 10.8 Determine the value of x-position or y-position for cue as per the
596     // appropriate rules from the following list:
597     if (m_writingDirection == Horizontal) {
598         switch (m_cueAlignment) {
599         case Start:
600             if (m_displayDirection == CSSValueLtr)
601                 m_displayPosition.first = m_textPosition;
602             else
603                 m_displayPosition.first = 100 - m_textPosition - m_displaySize;
604             break;
605         case End:
606             if (m_displayDirection == CSSValueRtl)
607                 m_displayPosition.first = 100 - m_textPosition;
608             else
609                 m_displayPosition.first = m_textPosition - m_displaySize;
610             break;
611         case Left:
612             if (m_displayDirection == CSSValueLtr)
613                 m_displayPosition.first = m_textPosition;
614             else
615                 m_displayPosition.first = 100 - m_textPosition;
616             break;
617         case Right:
618             if (m_displayDirection == CSSValueLtr)
619                 m_displayPosition.first = m_textPosition - m_displaySize;
620             else
621                 m_displayPosition.first = 100 - m_textPosition - m_displaySize;
622             break;
623         case Middle:
624             if (m_displayDirection == CSSValueLtr)
625                 m_displayPosition.first = m_textPosition - m_displaySize / 2;
626             else
627                 m_displayPosition.first = 100 - m_textPosition - m_displaySize / 2;
628             break;
629         case NumberOfAlignments:
630             ASSERT_NOT_REACHED();
631         }
632     } else {
633         // Cases for m_writingDirection being VerticalGrowing{Left|Right}
634         switch (m_cueAlignment) {
635         case Start:
636         case Left:
637             m_displayPosition.second = m_textPosition;
638             break;
639         case End:
640         case Right:
641             m_displayPosition.second = m_textPosition - m_displaySize;
642             break;
643         case Middle:
644             m_displayPosition.second = m_textPosition - m_displaySize / 2;
645             break;
646         case NumberOfAlignments:
647             ASSERT_NOT_REACHED();
648         }
649     }
650
651     // A text track cue has a text track cue computed line position whose value
652     // is defined in terms of the other aspects of the cue.
653     m_computedLinePosition = calculateComputedLinePosition();
654
655     // 10.9 Determine the value of whichever of x-position or y-position is not
656     // yet calculated for cue as per the appropriate rules from the following
657     // list:
658     if (m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
659         m_displayPosition.second = 0;
660
661     if (!m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
662         m_displayPosition.second = m_computedLinePosition;
663
664     if (m_snapToLines && m_displayPosition.first == undefinedPosition
665         && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
666         m_displayPosition.first = 0;
667
668     if (!m_snapToLines && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
669         m_displayPosition.first = m_computedLinePosition;
670 }
671
672 void VTTCue::markFutureAndPastNodes(ContainerNode* root, double previousTimestamp, double movieTime)
673 {
674     DEFINE_STATIC_LOCAL(const String, timestampTag, ("timestamp"));
675
676     bool isPastNode = true;
677     double currentTimestamp = previousTimestamp;
678     if (currentTimestamp > movieTime)
679         isPastNode = false;
680
681     for (Node* child = root->firstChild(); child; child = NodeTraversal::next(*child, root)) {
682         if (child->nodeName() == timestampTag) {
683             double currentTimestamp;
684             bool check = VTTParser::collectTimeStamp(child->nodeValue(), currentTimestamp);
685             ASSERT_UNUSED(check, check);
686
687             if (currentTimestamp > movieTime)
688                 isPastNode = false;
689         }
690
691         if (child->isVTTElement()) {
692             toVTTElement(child)->setIsPastNode(isPastNode);
693             // Make an elemenet id match a cue id for style matching purposes.
694             if (!id().isEmpty())
695                 toElement(child)->setIdAttribute(id());
696         }
697     }
698 }
699
700 void VTTCue::updateDisplayTree(double movieTime)
701 {
702     // The display tree may contain WebVTT timestamp objects representing
703     // timestamps (processing instructions), along with displayable nodes.
704
705     if (!track()->isRendered())
706         return;
707
708     // Clear the contents of the set.
709     m_cueBackgroundBox->removeChildren();
710
711     // Update the two sets containing past and future WebVTT objects.
712     RefPtr<DocumentFragment> referenceTree = createCueRenderingTree();
713     markFutureAndPastNodes(referenceTree.get(), startTime(), movieTime);
714     m_cueBackgroundBox->appendChild(referenceTree, ASSERT_NO_EXCEPTION);
715 }
716
717 PassRefPtrWillBeRawPtr<VTTCueBox> VTTCue::getDisplayTree(const IntSize& videoSize)
718 {
719     RefPtrWillBeRawPtr<VTTCueBox> displayTree(ensureDisplayTree());
720     if (!m_displayTreeShouldChange || !track()->isRendered())
721         return displayTree.release();
722
723     // 10.1 - 10.10
724     calculateDisplayParameters();
725
726     // 10.11. Apply the terms of the CSS specifications to nodes within the
727     // following constraints, thus obtaining a set of CSS boxes positioned
728     // relative to an initial containing block:
729     displayTree->removeChildren();
730
731     // The document tree is the tree of WebVTT Node Objects rooted at nodes.
732
733     // The children of the nodes must be wrapped in an anonymous box whose
734     // 'display' property has the value 'inline'. This is the WebVTT cue
735     // background box.
736
737     // Note: This is contained by default in m_cueBackgroundBox.
738     m_cueBackgroundBox->setShadowPseudoId(cueShadowPseudoId());
739     displayTree->appendChild(m_cueBackgroundBox);
740
741     // FIXME(BUG 79916): Runs of children of WebVTT Ruby Objects that are not
742     // WebVTT Ruby Text Objects must be wrapped in anonymous boxes whose
743     // 'display' property has the value 'ruby-base'.
744
745     // FIXME(BUG 79916): Text runs must be wrapped according to the CSS
746     // line-wrapping rules, except that additionally, regardless of the value of
747     // the 'white-space' property, lines must be wrapped at the edge of their
748     // containing blocks, even if doing so requires splitting a word where there
749     // is no line breaking opportunity. (Thus, normally text wraps as needed,
750     // but if there is a particularly long word, it does not overflow as it
751     // normally would in CSS, it is instead forcibly wrapped at the box's edge.)
752     displayTree->applyCSSProperties(videoSize);
753
754     m_displayTreeShouldChange = false;
755
756     // 10.15. Let cue's text track cue display state have the CSS boxes in
757     // boxes.
758     return displayTree.release();
759 }
760
761 void VTTCue::removeDisplayTree()
762 {
763     if (m_notifyRegion && track()->regions()) {
764         // The region needs to be informed about the cue removal.
765         VTTRegion* region = track()->regions()->getRegionById(m_regionId);
766         if (region)
767             region->willRemoveVTTCueBox(m_displayTree.get());
768     }
769
770     if (m_displayTree)
771         m_displayTree->remove(ASSERT_NO_EXCEPTION);
772 }
773
774 void VTTCue::updateDisplay(const IntSize& videoSize, HTMLDivElement& container)
775 {
776     UseCounter::count(document(), UseCounter::VTTCueRender);
777
778     if (m_writingDirection != Horizontal)
779         UseCounter::count(document(), UseCounter::VTTCueRenderVertical);
780
781     if (!m_snapToLines)
782         UseCounter::count(document(), UseCounter::VTTCueRenderSnapToLinesFalse);
783
784     if (m_linePosition != undefinedPosition)
785         UseCounter::count(document(), UseCounter::VTTCueRenderLineNotAuto);
786
787     if (m_textPosition != 50)
788         UseCounter::count(document(), UseCounter::VTTCueRenderPositionNot50);
789
790     if (m_cueSize != 100)
791         UseCounter::count(document(), UseCounter::VTTCueRenderSizeNot100);
792
793     if (m_cueAlignment != Middle)
794         UseCounter::count(document(), UseCounter::VTTCueRenderAlignNotMiddle);
795
796     RefPtrWillBeRawPtr<VTTCueBox> displayBox = getDisplayTree(videoSize);
797     VTTRegion* region = 0;
798     if (track()->regions())
799         region = track()->regions()->getRegionById(regionId());
800
801     if (!region) {
802         // If cue has an empty text track cue region identifier or there is no
803         // WebVTT region whose region identifier is identical to cue's text
804         // track cue region identifier, run the following substeps:
805         if (displayBox->hasChildren() && !container.contains(displayBox.get())) {
806             // Note: the display tree of a cue is removed when the active flag of the cue is unset.
807             container.appendChild(displayBox);
808         }
809     } else {
810         // Let region be the WebVTT region whose region identifier
811         // matches the text track cue region identifier of cue.
812         RefPtr<HTMLDivElement> regionNode = region->getDisplayTree(document());
813
814         // Append the region to the viewport, if it was not already.
815         if (!container.contains(regionNode.get()))
816             container.appendChild(regionNode);
817
818         region->appendVTTCueBox(displayBox);
819     }
820 }
821
822 std::pair<double, double> VTTCue::getPositionCoordinates() const
823 {
824     // This method is used for setting x and y when snap to lines is not set.
825     std::pair<double, double> coordinates;
826
827     if (m_writingDirection == Horizontal && m_displayDirection == CSSValueLtr) {
828         coordinates.first = m_textPosition;
829         coordinates.second = m_computedLinePosition;
830
831         return coordinates;
832     }
833
834     if (m_writingDirection == Horizontal && m_displayDirection == CSSValueRtl) {
835         coordinates.first = 100 - m_textPosition;
836         coordinates.second = m_computedLinePosition;
837
838         return coordinates;
839     }
840
841     if (m_writingDirection == VerticalGrowingLeft) {
842         coordinates.first = 100 - m_computedLinePosition;
843         coordinates.second = m_textPosition;
844
845         return coordinates;
846     }
847
848     if (m_writingDirection == VerticalGrowingRight) {
849         coordinates.first = m_computedLinePosition;
850         coordinates.second = m_textPosition;
851
852         return coordinates;
853     }
854
855     ASSERT_NOT_REACHED();
856
857     return coordinates;
858 }
859
860 VTTCue::CueSetting VTTCue::settingName(VTTScanner& input)
861 {
862     CueSetting parsedSetting = None;
863     if (input.scan("vertical"))
864         parsedSetting = Vertical;
865     else if (input.scan("line"))
866         parsedSetting = Line;
867     else if (input.scan("position"))
868         parsedSetting = Position;
869     else if (input.scan("size"))
870         parsedSetting = Size;
871     else if (input.scan("align"))
872         parsedSetting = Align;
873     else if (RuntimeEnabledFeatures::webVTTRegionsEnabled() && input.scan("region"))
874         parsedSetting = RegionId;
875     // Verify that a ':' follows.
876     if (parsedSetting != None && input.scan(':'))
877         return parsedSetting;
878     return None;
879 }
880
881 // Used for 'position' and 'size'.
882 static bool scanPercentage(VTTScanner& input, const VTTScanner::Run& valueRun, int& number)
883 {
884     // 1. If value contains any characters other than U+0025 PERCENT SIGN
885     //    characters (%) and characters in the range U+0030 DIGIT ZERO (0) to
886     //    U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
887     // 2. If value does not contain at least one character in the range U+0030
888     //    DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step
889     //    labeled next setting.
890     if (!input.scanDigits(number))
891         return false;
892
893     // 3. If any character in value other than the last character is a U+0025
894     //    PERCENT SIGN character (%), then jump to the step labeled next
895     //    setting.
896     // 4. If the last character in value is not a U+0025 PERCENT SIGN character
897     //    (%), then jump to the step labeled next setting.
898     if (!input.scan('%') || !input.isAt(valueRun.end()))
899         return false;
900
901     // 5. Ignoring the trailing percent sign, interpret value as an integer,
902     //    and let number be that number.
903     // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step
904     //    labeled next setting.
905     return number >= 0 && number <= 100;
906 }
907
908 void VTTCue::parseSettings(const String& inputString)
909 {
910     VTTScanner input(inputString);
911
912     while (!input.isAtEnd()) {
913
914         // The WebVTT cue settings part of a WebVTT cue consists of zero or more of the following components, in any order,
915         // separated from each other by one or more U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters.
916         input.skipWhile<VTTParser::isValidSettingDelimiter>();
917
918         if (input.isAtEnd())
919             break;
920
921         // When the user agent is to parse the WebVTT settings given by a string input for a text track cue cue,
922         // the user agent must run the following steps:
923         // 1. Let settings be the result of splitting input on spaces.
924         // 2. For each token setting in the list settings, run the following substeps:
925         //    1. If setting does not contain a U+003A COLON character (:), or if the first U+003A COLON character (:)
926         //       in setting is either the first or last character of setting, then jump to the step labeled next setting.
927         //    2. Let name be the leading substring of setting up to and excluding the first U+003A COLON character (:) in that string.
928         CueSetting name = settingName(input);
929
930         // 3. Let value be the trailing substring of setting starting from the character immediately after the first U+003A COLON character (:) in that string.
931         VTTScanner::Run valueRun = input.collectUntil<VTTParser::isValidSettingDelimiter>();
932
933         // 4. Run the appropriate substeps that apply for the value of name, as follows:
934         switch (name) {
935         case Vertical: {
936             // If name is a case-sensitive match for "vertical"
937             // 1. If value is a case-sensitive match for the string "rl", then let cue's text track cue writing direction
938             //    be vertical growing left.
939             if (input.scanRun(valueRun, verticalGrowingLeftKeyword()))
940                 m_writingDirection = VerticalGrowingLeft;
941
942             // 2. Otherwise, if value is a case-sensitive match for the string "lr", then let cue's text track cue writing
943             //    direction be vertical growing right.
944             else if (input.scanRun(valueRun, verticalGrowingRightKeyword()))
945                 m_writingDirection = VerticalGrowingRight;
946             break;
947         }
948         case Line: {
949             // 1-2 - Collect chars that are either '-', '%', or a digit.
950             // 1. If value contains any characters other than U+002D HYPHEN-MINUS characters (-), U+0025 PERCENT SIGN
951             //    characters (%), and characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump
952             //    to the step labeled next setting.
953             bool isNegative = input.scan('-');
954             int linePosition;
955             unsigned numDigits = input.scanDigits(linePosition);
956             bool isPercentage = input.scan('%');
957
958             if (!input.isAt(valueRun.end()))
959                 break;
960
961             // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT
962             //    NINE (9), then jump to the step labeled next setting.
963             // 3. If any character in value other than the first character is a U+002D HYPHEN-MINUS character (-), then
964             //    jump to the step labeled next setting.
965             // 4. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then
966             //    jump to the step labeled next setting.
967
968             // 5. If the first character in value is a U+002D HYPHEN-MINUS character (-) and the last character in value is a
969             //    U+0025 PERCENT SIGN character (%), then jump to the step labeled next setting.
970             if (!numDigits || (isPercentage && isNegative))
971                 break;
972
973             // 6. Ignoring the trailing percent sign, if any, interpret value as a (potentially signed) integer, and
974             //    let number be that number.
975             // 7. If the last character in value is a U+0025 PERCENT SIGN character (%), but number is not in the range
976             //    0 ≤ number ≤ 100, then jump to the step labeled next setting.
977             // 8. Let cue's text track cue line position be number.
978             // 9. If the last character in value is a U+0025 PERCENT SIGN character (%), then let cue's text track cue
979             //    snap-to-lines flag be false. Otherwise, let it be true.
980             if (isPercentage) {
981                 if (linePosition < 0 || linePosition > 100)
982                     break;
983                 // 10 - If '%' then set snap-to-lines flag to false.
984                 m_snapToLines = false;
985             } else {
986                 if (isNegative)
987                     linePosition = -linePosition;
988                 m_snapToLines = true;
989             }
990             m_linePosition = linePosition;
991             break;
992         }
993         case Position: {
994             int number;
995             // Steps 1 - 6.
996             if (!scanPercentage(input, valueRun, number))
997                 break;
998
999             // 7. Let cue's text track cue text position be number.
1000             m_textPosition = number;
1001             break;
1002         }
1003         case Size: {
1004             int number;
1005             // Steps 1 - 6.
1006             if (!scanPercentage(input, valueRun, number))
1007                 break;
1008
1009             // 7. Let cue's text track cue size be number.
1010             m_cueSize = number;
1011             break;
1012         }
1013         case Align: {
1014             // 1. If value is a case-sensitive match for the string "start", then let cue's text track cue alignment be start alignment.
1015             if (input.scanRun(valueRun, startKeyword()))
1016                 m_cueAlignment = Start;
1017
1018             // 2. If value is a case-sensitive match for the string "middle", then let cue's text track cue alignment be middle alignment.
1019             else if (input.scanRun(valueRun, middleKeyword()))
1020                 m_cueAlignment = Middle;
1021
1022             // 3. If value is a case-sensitive match for the string "end", then let cue's text track cue alignment be end alignment.
1023             else if (input.scanRun(valueRun, endKeyword()))
1024                 m_cueAlignment = End;
1025
1026             // 4. If value is a case-sensitive match for the string "left", then let cue's text track cue alignment be left alignment.
1027             else if (input.scanRun(valueRun, leftKeyword()))
1028                 m_cueAlignment = Left;
1029
1030             // 5. If value is a case-sensitive match for the string "right", then let cue's text track cue alignment be right alignment.
1031             else if (input.scanRun(valueRun, rightKeyword()))
1032                 m_cueAlignment = Right;
1033             break;
1034         }
1035         case RegionId:
1036             m_regionId = input.extractString(valueRun);
1037             break;
1038         case None:
1039             break;
1040         }
1041
1042         // Make sure the entire run is consumed.
1043         input.skipRun(valueRun);
1044     }
1045
1046     // If cue's line position is not auto or cue's size is not 100 or cue's
1047     // writing direction is not horizontal, but cue's region identifier is not
1048     // the empty string, let cue's region identifier be the empty string.
1049     if (m_regionId.isEmpty())
1050         return;
1051
1052     if (m_linePosition != undefinedPosition || m_cueSize != 100 || m_writingDirection != Horizontal)
1053         m_regionId = emptyString();
1054 }
1055
1056 CSSValueID VTTCue::getCSSAlignment() const
1057 {
1058     return displayAlignmentMap[m_cueAlignment];
1059 }
1060
1061 CSSValueID VTTCue::getCSSWritingDirection() const
1062 {
1063     return m_displayDirection;
1064 }
1065
1066 CSSValueID VTTCue::getCSSWritingMode() const
1067 {
1068     return displayWritingModeMap[m_writingDirection];
1069 }
1070
1071 int VTTCue::getCSSSize() const
1072 {
1073     ASSERT(m_displaySize != undefinedSize);
1074     return m_displaySize;
1075 }
1076
1077 std::pair<double, double> VTTCue::getCSSPosition() const
1078 {
1079     if (!m_snapToLines)
1080         return getPositionCoordinates();
1081
1082     return m_displayPosition;
1083 }
1084
1085 ExecutionContext* VTTCue::executionContext() const
1086 {
1087     ASSERT(m_cueBackgroundBox);
1088     return m_cueBackgroundBox->executionContext();
1089 }
1090
1091 Document& VTTCue::document() const
1092 {
1093     ASSERT(m_cueBackgroundBox);
1094     return m_cueBackgroundBox->document();
1095 }
1096
1097 void VTTCue::trace(Visitor* visitor)
1098 {
1099     visitor->trace(m_vttNodeTree);
1100     visitor->trace(m_cueBackgroundBox);
1101     visitor->trace(m_displayTree);
1102     TextTrackCue::trace(visitor);
1103 }
1104
1105 } // namespace WebCore