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
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const { PictureInPicture } = ChromeUtils.importESModule(
"resource://gre/modules/PictureInPicture.sys.mjs"
);
const { ShortcutUtils } = ChromeUtils.importESModule(
"resource://gre/modules/ShortcutUtils.sys.mjs"
);
const { DeferredTask } = ChromeUtils.importESModule(
"resource://gre/modules/DeferredTask.sys.mjs"
);
const { AppConstants } = ChromeUtils.importESModule(
"resource://gre/modules/AppConstants.sys.mjs"
);
const AUDIO_TOGGLE_ENABLED_PREF =
"media.videocontrols.picture-in-picture.audio-toggle.enabled";
const KEYBOARD_CONTROLS_ENABLED_PREF =
"media.videocontrols.picture-in-picture.keyboard-controls.enabled";
const CAPTIONS_ENABLED_PREF =
"media.videocontrols.picture-in-picture.display-text-tracks.enabled";
const CAPTIONS_TOGGLE_ENABLED_PREF =
"media.videocontrols.picture-in-picture.display-text-tracks.toggle.enabled";
const TEXT_TRACK_FONT_SIZE_PREF =
"media.videocontrols.picture-in-picture.display-text-tracks.size";
const IMPROVED_CONTROLS_ENABLED_PREF =
"media.videocontrols.picture-in-picture.improved-video-controls.enabled";
// Time to fade the Picture-in-Picture video controls after first opening.
const CONTROLS_FADE_TIMEOUT_MS = 3000;
const RESIZE_DEBOUNCE_RATE_MS = 500;
/**
Quadrants!
* 2 | 1
* 3 | 4
*/
const TOP_RIGHT_QUADRANT = 1;
const TOP_LEFT_QUADRANT = 2;
const BOTTOM_LEFT_QUADRANT = 3;
const BOTTOM_RIGHT_QUADRANT = 4;
/**
* Public function to be called from PictureInPicture.jsm. This is the main
* entrypoint for initializing the player window.
*
* @param {Number} id
* A unique numeric ID for the window, used for Telemetry Events.
* @param {WindowGlobalParent} wgp
* The WindowGlobalParent that is hosting the originating video.
* @param {ContentDOMReference} videoRef
* A reference to the video element that a Picture-in-Picture window
* is being created for
*/
function setupPlayer(id, wgp, videoRef) {
Player.init(id, wgp, videoRef);
}
/**
* Public function to be called from PictureInPicture.jsm. This update the
* controls based on whether or not the video is playing.
*
* @param {Boolean} isPlaying
* True if the Picture-in-Picture video is playing.
*/
function setIsPlayingState(isPlaying) {
Player.isPlaying = isPlaying;
}
/**
* Public function to be called from PictureInPicture.jsm. This update the
* controls based on whether or not the video is muted.
*
* @param {Boolean} isMuted
* True if the Picture-in-Picture video is muted.
*/
function setIsMutedState(isMuted) {
Player.isMuted = isMuted;
}
/**
* Function to resize and reposition the PiP window
* @param {Object} rect
* An object containing `left`, `top`, `width`, and `height` for the PiP
* window
*/
function resizeToVideo(rect) {
Player.resizeToVideo(rect);
}
/**
* Returns an object containing `left`, `top`, `width`, and `height` of the
* PiP window before entering fullscreen. Will be null if the PiP window is
* not in fullscreen.
*/
function getDeferredResize() {
return Player.deferredResize;
}
function enableSubtitlesButton() {
Player.enableSubtitlesButton();
}
function disableSubtitlesButton() {
Player.disableSubtitlesButton();
}
function setScrubberPosition(position) {
Player.setScrubberPosition(position);
}
function setTimestamp(timeString) {
Player.setTimestamp(timeString);
}
/**
* The Player object handles initializing the player, holds state, and handles
* events for updating state.
*/
let Player = {
WINDOW_EVENTS: [
"click",
"contextmenu",
"dblclick",
"keydown",
"mouseup",
"mousemove",
"MozDOMFullscreen:Entered",
"MozDOMFullscreen:Exited",
"resize",
"unload",
"draggableregionleftmousedown",
],
actor: null,
/**
* Used for resizing Telemetry to avoid recording an event for every resize
* event. Instead, we wait until RESIZE_DEBOUNCE_RATE_MS has passed since the
* last resize event before recording.
*/
resizeDebouncer: null,
/**
* Used for Telemetry to identify the window.
*/
id: -1,
/**
* When set to a non-null value, a timer is scheduled to hide the controls
* after CONTROLS_FADE_TIMEOUT_MS milliseconds.
*/
showingTimeout: null,
/**
* Used to determine old window location when mouseup-ed for corner
* snapping drag vector calculation
*/
oldMouseUpWindowX: window.screenX,
oldMouseUpWindowY: window.screenY,
/**
* Used to determine if hovering the mouse cursor over the pip window or not.
* Gets updated whenever a new hover state is detected.
*/
isCurrentHover: false,
/**
* Store the size and position of the window before entering fullscreen and
* use this to correctly position the window when exiting fullscreen
*/
deferredResize: null,
/**
* Initializes the player browser, and sets up the initial state.
*
* @param {Number} id
* A unique numeric ID for the window, used for Telemetry Events.
* @param {WindowGlobalParent} wgp
* The WindowGlobalParent that is hosting the originating video.
* @param {ContentDOMReference} videoRef
* A reference to the video element that a Picture-in-Picture window
* is being created for
*/
init(id, wgp, videoRef) {
this.id = id;
// State for whether or not we are adjusting the time via the scrubber
this.scrubbing = false;
let holder = document.querySelector(".player-holder");
let browser = document.getElementById("browser");
browser.remove();
browser.setAttribute("nodefaultsrc", "true");
this.setupTooltip("close", "pictureinpicture-close-btn", "closeShortcut");
let strId = this.isFullscreen
? `pictureinpicture-exit-fullscreen-btn2`
: `pictureinpicture-fullscreen-btn2`;
this.setupTooltip("fullscreen", strId, "fullscreenToggleShortcut");
// Set the specific remoteType and browsingContextGroupID to use for the
// initial about:blank load. The combination of these two properties will
// ensure that the browser loads in the same process as our originating
// browser.
browser.setAttribute("remoteType", wgp.domProcess.remoteType);
browser.setAttribute(
"initialBrowsingContextGroupId",
wgp.browsingContext.group.id
);
holder.appendChild(browser);
this.actor =
browser.browsingContext.currentWindowGlobal.getActor("PictureInPicture");
this.actor.sendAsyncMessage("PictureInPicture:SetupPlayer", {
videoRef,
});
PictureInPicture.weakPipToWin.set(this.actor, window);
for (let eventType of this.WINDOW_EVENTS) {
addEventListener(eventType, this);
}
this.controls.addEventListener("mouseleave", () => {
this.onMouseLeave();
});
this.controls.addEventListener("mouseenter", () => {
this.onMouseEnter();
});
this.scrubber.addEventListener("input", event => {
this.handleScrubbing(event);
});
this.scrubber.addEventListener("change", event => {
this.handleScrubbingDone(event);
});
for (let radio of document.querySelectorAll(
'input[type=radio][name="cc-size"]'
)) {
radio.addEventListener("change", event => {
this.onSubtitleChange(event.target.id);
});
}
document
.querySelector("#subtitles-toggle")
.addEventListener("change", () => {
this.onToggleChange();
});
// If the content process hosting the video crashes, let's
// just close the window for now.
browser.addEventListener("oop-browser-crashed", this);
this.revealControls(false);
if (Services.prefs.getBoolPref(AUDIO_TOGGLE_ENABLED_PREF, false)) {
const audioButton = document.getElementById("audio");
audioButton.hidden = false;
}
if (Services.prefs.getBoolPref(CAPTIONS_ENABLED_PREF, false)) {
this.closedCaptionButton.hidden = false;
}
if (Services.prefs.getBoolPref(IMPROVED_CONTROLS_ENABLED_PREF, false)) {
const fullscreenButton = document.getElementById("fullscreen");
fullscreenButton.hidden = false;
const seekBackwardButton = document.getElementById("seekBackward");
seekBackwardButton.hidden = false;
const seekForwardButton = document.getElementById("seekForward");
seekForwardButton.hidden = false;
this.scrubber.hidden = false;
this.timestamp.hidden = false;
const controlsBottomGradient = document.getElementById(
"controls-bottom-gradient"
);
controlsBottomGradient.hidden = false;
}
this.alignEndControlsButtonTooltips();
this.resizeDebouncer = new DeferredTask(() => {
this.alignEndControlsButtonTooltips();
this.recordEvent("resize", {
width: window.outerWidth.toString(),
height: window.outerHeight.toString(),
});
}, RESIZE_DEBOUNCE_RATE_MS);
this.computeAndSetMinimumSize(window.outerWidth, window.outerHeight);
// alwaysontop windows are not focused by default, so we have to do it
// ourselves. We use requestAnimationFrame since we have to wait until the
// window is visible before it can focus.
window.requestAnimationFrame(() => {
window.focus();
});
let fontSize = Services.prefs.getCharPref(
TEXT_TRACK_FONT_SIZE_PREF,
"medium"
);
// fallback to medium if the pref value is not a valid option
if (fontSize === "small" || fontSize === "large") {
document.querySelector(`#${fontSize}`).checked = "true";
} else {
document.querySelector("#medium").checked = "true";
}
},
uninit() {
this.resizeDebouncer.disarm();
PictureInPicture.unload(window, this.actor);
},
setupTooltip(elId, l10nId, shortcutId) {
const el = document.getElementById(elId);
const shortcut = document.getElementById(shortcutId);
let l10nObj = shortcut
? { shortcut: ShortcutUtils.prettifyShortcut(shortcut) }
: {};
document.l10n.setAttributes(el, l10nId, l10nObj);
},
handleEvent(event) {
switch (event.type) {
case "click": {
// Don't run onClick if middle or right click is pressed respectively
if (event.button !== 1 && event.button !== 2) {
this.onClick(event);
this.controls.removeAttribute("keying");
}
break;
}
case "contextmenu": {
event.preventDefault();
break;
}
case "dblclick": {
this.onDblClick(event);
break;
}
case "keydown": {
if (event.keyCode == KeyEvent.DOM_VK_TAB) {
this.controls.setAttribute("keying", true);
this.showVideoControls();
} else if (event.keyCode == KeyEvent.DOM_VK_ESCAPE) {
let isSettingsPanelInFocus = this.settingsPanel.contains(
document.activeElement
);
event.preventDefault();
if (!this.settingsPanel.classList.contains("hide")) {
// If the subtitles settings panel is open, let the ESC key close it
this.toggleSubtitlesSettingsPanel({ forceHide: true });
if (isSettingsPanelInFocus) {
document.getElementById("closed-caption").focus();
}
} else if (this.isFullscreen) {
// We handle the ESC key, in fullscreen modus as intent to leave only the fullscreen mode
document.exitFullscreen();
} else {
// We handle the ESC key, as an intent to leave the picture-in-picture modus
this.onClose();
}
} else if (
Services.prefs.getBoolPref(KEYBOARD_CONTROLS_ENABLED_PREF, false) &&
(event.keyCode != KeyEvent.DOM_VK_SPACE || !event.target.id)
) {
// Pressing "space" fires a "keydown" event which can also trigger a control
// button's "click" event. Handle the "keydown" event only when the event did
// not originate from a control button and it is not a "space" keypress.
this.onKeyDown(event);
}
break;
}
case "mouseup": {
this.onMouseUp(event);
break;
}
case "mousemove": {
this.onMouseMove();
break;
}
// Normally, the DOMFullscreenParent / DOMFullscreenChild actors
// would take care of firing the `fullscreen-painted` notification,
// however, those actors are only ever instantiated when a <browser>
// is fullscreened, and not a <body> element in a parent-process
// chrome privileged DOM window.
//
// Rather than trying to re-engineer JSWindowActors to be re-usable for
// this edge-case, we do the work of firing fullscreen-painted when
// transitioning in and out of fullscreen ourselves here.
case "MozDOMFullscreen:Entered":
// Intentional fall-through
case "MozDOMFullscreen:Exited": {
let { lastTransactionId } = window.windowUtils;
window.addEventListener("MozAfterPaint", function onPainted(event) {
if (event.transactionId > lastTransactionId) {
window.removeEventListener("MozAfterPaint", onPainted);
Services.obs.notifyObservers(window, "fullscreen-painted");
}
});
// If we are exiting fullscreen we want to resize the window to the
// stored size and position
if (this.deferredResize && event.type === "MozDOMFullscreen:Exited") {
this.resizeToVideo(this.deferredResize);
this.deferredResize = null;
}
// Sets the title for fullscreen button when PIP is in Enter Fullscreen mode and Exit Fullscreen mode
let strId = this.isFullscreen
? `pictureinpicture-exit-fullscreen-btn2`
: `pictureinpicture-fullscreen-btn2`;
this.setupTooltip("fullscreen", strId, "fullscreenToggleShortcut");
window.focus();
if (this.isFullscreen) {
this.actor.sendAsyncMessage("PictureInPicture:EnterFullscreen", {
isFullscreen: true,
isVideoControlsShowing: null,
playerBottomControlsDOMRect: null,
});
} else {
this.actor.sendAsyncMessage("PictureInPicture:ExitFullscreen", {
isFullscreen: this.isFullscreen,
isVideoControlsShowing:
!!this.controls.getAttribute("showing") ||
!!this.controls.getAttribute("keying"),
playerBottomControlsDOMRect:
this.controlsBottom.getBoundingClientRect(),
});
}
// The subtitles settings panel gets selected when entering/exiting fullscreen even though
// user-select is set to none. I don't know why this happens or how to prevent so we just
// remove the selection when fullscreen is entered/exited.
let selection = window.getSelection();
selection.removeAllRanges();
break;
}
case "oop-browser-crashed": {
this.closePipWindow({ reason: "browser-crash" });
break;
}
case "resize": {
this.onResize(event);
break;
}
case "unload": {
this.uninit();
break;
}
case "draggableregionleftmousedown": {
this.toggleSubtitlesSettingsPanel({ forceHide: true });
break;
}
}
},
/**
* This function handles when the scrubber is being scrubbed by the mouse
* because if we get an input event from the keyboard, onKeyDown will set
* this.preventNextInputEvent to true.
* This function is called by input events on the scrubber
* @param {Event} event The input event
*/
handleScrubbing(event) {
// When using the keyboard to scrub, we get both a keydown and an input
// event. The input event is fired after the keydown and we have already
// handle the keydown event in onKeyDown and we don't want to handle it twice
if (this.preventNextInputEvent) {
this.preventNextInputEvent = false;
return;
}
if (!this.scrubbing) {
this.wasPlaying = this.isPlaying;
if (this.isPlaying) {
this.actor.sendAsyncMessage("PictureInPicture:Pause");
}
this.scrubbing = true;
}
let scrubberPosition = this.getScrubberPositionFromEvent(event);
this.setVideoTime(scrubberPosition);
},
/**
* This function handles setting the scrubbing state to false and playing
* the video if we paused it before scrubbing.
* @param {Event} event The change event
*/
handleScrubbingDone(event) {
if (!this.scrubbing) {
return;
}
let scrubberPosition = this.getScrubberPositionFromEvent(event);
this.setVideoTime(scrubberPosition);
if (this.wasPlaying) {
this.actor.sendAsyncMessage("PictureInPicture:Play");
}
this.scrubbing = false;
},
getScrubberPositionFromEvent(event) {
return event.target.value;
},
setVideoTime(scrubberPosition) {
let wasPlaying = this.scrubbing ? this.wasPlaying : this.isPlaying;
this.setScrubberPosition(scrubberPosition);
this.actor.sendAsyncMessage("PictureInPicture:SetVideoTime", {
scrubberPosition,
wasPlaying,
});
},
setScrubberPosition(value) {
this.scrubber.value = value;
this.scrubber.hidden = value === undefined;
// Also hide the seek buttons when we hide the scrubber
this.seekBackward.hidden = value === undefined;
this.seekForward.hidden = value === undefined;
},
setTimestamp(timestamp) {
this.timestamp.textContent = timestamp;
this.timestamp.hidden = timestamp === undefined;
},
closePipWindow(closeData) {
// Set the subtitles font size prefs
Services.prefs.setBoolPref(
CAPTIONS_TOGGLE_ENABLED_PREF,
document.querySelector("#subtitles-toggle").checked
);
for (let radio of document.querySelectorAll(
'input[type=radio][name="cc-size"]'
)) {
if (radio.checked) {
Services.prefs.setCharPref(TEXT_TRACK_FONT_SIZE_PREF, radio.id);
break;
}
}
const { reason } = closeData;
PictureInPicture.closeSinglePipWindow({ reason, actorRef: this.actor });
},
onDblClick(event) {
if (event.target.id == "controls") {
this.fullscreenModeToggle();
event.preventDefault();
}
},
onClick(event) {
switch (event.target.id) {
case "audio": {
if (this.isMuted) {
this.actor.sendAsyncMessage("PictureInPicture:Unmute");
} else {
this.actor.sendAsyncMessage("PictureInPicture:Mute");
}
break;
}
case "close": {
this.onClose();
break;
}
case "playpause": {
if (!this.isPlaying) {
this.actor.sendAsyncMessage("PictureInPicture:Play");
this.revealControls(false);
} else {
this.actor.sendAsyncMessage("PictureInPicture:Pause");
this.revealControls(true);
}
break;
}
case "seekBackward": {
this.actor.sendAsyncMessage("PictureInPicture:SeekBackward");
break;
}
case "seekForward": {
this.actor.sendAsyncMessage("PictureInPicture:SeekForward");
break;
}
case "unpip": {
PictureInPicture.focusTabAndClosePip(window, this.actor);
break;
}
case "closed-caption": {
let options = {};
if (event.mozInputSource == MouseEvent.MOZ_SOURCE_KEYBOARD) {
options.isKeyboard = true;
}
this.toggleSubtitlesSettingsPanel(options);
// Early return to prevent hiding the panel below
return;
}
case "fullscreen": {
this.fullscreenModeToggle();
this.recordEvent("fullscreen", {
enter: (!this.isFullscreen).toString(),
});
break;
}
case "font-size-selection-radio-small": {
document.getElementById("small").click();
break;
}
case "font-size-selection-radio-medium": {
document.getElementById("medium").click();
break;
}
case "font-size-selection-radio-large": {
document.getElementById("large").click();
break;
}
}
// If the click came from a element that is not inside the subtitles settings panel
// then we want to hide the panel
if (!this.settingsPanel.contains(event.target)) {
this.toggleSubtitlesSettingsPanel({ forceHide: true });
}
},
/**
* Function to toggle the visibility of the subtitles settings panel
* @param {Object} options [optional] Object containing options for the function
* - forceHide: true to force hide the subtitles settings panel
* - isKeyboard: true if the subtitles button was activated using the keyboard
* to show or hide the subtitles settings panel
*/
toggleSubtitlesSettingsPanel(options) {
let settingsPanelVisible = !this.settingsPanel.classList.contains("hide");
if (options?.forceHide || settingsPanelVisible) {
this.settingsPanel.classList.add("hide");
this.closedCaptionButton.setAttribute("aria-expanded", false);
this.controls.removeAttribute("donthide");
if (
this.controls.getAttribute("keying") ||
this.isCurrentHover ||
this.controls.getAttribute("showing")
) {
return;
}
this.actor.sendAsyncMessage("PictureInPicture:HideVideoControls", {
isFullscreen: this.isFullscreen,
isVideoControlsShowing: false,
playerBottomControlsDOMRect: null,
});
} else {
this.settingsPanel.classList.remove("hide");
this.closedCaptionButton.setAttribute("aria-expanded", true);
this.controls.setAttribute("donthide", true);
this.showVideoControls();
if (options?.isKeyboard) {
document.querySelector("#subtitles-toggle").focus();
}
}
},
onClose() {
this.actor.sendAsyncMessage("PictureInPicture:Pause", {
reason: "pip-closed",
});
this.closePipWindow({ reason: "closeButton" });
},
fullscreenModeToggle() {
if (this.isFullscreen) {
document.exitFullscreen();
} else {
this.deferredResize = {
left: window.screenX,
top: window.screenY,
width: window.innerWidth,
height: window.innerHeight,
};
document.body.requestFullscreen();
}
},
resizeToVideo(rect) {
if (this.isFullscreen) {
// We store the size and position because resizing the PiP window
// while fullscreened will cause issues
this.deferredResize = rect;
} else {
let { left, top, width, height } = rect;
window.resizeTo(width, height);
window.moveTo(left, top);
}
},
onKeyDown(event) {
// We don't want to send a keydown event if the event target was one of the
// font sizes in the settings panel
if (
event.target.parentElement?.parentElement?.classList?.contains(
"font-size-selection"
)
) {
return;
}
let eventKeys = {
altKey: event.altKey,
shiftKey: event.shiftKey,
metaKey: event.metaKey,
ctrlKey: event.ctrlKey,
keyCode: event.keyCode,
};
// If the up or down arrow is pressed while the scrubber is focused then we
// want to hijack these keydown events to act as left or right arrow
// respectively to correctly seek the video.
if (
event.target.id === "scrubber" &&
event.keyCode === window.KeyEvent.DOM_VK_UP
) {
eventKeys.keyCode = window.KeyEvent.DOM_VK_RIGHT;
} else if (
event.target.id === "scrubber" &&
event.keyCode === window.KeyEvent.DOM_VK_DOWN
) {
eventKeys.keyCode = window.KeyEvent.DOM_VK_LEFT;
}
// If the keydown event was one of the arrow keys and the scrubber was
// focused then we will also get an input event that will overwrite the
// keydown event if we dont' prevent the input event.
if (
event.target.id === "scrubber" &&
[
window.KeyEvent.DOM_VK_LEFT,
window.KeyEvent.DOM_VK_RIGHT,
window.KeyEvent.DOM_VK_UP,
window.KeyEvent.DOM_VK_DOWN,
].includes(event.keyCode)
) {
this.preventNextInputEvent = true;
}
this.actor.sendAsyncMessage("PictureInPicture:KeyDown", eventKeys);
},
onSubtitleChange(size) {
Services.prefs.setCharPref(TEXT_TRACK_FONT_SIZE_PREF, size);
this.actor.sendAsyncMessage("PictureInPicture:ChangeFontSizeTextTracks");
},
onToggleChange() {
// The subtitles toggle has been click in the settings panel so we toggle
// the overlay above the font sizes and send a message to toggle the
// visibility of the subtitles and set the toggle pref
document
.querySelector(".font-size-selection")
.classList.toggle("font-size-overlay");
this.actor.sendAsyncMessage("PictureInPicture:ToggleTextTracks");
this.captionsToggleEnabled = !this.captionsToggleEnabled;
Services.prefs.setBoolPref(
CAPTIONS_TOGGLE_ENABLED_PREF,
this.captionsToggleEnabled
);
},
/**
* PiP Corner Snapping Helper Function
* Determines the quadrant the PiP window is currently in.
*/
determineCurrentQuadrant() {
// Determine center coordinates of window.
let windowCenterX = window.screenX + window.innerWidth / 2;
let windowCenterY = window.screenY + window.innerHeight / 2;
let quadrant = null;
let halfWidth = window.screen.availLeft + window.screen.availWidth / 2;
let halfHeight = window.screen.availTop + window.screen.availHeight / 2;
let leftHalf = windowCenterX < halfWidth;
let rightHalf = windowCenterX > halfWidth;
let topHalf = windowCenterY < halfHeight;
let bottomHalf = windowCenterY > halfHeight;
if (leftHalf && topHalf) {
quadrant = TOP_LEFT_QUADRANT;
} else if (rightHalf && topHalf) {
quadrant = TOP_RIGHT_QUADRANT;
} else if (leftHalf && bottomHalf) {
quadrant = BOTTOM_LEFT_QUADRANT;
} else if (rightHalf && bottomHalf) {
quadrant = BOTTOM_RIGHT_QUADRANT;
}
return quadrant;
},
/**
* Helper function to actually move/snap the PiP window.
* Moves the PiP window to the top right.
*/
moveToTopRight() {
window.moveTo(
window.screen.availLeft + window.screen.availWidth - window.innerWidth,
window.screen.availTop
);
},
/**
* Moves the PiP window to the top left.
*/
moveToTopLeft() {
window.moveTo(window.screen.availLeft, window.screen.availTop);
},
/**
* Moves the PiP window to the bottom right.
*/
moveToBottomRight() {
window.moveTo(
window.screen.availLeft + window.screen.availWidth - window.innerWidth,
window.screen.availTop + window.screen.availHeight - window.innerHeight
);
},
/**
* Moves the PiP window to the bottom left.
*/
moveToBottomLeft() {
window.moveTo(
window.screen.availLeft,
window.screen.availTop + window.screen.availHeight - window.innerHeight
);
},
/**
* Uses the PiP window's change in position to determine which direction
* the window has been moved in.
*/
determineDirectionDragged() {
// Determine change in window location.
let deltaX = this.oldMouseUpWindowX - window.screenX;
let deltaY = this.oldMouseUpWindowY - window.screenY;
let dragDirection = "";
if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX < 0) {
dragDirection = "draggedRight";
} else if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX > 0) {
dragDirection = "draggedLeft";
} else if (Math.abs(deltaX) < Math.abs(deltaY) && deltaY < 0) {
dragDirection = "draggedDown";
} else if (Math.abs(deltaX) < Math.abs(deltaY) && deltaY > 0) {
dragDirection = "draggedUp";
}
return dragDirection;
},
/**
* Event handler for "mouseup" events on the PiP window.
*
* @param {Event} event
* Event context details
*/
onMouseUp(event) {
// Corner snapping changes start here.
// Check if metakey pressed and macOS
let quadrant = this.determineCurrentQuadrant();
let dragAction = this.determineDirectionDragged();
if (event.metaKey && AppConstants.platform == "macosx" && dragAction) {
// Moving logic based on current quadrant and direction of drag.
switch (quadrant) {
case TOP_RIGHT_QUADRANT:
switch (dragAction) {
case "draggedRight":
this.moveToTopRight();
break;
case "draggedLeft":
this.moveToTopLeft();
break;
case "draggedDown":
this.moveToBottomRight();
break;
case "draggedUp":
this.moveToTopRight();
break;
}
break;
case TOP_LEFT_QUADRANT:
switch (dragAction) {
case "draggedRight":
this.moveToTopRight();
break;
case "draggedLeft":
this.moveToTopLeft();
break;
case "draggedDown":
this.moveToBottomLeft();
break;
case "draggedUp":
this.moveToTopLeft();
break;
}
break;
case BOTTOM_LEFT_QUADRANT:
switch (dragAction) {
case "draggedRight":
this.moveToBottomRight();
break;
case "draggedLeft":
this.moveToBottomLeft();
break;
case "draggedDown":
this.moveToBottomLeft();
break;
case "draggedUp":
this.moveToTopLeft();
break;
}
break;
case BOTTOM_RIGHT_QUADRANT:
switch (dragAction) {
case "draggedRight":
this.moveToBottomRight();
break;
case "draggedLeft":
this.moveToBottomLeft();
break;
case "draggedDown":
this.moveToBottomRight();
break;
case "draggedUp":
this.moveToTopRight();
break;
}
break;
} // Switch close.
} // Metakey close.
this.oldMouseUpWindowX = window.screenX;
this.oldMouseUpWindowY = window.screenY;
},
/**
* Event handler for mousemove the PiP Window
*/
onMouseMove() {
if (this.isFullscreen) {
this.revealControls(false);
}
},
onMouseEnter() {
if (!this.isFullscreen) {
this.isCurrentHover = true;
this.showVideoControls();
}
},
onMouseLeave() {
if (!this.isFullscreen) {
this.isCurrentHover = false;
if (
!this.controls.getAttribute("showing") &&
!this.controls.getAttribute("keying") &&
!this.controls.getAttribute("donthide")
) {
this.actor.sendAsyncMessage("PictureInPicture:HideVideoControls", {
isFullscreen: this.isFullscreen,
isVideoControlsShowing: false,
playerBottomControlsDOMRect: null,
});
}
}
},
enableSubtitlesButton() {
this.closedCaptionButton.disabled = false;
this.alignEndControlsButtonTooltips();
this.captionsToggleEnabled = true;
// If the CAPTIONS_TOGGLE_ENABLED_PREF pref is false then we will click
// the UI toggle to change the toggle to unchecked. This will call
// onToggleChange where this.captionsToggleEnabled will be updated
if (!Services.prefs.getBoolPref(CAPTIONS_TOGGLE_ENABLED_PREF, true)) {
document.querySelector("#subtitles-toggle").click();
}
},
disableSubtitlesButton() {
this.closedCaptionButton.disabled = true;
this.alignEndControlsButtonTooltips();
},
/**
* Sets focus state inline end tooltip for rightmost playback controls
*/
alignEndControlsButtonTooltips() {
let audioBtn = document.getElementById("audio");
let width = window.outerWidth;
if (300 < width && width <= 400) {
audioBtn.classList.replace("center-tooltip", "inline-end-tooltip");
} else {
audioBtn.classList.replace("inline-end-tooltip", "center-tooltip");
}
},
/**
* Event handler for resizing the PiP Window
*
* @param {Event} event
* Event context data object
*/
onResize(event) {
this.toggleSubtitlesSettingsPanel({ forceHide: true });
this.resizeDebouncer.disarm();
this.resizeDebouncer.arm();
},
/**
* Event handler for user issued commands
*
* @param {Event} event
* Event context data object
*/
onCommand(event) {
this.closePipWindow({ reason: "shortcut" });
},
get controls() {
delete this.controls;
return (this.controls = document.getElementById("controls"));
},
get scrubber() {
delete this.scrubber;
return (this.scrubber = document.getElementById("scrubber"));
},
get timestamp() {
delete this.timestamp;
return (this.timestamp = document.getElementById("timestamp"));
},
get controlsBottom() {
delete this.controlsBottom;
return (this.controlsBottom = document.getElementById("controls-bottom"));
},
get seekBackward() {
delete this.seekBackward;
return (this.seekBackward = document.getElementById("seekBackward"));
},
get seekForward() {
delete this.seekForward;
return (this.seekForward = document.getElementById("seekForward"));
},
get closedCaptionButton() {
delete this.closedCaptionButton;
return (this.closedCaptionButton =
document.getElementById("closed-caption"));
},
get settingsPanel() {
delete this.settingsPanel;
return (this.settingsPanel = document.getElementById("settings"));
},
_isPlaying: false,
/**
* GET isPlaying returns true if the video is currently playing.
*
* SET isPlaying to true if the video is playing, false otherwise. This will
* update the internal state and displayed controls.
*
* @type {Boolean}
*/
get isPlaying() {
return this._isPlaying;
},
set isPlaying(isPlaying) {
this._isPlaying = isPlaying;
this.controls.classList.toggle("playing", isPlaying);
let strId = isPlaying
? `pictureinpicture-pause-btn`
: `pictureinpicture-play-btn`;
this.setupTooltip("playpause", strId);
},
_isMuted: false,
/**
* GET isMuted returns true if the video is currently muted.
*
* SET isMuted to true if the video is muted, false otherwise. This will
* update the internal state and displayed controls.
*
* @type {Boolean}
*/
get isMuted() {
return this._isMuted;
},
set isMuted(isMuted) {
this._isMuted = isMuted;
this.controls.classList.toggle("muted", isMuted);
let strId = isMuted
? `pictureinpicture-unmute-btn`
: `pictureinpicture-mute-btn`;
let shortcutId = isMuted ? "unMuteShortcut" : "muteShortcut";
this.setupTooltip("audio", strId, shortcutId);
},
/**
* GET isFullscreen returns true if the video is running in fullscreen mode
*
* @returns {boolean}
*/
get isFullscreen() {
return document.fullscreenElement == document.body;
},
/**
* Used for recording telemetry in Picture-in-Picture.
*
* @param {string} type
* The type of PiP event being recorded.
* @param {object} args
* The data to pass to telemetry when the event is recorded.
*/
recordEvent(type, args) {
Services.telemetry.recordEvent(
"pictureinpicture",
type,
"player",
this.id,
args
);
},
/**
* Send a message to PiPChild to adjust the subtitles position
*/
showVideoControls() {
// offsetParent returns null when the element or any ancestor has display: none
// See https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent
this.actor.sendAsyncMessage("PictureInPicture:ShowVideoControls", {
isFullscreen: this.isFullscreen,
isVideoControlsShowing: true,
playerBottomControlsDOMRect: this.controlsBottom.getBoundingClientRect(),
isScrubberShowing: !!this.scrubber.offsetParent,
});
},
/**
* Makes the player controls visible.
*
* @param {Boolean} revealIndefinitely
* If false, this will hide the controls again after
* CONTROLS_FADE_TIMEOUT_MS milliseconds has passed. If true, the controls
* will remain visible until revealControls is called again with
* revealIndefinitely set to false.
*/
revealControls(revealIndefinitely) {
clearTimeout(this.showingTimeout);
this.showingTimeout = null;
this.controls.setAttribute("showing", true);
if (!this.isFullscreen) {
// revealControls() is called everytime we hover over fullscreen pip window.
// Only communicate with pipchild when not in fullscreen mode for performance reasons.
this.showVideoControls();
}
if (!revealIndefinitely) {
this.showingTimeout = setTimeout(() => {
const isHoverOverControlItem = this.controls.querySelector(
".control-item:hover"
);
if (this.isFullscreen && isHoverOverControlItem) {
return;
}
this.controls.removeAttribute("showing");
if (
!this.isFullscreen &&
!this.isCurrentHover &&
!this.controls.getAttribute("keying") &&
!this.controls.getAttribute("donthide")
) {
this.actor.sendAsyncMessage("PictureInPicture:HideVideoControls", {
isFullscreen: false,
isVideoControlsShowing: false,
playerBottomControlsDOMRect: null,
});
}
}, CONTROLS_FADE_TIMEOUT_MS);
}
},
/**
* Given a width and height for a video, computes the minimum dimensions for
* the player window, and then sets them on the root element.
*
* This is currently only used on Linux GTK, where the OS doesn't already
* impose a minimum window size. For other platforms, this function is a
* no-op.
*
* @param {Number} width
* The width of the video being played.
* @param {Number} height
* The height of the video being played.
*/
computeAndSetMinimumSize(width, height) {
if (!AppConstants.MOZ_WIDGET_GTK) {
return;
}
// Using inspection, these seem to be the right minimums for each dimension
// so that the controls don't get too crowded.
const MIN_WIDTH = 120;
const MIN_HEIGHT = 80;
let resultWidth = width;
let resultHeight = height;
let aspectRatio = width / height;
// Take the smaller of the two dimensions, and set it to the minimum.
// Then calculate the other dimension using the aspect ratio to get
// both minimums.
if (width < height) {
resultWidth = MIN_WIDTH;
resultHeight = Math.round(MIN_WIDTH / aspectRatio);
} else {
resultHeight = MIN_HEIGHT;
resultWidth = Math.round(MIN_HEIGHT * aspectRatio);
}
document.documentElement.style.minWidth = resultWidth + "px";
document.documentElement.style.minHeight = resultHeight + "px";
},
};
|