File: MediaControlElements.cpp

package info (click to toggle)
chromium-browser 57.0.2987.98-1~deb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 2,637,852 kB
  • ctags: 2,544,394
  • sloc: cpp: 12,815,961; ansic: 3,676,222; python: 1,147,112; asm: 526,608; java: 523,212; xml: 286,794; perl: 92,654; sh: 86,408; objc: 73,271; makefile: 27,698; cs: 18,487; yacc: 13,031; tcl: 12,957; pascal: 4,875; ml: 4,716; lex: 3,904; sql: 3,862; ruby: 1,982; lisp: 1,508; php: 1,368; exp: 404; awk: 325; csh: 117; jsp: 39; sed: 37
file content (1047 lines) | stat: -rw-r--r-- 36,620 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
/*
 * Copyright (C) 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
 * Copyright (C) 2012 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "core/html/shadow/MediaControlElements.h"

#include "bindings/core/v8/ExceptionState.h"
#include "core/InputTypeNames.h"
#include "core/dom/ClientRect.h"
#include "core/dom/Text.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/events/MouseEvent.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/html/HTMLAnchorElement.h"
#include "core/html/HTMLLabelElement.h"
#include "core/html/HTMLMediaSource.h"
#include "core/html/HTMLSpanElement.h"
#include "core/html/HTMLVideoElement.h"
#include "core/html/TimeRanges.h"
#include "core/html/shadow/MediaControls.h"
#include "core/html/track/TextTrackList.h"
#include "core/input/EventHandler.h"
#include "core/layout/api/LayoutSliderItem.h"
#include "core/page/Page.h"
#include "platform/EventDispatchForbiddenScope.h"
#include "platform/Histogram.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/text/PlatformLocale.h"
#include "public/platform/Platform.h"
#include "public/platform/UserMetricsAction.h"

namespace blink {

using namespace HTMLNames;

namespace {

// This is the duration from mediaControls.css
const double fadeOutDuration = 0.3;

const QualifiedName& trackIndexAttrName() {
  // Save the track index in an attribute to avoid holding a pointer to the text
  // track.
  DEFINE_STATIC_LOCAL(QualifiedName, trackIndexAttr,
                      (nullAtom, "data-track-index", nullAtom));
  return trackIndexAttr;
}

// When specified as trackIndex, disable text tracks.
const int trackIndexOffValue = -1;

bool isUserInteractionEvent(Event* event) {
  const AtomicString& type = event->type();
  return type == EventTypeNames::mousedown || type == EventTypeNames::mouseup ||
         type == EventTypeNames::click || type == EventTypeNames::dblclick ||
         event->isKeyboardEvent() || event->isTouchEvent();
}

// Sliders (the volume control and timeline) need to capture some additional
// events used when dragging the thumb.
bool isUserInteractionEventForSlider(Event* event, LayoutObject* layoutObject) {
  // It is unclear if this can be converted to isUserInteractionEvent(), since
  // mouse* events seem to be eaten during a drag anyway.  crbug.com/516416 .
  if (isUserInteractionEvent(event))
    return true;

  // Some events are only captured during a slider drag.
  LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject));
  if (!slider.isNull() && !slider.inDragMode())
    return false;

  const AtomicString& type = event->type();
  return type == EventTypeNames::mouseover ||
         type == EventTypeNames::mouseout ||
         type == EventTypeNames::mousemove ||
         type == EventTypeNames::pointerover ||
         type == EventTypeNames::pointerout ||
         type == EventTypeNames::pointermove;
}

Element* elementFromCenter(Element& element) {
  ClientRect* clientRect = element.getBoundingClientRect();
  int centerX =
      static_cast<int>((clientRect->left() + clientRect->right()) / 2);
  int centerY =
      static_cast<int>((clientRect->top() + clientRect->bottom()) / 2);

  return element.document().elementFromPoint(centerX, centerY);
}

bool hasDuplicateLabel(TextTrack* currentTrack) {
  DCHECK(currentTrack);
  TextTrackList* trackList = currentTrack->trackList();
  // The runtime of this method is quadratic but since there are usually very
  // few text tracks it won't affect the performance much.
  String currentTrackLabel = currentTrack->label();
  for (unsigned i = 0; i < trackList->length(); i++) {
    TextTrack* track = trackList->anonymousIndexedGetter(i);
    if (currentTrack != track && currentTrackLabel == track->label())
      return true;
  }
  return false;
}

}  // anonymous namespace

MediaControlPanelElement::MediaControlPanelElement(MediaControls& mediaControls)
    : MediaControlDivElement(mediaControls, MediaControlsPanel),
      m_isDisplayed(false),
      m_opaque(true),
      m_transitionTimer(this, &MediaControlPanelElement::transitionTimerFired) {
}

MediaControlPanelElement* MediaControlPanelElement::create(
    MediaControls& mediaControls) {
  MediaControlPanelElement* panel = new MediaControlPanelElement(mediaControls);
  panel->setShadowPseudoId(AtomicString("-webkit-media-controls-panel"));
  return panel;
}

void MediaControlPanelElement::defaultEventHandler(Event* event) {
  // Suppress the media element activation behavior (toggle play/pause) when
  // any part of the control panel is clicked.
  if (event->type() == EventTypeNames::click) {
    event->setDefaultHandled();
    return;
  }
  HTMLDivElement::defaultEventHandler(event);
}

void MediaControlPanelElement::startTimer() {
  stopTimer();

  // The timer is required to set the property display:'none' on the panel,
  // such that captions are correctly displayed at the bottom of the video
  // at the end of the fadeout transition.
  // FIXME: Racing a transition with a setTimeout like this is wrong.
  m_transitionTimer.startOneShot(fadeOutDuration, BLINK_FROM_HERE);
}

void MediaControlPanelElement::stopTimer() {
  m_transitionTimer.stop();
}

void MediaControlPanelElement::transitionTimerFired(TimerBase*) {
  if (!m_opaque)
    setIsWanted(false);

  stopTimer();
}

void MediaControlPanelElement::didBecomeVisible() {
  DCHECK(m_isDisplayed && m_opaque);
  mediaElement().mediaControlsDidBecomeVisible();
}

bool MediaControlPanelElement::isOpaque() const {
  return m_opaque;
}

void MediaControlPanelElement::makeOpaque() {
  if (m_opaque)
    return;

  setInlineStyleProperty(CSSPropertyOpacity, 1.0,
                         CSSPrimitiveValue::UnitType::Number);
  m_opaque = true;

  if (m_isDisplayed) {
    setIsWanted(true);
    didBecomeVisible();
  }
}

void MediaControlPanelElement::makeTransparent() {
  if (!m_opaque)
    return;

  setInlineStyleProperty(CSSPropertyOpacity, 0.0,
                         CSSPrimitiveValue::UnitType::Number);

  m_opaque = false;
  startTimer();
}

void MediaControlPanelElement::setIsDisplayed(bool isDisplayed) {
  if (m_isDisplayed == isDisplayed)
    return;

  m_isDisplayed = isDisplayed;
  if (m_isDisplayed && m_opaque)
    didBecomeVisible();
}

bool MediaControlPanelElement::keepEventInNode(Event* event) {
  return isUserInteractionEvent(event);
}

// ----------------------------

MediaControlPanelEnclosureElement::MediaControlPanelEnclosureElement(
    MediaControls& mediaControls)
    // Mapping onto same MediaControlElementType as panel element, since it has
    // similar properties.
    : MediaControlDivElement(mediaControls, MediaControlsPanel) {}

MediaControlPanelEnclosureElement* MediaControlPanelEnclosureElement::create(
    MediaControls& mediaControls) {
  MediaControlPanelEnclosureElement* enclosure =
      new MediaControlPanelEnclosureElement(mediaControls);
  enclosure->setShadowPseudoId(
      AtomicString("-webkit-media-controls-enclosure"));
  return enclosure;
}

// ----------------------------

MediaControlOverlayEnclosureElement::MediaControlOverlayEnclosureElement(
    MediaControls& mediaControls)
    // Mapping onto same MediaControlElementType as panel element, since it has
    // similar properties.
    : MediaControlDivElement(mediaControls, MediaControlsPanel) {}

MediaControlOverlayEnclosureElement*
MediaControlOverlayEnclosureElement::create(MediaControls& mediaControls) {
  MediaControlOverlayEnclosureElement* enclosure =
      new MediaControlOverlayEnclosureElement(mediaControls);
  enclosure->setShadowPseudoId(
      AtomicString("-webkit-media-controls-overlay-enclosure"));
  return enclosure;
}

EventDispatchHandlingState*
MediaControlOverlayEnclosureElement::preDispatchEventHandler(Event* event) {
  // When the media element is clicked or touched we want to make the overlay
  // cast button visible (if the other requirements are right) even if
  // JavaScript is doing its own handling of the event.  Doing it in
  // preDispatchEventHandler prevents any interference from JavaScript.
  // Note that we can't simply test for click, since JS handling of touch events
  // can prevent their translation to click events.
  if (event && (event->type() == EventTypeNames::click ||
                event->type() == EventTypeNames::touchstart))
    mediaControls().showOverlayCastButtonIfNeeded();
  return MediaControlDivElement::preDispatchEventHandler(event);
}

// ----------------------------

MediaControlMuteButtonElement::MediaControlMuteButtonElement(
    MediaControls& mediaControls)
    : MediaControlInputElement(mediaControls, MediaMuteButton) {}

MediaControlMuteButtonElement* MediaControlMuteButtonElement::create(
    MediaControls& mediaControls) {
  MediaControlMuteButtonElement* button =
      new MediaControlMuteButtonElement(mediaControls);
  button->ensureUserAgentShadowRoot();
  button->setType(InputTypeNames::button);
  button->setShadowPseudoId(AtomicString("-webkit-media-controls-mute-button"));
  return button;
}

void MediaControlMuteButtonElement::defaultEventHandler(Event* event) {
  if (event->type() == EventTypeNames::click) {
    if (mediaElement().muted())
      Platform::current()->recordAction(
          UserMetricsAction("Media.Controls.Unmute"));
    else
      Platform::current()->recordAction(
          UserMetricsAction("Media.Controls.Mute"));

    mediaElement().setMuted(!mediaElement().muted());
    event->setDefaultHandled();
  }

  MediaControlInputElement::defaultEventHandler(event);
}

void MediaControlMuteButtonElement::updateDisplayType() {
  // TODO(mlamouri): checking for volume == 0 because the mute button will look
  // 'muted' when the volume is 0 even if the element is not muted. This allows
  // the painting and the display type to actually match.
  setDisplayType((mediaElement().muted() || mediaElement().volume() == 0)
                     ? MediaUnMuteButton
                     : MediaMuteButton);
  updateOverflowString();
}

WebLocalizedString::Name
MediaControlMuteButtonElement::getOverflowStringName() {
  if (mediaElement().muted())
    return WebLocalizedString::OverflowMenuUnmute;
  return WebLocalizedString::OverflowMenuMute;
}

// ----------------------------

MediaControlPlayButtonElement::MediaControlPlayButtonElement(
    MediaControls& mediaControls)
    : MediaControlInputElement(mediaControls, MediaPlayButton) {}

MediaControlPlayButtonElement* MediaControlPlayButtonElement::create(
    MediaControls& mediaControls) {
  MediaControlPlayButtonElement* button =
      new MediaControlPlayButtonElement(mediaControls);
  button->ensureUserAgentShadowRoot();
  button->setType(InputTypeNames::button);
  button->setShadowPseudoId(AtomicString("-webkit-media-controls-play-button"));
  return button;
}

void MediaControlPlayButtonElement::defaultEventHandler(Event* event) {
  if (event->type() == EventTypeNames::click) {
    if (mediaElement().paused())
      Platform::current()->recordAction(
          UserMetricsAction("Media.Controls.Play"));
    else
      Platform::current()->recordAction(
          UserMetricsAction("Media.Controls.Pause"));

    // Allow play attempts for plain src= media to force a reload in the error
    // state. This allows potential recovery for transient network and decoder
    // resource issues.
    const String& url = mediaElement().currentSrc().getString();
    if (mediaElement().error() && !HTMLMediaElement::isMediaStreamURL(url) &&
        !HTMLMediaSource::lookup(url))
      mediaElement().load();

    mediaElement().togglePlayState();
    updateDisplayType();
    event->setDefaultHandled();
  }
  MediaControlInputElement::defaultEventHandler(event);
}

void MediaControlPlayButtonElement::updateDisplayType() {
  setDisplayType(mediaElement().paused() ? MediaPlayButton : MediaPauseButton);
  updateOverflowString();
}

WebLocalizedString::Name
MediaControlPlayButtonElement::getOverflowStringName() {
  if (mediaElement().paused())
    return WebLocalizedString::OverflowMenuPlay;
  return WebLocalizedString::OverflowMenuPause;
}

// ----------------------------

MediaControlOverlayPlayButtonElement::MediaControlOverlayPlayButtonElement(
    MediaControls& mediaControls)
    : MediaControlInputElement(mediaControls, MediaOverlayPlayButton) {}

MediaControlOverlayPlayButtonElement*
MediaControlOverlayPlayButtonElement::create(MediaControls& mediaControls) {
  MediaControlOverlayPlayButtonElement* button =
      new MediaControlOverlayPlayButtonElement(mediaControls);
  button->ensureUserAgentShadowRoot();
  button->setType(InputTypeNames::button);
  button->setShadowPseudoId(
      AtomicString("-webkit-media-controls-overlay-play-button"));
  return button;
}

void MediaControlOverlayPlayButtonElement::defaultEventHandler(Event* event) {
  if (event->type() == EventTypeNames::click && mediaElement().paused()) {
    Platform::current()->recordAction(
        UserMetricsAction("Media.Controls.PlayOverlay"));
    mediaElement().play();
    updateDisplayType();
    event->setDefaultHandled();
  }
}

void MediaControlOverlayPlayButtonElement::updateDisplayType() {
  setIsWanted(mediaElement().shouldShowControls() && mediaElement().paused());
}

bool MediaControlOverlayPlayButtonElement::keepEventInNode(Event* event) {
  return isUserInteractionEvent(event);
}

// ----------------------------

MediaControlToggleClosedCaptionsButtonElement::
    MediaControlToggleClosedCaptionsButtonElement(MediaControls& mediaControls)
    : MediaControlInputElement(mediaControls, MediaShowClosedCaptionsButton) {}

MediaControlToggleClosedCaptionsButtonElement*
MediaControlToggleClosedCaptionsButtonElement::create(
    MediaControls& mediaControls) {
  MediaControlToggleClosedCaptionsButtonElement* button =
      new MediaControlToggleClosedCaptionsButtonElement(mediaControls);
  button->ensureUserAgentShadowRoot();
  button->setType(InputTypeNames::button);
  button->setShadowPseudoId(
      AtomicString("-webkit-media-controls-toggle-closed-captions-button"));
  button->setIsWanted(false);
  return button;
}

void MediaControlToggleClosedCaptionsButtonElement::updateDisplayType() {
  bool captionsVisible = mediaElement().textTracksVisible();
  setDisplayType(captionsVisible ? MediaHideClosedCaptionsButton
                                 : MediaShowClosedCaptionsButton);
}

void MediaControlToggleClosedCaptionsButtonElement::defaultEventHandler(
    Event* event) {
  if (event->type() == EventTypeNames::click) {
    if (mediaElement().textTracks()->length() == 1) {
      // If only one track exists, toggle it on/off
      if (mediaElement().textTracks()->hasShowingTracks()) {
        mediaControls().disableShowingTextTracks();
      } else {
        mediaControls().showTextTrackAtIndex(0);
      }
    } else {
      mediaControls().toggleTextTrackList();
    }

    updateDisplayType();
    event->setDefaultHandled();
  }

  MediaControlInputElement::defaultEventHandler(event);
}

WebLocalizedString::Name
MediaControlToggleClosedCaptionsButtonElement::getOverflowStringName() {
  return WebLocalizedString::OverflowMenuCaptions;
}

// ----------------------------

MediaControlTextTrackListElement::MediaControlTextTrackListElement(
    MediaControls& mediaControls)
    : MediaControlDivElement(mediaControls, MediaTextTrackList) {}

MediaControlTextTrackListElement* MediaControlTextTrackListElement::create(
    MediaControls& mediaControls) {
  MediaControlTextTrackListElement* element =
      new MediaControlTextTrackListElement(mediaControls);
  element->setShadowPseudoId(
      AtomicString("-internal-media-controls-text-track-list"));
  element->setIsWanted(false);
  return element;
}

void MediaControlTextTrackListElement::defaultEventHandler(Event* event) {
  if (event->type() == EventTypeNames::change) {
    // Identify which input element was selected and set track to showing
    Node* target = event->target()->toNode();
    if (!target || !target->isElementNode())
      return;

    mediaControls().disableShowingTextTracks();
    int trackIndex =
        toElement(target)->getIntegralAttribute(trackIndexAttrName());
    if (trackIndex != trackIndexOffValue) {
      DCHECK_GE(trackIndex, 0);
      mediaControls().showTextTrackAtIndex(trackIndex);
      mediaElement().disableAutomaticTextTrackSelection();
    }

    event->setDefaultHandled();
  }
  MediaControlDivElement::defaultEventHandler(event);
}

void MediaControlTextTrackListElement::setVisible(bool visible) {
  if (visible) {
    setIsWanted(true);
    refreshTextTrackListMenu();
  } else {
    setIsWanted(false);
  }
}

String MediaControlTextTrackListElement::getTextTrackLabel(TextTrack* track) {
  if (!track) {
    return mediaElement().locale().queryString(
        WebLocalizedString::TextTracksOff);
  }

  String trackLabel = track->label();

  if (trackLabel.isEmpty())
    trackLabel = track->language();

  if (trackLabel.isEmpty()) {
    trackLabel = String(mediaElement().locale().queryString(
        WebLocalizedString::TextTracksNoLabel,
        String::number(track->trackIndex() + 1)));
  }

  return trackLabel;
}

// TextTrack parameter when passed in as a nullptr, creates the "Off" list item
// in the track list.
Element* MediaControlTextTrackListElement::createTextTrackListItem(
    TextTrack* track) {
  int trackIndex = track ? track->trackIndex() : trackIndexOffValue;
  HTMLLabelElement* trackItem = HTMLLabelElement::create(document());
  trackItem->setShadowPseudoId(
      AtomicString("-internal-media-controls-text-track-list-item"));
  HTMLInputElement* trackItemInput =
      HTMLInputElement::create(document(), false);
  trackItemInput->setShadowPseudoId(
      AtomicString("-internal-media-controls-text-track-list-item-input"));
  trackItemInput->setType(InputTypeNames::checkbox);
  trackItemInput->setIntegralAttribute(trackIndexAttrName(), trackIndex);
  if (!mediaElement().textTracksVisible()) {
    if (!track)
      trackItemInput->setChecked(true);
  } else {
    // If there are multiple text tracks set to showing, they must all have
    // checkmarks displayed.
    if (track && track->mode() == TextTrack::showingKeyword())
      trackItemInput->setChecked(true);
  }

  trackItem->appendChild(trackItemInput);
  String trackLabel = getTextTrackLabel(track);
  trackItem->appendChild(Text::create(document(), trackLabel));
  // Add a track kind marker icon if there are multiple tracks with the same
  // label or if the track has no label.
  if (track && (track->label().isEmpty() || hasDuplicateLabel(track))) {
    HTMLSpanElement* trackKindMarker = HTMLSpanElement::create(document());
    if (track->kind() == track->captionsKeyword()) {
      trackKindMarker->setShadowPseudoId(AtomicString(
          "-internal-media-controls-text-track-list-kind-captions"));
    } else {
      DCHECK_EQ(track->kind(), track->subtitlesKeyword());
      trackKindMarker->setShadowPseudoId(AtomicString(
          "-internal-media-controls-text-track-list-kind-subtitles"));
    }
    trackItem->appendChild(trackKindMarker);
  }
  return trackItem;
}

void MediaControlTextTrackListElement::refreshTextTrackListMenu() {
  if (!mediaElement().hasClosedCaptions() ||
      !mediaElement().textTracksAreReady())
    return;

  EventDispatchForbiddenScope::AllowUserAgentEvents allowEvents;
  removeChildren(OmitSubtreeModifiedEvent);

  // Construct a menu for subtitles and captions.  Pass in a nullptr to
  // createTextTrackListItem to create the "Off" track item.
  appendChild(createTextTrackListItem(nullptr));

  TextTrackList* trackList = mediaElement().textTracks();
  for (unsigned i = 0; i < trackList->length(); i++) {
    TextTrack* track = trackList->anonymousIndexedGetter(i);
    if (!track->canBeRendered())
      continue;
    appendChild(createTextTrackListItem(track));
  }
}

// ----------------------------
MediaControlOverflowMenuButtonElement::MediaControlOverflowMenuButtonElement(
    MediaControls& mediaControls)
    : MediaControlInputElement(mediaControls, MediaOverflowButton) {}

MediaControlOverflowMenuButtonElement*
MediaControlOverflowMenuButtonElement::create(MediaControls& mediaControls) {
  MediaControlOverflowMenuButtonElement* button =
      new MediaControlOverflowMenuButtonElement(mediaControls);
  button->ensureUserAgentShadowRoot();
  button->setType(InputTypeNames::button);
  button->setShadowPseudoId(
      AtomicString("-internal-media-controls-overflow-button"));
  button->setIsWanted(false);
  return button;
}

void MediaControlOverflowMenuButtonElement::defaultEventHandler(Event* event) {
  if (event->type() == EventTypeNames::click) {
    if (mediaControls().overflowMenuVisible())
      Platform::current()->recordAction(
          UserMetricsAction("Media.Controls.OverflowClose"));
    else
      Platform::current()->recordAction(
          UserMetricsAction("Media.Controls.OverflowOpen"));

    mediaControls().toggleOverflowMenu();
    event->setDefaultHandled();
  }

  MediaControlInputElement::defaultEventHandler(event);
}

// ----------------------------
MediaControlOverflowMenuListElement::MediaControlOverflowMenuListElement(
    MediaControls& mediaControls)
    : MediaControlDivElement(mediaControls, MediaOverflowList) {}

MediaControlOverflowMenuListElement*
MediaControlOverflowMenuListElement::create(MediaControls& mediaControls) {
  MediaControlOverflowMenuListElement* element =
      new MediaControlOverflowMenuListElement(mediaControls);
  element->setIsWanted(false);
  element->setShadowPseudoId(
      AtomicString("-internal-media-controls-overflow-menu-list"));
  return element;
}

void MediaControlOverflowMenuListElement::defaultEventHandler(Event* event) {
  if (event->type() == EventTypeNames::click)
    event->setDefaultHandled();

  MediaControlDivElement::defaultEventHandler(event);
}

// ----------------------------
MediaControlDownloadButtonElement::MediaControlDownloadButtonElement(
    MediaControls& mediaControls)
    : MediaControlInputElement(mediaControls, MediaDownloadButton) {}

MediaControlDownloadButtonElement* MediaControlDownloadButtonElement::create(
    MediaControls& mediaControls) {
  MediaControlDownloadButtonElement* button =
      new MediaControlDownloadButtonElement(mediaControls);
  button->ensureUserAgentShadowRoot();
  button->setType(InputTypeNames::button);
  button->setShadowPseudoId(
      AtomicString("-internal-media-controls-download-button"));
  button->setIsWanted(false);
  return button;
}

WebLocalizedString::Name
MediaControlDownloadButtonElement::getOverflowStringName() {
  return WebLocalizedString::OverflowMenuDownload;
}

bool MediaControlDownloadButtonElement::shouldDisplayDownloadButton() {
  const KURL& url = mediaElement().currentSrc();

  // Check page settings to see if download is disabled.
  if (document().page() && document().page()->settings().getHideDownloadUI())
    return false;

  // URLs that lead to nowhere are ignored.
  if (url.isNull() || url.isEmpty())
    return false;

  // Local files and blobs should not have a download button.
  if (url.isLocalFile() || url.protocolIs("blob"))
    return false;

  // MediaStream can't be downloaded.
  if (HTMLMediaElement::isMediaStreamURL(url.getString()))
    return false;

  // MediaSource can't be downloaded.
  if (HTMLMediaSource::lookup(url))
    return false;

  // HLS stream shouldn't have a download button.
  if (HTMLMediaElement::isHLSURL(url))
    return false;

  return true;
}

void MediaControlDownloadButtonElement::defaultEventHandler(Event* event) {
  const KURL& url = mediaElement().currentSrc();
  if (event->type() == EventTypeNames::click &&
      !(url.isNull() || url.isEmpty())) {
    Platform::current()->recordAction(
        UserMetricsAction("Media.Controls.Download"));
    if (!m_anchor) {
      HTMLAnchorElement* anchor = HTMLAnchorElement::create(document());
      anchor->setAttribute(HTMLNames::downloadAttr, "");
      m_anchor = anchor;
    }
    m_anchor->setURL(url);
    m_anchor->dispatchSimulatedClick(event);
  }
  MediaControlInputElement::defaultEventHandler(event);
}

DEFINE_TRACE(MediaControlDownloadButtonElement) {
  visitor->trace(m_anchor);
  MediaControlInputElement::trace(visitor);
}

// ----------------------------

MediaControlTimelineElement::MediaControlTimelineElement(
    MediaControls& mediaControls)
    : MediaControlInputElement(mediaControls, MediaSlider) {}

MediaControlTimelineElement* MediaControlTimelineElement::create(
    MediaControls& mediaControls) {
  MediaControlTimelineElement* timeline =
      new MediaControlTimelineElement(mediaControls);
  timeline->ensureUserAgentShadowRoot();
  timeline->setType(InputTypeNames::range);
  timeline->setAttribute(stepAttr, "any");
  timeline->setShadowPseudoId(AtomicString("-webkit-media-controls-timeline"));
  return timeline;
}

void MediaControlTimelineElement::defaultEventHandler(Event* event) {
  if (event->isMouseEvent() &&
      toMouseEvent(event)->button() !=
          static_cast<short>(WebPointerProperties::Button::Left))
    return;

  if (!isConnected() || !document().isActive())
    return;

  if (event->type() == EventTypeNames::mousedown) {
    Platform::current()->recordAction(
        UserMetricsAction("Media.Controls.ScrubbingBegin"));
    mediaControls().beginScrubbing();
  }

  if (event->type() == EventTypeNames::mouseup) {
    Platform::current()->recordAction(
        UserMetricsAction("Media.Controls.ScrubbingEnd"));
    mediaControls().endScrubbing();
  }

  MediaControlInputElement::defaultEventHandler(event);

  if (event->type() != EventTypeNames::input)
    return;

  double time = value().toDouble();

  // FIXME: This will need to take the timeline offset into consideration
  // once that concept is supported, see https://crbug.com/312699
  if (mediaElement().seekable()->contain(time))
    mediaElement().setCurrentTime(time);

  LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject()));
  if (!slider.isNull() && slider.inDragMode())
    mediaControls().updateCurrentTimeDisplay();
}

bool MediaControlTimelineElement::willRespondToMouseClickEvents() {
  return isConnected() && document().isActive();
}

void MediaControlTimelineElement::setPosition(double currentTime) {
  setValue(String::number(currentTime));

  if (LayoutObject* layoutObject = this->layoutObject())
    layoutObject->setShouldDoFullPaintInvalidation();
}

void MediaControlTimelineElement::setDuration(double duration) {
  setFloatingPointAttribute(maxAttr, std::isfinite(duration) ? duration : 0);

  if (LayoutObject* layoutObject = this->layoutObject())
    layoutObject->setShouldDoFullPaintInvalidation();
}

bool MediaControlTimelineElement::keepEventInNode(Event* event) {
  return isUserInteractionEventForSlider(event, layoutObject());
}

// ----------------------------

MediaControlVolumeSliderElement::MediaControlVolumeSliderElement(
    MediaControls& mediaControls)
    : MediaControlInputElement(mediaControls, MediaVolumeSlider) {}

MediaControlVolumeSliderElement* MediaControlVolumeSliderElement::create(
    MediaControls& mediaControls) {
  MediaControlVolumeSliderElement* slider =
      new MediaControlVolumeSliderElement(mediaControls);
  slider->ensureUserAgentShadowRoot();
  slider->setType(InputTypeNames::range);
  slider->setAttribute(stepAttr, "any");
  slider->setAttribute(maxAttr, "1");
  slider->setShadowPseudoId(
      AtomicString("-webkit-media-controls-volume-slider"));
  return slider;
}

void MediaControlVolumeSliderElement::defaultEventHandler(Event* event) {
  if (!isConnected() || !document().isActive())
    return;

  MediaControlInputElement::defaultEventHandler(event);

  if (event->type() == EventTypeNames::mousedown)
    Platform::current()->recordAction(
        UserMetricsAction("Media.Controls.VolumeChangeBegin"));

  if (event->type() == EventTypeNames::mouseup)
    Platform::current()->recordAction(
        UserMetricsAction("Media.Controls.VolumeChangeEnd"));

  if (event->type() == EventTypeNames::input) {
    double volume = value().toDouble();
    mediaElement().setVolume(volume);
    mediaElement().setMuted(false);
  }
}

bool MediaControlVolumeSliderElement::willRespondToMouseMoveEvents() {
  if (!isConnected() || !document().isActive())
    return false;

  return MediaControlInputElement::willRespondToMouseMoveEvents();
}

bool MediaControlVolumeSliderElement::willRespondToMouseClickEvents() {
  if (!isConnected() || !document().isActive())
    return false;

  return MediaControlInputElement::willRespondToMouseClickEvents();
}

void MediaControlVolumeSliderElement::setVolume(double volume) {
  if (value().toDouble() == volume)
    return;

  setValue(String::number(volume));
  if (LayoutObject* layoutObject = this->layoutObject())
    layoutObject->setShouldDoFullPaintInvalidation();
}

bool MediaControlVolumeSliderElement::keepEventInNode(Event* event) {
  return isUserInteractionEventForSlider(event, layoutObject());
}

// ----------------------------

MediaControlFullscreenButtonElement::MediaControlFullscreenButtonElement(
    MediaControls& mediaControls)
    : MediaControlInputElement(mediaControls, MediaEnterFullscreenButton) {}

MediaControlFullscreenButtonElement*
MediaControlFullscreenButtonElement::create(MediaControls& mediaControls) {
  MediaControlFullscreenButtonElement* button =
      new MediaControlFullscreenButtonElement(mediaControls);
  button->ensureUserAgentShadowRoot();
  button->setType(InputTypeNames::button);
  button->setShadowPseudoId(
      AtomicString("-webkit-media-controls-fullscreen-button"));
  button->setIsFullscreen(mediaControls.mediaElement().isFullscreen());
  button->setIsWanted(false);
  return button;
}

void MediaControlFullscreenButtonElement::defaultEventHandler(Event* event) {
  if (event->type() == EventTypeNames::click) {
    if (mediaElement().isFullscreen()) {
      Platform::current()->recordAction(
          UserMetricsAction("Media.Controls.ExitFullscreen"));
      mediaControls().exitFullscreen();
    } else {
      Platform::current()->recordAction(
          UserMetricsAction("Media.Controls.EnterFullscreen"));
      mediaControls().enterFullscreen();
    }
    event->setDefaultHandled();
  }
  MediaControlInputElement::defaultEventHandler(event);
}

void MediaControlFullscreenButtonElement::setIsFullscreen(bool isFullscreen) {
  setDisplayType(isFullscreen ? MediaExitFullscreenButton
                              : MediaEnterFullscreenButton);
}

WebLocalizedString::Name
MediaControlFullscreenButtonElement::getOverflowStringName() {
  if (mediaElement().isFullscreen())
    return WebLocalizedString::OverflowMenuExitFullscreen;
  return WebLocalizedString::OverflowMenuEnterFullscreen;
}

// ----------------------------

MediaControlCastButtonElement::MediaControlCastButtonElement(
    MediaControls& mediaControls,
    bool isOverlayButton)
    : MediaControlInputElement(mediaControls, MediaCastOnButton),
      m_isOverlayButton(isOverlayButton) {
  if (m_isOverlayButton)
    recordMetrics(CastOverlayMetrics::Created);
  setIsPlayingRemotely(false);
}

MediaControlCastButtonElement* MediaControlCastButtonElement::create(
    MediaControls& mediaControls,
    bool isOverlayButton) {
  MediaControlCastButtonElement* button =
      new MediaControlCastButtonElement(mediaControls, isOverlayButton);
  button->ensureUserAgentShadowRoot();
  button->setType(InputTypeNames::button);
  return button;
}

void MediaControlCastButtonElement::defaultEventHandler(Event* event) {
  if (event->type() == EventTypeNames::click) {
    if (m_isOverlayButton)
      Platform::current()->recordAction(
          UserMetricsAction("Media.Controls.CastOverlay"));
    else
      Platform::current()->recordAction(
          UserMetricsAction("Media.Controls.Cast"));

    if (m_isOverlayButton && !m_clickUseCounted) {
      m_clickUseCounted = true;
      recordMetrics(CastOverlayMetrics::Clicked);
    }
    if (mediaElement().isPlayingRemotely()) {
      mediaElement().requestRemotePlaybackControl();
    } else {
      mediaElement().requestRemotePlayback();
    }
  }
  MediaControlInputElement::defaultEventHandler(event);
}

const AtomicString& MediaControlCastButtonElement::shadowPseudoId() const {
  DEFINE_STATIC_LOCAL(AtomicString, id_nonOverlay,
                      ("-internal-media-controls-cast-button"));
  DEFINE_STATIC_LOCAL(AtomicString, id_overlay,
                      ("-internal-media-controls-overlay-cast-button"));
  return m_isOverlayButton ? id_overlay : id_nonOverlay;
}

void MediaControlCastButtonElement::setIsPlayingRemotely(
    bool isPlayingRemotely) {
  if (isPlayingRemotely) {
    if (m_isOverlayButton) {
      setDisplayType(MediaOverlayCastOnButton);
    } else {
      setDisplayType(MediaCastOnButton);
    }
  } else {
    if (m_isOverlayButton) {
      setDisplayType(MediaOverlayCastOffButton);
    } else {
      setDisplayType(MediaCastOffButton);
    }
  }
  updateOverflowString();
}

WebLocalizedString::Name
MediaControlCastButtonElement::getOverflowStringName() {
  if (mediaElement().isPlayingRemotely())
    return WebLocalizedString::OverflowMenuStopCast;
  return WebLocalizedString::OverflowMenuCast;
}

void MediaControlCastButtonElement::tryShowOverlay() {
  DCHECK(m_isOverlayButton);

  setIsWanted(true);
  if (elementFromCenter(*this) != &mediaElement()) {
    setIsWanted(false);
    return;
  }

  DCHECK(isWanted());
  if (!m_showUseCounted) {
    m_showUseCounted = true;
    recordMetrics(CastOverlayMetrics::Shown);
  }
}

bool MediaControlCastButtonElement::keepEventInNode(Event* event) {
  return isUserInteractionEvent(event);
}

void MediaControlCastButtonElement::recordMetrics(CastOverlayMetrics metric) {
  DCHECK(m_isOverlayButton);
  DEFINE_STATIC_LOCAL(
      EnumerationHistogram, overlayHistogram,
      ("Cast.Sender.Overlay", static_cast<int>(CastOverlayMetrics::Count)));
  overlayHistogram.count(static_cast<int>(metric));
}

// ----------------------------

MediaControlTimeRemainingDisplayElement::
    MediaControlTimeRemainingDisplayElement(MediaControls& mediaControls)
    : MediaControlTimeDisplayElement(mediaControls, MediaTimeRemainingDisplay) {
}

MediaControlTimeRemainingDisplayElement*
MediaControlTimeRemainingDisplayElement::create(MediaControls& mediaControls) {
  MediaControlTimeRemainingDisplayElement* element =
      new MediaControlTimeRemainingDisplayElement(mediaControls);
  element->setShadowPseudoId(
      AtomicString("-webkit-media-controls-time-remaining-display"));
  return element;
}

// ----------------------------

MediaControlCurrentTimeDisplayElement::MediaControlCurrentTimeDisplayElement(
    MediaControls& mediaControls)
    : MediaControlTimeDisplayElement(mediaControls, MediaCurrentTimeDisplay) {}

MediaControlCurrentTimeDisplayElement*
MediaControlCurrentTimeDisplayElement::create(MediaControls& mediaControls) {
  MediaControlCurrentTimeDisplayElement* element =
      new MediaControlCurrentTimeDisplayElement(mediaControls);
  element->setShadowPseudoId(
      AtomicString("-webkit-media-controls-current-time-display"));
  return element;
}

}  // namespace blink