DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (c68fe15a81fc)

VCS Links

Line Code
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
/* 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
 * 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/. */

"use strict";

var EXPORTED_SYMBOLS = [
var EXPORTED_SYMBOLS = [
  "PictureInPicture",
  "PictureInPictureParent",
  "PictureInPictureToggleParent",
];


const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { AppConstants } = ChromeUtils.import(
  "resource://gre/modules/AppConstants.jsm"
);


const PLAYER_URI = "chrome://global/content/pictureinpicture/player.xhtml";
var PLAYER_FEATURES =
  "chrome,titlebar=yes,alwaysontop,lockaspectratio,resizable";
/* Don't use dialog on Gtk as it adds extra border and titlebar to PIP window */
if (!AppConstants.MOZ_WIDGET_GTK) {
if (!AppConstants.MOZ_WIDGET_GTK) {
  PLAYER_FEATURES += ",dialog";
}
const WINDOW_TYPE = "Toolkit:PictureInPicture";
const TOGGLE_ENABLED_PREF =
  "media.videocontrols.picture-in-picture.video-toggle.enabled";


/**
 * If closing the Picture-in-Picture player window occurred for a reason that
 * we can easily detect (user clicked on the close button, originating tab unloaded,
 * user clicked on the unpip button), that will be stashed in gCloseReasons so that
 * we can note it in Telemetry when the window finally unloads.
 * we can note it in Telemetry when the window finally unloads.
 */
let gCloseReasons = new WeakMap();

/**
 * To differentiate windows in the Telemetry Event Log, each Picture-in-Picture
 * player window is given a unique ID.
 */
 */
let gNextWindowID = 0;

class PictureInPictureToggleParent extends JSWindowActorParent {
  receiveMessage(aMessage) {
    let browsingContext = aMessage.target.browsingContext;
    let browsingContext = aMessage.target.browsingContext;
    let browser = browsingContext.top.embedderElement;
    switch (aMessage.name) {
      case "PictureInPicture:OpenToggleContextMenu": {
        let win = browser.ownerGlobal;
        PictureInPicture.openToggleContextMenu(win, aMessage.data);
        PictureInPicture.openToggleContextMenu(win, aMessage.data);
        break;
      }
    }
  }
}


/**
 * This module is responsible for creating a Picture in Picture window to host
 * a clone of a video element running in web content.
 */

class PictureInPictureParent extends JSWindowActorParent {
  receiveMessage(aMessage) {
  receiveMessage(aMessage) {
    let browsingContext = aMessage.target.browsingContext;
    let browser = browsingContext.top.embedderElement;

    switch (aMessage.name) {
      case "PictureInPicture:Request": {
      case "PictureInPicture:Request": {
        let videoData = aMessage.data;
        PictureInPicture.handlePictureInPictureRequest(browser, videoData);
        break;
      }
      case "PictureInPicture:Resize": {
      case "PictureInPicture:Resize": {
        let videoData = aMessage.data;
        PictureInPicture.resizePictureInPictureWindow(videoData);
        break;
      }
      case "PictureInPicture:Close": {
      case "PictureInPicture:Close": {
        /**
         * Content has requested that its Picture in Picture window go away.
         */
        let reason = aMessage.data.reason;
        PictureInPicture.closePipWindow({ reason });
        PictureInPicture.closePipWindow({ reason });
        break;
      }
      case "PictureInPicture:Playing": {
        let player = PictureInPicture.getWeakPipPlayer();
        let player = PictureInPicture.getWeakPipPlayer();
        if (player) {
          player.setIsPlayingState(true);
        }
        break;
      }
      case "PictureInPicture:Paused": {
        let player = PictureInPicture.getWeakPipPlayer();
        let player = PictureInPicture.getWeakPipPlayer();
        if (player) {
          player.setIsPlayingState(false);
        }
        break;
      }
      }
      case "PictureInPicture:Muting": {
        let player = PictureInPicture.getWeakPipPlayer();
        if (player) {
          player.setIsMutedState(true);
        }
        }
        break;
      }
      case "PictureInPicture:Unmuting": {
        let player = PictureInPicture.getWeakPipPlayer();
        if (player) {
        if (player) {
          player.setIsMutedState(false);
        }
        break;
      }
    }
    }
  }
}

/**
 * This module is responsible for creating a Picture in Picture window to host
 * a clone of a video element running in web content.
 */

var PictureInPicture = {
var PictureInPicture = {
  /**
   * Returns the player window if one exists and if it hasn't yet been closed.
   *
   * @return {DOM Window} the player window if it exists and is not in the
   * process of being closed. Returns null otherwise.
   * process of being closed. Returns null otherwise.
   */
  getWeakPipPlayer() {
    let weakRef = this._weakPipPlayer;
    if (weakRef) {
      let playerWin;
      let playerWin;

      // Bug 800957 - Accessing weakrefs at the wrong time can cause us to
      // throw NS_ERROR_XPC_BAD_CONVERT_NATIVE
      try {
        playerWin = weakRef.get();
        playerWin = weakRef.get();
      } catch (e) {
        return null;
      }

      if (!playerWin || playerWin.closed) {
      if (!playerWin || playerWin.closed) {
        return null;
      }


      return playerWin;
    }
    return null;
  },


  /**
   * Called when the browser UI handles the View:PictureInPicture command via
   * the keyboard.
   */
  onCommand(event) {
  onCommand(event) {
    let win = event.target.ownerGlobal;
    let browser = win.gBrowser.selectedBrowser;
    let actor = browser.browsingContext.currentWindowGlobal.getActor(
      "PictureInPicture"
    );
    actor.sendAsyncMessage("PictureInPicture:KeyToggle");
  },
  },

  async focusTabAndClosePip() {
    let gBrowser = this.browser.ownerGlobal.gBrowser;
    let tab = gBrowser.getTabForBrowser(this.browser);
    gBrowser.selectedTab = tab;
    gBrowser.selectedTab = tab;
    await this.closePipWindow({ reason: "unpip" });
  },

  /**
   * Remove attribute which enables pip icon in tab
   * Remove attribute which enables pip icon in tab
   */
  clearPipTabIcon() {
  clearPipTabIcon() {
    let win = this.browser.ownerGlobal;
    let tab = win.gBrowser.getTabForBrowser(this.browser);
    if (tab) {
      tab.removeAttribute("pictureinpicture");
    }
    }
  },

  /**
   * Find and close any pre-existing Picture in Picture windows.
   */
   */
  async closePipWindow({ reason }) {
    // This uses an enumerator, but there really should only be one of
    // these things.
    for (let win of Services.wm.getEnumerator(WINDOW_TYPE)) {
    for (let win of Services.wm.getEnumerator(WINDOW_TYPE)) {
      if (win.closed) {
        continue;
      }
      let closedPromise = new Promise(resolve => {
        win.addEventListener("unload", resolve, { once: true });
        win.addEventListener("unload", resolve, { once: true });
      });
      gCloseReasons.set(win, reason);
      win.close();
      await closedPromise;
    }
    }
  },

  /**
   * A request has come up from content to open a Picture in Picture
   * window.
   * window.
   *
   * @param browser (xul:browser)
   * @param browser (xul:browser)
   *   The browser that is requesting the Picture in Picture window.
   *
   * @param videoData (object)
   *   An object containing the following properties:
   *
   *
   *   videoHeight (int):
   *     The preferred height of the video.
   *
   *   videoWidth (int):
   *     The preferred width of the video.
   *     The preferred width of the video.
   *
   * @returns Promise
   *   Resolves once the Picture in Picture window has been created, and
   *   the player component inside it has finished loading.
   */
   */
  async handlePictureInPictureRequest(browser, videoData) {
    // If there's a pre-existing PiP window, close it first.
    await this.closePipWindow({ reason: "new-pip" });

    let parentWin = browser.ownerGlobal;
    let parentWin = browser.ownerGlobal;
    this.browser = browser;
    let win = await this.openPipWindow(parentWin, videoData);
    this._weakPipPlayer = Cu.getWeakReference(win);
    win.setIsPlayingState(videoData.playing);
    win.setIsPlayingState(videoData.playing);
    win.setIsMutedState(videoData.isMuted);

    // set attribute which shows pip icon in tab
    let tab = parentWin.gBrowser.getTabForBrowser(browser);
    tab.setAttribute("pictureinpicture", true);
    tab.setAttribute("pictureinpicture", true);

    win.setupPlayer(gNextWindowID.toString(), browser);
    gNextWindowID++;
  },


  /**
   * unload event has been called in player.js, cleanup our preserved
   * browser object.
   */
  unload(window) {
  unload(window) {
    TelemetryStopwatch.finish(
      "FX_PICTURE_IN_PICTURE_WINDOW_OPEN_DURATION",
      window
    );


    let reason = gCloseReasons.get(window) || "other";
    Services.telemetry.keyedScalarAdd(
      "pictureinpicture.closed_method",
      reason,
      1
      1
    );

    this.clearPipTabIcon();
    delete this._weakPipPlayer;
    delete this.browser;
    delete this.browser;
  },

  /**
   * Open a Picture in Picture window on the same screen as parentWin,
   * sized based on the information in videoData.
   *
   *
   * @param parentWin (chrome window)
   *   The window hosting the browser that requested the Picture in
   *   Picture window.
   *
   * @param videoData (object)
   *   An object containing the following properties:
   *
   *
   *   videoHeight (int):
   *     The preferred height of the video.
   *
   *   videoWidth (int):
   *     The preferred width of the video.
   *     The preferred width of the video.
   *
   * @returns Promise
   *   Resolves once the window has opened and loaded the player component.
   */
  async openPipWindow(parentWin, videoData) {
  async openPipWindow(parentWin, videoData) {
    let { top, left, width, height } = this.fitToScreen(parentWin, videoData);

    let features =
      `${PLAYER_FEATURES},top=${top},left=${left},` +
      `outerWidth=${width},outerHeight=${height}`;
      `outerWidth=${width},outerHeight=${height}`;

    let pipWindow = Services.ww.openWindow(
      parentWin,
      PLAYER_URI,
      null,
      null,
      features,
      null
    );

    TelemetryStopwatch.start(
      "FX_PICTURE_IN_PICTURE_WINDOW_OPEN_DURATION",
      pipWindow,
      {
        inSeconds: true,
        inSeconds: true,
      }
    );

    return new Promise(resolve => {
      pipWindow.addEventListener(
      pipWindow.addEventListener(
        "load",
        () => {
          resolve(pipWindow);
        },
        { once: true }
        { once: true }
      );
    });
  },

  /**
  /**
   * Calculate the desired size and position for a Picture in Picture window
   * for the provided window and videoData.
   *
   * @param windowOrPlayer (chrome window|player window)
   *   The window hosting the browser that requested the Picture in
   *   The window hosting the browser that requested the Picture in
   *   Picture window. If this is an existing player window then the returned
   *   player size and position will be determined based on the existing
   *   player size and position will be determined based on the existing
   *   player window's size and position.
   *
   * @param videoData (object)
   *   An object containing the following properties:
   *
   *
   *   videoHeight (int):
   *     The preferred height of the video.
   *
   *   videoWidth (int):
   *   videoWidth (int):
   *     The preferred width of the video.
   *
   * @returns object
   *   The size and position for the player window.
   *
   *
   *   top (int):
   *     The top position for the player window.
   *
   *   left (int):
   *     The left position for the player window.
   *     The left position for the player window.
   *
   *   width (int):
   *     The width of the player window.
   *
   *   height (int):
   *   height (int):
   *     The height of the player window.
   */
  fitToScreen(windowOrPlayer, videoData) {
    let { videoHeight, videoWidth } = videoData;
    let isPlayerWindow = windowOrPlayer == this.getWeakPipPlayer();

    // The Picture in Picture window will open on the same display as the
    // originating window, and anchor to the bottom right.
    let screenManager = Cc["@mozilla.org/gfx/screenmanager;1"].getService(
    let screenManager = Cc["@mozilla.org/gfx/screenmanager;1"].getService(
      Ci.nsIScreenManager
    );
    let screen = screenManager.screenForRect(
      windowOrPlayer.screenX,
      windowOrPlayer.screenY,
      windowOrPlayer.screenY,
      1,
      1
    );

    // Now that we have the right screen, let's see how much available
    // Now that we have the right screen, let's see how much available
    // real-estate there is for us to work with.
    let screenLeft = {},
      screenTop = {},
      screenTop = {},
      screenWidth = {},
      screenWidth = {},
      screenHeight = {};
    screen.GetAvailRectDisplayPix(
      screenLeft,
      screenLeft,
      screenTop,
      screenWidth,
      screenHeight
    );
    let fullLeft = {},
    let fullLeft = {},
      fullTop = {},
      fullWidth = {},
      fullHeight = {};
    screen.GetRectDisplayPix(fullLeft, fullTop, fullWidth, fullHeight);


    // We have to divide these dimensions by the CSS scale factor for the
    // display in order for the video to be positioned correctly on displays
    // that are not at a 1.0 scaling.
    let scaleFactor = screen.contentsScaleFactor / screen.defaultCSSScaleFactor;
    screenWidth.value *= scaleFactor;
    screenWidth.value *= scaleFactor;
    screenHeight.value *= scaleFactor;
    screenLeft.value =
      (screenLeft.value - fullLeft.value) * scaleFactor + fullLeft.value;
    screenTop.value =
      (screenTop.value - fullTop.value) * scaleFactor + fullTop.value;
      (screenTop.value - fullTop.value) * scaleFactor + fullTop.value;

    // If we have a player window, maintain the previous player window's size by
    // clamping the new video's largest dimension to the player window's
    // largest dimension.
    //
    //
    // Otherwise the Picture in Picture window will be a maximum of a quarter of
    // the screen height, and a third of the screen width.
    let preferredSize;
    if (isPlayerWindow) {
    if (isPlayerWindow) {
      let prevWidth = windowOrPlayer.innerWidth;
      let prevHeight = windowOrPlayer.innerHeight;
      preferredSize = prevWidth >= prevHeight ? prevWidth : prevHeight;
    }
    const MAX_HEIGHT = preferredSize || screenHeight.value / 4;
    const MAX_HEIGHT = preferredSize || screenHeight.value / 4;
    const MAX_WIDTH = preferredSize || screenWidth.value / 3;

    let width = videoWidth;
    let height = videoHeight;
    let aspectRatio = videoWidth / videoHeight;
    let aspectRatio = videoWidth / videoHeight;


    if (
      videoHeight > MAX_HEIGHT ||
      videoWidth > MAX_WIDTH ||
      (isPlayerWindow && videoHeight < MAX_HEIGHT && videoWidth < MAX_WIDTH)
    ) {
    ) {
      // We're bigger than the max, or smaller than the previous player window.
      // Take the largest dimension and clamp it to the associated max.
      // Recalculate the other dimension to maintain aspect ratio.
      if (videoWidth >= videoHeight) {
        // We're clamping the width, so the height must be adjusted to match
        // We're clamping the width, so the height must be adjusted to match
        // the original aspect ratio. Since aspect ratio is width over height,
        // that means we need to _divide_ the MAX_WIDTH by the aspect ratio to
        // calculate the appropriate height.
        width = MAX_WIDTH;
        height = Math.round(MAX_WIDTH / aspectRatio);
        height = Math.round(MAX_WIDTH / aspectRatio);
      } else {
        // We're clamping the height, so the width must be adjusted to match
        // the original aspect ratio. Since aspect ratio is width over height,
        // this means we need to _multiply_ the MAX_HEIGHT by the aspect ratio
        // to calculate the appropriate width.
        // to calculate the appropriate width.
        height = MAX_HEIGHT;
        width = Math.round(MAX_HEIGHT * aspectRatio);
      }
    }


    // Figure out where to position the window on screen. If we have a player
    // window this will account for any change in video size. Otherwise the
    // video will be positioned in the bottom right.


    if (isPlayerWindow) {
      // We might need to move the window to keep its positioning in a similar
      // part of the screen.
      //
      // Find the distance from each edge of the screen of the old video, we'll
      // Find the distance from each edge of the screen of the old video, we'll
      // keep the closest edge in the same spot.
      let prevWidth = windowOrPlayer.innerWidth;
      let prevHeight = windowOrPlayer.innerHeight;
      let prevHeight = windowOrPlayer.innerHeight;
      let distanceLeft = windowOrPlayer.screenX;
      let distanceLeft = windowOrPlayer.screenX;
      let distanceRight =
      let distanceRight =
        screenWidth.value - windowOrPlayer.screenX - prevWidth;
      let distanceTop = windowOrPlayer.screenY;
      let distanceBottom =
        screenHeight.value - windowOrPlayer.screenY - prevHeight;


      let left = windowOrPlayer.screenX;
      let top = windowOrPlayer.screenY;

      if (distanceRight < distanceLeft) {
        // Closer to the right edge than the left. Move the window right by
        // Closer to the right edge than the left. Move the window right by
        // the difference in the video widths.
        left += prevWidth - width;
      }

      if (distanceBottom < distanceTop) {
      if (distanceBottom < distanceTop) {
        // Closer to the bottom edge than the top. Move the window down by
        // the difference in the video heights.
        top += prevHeight - height;
      }


      return { top, left, width, height };
    }

    // Now that we have the dimensions of the video, we need to figure out how
    // to position it in the bottom right corner. Since we know the width of the
    // to position it in the bottom right corner. Since we know the width of the
    // available rect, we need to subtract the dimensions of the window we're
    // opening to get the top left coordinates that openWindow expects.
    //
    // In event that the user has multiple displays connected, we have to
    // calculate the top-left coordinate of the new window in absolute
    // calculate the top-left coordinate of the new window in absolute
    // coordinates that span the entire display space, since this is what the
    // openWindow expects for its top and left feature values.
    //
    // The screenWidth and screenHeight values only tell us the available
    // dimensions on the screen that the parent window is on. We add these to
    // the screenLeft and screenTop values, which tell us where this screen is
    // located relative to the "origin" in absolute coordinates.
    // located relative to the "origin" in absolute coordinates.
    let isRTL = Services.locale.isAppLocaleRTL;
    let left = isRTL
      ? screenLeft.value
      : screenLeft.value + screenWidth.value - width;
    let top = screenTop.value + screenHeight.value - height;
    let top = screenTop.value + screenHeight.value - height;

    return { top, left, width, height };
  },

  resizePictureInPictureWindow(videoData) {
  resizePictureInPictureWindow(videoData) {
    let win = this.getWeakPipPlayer();

    if (!win) {
      return;
    }

    let { top, left, width, height } = this.fitToScreen(win, videoData);
    win.resizeTo(width, height);
    win.resizeTo(width, height);
    win.moveTo(left, top);
  },

  openToggleContextMenu(window, data) {
    let document = window.document;
    let document = window.document;
    let popup = document.getElementById("pictureInPictureToggleContextMenu");

    // We synthesize a new MouseEvent to propagate the inputSource to the
    // subsequently triggered popupshowing event.
    let newEvent = document.createEvent("MouseEvent");
    let newEvent = document.createEvent("MouseEvent");
    newEvent.initNSMouseEvent(
      "contextmenu",
      true,
      true,
      null,
      null,
      0,
      data.screenX,
      data.screenY,
      0,
      0,
      0,
      false,
      false,
      false,
      false,
      false,
      0,
      null,
      0,
      data.mozInputSource
    );
    );
    popup.openPopupAtScreen(newEvent.screenX, newEvent.screenY, true, newEvent);
  },

  hideToggle() {
  hideToggle() {
    Services.prefs.setBoolPref(TOGGLE_ENABLED_PREF, false);
  },
};