summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/modules/media_controls/touchless/media_controls_touchless_impl.cc
blob: fd6b6b7719a20b17b045491908f44d4deb8b415e (plain)
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
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/modules/media_controls/touchless/media_controls_touchless_impl.h"

#include <algorithm>

#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_screen_info.h"
#include "third_party/blink/renderer/core/dom/dom_token_list.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/events/keyboard_event.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen.h"
#include "third_party/blink/renderer/core/html/media/html_media_element.h"
#include "third_party/blink/renderer/core/html/media/html_video_element.h"
#include "third_party/blink/renderer/core/html/track/text_track.h"
#include "third_party/blink/renderer/core/html/track/text_track_list.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_elements_helper.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_shared_helper.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_text_track_manager.h"
#include "third_party/blink/renderer/modules/media_controls/touchless/elements/media_controls_touchless_bottom_container_element.h"
#include "third_party/blink/renderer/modules/media_controls/touchless/elements/media_controls_touchless_overlay_element.h"
#include "third_party/blink/renderer/modules/media_controls/touchless/elements/media_controls_touchless_volume_container_element.h"
#include "third_party/blink/renderer/modules/media_controls/touchless/media_controls_touchless_media_event_listener.h"
#include "third_party/blink/renderer/modules/media_controls/touchless/media_controls_touchless_resource_loader.h"
#include "third_party/blink/renderer/platform/keyboard_codes.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"

namespace blink {

namespace {

// When specified as trackIndex, disable text tracks.
constexpr int kTrackIndexOffValue = -1;

// Number of seconds to jump when press left/right arrow.
constexpr int kNumberOfSecondsToJumpForTouchless = 10;

// Amount of volume to change when press up/down arrow.
constexpr double kVolumeToChangeForTouchless = 0.05;

const char kInlineCSSClass[] = "inline";

}  // namespace

enum class MediaControlsTouchlessImpl::ArrowDirection {
  kUp,
  kDown,
  kLeft,
  kRight,
};

MediaControlsTouchlessImpl::MediaControlsTouchlessImpl(
    HTMLMediaElement& media_element)
    : HTMLDivElement(media_element.GetDocument()),
      MediaControls(media_element),
      overlay_(nullptr),
      bottom_container_(nullptr),
      media_event_listener_(
          MakeGarbageCollected<MediaControlsTouchlessMediaEventListener>(
              media_element)),
      text_track_manager_(
          MakeGarbageCollected<MediaControlsTextTrackManager>(media_element)),
      orientation_lock_delegate_(nullptr) {
  SetShadowPseudoId(AtomicString("-webkit-media-controls-touchless"));
  media_event_listener_->AddObserver(this);
}

MediaControlsTouchlessImpl* MediaControlsTouchlessImpl::Create(
    HTMLMediaElement& media_element,
    ShadowRoot& shadow_root) {
  MediaControlsTouchlessImpl* controls =
      MakeGarbageCollected<MediaControlsTouchlessImpl>(media_element);
  controls->bottom_container_ =
      MakeGarbageCollected<MediaControlsTouchlessBottomContainerElement>(
          *controls);
  controls->overlay_ =
      MakeGarbageCollected<MediaControlsTouchlessOverlayElement>(*controls);
  controls->volume_container_ =
      MakeGarbageCollected<MediaControlsTouchlessVolumeContainerElement>(
          *controls);

  controls->ParserAppendChild(controls->bottom_container_);
  controls->ParserAppendChild(controls->overlay_);
  controls->ParserAppendChild(controls->volume_container_);

  // Controls start hidden.
  if (!media_element.paused())
    controls->bottom_container_->MakeTransparent();
  controls->overlay_->MakeTransparent();
  controls->volume_container_->MakeTransparent();

  if (RuntimeEnabledFeatures::VideoFullscreenOrientationLockEnabled() &&
      media_element.IsHTMLVideoElement()) {
    // Initialize the orientation lock when going fullscreen feature.
    controls->orientation_lock_delegate_ =
        MakeGarbageCollected<MediaControlsOrientationLockDelegate>(
            ToHTMLVideoElement(media_element));
  }

  MediaControlsTouchlessResourceLoader::
      InjectMediaControlsTouchlessUAStyleSheet();

  if (!media_element.IsFullscreen())
    controls->classList().Add(kInlineCSSClass);

  shadow_root.ParserAppendChild(controls);
  return controls;
}

Node::InsertionNotificationRequest MediaControlsTouchlessImpl::InsertedInto(
    ContainerNode& root) {
  media_event_listener_->Attach();

  if (orientation_lock_delegate_)
    orientation_lock_delegate_->Attach();

  return HTMLDivElement::InsertedInto(root);
}

void MediaControlsTouchlessImpl::RemovedFrom(ContainerNode& insertion_point) {
  HTMLDivElement::RemovedFrom(insertion_point);

  Hide();

  media_event_listener_->Detach();

  if (orientation_lock_delegate_)
    orientation_lock_delegate_->Detach();
}

void MediaControlsTouchlessImpl::MaybeShow() {
  RemoveInlineStyleProperty(CSSPropertyID::kDisplay);
}

void MediaControlsTouchlessImpl::Hide() {
  SetInlineStyleProperty(CSSPropertyID::kDisplay, CSSValueID::kNone);
}

LayoutObject* MediaControlsTouchlessImpl::PanelLayoutObject() {
  return nullptr;
}

LayoutObject* MediaControlsTouchlessImpl::TimelineLayoutObject() {
  return bottom_container_->TimelineLayoutObject();
}

LayoutObject* MediaControlsTouchlessImpl::ButtonPanelLayoutObject() {
  return bottom_container_->TimeDisplayLayoutObject();
}

LayoutObject* MediaControlsTouchlessImpl::ContainerLayoutObject() {
  return GetLayoutObject();
}

MediaControlsTouchlessMediaEventListener&
MediaControlsTouchlessImpl::MediaEventListener() const {
  return *media_event_listener_;
}

void MediaControlsTouchlessImpl::OnFocusIn() {
  if (MediaElement().ShouldShowControls()) {
    bottom_container_->MakeOpaque(!MediaElement().paused());
    overlay_->MakeOpaque(true);
  }
}

void MediaControlsTouchlessImpl::OnPlay() {
  bottom_container_->MakeOpaque(true);
}

void MediaControlsTouchlessImpl::OnPause() {
  bottom_container_->MakeOpaque(false);
}

void MediaControlsTouchlessImpl::OnEnterFullscreen() {
  classList().Remove(kInlineCSSClass);
}

void MediaControlsTouchlessImpl::OnExitFullscreen() {
  classList().Add(kInlineCSSClass);
}

void MediaControlsTouchlessImpl::OnKeyDown(KeyboardEvent* event) {
  bool handled = true;
  switch (event->keyCode()) {
    case VKEY_RETURN:
      volume_container_->MakeTransparent(true);
      overlay_->MakeOpaque(true);
      MediaElement().TogglePlayState();
      break;
    case VKEY_LEFT:
      HandleOrientedArrowPress(OrientArrowPress(ArrowDirection::kLeft));
      break;
    case VKEY_RIGHT:
      HandleOrientedArrowPress(OrientArrowPress(ArrowDirection::kRight));
      break;
    case VKEY_UP:
      HandleOrientedArrowPress(OrientArrowPress(ArrowDirection::kUp));
      break;
    case VKEY_DOWN:
      HandleOrientedArrowPress(OrientArrowPress(ArrowDirection::kDown));
      break;
    default:
      handled = false;
      break;
  }

  if (handled)
    event->SetDefaultHandled();
}

void MediaControlsTouchlessImpl::EnsureMediaControlsMenuHost() {
  if (!media_controls_host_) {
    GetDocument().GetFrame()->GetInterfaceProvider().GetInterface(
        mojo::MakeRequest(&media_controls_host_,
                          GetExecutionContext()->GetTaskRunner(
                              blink::TaskType::kMediaElementEvent)));
    media_controls_host_.set_connection_error_handler(WTF::Bind(
        &MediaControlsTouchlessImpl::OnMediaControlsMenuHostConnectionError,
        WrapWeakPersistent(this)));
  }
}

mojom::blink::VideoStatePtr MediaControlsTouchlessImpl::GetVideoState() {
  mojom::blink::VideoStatePtr video_state = mojom::blink::VideoState::New();
  video_state->is_muted = MediaElement().muted();
  video_state->is_fullscreen = MediaElement().IsFullscreen();
  return video_state;
}

WTF::Vector<mojom::blink::TextTrackMetadataPtr>
MediaControlsTouchlessImpl::GetTextTracks() {
  WTF::Vector<mojom::blink::TextTrackMetadataPtr> text_tracks;
  TextTrackList* track_list = MediaElement().textTracks();
  for (unsigned i = 0; i < track_list->length(); i++) {
    TextTrack* track = track_list->AnonymousIndexedGetter(i);
    if (!track->CanBeRendered())
      continue;

    mojom::blink::TextTrackMetadataPtr text_track(
        mojom::blink::TextTrackMetadata::New());
    text_track->track_index = track->TrackIndex();
    text_track->label = text_track_manager_->GetTextTrackLabel(track);
    text_tracks.push_back(std::move(text_track));
  }

  if (!text_tracks.IsEmpty()) {
    mojom::blink::TextTrackMetadataPtr text_track(
        mojom::blink::TextTrackMetadata::New());
    text_track->track_index = kTrackIndexOffValue;
    text_track->label = text_track_manager_->GetTextTrackLabel(nullptr);
    text_tracks.push_front(std::move(text_track));
  }

  return text_tracks;
}

void MediaControlsTouchlessImpl::ShowContextMenu() {
  EnsureMediaControlsMenuHost();

  mojom::blink::VideoStatePtr video_state = GetVideoState();
  WTF::Vector<mojom::blink::TextTrackMetadataPtr> text_tracks = GetTextTracks();

  WTF::Vector<mojom::blink::MenuItem> menu_items;

  if (MediaControlsSharedHelpers::ShouldShowFullscreenButton(MediaElement()))
    menu_items.push_back(mojom::blink::MenuItem::FULLSCREEN);

  if (MediaElement().HasAudio())
    menu_items.push_back(mojom::blink::MenuItem::MUTE);

  if (MediaElement().SupportsSave())
    menu_items.push_back(mojom::blink::MenuItem::DOWNLOAD);

  if (!text_tracks.IsEmpty())
    menu_items.push_back(mojom::blink::MenuItem::CAPTIONS);

  media_controls_host_->ShowMediaMenu(
      std::move(menu_items), std::move(video_state), std::move(text_tracks),
      WTF::Bind(&MediaControlsTouchlessImpl::OnMediaMenuResult,
                WrapWeakPersistent(this)));
}

void MediaControlsTouchlessImpl::OnMediaMenuResult(
    mojom::blink::MenuResponsePtr response) {
  if (response.is_null())
    return;

  switch (response->clicked) {
    case mojom::blink::MenuItem::FULLSCREEN:
      if (MediaElement().IsFullscreen())
        Fullscreen::ExitFullscreen(GetDocument());
      else
        Fullscreen::RequestFullscreen(MediaElement());
      break;
    case mojom::blink::MenuItem::MUTE:
      MediaElement().setMuted(!MediaElement().muted());
      break;
    case mojom::blink::MenuItem::DOWNLOAD:
      Download();
      break;
    case mojom::blink::MenuItem::CAPTIONS:
      text_track_manager_->DisableShowingTextTracks();
      if (response->track_index >= 0)
        text_track_manager_->ShowTextTrackAtIndex(response->track_index);
      break;
  }
}

void MediaControlsTouchlessImpl::Download() {
  const KURL& url = MediaElement().currentSrc();
  if (url.IsNull() || url.IsEmpty())
    return;
  ResourceRequest request(url);
  request.SetSuggestedFilename(MediaElement().title());
  request.SetRequestContext(mojom::RequestContextType::DOWNLOAD);
  request.SetRequestorOrigin(SecurityOrigin::Create(GetDocument().Url()));
  GetDocument().GetFrame()->Client()->DownloadURL(
      request, DownloadCrossOriginRedirects::kFollow);
}

void MediaControlsTouchlessImpl::OnMediaControlsMenuHostConnectionError() {
  media_controls_host_.reset();
}

MediaControlsTouchlessImpl::ArrowDirection
MediaControlsTouchlessImpl::OrientArrowPress(ArrowDirection direction) {
  switch (GetOrientation()) {
    case kWebScreenOrientationUndefined:
    case kWebScreenOrientationPortraitPrimary:
      return direction;
    case kWebScreenOrientationPortraitSecondary:
      switch (direction) {
        case ArrowDirection::kUp:
          return ArrowDirection::kDown;
        case ArrowDirection::kDown:
          return ArrowDirection::kUp;
        case ArrowDirection::kLeft:
          return ArrowDirection::kRight;
        case ArrowDirection::kRight:
          return ArrowDirection::kLeft;
      }
    case kWebScreenOrientationLandscapePrimary:
      switch (direction) {
        case ArrowDirection::kUp:
          return ArrowDirection::kLeft;
        case ArrowDirection::kDown:
          return ArrowDirection::kRight;
        case ArrowDirection::kLeft:
          return ArrowDirection::kDown;
        case ArrowDirection::kRight:
          return ArrowDirection::kUp;
      }
    case kWebScreenOrientationLandscapeSecondary:
      switch (direction) {
        case ArrowDirection::kUp:
          return ArrowDirection::kRight;
        case ArrowDirection::kDown:
          return ArrowDirection::kLeft;
        case ArrowDirection::kLeft:
          return ArrowDirection::kUp;
        case ArrowDirection::kRight:
          return ArrowDirection::kDown;
      }
  }
}

void MediaControlsTouchlessImpl::HandleOrientedArrowPress(
    ArrowDirection direction) {
  switch (direction) {
    case ArrowDirection::kUp:
      HandleTopButtonPress();
      break;
    case ArrowDirection::kDown:
      HandleBottomButtonPress();
      break;
    case ArrowDirection::kLeft:
      HandleLeftButtonPress();
      break;
    case ArrowDirection::kRight:
      HandleRightButtonPress();
      break;
  }
}

WebScreenOrientationType MediaControlsTouchlessImpl::GetOrientation() {
  LocalFrame* frame = GetDocument().GetFrame();
  if (!frame)
    return kWebScreenOrientationUndefined;

  return frame->GetChromeClient().GetScreenInfo().orientation_type;
}

void MediaControlsTouchlessImpl::HandleTopButtonPress() {
  MaybeChangeVolume(kVolumeToChangeForTouchless);
  volume_container_->UpdateVolume();
  overlay_->MakeTransparent(true);
  volume_container_->MakeOpaque(true);
}

void MediaControlsTouchlessImpl::HandleBottomButtonPress() {
  MaybeChangeVolume(kVolumeToChangeForTouchless * -1);
  volume_container_->UpdateVolume();
  overlay_->MakeTransparent(true);
  volume_container_->MakeOpaque(true);
}

void MediaControlsTouchlessImpl::HandleLeftButtonPress() {
  if (!MediaElement().paused())
    bottom_container_->MakeOpaque(true);
  MaybeJump(kNumberOfSecondsToJumpForTouchless * -1);
}

void MediaControlsTouchlessImpl::HandleRightButtonPress() {
  if (!MediaElement().paused())
    bottom_container_->MakeOpaque(true);
  MaybeJump(kNumberOfSecondsToJumpForTouchless);
}

void MediaControlsTouchlessImpl::MaybeChangeVolume(double volume_to_change) {
  double new_volume = std::max(0.0, MediaElement().volume() + volume_to_change);
  new_volume = std::min(new_volume, 1.0);
  MediaElement().setVolume(new_volume);
}

void MediaControlsTouchlessImpl::MaybeJump(int seconds) {
  double new_time = std::max(0.0, MediaElement().currentTime() + seconds);
  new_time = std::min(new_time, MediaElement().duration());
  MediaElement().setCurrentTime(new_time);
}

void MediaControlsTouchlessImpl::Trace(blink::Visitor* visitor) {
  visitor->Trace(bottom_container_);
  visitor->Trace(overlay_);
  visitor->Trace(media_event_listener_);
  visitor->Trace(text_track_manager_);
  visitor->Trace(orientation_lock_delegate_);
  visitor->Trace(volume_container_);
  MediaControls::Trace(visitor);
  HTMLDivElement::Trace(visitor);
}

void MediaControlsTouchlessImpl::SetMediaControlsMenuHostForTesting(
    mojom::blink::MediaControlsMenuHostPtr menu_host) {
  media_controls_host_ = std::move(menu_host);
}

void MediaControlsTouchlessImpl::MenuHostFlushForTesting() {
  media_controls_host_.FlushForTesting();
}

}  // namespace blink