Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(74)

Side by Side Diff: Source/core/html/track/vtt/VTTCue.cpp

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

Powered by Google App Engine
This is Rietveld 408576698