2 * Copyright (C) 2011 Google Inc. All rights reserved.
3 * Copyright (C) 2011, 2012, 2013 Apple Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
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
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.
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.
33 #include "core/html/track/TextTrackCue.h"
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"
54 static const int invalidCueIndex = -1;
55 static const int undefinedPosition = -1;
57 static const CSSValueID displayWritingModeMap[] = {
58 CSSValueHorizontalTb, CSSValueVerticalRl, CSSValueVerticalLr
60 COMPILE_ASSERT(WTF_ARRAY_LENGTH(displayWritingModeMap) == TextTrackCue::NumberOfWritingDirections,
61 displayWritingModeMap_has_wrong_size);
63 static const CSSValueID displayAlignmentMap[] = {
64 CSSValueStart, CSSValueCenter, CSSValueEnd, CSSValueLeft, CSSValueRight
66 COMPILE_ASSERT(WTF_ARRAY_LENGTH(displayAlignmentMap) == TextTrackCue::NumberOfAlignments,
67 displayAlignmentMap_has_wrong_size);
69 static const String& startKeyword()
71 DEFINE_STATIC_LOCAL(const String, start, ("start"));
75 static const String& middleKeyword()
77 DEFINE_STATIC_LOCAL(const String, middle, ("middle"));
81 static const String& endKeyword()
83 DEFINE_STATIC_LOCAL(const String, end, ("end"));
87 static const String& leftKeyword()
89 DEFINE_STATIC_LOCAL(const String, left, ("left"));
93 static const String& rightKeyword()
95 DEFINE_STATIC_LOCAL(const String, right, ("right"));
99 static const String& horizontalKeyword()
101 return emptyString();
104 static const String& verticalGrowingLeftKeyword()
106 DEFINE_STATIC_LOCAL(const String, verticalrl, ("rl"));
110 static const String& verticalGrowingRightKeyword()
112 DEFINE_STATIC_LOCAL(const String, verticallr, ("lr"));
116 // ----------------------------
118 TextTrackCueBox::TextTrackCueBox(Document& document, TextTrackCue* cue)
119 : HTMLDivElement(divTag, document)
122 setPart(textTrackCueBoxShadowPseudoId());
125 TextTrackCue* TextTrackCueBox::getCue() const
130 void TextTrackCueBox::applyCSSProperties(const IntSize&)
132 // FIXME: Apply all the initial CSS positioning properties. http://wkb.ug/79916
133 if (!m_cue->regionId().isEmpty()) {
134 setInlineStyleProperty(CSSPropertyPosition, CSSValueRelative);
138 // 3.5.1 On the (root) List of WebVTT Node Objects:
140 // the 'position' property must be set to 'absolute'
141 setInlineStyleProperty(CSSPropertyPosition, CSSValueAbsolute);
143 // the 'unicode-bidi' property must be set to 'plaintext'
144 setInlineStyleProperty(CSSPropertyUnicodeBidi, CSSValueWebkitPlaintext);
146 // the 'direction' property must be set to direction
147 setInlineStyleProperty(CSSPropertyDirection, m_cue->getCSSWritingDirection());
149 // the 'writing-mode' property must be set to writing-mode
150 setInlineStyleProperty(CSSPropertyWebkitWritingMode, m_cue->getCSSWritingMode());
152 std::pair<float, float> position = m_cue->getCSSPosition();
154 // the 'top' property must be set to top,
155 setInlineStyleProperty(CSSPropertyTop, position.second, CSSPrimitiveValue::CSS_PERCENTAGE);
157 // the 'left' property must be set to left
158 setInlineStyleProperty(CSSPropertyLeft, position.first, CSSPrimitiveValue::CSS_PERCENTAGE);
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);
165 setInlineStyleProperty(CSSPropertyWidth, CSSValueAuto);
166 setInlineStyleProperty(CSSPropertyHeight, static_cast<double>(m_cue->getCSSSize()), CSSPrimitiveValue::CSS_PERCENTAGE);
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
173 setInlineStyleProperty(CSSPropertyTextAlign, m_cue->getCSSAlignment());
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.
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
186 setInlineStyleProperty(CSSPropertyWebkitTransform,
187 String::format("translate(-%.2f%%, -%.2f%%)", position.first, position.second));
189 setInlineStyleProperty(CSSPropertyWhiteSpace, CSSValuePre);
193 const AtomicString& TextTrackCueBox::textTrackCueBoxShadowPseudoId()
195 DEFINE_STATIC_LOCAL(const AtomicString, trackDisplayBoxShadowPseudoId, ("-webkit-media-text-track-display", AtomicString::ConstructFromLiteral));
196 return trackDisplayBoxShadowPseudoId;
199 RenderObject* TextTrackCueBox::createRenderer(RenderStyle*)
201 return new RenderTextTrackCue(this);
204 // ----------------------------
206 TextTrackCue::TextTrackCue(Document& document, double start, double end, const String& content)
210 , m_linePosition(undefinedPosition)
211 , m_computedLinePosition(undefinedPosition)
214 , m_cueIndex(invalidCueIndex)
215 , m_writingDirection(Horizontal)
216 , m_cueAlignment(Middle)
217 , m_webVTTNodeTree(0)
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)
227 ScriptWrappable::init(this);
230 TextTrackCue::~TextTrackCue()
232 displayTreeInternal()->remove(ASSERT_NO_EXCEPTION);
235 PassRefPtr<TextTrackCueBox> TextTrackCue::displayTreeInternal()
238 m_displayTree = TextTrackCueBox::create(document(), this);
239 return m_displayTree;
242 void TextTrackCue::cueWillChange()
245 m_track->cueWillChange(this);
248 void TextTrackCue::cueDidChange()
251 m_track->cueDidChange(this);
253 m_displayTreeShouldChange = true;
256 TextTrack* TextTrackCue::track() const
261 void TextTrackCue::setTrack(TextTrack* track)
266 void TextTrackCue::setId(const String& id)
276 void TextTrackCue::setStartTime(double value, ExceptionState& es)
278 // NaN, Infinity and -Infinity values should trigger a TypeError.
279 if (std::isinf(value) || std::isnan(value)) {
280 es.throwUninformativeAndGenericTypeError();
284 // TODO(93143): Add spec-compliant behavior for negative time values.
285 if (m_startTime == value || value < 0)
293 void TextTrackCue::setEndTime(double value, ExceptionState& es)
295 // NaN, Infinity and -Infinity values should trigger a TypeError.
296 if (std::isinf(value) || std::isnan(value)) {
297 es.throwUninformativeAndGenericTypeError();
301 // TODO(93143): Add spec-compliant behavior for negative time values.
302 if (m_endTime == value || value < 0)
310 void TextTrackCue::setPauseOnExit(bool value)
312 if (m_pauseOnExit == value)
316 m_pauseOnExit = value;
320 const String& TextTrackCue::vertical() const
322 switch (m_writingDirection) {
324 return horizontalKeyword();
325 case VerticalGrowingLeft:
326 return verticalGrowingLeftKeyword();
327 case VerticalGrowingRight:
328 return verticalGrowingRightKeyword();
330 ASSERT_NOT_REACHED();
331 return emptyString();
335 void TextTrackCue::setVertical(const String& value, ExceptionState& es)
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.
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;
351 es.throwUninformativeAndGenericDOMException(SyntaxError);
353 if (direction == m_writingDirection)
357 m_writingDirection = direction;
361 void TextTrackCue::setSnapToLines(bool value)
363 if (m_snapToLines == value)
367 m_snapToLines = value;
371 void TextTrackCue::setLine(int position, ExceptionState& es)
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);
381 // Otherwise, set the text track cue line position to the new value.
382 if (m_linePosition == position)
386 m_linePosition = position;
387 m_computedLinePosition = calculateComputedLinePosition();
391 void TextTrackCue::setPosition(int position, ExceptionState& es)
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);
401 // Otherwise, set the text track cue line position to the new value.
402 if (m_textPosition == position)
406 m_textPosition = position;
410 void TextTrackCue::setSize(int size, ExceptionState& es)
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);
420 // Otherwise, set the text track cue line position to the new value.
421 if (m_cueSize == size)
429 const String& TextTrackCue::align() const
431 switch (m_cueAlignment) {
433 return startKeyword();
435 return middleKeyword();
439 return leftKeyword();
441 return rightKeyword();
443 ASSERT_NOT_REACHED();
444 return emptyString();
448 void TextTrackCue::setAlign(const String& value, ExceptionState& es)
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.
456 CueAlignment alignment = m_cueAlignment;
457 if (value == startKeyword())
459 else if (value == middleKeyword())
461 else if (value == endKeyword())
463 else if (value == leftKeyword())
465 else if (value == rightKeyword())
468 es.throwUninformativeAndGenericDOMException(SyntaxError);
470 if (alignment == m_cueAlignment)
474 m_cueAlignment = alignment;
478 void TextTrackCue::setText(const String& text)
480 if (m_content == text)
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;
491 int TextTrackCue::cueIndex()
493 if (m_cueIndex == invalidCueIndex)
494 m_cueIndex = track()->cues()->getCueIndex(this);
499 void TextTrackCue::invalidateCueIndex()
501 m_cueIndex = invalidCueIndex;
504 void TextTrackCue::createWebVTTNodeTree()
506 if (!m_webVTTNodeTree)
507 m_webVTTNodeTree = WebVTTParser::createDocumentFragmentFromCueText(document(), m_content);
510 void TextTrackCue::copyWebVTTNodeToDOMTree(ContainerNode* webVTTNode, ContainerNode* parent)
512 for (Node* node = webVTTNode->firstChild(); node; node = node->nextSibling()) {
513 RefPtr<Node> clonedNode;
514 if (node->isWebVTTElement())
515 clonedNode = toWebVTTElement(node)->createEquivalentHTMLElement(&document());
517 clonedNode = node->cloneNode(false);
518 parent->appendChild(clonedNode);
519 if (node->isContainerNode())
520 copyWebVTTNodeToDOMTree(toContainerNode(node), toContainerNode(clonedNode));
524 PassRefPtr<DocumentFragment> TextTrackCue::getCueAsHTML()
526 createWebVTTNodeTree();
527 RefPtr<DocumentFragment> clonedFragment = DocumentFragment::create(document());
528 copyWebVTTNodeToDOMTree(m_webVTTNodeTree.get(), clonedFragment.get());
529 return clonedFragment.release();
532 PassRefPtr<DocumentFragment> TextTrackCue::createCueRenderingTree()
534 RefPtr<DocumentFragment> clonedFragment;
535 createWebVTTNodeTree();
536 clonedFragment = DocumentFragment::create(document());
537 m_webVTTNodeTree->cloneChildNodes(clonedFragment.get());
538 return clonedFragment.release();
541 bool TextTrackCue::dispatchEvent(PassRefPtr<Event> event)
543 // When a TextTrack's mode is disabled: no cues are active, no events fired.
544 if (!track() || track()->mode() == TextTrack::disabledKeyword())
547 return EventTarget::dispatchEvent(event);
550 void TextTrackCue::setRegionId(const String& regionId)
552 if (m_regionId == regionId)
556 m_regionId = regionId;
560 void TextTrackCue::notifyRegionWhenRemovingDisplayTree(bool notifyRegion)
562 m_notifyRegion = notifyRegion;
565 bool TextTrackCue::isActive()
567 return m_isActive && track() && track()->mode() != TextTrack::disabledKeyword();
570 void TextTrackCue::setIsActive(bool active)
574 // Remove the display tree as soon as the cue becomes inactive.
579 int TextTrackCue::calculateComputedLinePosition()
581 // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-computed-line-position
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;
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;
593 // Otherwise, it is the value returned by the following algorithm:
595 // If cue is not associated with a text track, return -1 and abort these
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();
605 // Increment n by one.
614 static bool isCueParagraphSeparator(UChar character)
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;
621 void TextTrackCue::determineTextDirection()
623 DEFINE_STATIC_LOCAL(const String, rtTag, ("rt"));
624 createWebVTTNodeTree();
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)
635 paragraphBuilder.append(node->nodeValue());
638 String paragraph = paragraphBuilder.toString();
639 if (!paragraph.length())
642 for (size_t i = 0; i < paragraph.length(); ++i) {
643 UChar current = paragraph[i];
644 if (!current || isCueParagraphSeparator(current))
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;
653 if (charDirection == WTF::Unicode::RightToLeft
654 || charDirection == WTF::Unicode::RightToLeftArabic) {
655 m_displayDirection = CSSValueRtl;
662 void TextTrackCue::calculateDisplayParameters()
665 determineTextDirection();
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
673 // The above step is done through the writing direction static map.
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;
694 ASSERT_NOT_REACHED();
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);
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
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) {
709 if (m_displayDirection == CSSValueLtr)
710 m_displayPosition.first = m_textPosition;
712 m_displayPosition.first = 100 - m_textPosition - m_displaySize;
715 if (m_displayDirection == CSSValueRtl)
716 m_displayPosition.first = 100 - m_textPosition;
718 m_displayPosition.first = m_textPosition - m_displaySize;
721 if (m_displayDirection == CSSValueLtr)
722 m_displayPosition.first = m_textPosition;
724 m_displayPosition.first = 100 - m_textPosition;
727 if (m_displayDirection == CSSValueLtr)
728 m_displayPosition.first = m_textPosition - m_displaySize;
730 m_displayPosition.first = 100 - m_textPosition - m_displaySize;
733 if (m_displayDirection == CSSValueLtr)
734 m_displayPosition.first = m_textPosition - m_displaySize / 2;
736 m_displayPosition.first = 100 - m_textPosition - m_displaySize / 2;
738 case NumberOfAlignments:
739 ASSERT_NOT_REACHED();
742 // Cases for m_writingDirection being VerticalGrowing{Left|Right}
743 switch (m_cueAlignment) {
746 m_displayPosition.second = m_textPosition;
750 m_displayPosition.second = m_textPosition - m_displaySize;
753 m_displayPosition.second = m_textPosition - m_displaySize / 2;
755 case NumberOfAlignments:
756 ASSERT_NOT_REACHED();
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();
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
767 if (m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
768 m_displayPosition.second = 0;
770 if (!m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
771 m_displayPosition.second = m_computedLinePosition;
773 if (m_snapToLines && m_displayPosition.first == undefinedPosition
774 && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
775 m_displayPosition.first = 0;
777 if (!m_snapToLines && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
778 m_displayPosition.first = m_computedLinePosition;
781 void TextTrackCue::markFutureAndPastNodes(ContainerNode* root, double previousTimestamp, double movieTime)
783 DEFINE_STATIC_LOCAL(const String, timestampTag, ("timestamp"));
785 bool isPastNode = true;
786 double currentTimestamp = previousTimestamp;
787 if (currentTimestamp > movieTime)
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);
797 if (currentTimestamp > movieTime)
801 if (child->isWebVTTElement()) {
802 toWebVTTElement(child)->setIsPastNode(isPastNode);
803 // Make an elemenet id match a cue id for style matching purposes.
805 toElement(child)->setIdAttribute(m_id);
810 void TextTrackCue::updateDisplayTree(double movieTime)
812 // The display tree may contain WebVTT timestamp objects representing
813 // timestamps (processing instructions), along with displayable nodes.
815 if (!track()->isRendered())
818 // Clear the contents of the set.
819 m_cueBackgroundBox->removeChildren();
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);
827 PassRefPtr<TextTrackCueBox> TextTrackCue::getDisplayTree(const IntSize& videoSize)
829 RefPtr<TextTrackCueBox> displayTree = displayTreeInternal();
830 if (!m_displayTreeShouldChange || !track()->isRendered())
834 calculateDisplayParameters();
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();
841 // The document tree is the tree of WebVTT Node Objects rooted at nodes.
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
847 // Note: This is contained by default in m_cueBackgroundBox.
848 m_cueBackgroundBox->setPart(cueShadowPseudoId());
849 displayTree->appendChild(m_cueBackgroundBox);
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'.
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);
864 m_displayTreeShouldChange = false;
866 // 10.15. Let cue's text track cue display state have the CSS boxes in
871 void TextTrackCue::removeDisplayTree()
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);
877 region->willRemoveTextTrackCueBox(m_displayTree.get());
880 displayTreeInternal()->remove(ASSERT_NO_EXCEPTION);
883 std::pair<double, double> TextTrackCue::getPositionCoordinates() const
885 // This method is used for setting x and y when snap to lines is not set.
886 std::pair<double, double> coordinates;
888 if (m_writingDirection == Horizontal && m_displayDirection == CSSValueLtr) {
889 coordinates.first = m_textPosition;
890 coordinates.second = m_computedLinePosition;
895 if (m_writingDirection == Horizontal && m_displayDirection == CSSValueRtl) {
896 coordinates.first = 100 - m_textPosition;
897 coordinates.second = m_computedLinePosition;
902 if (m_writingDirection == VerticalGrowingLeft) {
903 coordinates.first = 100 - m_computedLinePosition;
904 coordinates.second = m_textPosition;
909 if (m_writingDirection == VerticalGrowingRight) {
910 coordinates.first = m_computedLinePosition;
911 coordinates.second = m_textPosition;
916 ASSERT_NOT_REACHED();
921 TextTrackCue::CueSetting TextTrackCue::settingName(const String& name)
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"));
930 if (name == verticalKeyword)
932 else if (name == lineKeyword)
934 else if (name == positionKeyword)
936 else if (name == sizeKeyword)
938 else if (name == alignKeyword)
940 else if (RuntimeEnabledFeatures::webVTTRegionsEnabled() && name == regionIdKeyword)
946 void TextTrackCue::setCueSettings(const String& input)
949 unsigned position = 0;
951 while (position < input.length()) {
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]))
957 if (position >= input.length())
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);
969 size_t colonOffset = setting.find(':', 1);
970 if (colonOffset == kNotFound || !colonOffset || colonOffset == setting.length() - 1)
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));
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())
981 // 4. Run the appropriate substeps that apply for the value of name, as follows:
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;
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;
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]))
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)
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] == '%')
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 '%'.
1029 int number = linePosition.toInt(&validNumber);
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)
1042 // 10 - If '%' then set snap-to-lines flag to false.
1043 m_snapToLines = false;
1046 m_linePosition = number;
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())
1058 if (position >= input.length())
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
1065 if (input[position++] != '%')
1067 if (position < input.length() && !WebVTTParser::isValidSettingDelimiter(input[position]))
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 '%'.
1074 int number = textPosition.toInt(&validNumber);
1077 if (number < 0 || number > 100)
1080 // 7. Let cue's text track cue text position be number.
1081 m_textPosition = number;
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())
1093 if (position >= input.length())
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++] != '%')
1102 if (position < input.length() && !WebVTTParser::isValidSettingDelimiter(input[position]))
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.
1108 int number = cueSize.toInt(&validNumber);
1111 if (number < 0 || number > 100)
1114 // 7. Let cue's text track cue size be number.
1120 String cueAlignment = WebVTTParser::collectWord(input, &position);
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;
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;
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;
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;
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;
1144 m_regionId = WebVTTParser::collectWord(input, &position);
1151 position = endOfSetting;
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())
1160 if (m_linePosition != undefinedPosition || m_cueSize != 100 || m_writingDirection != Horizontal)
1161 m_regionId = emptyString();
1164 CSSValueID TextTrackCue::getCSSAlignment() const
1166 return displayAlignmentMap[m_cueAlignment];
1169 CSSValueID TextTrackCue::getCSSWritingDirection() const
1171 return m_displayDirection;
1174 CSSValueID TextTrackCue::getCSSWritingMode() const
1176 return displayWritingModeMap[m_writingDirection];
1179 int TextTrackCue::getCSSSize() const
1181 return m_displaySize;
1184 std::pair<double, double> TextTrackCue::getCSSPosition() const
1187 return getPositionCoordinates();
1189 return m_displayPosition;
1192 const AtomicString& TextTrackCue::interfaceName() const
1194 return EventTargetNames::TextTrackCue;
1197 ExecutionContext* TextTrackCue::executionContext() const
1199 ASSERT(m_cueBackgroundBox);
1200 return m_cueBackgroundBox->executionContext();
1203 Document& TextTrackCue::document() const
1205 ASSERT(m_cueBackgroundBox);
1206 return m_cueBackgroundBox->document();
1209 bool TextTrackCue::operator==(const TextTrackCue& cue) const
1211 if (m_endTime != cue.endTime())
1213 if (m_startTime != cue.startTime())
1215 if (m_content != cue.text())
1217 if (m_settings != cue.cueSettings())
1219 if (m_id != cue.id())
1221 if (m_textPosition != cue.position())
1223 if (m_linePosition != cue.line())
1225 if (m_cueSize != cue.size())
1227 if (align() != cue.align())
1233 } // namespace WebCore