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