2 * Copyright (c) 2013, Opera Software ASA. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
31 #include "core/html/track/vtt/VTTCue.h"
33 #include "bindings/core/v8/ExceptionMessages.h"
34 #include "bindings/core/v8/ExceptionStatePlaceholder.h"
35 #include "core/CSSPropertyNames.h"
36 #include "core/CSSValueKeywords.h"
37 #include "core/dom/DocumentFragment.h"
38 #include "core/dom/NodeTraversal.h"
39 #include "core/events/Event.h"
40 #include "core/frame/UseCounter.h"
41 #include "core/html/HTMLDivElement.h"
42 #include "core/html/track/TextTrack.h"
43 #include "core/html/track/TextTrackCueList.h"
44 #include "core/html/track/vtt/VTTElement.h"
45 #include "core/html/track/vtt/VTTParser.h"
46 #include "core/html/track/vtt/VTTRegionList.h"
47 #include "core/html/track/vtt/VTTScanner.h"
48 #include "core/rendering/RenderVTTCue.h"
49 #include "platform/RuntimeEnabledFeatures.h"
50 #include "platform/text/BidiResolver.h"
51 #include "platform/text/TextRunIterator.h"
52 #include "wtf/MathExtras.h"
53 #include "wtf/text/StringBuilder.h"
57 static const int undefinedPosition = -1;
58 static const int undefinedSize = -1;
60 static const CSSValueID displayWritingModeMap[] = {
61 CSSValueHorizontalTb, CSSValueVerticalRl, CSSValueVerticalLr
63 COMPILE_ASSERT(WTF_ARRAY_LENGTH(displayWritingModeMap) == VTTCue::NumberOfWritingDirections,
64 displayWritingModeMap_has_wrong_size);
66 static const CSSValueID displayAlignmentMap[] = {
67 CSSValueStart, CSSValueCenter, CSSValueEnd, CSSValueLeft, CSSValueRight
69 COMPILE_ASSERT(WTF_ARRAY_LENGTH(displayAlignmentMap) == VTTCue::NumberOfAlignments,
70 displayAlignmentMap_has_wrong_size);
72 static const String& startKeyword()
74 DEFINE_STATIC_LOCAL(const String, start, ("start"));
78 static const String& middleKeyword()
80 DEFINE_STATIC_LOCAL(const String, middle, ("middle"));
84 static const String& endKeyword()
86 DEFINE_STATIC_LOCAL(const String, end, ("end"));
90 static const String& leftKeyword()
92 DEFINE_STATIC_LOCAL(const String, left, ("left"));
96 static const String& rightKeyword()
98 DEFINE_STATIC_LOCAL(const String, right, ("right"));
102 static const String& horizontalKeyword()
104 return emptyString();
107 static const String& verticalGrowingLeftKeyword()
109 DEFINE_STATIC_LOCAL(const String, verticalrl, ("rl"));
113 static const String& verticalGrowingRightKeyword()
115 DEFINE_STATIC_LOCAL(const String, verticallr, ("lr"));
119 static bool isInvalidPercentage(int value, ExceptionState& exceptionState)
121 if (value < 0 || value > 100) {
122 exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::indexOutsideRange("value", value, 0, ExceptionMessages::InclusiveBound, 100, ExceptionMessages::InclusiveBound));
128 VTTCueBox::VTTCueBox(Document& document, VTTCue* cue)
129 : HTMLDivElement(document)
132 setShadowPseudoId(AtomicString("-webkit-media-text-track-display", AtomicString::ConstructFromLiteral));
135 void VTTCueBox::applyCSSProperties(const IntSize&)
137 // FIXME: Apply all the initial CSS positioning properties. http://wkb.ug/79916
138 if (!m_cue->regionId().isEmpty()) {
139 setInlineStyleProperty(CSSPropertyPosition, CSSValueRelative);
143 // 3.5.1 On the (root) List of WebVTT Node Objects:
145 // the 'position' property must be set to 'absolute'
146 setInlineStyleProperty(CSSPropertyPosition, CSSValueAbsolute);
148 // the 'unicode-bidi' property must be set to 'plaintext'
149 setInlineStyleProperty(CSSPropertyUnicodeBidi, CSSValueWebkitPlaintext);
151 // the 'direction' property must be set to direction
152 setInlineStyleProperty(CSSPropertyDirection, m_cue->getCSSWritingDirection());
154 // the 'writing-mode' property must be set to writing-mode
155 setInlineStyleProperty(CSSPropertyWebkitWritingMode, m_cue->getCSSWritingMode());
157 std::pair<float, float> position = m_cue->getCSSPosition();
159 // the 'top' property must be set to top,
160 setInlineStyleProperty(CSSPropertyTop, position.second, CSSPrimitiveValue::CSS_PERCENTAGE);
162 // the 'left' property must be set to left
163 setInlineStyleProperty(CSSPropertyLeft, position.first, CSSPrimitiveValue::CSS_PERCENTAGE);
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);
170 setInlineStyleProperty(CSSPropertyWidth, CSSValueAuto);
171 setInlineStyleProperty(CSSPropertyHeight, static_cast<double>(m_cue->getCSSSize()), CSSPrimitiveValue::CSS_PERCENTAGE);
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
178 setInlineStyleProperty(CSSPropertyTextAlign, m_cue->getCSSAlignment());
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.
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
191 setInlineStyleProperty(CSSPropertyWebkitTransform,
192 String::format("translate(-%.2f%%, -%.2f%%)", position.first, position.second));
194 setInlineStyleProperty(CSSPropertyWhiteSpace, CSSValuePre);
198 RenderObject* VTTCueBox::createRenderer(RenderStyle*)
200 return new RenderVTTCue(this);
203 void VTTCueBox::trace(Visitor* visitor)
205 visitor->trace(m_cue);
206 HTMLDivElement::trace(visitor);
209 VTTCue::VTTCue(Document& document, double startTime, double endTime, const String& text)
210 : TextTrackCue(startTime, endTime)
212 , m_linePosition(undefinedPosition)
213 , m_computedLinePosition(undefinedPosition)
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)
226 UseCounter::count(document, UseCounter::VTTCue);
231 // Using oilpan, if m_displayTree is in the document it will strongly keep
232 // the cue alive. Thus, if the cue is dead, either m_displayTree is not in
233 // the document or the entire document is dead too.
235 // FIXME: This is scary, we should make the life cycle smarter so the destructor
236 // doesn't need to do DOM mutations.
238 m_displayTree->remove(ASSERT_NO_EXCEPTION);
243 String VTTCue::toString() const
245 return String::format("%p id=%s interval=%f-->%f cue=%s)", this, id().utf8().data(), startTime(), endTime(), text().utf8().data());
249 VTTCueBox& VTTCue::ensureDisplayTree()
252 m_displayTree = VTTCueBox::create(document(), this);
253 return *m_displayTree;
256 void VTTCue::cueDidChange()
258 TextTrackCue::cueDidChange();
259 m_displayTreeShouldChange = true;
262 const String& VTTCue::vertical() const
264 switch (m_writingDirection) {
266 return horizontalKeyword();
267 case VerticalGrowingLeft:
268 return verticalGrowingLeftKeyword();
269 case VerticalGrowingRight:
270 return verticalGrowingRightKeyword();
272 ASSERT_NOT_REACHED();
273 return emptyString();
277 void VTTCue::setVertical(const String& value)
279 WritingDirection direction = m_writingDirection;
280 if (value == horizontalKeyword())
281 direction = Horizontal;
282 else if (value == verticalGrowingLeftKeyword())
283 direction = VerticalGrowingLeft;
284 else if (value == verticalGrowingRightKeyword())
285 direction = VerticalGrowingRight;
287 ASSERT_NOT_REACHED();
289 if (direction == m_writingDirection)
293 m_writingDirection = direction;
297 void VTTCue::setSnapToLines(bool value)
299 if (m_snapToLines == value)
303 m_snapToLines = value;
307 void VTTCue::setLine(int position, ExceptionState& exceptionState)
309 // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-line
310 // On setting, if the text track cue snap-to-lines flag is not set, and the new
311 // value is negative or greater than 100, then throw an IndexSizeError exception.
312 if (!m_snapToLines && (position < 0 || position > 100)) {
313 exceptionState.throwDOMException(IndexSizeError, "The snap-to-lines flag is not set, and the value provided (" + String::number(position) + ") is not between 0 and 100.");
317 // Otherwise, set the text track cue line position to the new value.
318 if (m_linePosition == position)
322 m_linePosition = position;
323 m_computedLinePosition = calculateComputedLinePosition();
327 void VTTCue::setPosition(int position, ExceptionState& exceptionState)
329 // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-position
330 // On setting, if the new value is negative or greater than 100, then throw an IndexSizeError exception.
331 // Otherwise, set the text track cue text position to the new value.
332 if (isInvalidPercentage(position, exceptionState))
335 // Otherwise, set the text track cue line position to the new value.
336 if (m_textPosition == position)
340 m_textPosition = position;
344 void VTTCue::setSize(int size, ExceptionState& exceptionState)
346 // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-size
347 // On setting, if the new value is negative or greater than 100, then throw an IndexSizeError
348 // exception. Otherwise, set the text track cue size to the new value.
349 if (isInvalidPercentage(size, exceptionState))
352 // Otherwise, set the text track cue line position to the new value.
353 if (m_cueSize == size)
361 const String& VTTCue::align() const
363 switch (m_cueAlignment) {
365 return startKeyword();
367 return middleKeyword();
371 return leftKeyword();
373 return rightKeyword();
375 ASSERT_NOT_REACHED();
376 return emptyString();
380 void VTTCue::setAlign(const String& value)
382 CueAlignment alignment = m_cueAlignment;
383 if (value == startKeyword())
385 else if (value == middleKeyword())
387 else if (value == endKeyword())
389 else if (value == leftKeyword())
391 else if (value == rightKeyword())
394 ASSERT_NOT_REACHED();
396 if (alignment == m_cueAlignment)
400 m_cueAlignment = alignment;
404 void VTTCue::setText(const String& text)
410 // Clear the document fragment but don't bother to create it again just yet as we can do that
411 // when it is requested.
412 m_vttNodeTree = nullptr;
417 void VTTCue::createVTTNodeTree()
420 m_vttNodeTree = VTTParser::createDocumentFragmentFromCueText(document(), m_text);
423 void VTTCue::copyVTTNodeToDOMTree(ContainerNode* vttNode, ContainerNode* parent)
425 for (Node* node = vttNode->firstChild(); node; node = node->nextSibling()) {
426 RefPtrWillBeRawPtr<Node> clonedNode;
427 if (node->isVTTElement())
428 clonedNode = toVTTElement(node)->createEquivalentHTMLElement(document());
430 clonedNode = node->cloneNode(false);
431 parent->appendChild(clonedNode);
432 if (node->isContainerNode())
433 copyVTTNodeToDOMTree(toContainerNode(node), toContainerNode(clonedNode));
437 PassRefPtrWillBeRawPtr<DocumentFragment> VTTCue::getCueAsHTML()
440 RefPtrWillBeRawPtr<DocumentFragment> clonedFragment = DocumentFragment::create(document());
441 copyVTTNodeToDOMTree(m_vttNodeTree.get(), clonedFragment.get());
442 return clonedFragment.release();
445 PassRefPtrWillBeRawPtr<DocumentFragment> VTTCue::createCueRenderingTree()
448 RefPtrWillBeRawPtr<DocumentFragment> clonedFragment = DocumentFragment::create(document());
449 m_vttNodeTree->cloneChildNodes(clonedFragment.get());
450 return clonedFragment.release();
453 void VTTCue::setRegionId(const String& regionId)
455 if (m_regionId == regionId)
459 m_regionId = regionId;
463 void VTTCue::notifyRegionWhenRemovingDisplayTree(bool notifyRegion)
465 m_notifyRegion = notifyRegion;
468 int VTTCue::calculateComputedLinePosition()
470 // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-computed-line-position
472 // If the text track cue line position is numeric, then that is the text
473 // track cue computed line position.
474 if (m_linePosition != undefinedPosition)
475 return m_linePosition;
477 // If the text track cue snap-to-lines flag of the text track cue is not
478 // set, the text track cue computed line position is the value 100;
482 // Otherwise, it is the value returned by the following algorithm:
484 // If cue is not associated with a text track, return -1 and abort these
489 // Let n be the number of text tracks whose text track mode is showing or
490 // showing by default and that are in the media element's list of text
491 // tracks before track.
492 int n = track()->trackIndexRelativeToRenderedTracks();
494 // Increment n by one.
503 class VTTTextRunIterator : public TextRunIterator {
505 VTTTextRunIterator() { }
506 VTTTextRunIterator(const TextRun* textRun, unsigned offset) : TextRunIterator(textRun, offset) { }
508 bool atParagraphSeparator() const
510 // Within a cue, paragraph boundaries are only denoted by Type B characters,
511 // such as U+000A LINE FEED (LF), U+0085 NEXT LINE (NEL), and U+2029 PARAGRAPH SEPARATOR.
512 return WTF::Unicode::category(current()) & WTF::Unicode::Separator_Paragraph;
516 // Almost the same as determineDirectionality in core/html/HTMLElement.cpp, but
517 // that one uses a "plain" TextRunIterator (which only checks for '\n').
518 static TextDirection determineDirectionality(const String& value, bool& hasStrongDirectionality)
521 BidiResolver<VTTTextRunIterator, BidiCharacterRun> bidiResolver;
522 bidiResolver.setStatus(BidiStatus(LTR, false));
523 bidiResolver.setPositionIgnoringNestedIsolates(VTTTextRunIterator(&run, 0));
524 return bidiResolver.determineParagraphDirectionality(&hasStrongDirectionality);
527 static CSSValueID determineTextDirection(DocumentFragment* vttRoot)
529 DEFINE_STATIC_LOCAL(const String, rtTag, ("rt"));
532 // Apply the Unicode Bidirectional Algorithm's Paragraph Level steps to the
533 // concatenation of the values of each WebVTT Text Object in nodes, in a
534 // pre-order, depth-first traversal, excluding WebVTT Ruby Text Objects and
535 // their descendants.
536 TextDirection textDirection = LTR;
537 for (Node* node = vttRoot->firstChild(); node; node = NodeTraversal::next(*node, vttRoot)) {
538 if (!node->isTextNode() || node->localName() == rtTag)
541 bool hasStrongDirectionality;
542 textDirection = determineDirectionality(node->nodeValue(), hasStrongDirectionality);
543 if (hasStrongDirectionality)
546 return isLeftToRightDirection(textDirection) ? CSSValueLtr : CSSValueRtl;
549 void VTTCue::calculateDisplayParameters()
554 m_displayDirection = determineTextDirection(m_vttNodeTree.get());
556 if (m_displayDirection == CSSValueRtl)
557 UseCounter::count(document(), UseCounter::VTTCueRenderRtl);
559 // 10.4 If the text track cue writing direction is horizontal, then let
560 // block-flow be 'tb'. Otherwise, if the text track cue writing direction is
561 // vertical growing left, then let block-flow be 'lr'. Otherwise, the text
562 // track cue writing direction is vertical growing right; let block-flow be
565 // The above step is done through the writing direction static map.
567 // 10.5 Determine the value of maximum size for cue as per the appropriate
568 // rules from the following list:
569 int maximumSize = m_textPosition;
570 if ((m_writingDirection == Horizontal && m_cueAlignment == Start && m_displayDirection == CSSValueLtr)
571 || (m_writingDirection == Horizontal && m_cueAlignment == End && m_displayDirection == CSSValueRtl)
572 || (m_writingDirection == Horizontal && m_cueAlignment == Left)
573 || (m_writingDirection == VerticalGrowingLeft && (m_cueAlignment == Start || m_cueAlignment == Left))
574 || (m_writingDirection == VerticalGrowingRight && (m_cueAlignment == Start || m_cueAlignment == Left))) {
575 maximumSize = 100 - m_textPosition;
576 } else if ((m_writingDirection == Horizontal && m_cueAlignment == End && m_displayDirection == CSSValueLtr)
577 || (m_writingDirection == Horizontal && m_cueAlignment == Start && m_displayDirection == CSSValueRtl)
578 || (m_writingDirection == Horizontal && m_cueAlignment == Right)
579 || (m_writingDirection == VerticalGrowingLeft && (m_cueAlignment == End || m_cueAlignment == Right))
580 || (m_writingDirection == VerticalGrowingRight && (m_cueAlignment == End || m_cueAlignment == Right))) {
581 maximumSize = m_textPosition;
582 } else if (m_cueAlignment == Middle) {
583 maximumSize = m_textPosition <= 50 ? m_textPosition : (100 - m_textPosition);
584 maximumSize = maximumSize * 2;
586 ASSERT_NOT_REACHED();
589 // 10.6 If the text track cue size is less than maximum size, then let size
590 // be text track cue size. Otherwise, let size be maximum size.
591 m_displaySize = std::min(m_cueSize, maximumSize);
593 // FIXME: Understand why step 10.7 is missing (just a copy/paste error?)
594 // Could be done within a spec implementation check - http://crbug.com/301580
596 // 10.8 Determine the value of x-position or y-position for cue as per the
597 // appropriate rules from the following list:
598 if (m_writingDirection == Horizontal) {
599 switch (m_cueAlignment) {
601 if (m_displayDirection == CSSValueLtr)
602 m_displayPosition.first = m_textPosition;
604 m_displayPosition.first = 100 - m_textPosition - m_displaySize;
607 if (m_displayDirection == CSSValueRtl)
608 m_displayPosition.first = 100 - m_textPosition;
610 m_displayPosition.first = m_textPosition - m_displaySize;
613 if (m_displayDirection == CSSValueLtr)
614 m_displayPosition.first = m_textPosition;
616 m_displayPosition.first = 100 - m_textPosition;
619 if (m_displayDirection == CSSValueLtr)
620 m_displayPosition.first = m_textPosition - m_displaySize;
622 m_displayPosition.first = 100 - m_textPosition - m_displaySize;
625 if (m_displayDirection == CSSValueLtr)
626 m_displayPosition.first = m_textPosition - m_displaySize / 2;
628 m_displayPosition.first = 100 - m_textPosition - m_displaySize / 2;
631 ASSERT_NOT_REACHED();
634 // Cases for m_writingDirection being VerticalGrowing{Left|Right}
635 switch (m_cueAlignment) {
638 m_displayPosition.second = m_textPosition;
642 m_displayPosition.second = m_textPosition - m_displaySize;
645 m_displayPosition.second = m_textPosition - m_displaySize / 2;
648 ASSERT_NOT_REACHED();
652 // A text track cue has a text track cue computed line position whose value
653 // is defined in terms of the other aspects of the cue.
654 m_computedLinePosition = calculateComputedLinePosition();
656 // 10.9 Determine the value of whichever of x-position or y-position is not
657 // yet calculated for cue as per the appropriate rules from the following
659 if (m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
660 m_displayPosition.second = 0;
662 if (!m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
663 m_displayPosition.second = m_computedLinePosition;
665 if (m_snapToLines && m_displayPosition.first == undefinedPosition
666 && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
667 m_displayPosition.first = 0;
669 if (!m_snapToLines && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
670 m_displayPosition.first = m_computedLinePosition;
673 void VTTCue::markFutureAndPastNodes(ContainerNode* root, double previousTimestamp, double movieTime)
675 DEFINE_STATIC_LOCAL(const String, timestampTag, ("timestamp"));
677 bool isPastNode = true;
678 double currentTimestamp = previousTimestamp;
679 if (currentTimestamp > movieTime)
682 for (Node* child = root->firstChild(); child; child = NodeTraversal::next(*child, root)) {
683 if (child->nodeName() == timestampTag) {
684 double currentTimestamp;
685 bool check = VTTParser::collectTimeStamp(child->nodeValue(), currentTimestamp);
686 ASSERT_UNUSED(check, check);
688 if (currentTimestamp > movieTime)
692 if (child->isVTTElement()) {
693 toVTTElement(child)->setIsPastNode(isPastNode);
694 // Make an elemenet id match a cue id for style matching purposes.
696 toElement(child)->setIdAttribute(id());
701 void VTTCue::updateDisplayTree(double movieTime)
703 // The display tree may contain WebVTT timestamp objects representing
704 // timestamps (processing instructions), along with displayable nodes.
706 if (!track()->isRendered())
709 // Clear the contents of the set.
710 m_cueBackgroundBox->removeChildren();
712 // Update the two sets containing past and future WebVTT objects.
713 RefPtrWillBeRawPtr<DocumentFragment> referenceTree = createCueRenderingTree();
714 markFutureAndPastNodes(referenceTree.get(), startTime(), movieTime);
715 m_cueBackgroundBox->appendChild(referenceTree, ASSERT_NO_EXCEPTION);
718 PassRefPtrWillBeRawPtr<VTTCueBox> VTTCue::getDisplayTree(const IntSize& videoSize)
720 RefPtrWillBeRawPtr<VTTCueBox> displayTree(ensureDisplayTree());
721 if (!m_displayTreeShouldChange || !track()->isRendered())
722 return displayTree.release();
725 calculateDisplayParameters();
727 // 10.11. Apply the terms of the CSS specifications to nodes within the
728 // following constraints, thus obtaining a set of CSS boxes positioned
729 // relative to an initial containing block:
730 displayTree->removeChildren();
732 // The document tree is the tree of WebVTT Node Objects rooted at nodes.
734 // The children of the nodes must be wrapped in an anonymous box whose
735 // 'display' property has the value 'inline'. This is the WebVTT cue
738 // Note: This is contained by default in m_cueBackgroundBox.
739 m_cueBackgroundBox->setShadowPseudoId(cueShadowPseudoId());
740 displayTree->appendChild(m_cueBackgroundBox);
742 // FIXME(BUG 79916): Runs of children of WebVTT Ruby Objects that are not
743 // WebVTT Ruby Text Objects must be wrapped in anonymous boxes whose
744 // 'display' property has the value 'ruby-base'.
746 // FIXME(BUG 79916): Text runs must be wrapped according to the CSS
747 // line-wrapping rules, except that additionally, regardless of the value of
748 // the 'white-space' property, lines must be wrapped at the edge of their
749 // containing blocks, even if doing so requires splitting a word where there
750 // is no line breaking opportunity. (Thus, normally text wraps as needed,
751 // but if there is a particularly long word, it does not overflow as it
752 // normally would in CSS, it is instead forcibly wrapped at the box's edge.)
753 displayTree->applyCSSProperties(videoSize);
755 m_displayTreeShouldChange = false;
757 // 10.15. Let cue's text track cue display state have the CSS boxes in
759 return displayTree.release();
762 void VTTCue::removeDisplayTree()
764 if (m_notifyRegion && track()->regions()) {
765 // The region needs to be informed about the cue removal.
766 VTTRegion* region = track()->regions()->getRegionById(m_regionId);
768 region->willRemoveVTTCueBox(m_displayTree.get());
772 m_displayTree->remove(ASSERT_NO_EXCEPTION);
775 void VTTCue::updateDisplay(const IntSize& videoSize, HTMLDivElement& container)
777 UseCounter::count(document(), UseCounter::VTTCueRender);
779 if (m_writingDirection != Horizontal)
780 UseCounter::count(document(), UseCounter::VTTCueRenderVertical);
783 UseCounter::count(document(), UseCounter::VTTCueRenderSnapToLinesFalse);
785 if (m_linePosition != undefinedPosition)
786 UseCounter::count(document(), UseCounter::VTTCueRenderLineNotAuto);
788 if (m_textPosition != 50)
789 UseCounter::count(document(), UseCounter::VTTCueRenderPositionNot50);
791 if (m_cueSize != 100)
792 UseCounter::count(document(), UseCounter::VTTCueRenderSizeNot100);
794 if (m_cueAlignment != Middle)
795 UseCounter::count(document(), UseCounter::VTTCueRenderAlignNotMiddle);
797 RefPtrWillBeRawPtr<VTTCueBox> displayBox = getDisplayTree(videoSize);
798 VTTRegion* region = 0;
799 if (track()->regions())
800 region = track()->regions()->getRegionById(regionId());
803 // If cue has an empty text track cue region identifier or there is no
804 // WebVTT region whose region identifier is identical to cue's text
805 // track cue region identifier, run the following substeps:
806 if (displayBox->hasChildren() && !container.contains(displayBox.get())) {
807 // Note: the display tree of a cue is removed when the active flag of the cue is unset.
808 container.appendChild(displayBox);
811 // Let region be the WebVTT region whose region identifier
812 // matches the text track cue region identifier of cue.
813 RefPtrWillBeRawPtr<HTMLDivElement> regionNode = region->getDisplayTree(document());
815 // Append the region to the viewport, if it was not already.
816 if (!container.contains(regionNode.get()))
817 container.appendChild(regionNode);
819 region->appendVTTCueBox(displayBox);
823 std::pair<double, double> VTTCue::getPositionCoordinates() const
825 // This method is used for setting x and y when snap to lines is not set.
826 std::pair<double, double> coordinates;
828 if (m_writingDirection == Horizontal && m_displayDirection == CSSValueLtr) {
829 coordinates.first = m_textPosition;
830 coordinates.second = m_computedLinePosition;
835 if (m_writingDirection == Horizontal && m_displayDirection == CSSValueRtl) {
836 coordinates.first = 100 - m_textPosition;
837 coordinates.second = m_computedLinePosition;
842 if (m_writingDirection == VerticalGrowingLeft) {
843 coordinates.first = 100 - m_computedLinePosition;
844 coordinates.second = m_textPosition;
849 if (m_writingDirection == VerticalGrowingRight) {
850 coordinates.first = m_computedLinePosition;
851 coordinates.second = m_textPosition;
856 ASSERT_NOT_REACHED();
861 VTTCue::CueSetting VTTCue::settingName(VTTScanner& input)
863 CueSetting parsedSetting = None;
864 if (input.scan("vertical"))
865 parsedSetting = Vertical;
866 else if (input.scan("line"))
867 parsedSetting = Line;
868 else if (input.scan("position"))
869 parsedSetting = Position;
870 else if (input.scan("size"))
871 parsedSetting = Size;
872 else if (input.scan("align"))
873 parsedSetting = Align;
874 else if (RuntimeEnabledFeatures::webVTTRegionsEnabled() && input.scan("region"))
875 parsedSetting = RegionId;
876 // Verify that a ':' follows.
877 if (parsedSetting != None && input.scan(':'))
878 return parsedSetting;
882 // Used for 'position' and 'size'.
883 static bool scanPercentage(VTTScanner& input, const VTTScanner::Run& valueRun, int& number)
885 // 1. If value contains any characters other than U+0025 PERCENT SIGN
886 // characters (%) and characters in the range U+0030 DIGIT ZERO (0) to
887 // U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
888 // 2. If value does not contain at least one character in the range U+0030
889 // DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step
890 // labeled next setting.
891 if (!input.scanDigits(number))
894 // 3. If any character in value other than the last character is a U+0025
895 // PERCENT SIGN character (%), then jump to the step labeled next
897 // 4. If the last character in value is not a U+0025 PERCENT SIGN character
898 // (%), then jump to the step labeled next setting.
899 if (!input.scan('%') || !input.isAt(valueRun.end()))
902 // 5. Ignoring the trailing percent sign, interpret value as an integer,
903 // and let number be that number.
904 // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step
905 // labeled next setting.
906 return number >= 0 && number <= 100;
909 void VTTCue::parseSettings(const String& inputString)
911 VTTScanner input(inputString);
913 while (!input.isAtEnd()) {
915 // The WebVTT cue settings part of a WebVTT cue consists of zero or more of the following components, in any order,
916 // separated from each other by one or more U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters.
917 input.skipWhile<VTTParser::isValidSettingDelimiter>();
922 // When the user agent is to parse the WebVTT settings given by a string input for a text track cue cue,
923 // the user agent must run the following steps:
924 // 1. Let settings be the result of splitting input on spaces.
925 // 2. For each token setting in the list settings, run the following substeps:
926 // 1. If setting does not contain a U+003A COLON character (:), or if the first U+003A COLON character (:)
927 // in setting is either the first or last character of setting, then jump to the step labeled next setting.
928 // 2. Let name be the leading substring of setting up to and excluding the first U+003A COLON character (:) in that string.
929 CueSetting name = settingName(input);
931 // 3. Let value be the trailing substring of setting starting from the character immediately after the first U+003A COLON character (:) in that string.
932 VTTScanner::Run valueRun = input.collectUntil<VTTParser::isValidSettingDelimiter>();
934 // 4. Run the appropriate substeps that apply for the value of name, as follows:
937 // If name is a case-sensitive match for "vertical"
938 // 1. If value is a case-sensitive match for the string "rl", then let cue's text track cue writing direction
939 // be vertical growing left.
940 if (input.scanRun(valueRun, verticalGrowingLeftKeyword()))
941 m_writingDirection = VerticalGrowingLeft;
943 // 2. Otherwise, if value is a case-sensitive match for the string "lr", then let cue's text track cue writing
944 // direction be vertical growing right.
945 else if (input.scanRun(valueRun, verticalGrowingRightKeyword()))
946 m_writingDirection = VerticalGrowingRight;
950 // 1-2 - Collect chars that are either '-', '%', or a digit.
951 // 1. If value contains any characters other than U+002D HYPHEN-MINUS characters (-), U+0025 PERCENT SIGN
952 // characters (%), and characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump
953 // to the step labeled next setting.
954 bool isNegative = input.scan('-');
956 unsigned numDigits = input.scanDigits(linePosition);
957 bool isPercentage = input.scan('%');
959 if (!input.isAt(valueRun.end()))
962 // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT
963 // NINE (9), then jump to the step labeled next setting.
964 // 3. If any character in value other than the first character is a U+002D HYPHEN-MINUS character (-), then
965 // jump to the step labeled next setting.
966 // 4. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then
967 // jump to the step labeled next setting.
969 // 5. If the first character in value is a U+002D HYPHEN-MINUS character (-) and the last character in value is a
970 // U+0025 PERCENT SIGN character (%), then jump to the step labeled next setting.
971 if (!numDigits || (isPercentage && isNegative))
974 // 6. Ignoring the trailing percent sign, if any, interpret value as a (potentially signed) integer, and
975 // let number be that number.
976 // 7. If the last character in value is a U+0025 PERCENT SIGN character (%), but number is not in the range
977 // 0 ≤ number ≤ 100, then jump to the step labeled next setting.
978 // 8. Let cue's text track cue line position be number.
979 // 9. If the last character in value is a U+0025 PERCENT SIGN character (%), then let cue's text track cue
980 // snap-to-lines flag be false. Otherwise, let it be true.
982 if (linePosition < 0 || linePosition > 100)
984 // 10 - If '%' then set snap-to-lines flag to false.
985 m_snapToLines = false;
988 linePosition = -linePosition;
989 m_snapToLines = true;
991 m_linePosition = linePosition;
997 if (!scanPercentage(input, valueRun, number))
1000 // 7. Let cue's text track cue text position be number.
1001 m_textPosition = number;
1007 if (!scanPercentage(input, valueRun, number))
1010 // 7. Let cue's text track cue size be number.
1015 // 1. If value is a case-sensitive match for the string "start", then let cue's text track cue alignment be start alignment.
1016 if (input.scanRun(valueRun, startKeyword()))
1017 m_cueAlignment = Start;
1019 // 2. If value is a case-sensitive match for the string "middle", then let cue's text track cue alignment be middle alignment.
1020 else if (input.scanRun(valueRun, middleKeyword()))
1021 m_cueAlignment = Middle;
1023 // 3. If value is a case-sensitive match for the string "end", then let cue's text track cue alignment be end alignment.
1024 else if (input.scanRun(valueRun, endKeyword()))
1025 m_cueAlignment = End;
1027 // 4. If value is a case-sensitive match for the string "left", then let cue's text track cue alignment be left alignment.
1028 else if (input.scanRun(valueRun, leftKeyword()))
1029 m_cueAlignment = Left;
1031 // 5. If value is a case-sensitive match for the string "right", then let cue's text track cue alignment be right alignment.
1032 else if (input.scanRun(valueRun, rightKeyword()))
1033 m_cueAlignment = Right;
1037 m_regionId = input.extractString(valueRun);
1043 // Make sure the entire run is consumed.
1044 input.skipRun(valueRun);
1047 // If cue's line position is not auto or cue's size is not 100 or cue's
1048 // writing direction is not horizontal, but cue's region identifier is not
1049 // the empty string, let cue's region identifier be the empty string.
1050 if (m_regionId.isEmpty())
1053 if (m_linePosition != undefinedPosition || m_cueSize != 100 || m_writingDirection != Horizontal)
1054 m_regionId = emptyString();
1057 CSSValueID VTTCue::getCSSAlignment() const
1059 return displayAlignmentMap[m_cueAlignment];
1062 CSSValueID VTTCue::getCSSWritingDirection() const
1064 return m_displayDirection;
1067 CSSValueID VTTCue::getCSSWritingMode() const
1069 return displayWritingModeMap[m_writingDirection];
1072 int VTTCue::getCSSSize() const
1074 ASSERT(m_displaySize != undefinedSize);
1075 return m_displaySize;
1078 std::pair<double, double> VTTCue::getCSSPosition() const
1081 return getPositionCoordinates();
1083 return m_displayPosition;
1086 ExecutionContext* VTTCue::executionContext() const
1088 ASSERT(m_cueBackgroundBox);
1089 return m_cueBackgroundBox->executionContext();
1092 Document& VTTCue::document() const
1094 ASSERT(m_cueBackgroundBox);
1095 return m_cueBackgroundBox->document();
1098 void VTTCue::trace(Visitor* visitor)
1100 visitor->trace(m_vttNodeTree);
1101 visitor->trace(m_cueBackgroundBox);
1102 visitor->trace(m_displayTree);
1103 TextTrackCue::trace(visitor);
1106 } // namespace blink