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

"use strict";

var EXPORTED_SYMBOLS = ["webrtcUI", "MacOSWebRTCStatusbarIndicator"];

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

ChromeUtils.defineModuleGetter(
  this,
  "AppConstants",
  "resource://gre/modules/AppConstants.jsm"
);
ChromeUtils.defineModuleGetter(
  this,
  "PluralForm",
  "resource://gre/modules/PluralForm.jsm"
);
ChromeUtils.defineModuleGetter(
  this,
  "BrowserWindowTracker",
  "resource:///modules/BrowserWindowTracker.jsm"
);
ChromeUtils.defineModuleGetter(
  this,
  "XPCOMUtils",
  "resource://gre/modules/XPCOMUtils.jsm"
);

var webrtcUI = {
  initialized: false,

  peerConnectionBlockers: new Set(),
  emitter: new EventEmitter(),

  init() {
    if (!this.initialized) {
      Services.obs.addObserver(this, "browser-delayed-startup-finished");
      this.initialized = true;

      XPCOMUtils.defineLazyPreferenceGetter(
        this,
        "useLegacyGlobalIndicator",
        "privacy.webrtc.legacyGlobalIndicator",
        true
      );

      Services.telemetry.setEventRecordingEnabled("webrtc.ui", true);
    }
  },

  uninit() {
    if (this.initialized) {
      Services.obs.removeObserver(this, "browser-delayed-startup-finished");
      this.initialized = false;
    }
  },

  observe(subject, topic, data) {
    if (topic == "browser-delayed-startup-finished") {
      if (webrtcUI.showGlobalIndicator) {
        showOrCreateMenuForWindow(subject);
      }
    }
  },

  SHARING_NONE: 0,
  SHARING_WINDOW: 1,
  SHARING_SCREEN: 2,

  // Set of browser windows that are being shared over WebRTC.
  sharedBrowserWindows: new WeakSet(),

  // True if one or more screens is being shared.
  sharingScreen: false,

  allowedSharedBrowsers: new WeakSet(),
  allowTabSwitchesForSession: false,
  tabSwitchCountForSession: 0,

  // True if a window or screen is being shared.
  sharingDisplay: false,

  // The session ID is used to try to differentiate between instances
  // where the user is sharing their display somehow. If the user
  // transitions from a state of not sharing their display, to sharing a
  // display, we bump the ID.
  sharingDisplaySessionId: 0,

  // Map of browser elements to indicator data.
  perTabIndicators: new Map(),
  activePerms: new Map(),

  get showGlobalIndicator() {
    for (let [, indicators] of this.perTabIndicators) {
      if (
        indicators.showCameraIndicator ||
        indicators.showMicrophoneIndicator ||
        indicators.showScreenSharingIndicator
      ) {
        return true;
      }
    }
    return false;
  },

  get showCameraIndicator() {
    for (let [, indicators] of this.perTabIndicators) {
      if (indicators.showCameraIndicator) {
        return true;
      }
    }
    return false;
  },

  get showMicrophoneIndicator() {
    for (let [, indicators] of this.perTabIndicators) {
      if (indicators.showMicrophoneIndicator) {
        return true;
      }
    }
    return false;
  },

  get showScreenSharingIndicator() {
    let list = [""];
    for (let [, indicators] of this.perTabIndicators) {
      if (indicators.showScreenSharingIndicator) {
        list.push(indicators.showScreenSharingIndicator);
      }
    }

    let precedence = ["Screen", "Window", "Application", "Browser", ""];

    list.sort((a, b) => {
      return precedence.indexOf(a) - precedence.indexOf(b);
    });

    return list[0];
  },

  _streams: [],
  // The boolean parameters indicate which streams should be included in the result.
  getActiveStreams(aCamera, aMicrophone, aScreen, aWindow = false) {
    return webrtcUI._streams
      .filter(aStream => {
        let state = aStream.state;
        return (
          (aCamera && state.camera) ||
          (aMicrophone && state.microphone) ||
          (aScreen && state.screen) ||
          (aWindow && state.window)
        );
      })
      .map(aStream => {
        let state = aStream.state;
        let types = {
          camera: state.camera,
          microphone: state.microphone,
          screen: state.screen,
          window: state.window,
        };
        let browser = aStream.topBrowsingContext.embedderElement;
        let browserWindow = browser.ownerGlobal;
        let tab =
          browserWindow.gBrowser &&
          browserWindow.gBrowser.getTabForBrowser(browser);
        return {
          uri: state.documentURI,
          tab,
          browser,
          types,
          devices: state.devices,
        };
      });
  },

  /**
   * Determine the combined state of all the active streams associated with
   * the specified top-level browsing context.
   */
  getCombinedStateForBrowser(aTopBrowsingContext) {
    function combine(x, y) {
      if (
        x == Ci.nsIMediaManagerService.STATE_CAPTURE_ENABLED ||
        y == Ci.nsIMediaManagerService.STATE_CAPTURE_ENABLED
      ) {
        return Ci.nsIMediaManagerService.STATE_CAPTURE_ENABLED;
      }
      if (
        x == Ci.nsIMediaManagerService.STATE_CAPTURE_DISABLED ||
        y == Ci.nsIMediaManagerService.STATE_CAPTURE_DISABLED
      ) {
        return Ci.nsIMediaManagerService.STATE_CAPTURE_DISABLED;
      }
      return Ci.nsIMediaManagerService.STATE_NOCAPTURE;
    }

    let camera, microphone, screen, window, browser;
    for (let stream of this._streams) {
      if (stream.topBrowsingContext == aTopBrowsingContext) {
        camera = combine(stream.state.camera, camera);
        microphone = combine(stream.state.microphone, microphone);
        screen = combine(stream.state.screen, screen);
        window = combine(stream.state.window, window);
        browser = combine(stream.state.browser, browser);
      }
    }

    let tabState = { camera, microphone };
    if (screen == Ci.nsIMediaManagerService.STATE_CAPTURE_ENABLED) {
      tabState.screen = "Screen";
    } else if (window == Ci.nsIMediaManagerService.STATE_CAPTURE_ENABLED) {
      tabState.screen = "Window";
    } else if (browser == Ci.nsIMediaManagerService.STATE_CAPTURE_ENABLED) {
      tabState.screen = "Browser";
    } else if (screen == Ci.nsIMediaManagerService.STATE_CAPTURE_DISABLED) {
      tabState.screen = "ScreenPaused";
    } else if (window == Ci.nsIMediaManagerService.STATE_CAPTURE_DISABLED) {
      tabState.screen = "WindowPaused";
    } else if (browser == Ci.nsIMediaManagerService.STATE_CAPTURE_DISABLED) {
      tabState.screen = "BrowserPaused";
    }

    let screenEnabled = tabState.screen && !tabState.screen.includes("Paused");
    let cameraEnabled =
      tabState.camera == Ci.nsIMediaManagerService.STATE_CAPTURE_ENABLED;
    let microphoneEnabled =
      tabState.microphone == Ci.nsIMediaManagerService.STATE_CAPTURE_ENABLED;

    // tabState.sharing controls which global indicator should be shown
    // for the tab. It should always be set to the _enabled_ device which
    // we consider most intrusive (screen > camera > microphone).
    if (screenEnabled) {
      tabState.sharing = "screen";
    } else if (cameraEnabled) {
      tabState.sharing = "camera";
    } else if (microphoneEnabled) {
      tabState.sharing = "microphone";
    } else if (tabState.screen) {
      tabState.sharing = "screen";
    } else if (tabState.camera) {
      tabState.sharing = "camera";
    } else if (tabState.microphone) {
      tabState.sharing = "microphone";
    }

    // The stream is considered paused when we're sharing something
    // but all devices are off or set to disabled.
    tabState.paused =
      tabState.sharing &&
      !screenEnabled &&
      !cameraEnabled &&
      !microphoneEnabled;

    if (
      tabState.camera == Ci.nsIMediaManagerService.STATE_CAPTURE_ENABLED ||
      tabState.camera == Ci.nsIMediaManagerService.STATE_CAPTURE_DISABLED
    ) {
      tabState.showCameraIndicator = true;
    }
    if (
      tabState.microphone == Ci.nsIMediaManagerService.STATE_CAPTURE_ENABLED ||
      tabState.microphone == Ci.nsIMediaManagerService.STATE_CAPTURE_DISABLED
    ) {
      tabState.showMicrophoneIndicator = true;
    }

    tabState.showScreenSharingIndicator = "";
    if (tabState.screen) {
      if (tabState.screen.startsWith("Screen")) {
        tabState.showScreenSharingIndicator = "Screen";
      } else if (tabState.screen.startsWith("Window")) {
        if (tabState.showScreenSharingIndicator != "Screen") {
          tabState.showScreenSharingIndicator = "Window";
        }
      } else if (tabState.screen.startsWith("Browser")) {
        if (!tabState.showScreenSharingIndicator) {
          tabState.showScreenSharingIndicator = "Browser";
        }
      }
    }

    return tabState;
  },

  /*
   * Indicate that a stream has been added or removed from the given
   * browsing context. If it has been added, aData specifies the
   * specific indicator types it uses. If aData is null or has no
   * documentURI assigned, then the stream has been removed.
   */
  streamAddedOrRemoved(aBrowsingContext, aData) {
    this.init();

    let index;
    for (index = 0; index < webrtcUI._streams.length; ++index) {
      let stream = this._streams[index];
      if (stream.browsingContext == aBrowsingContext) {
        break;
      }
    }
    // The update is a removal of the stream, triggered by the
    // recording-window-ended notification.
    if (aData.remove) {
      if (index < this._streams.length) {
        this._streams.splice(index, 1);
      }
    } else {
      this._streams[index] = {
        browsingContext: aBrowsingContext,
        topBrowsingContext: aBrowsingContext.top,
        state: aData,
      };
    }

    let wasSharingDisplay = this.sharingDisplay;

    // Reset our internal notion of whether or not we're sharing
    // a screen or browser window. Now we'll go through the shared
    // devices and re-determine what's being shared.
    let sharingBrowserWindow = false;
    let sharedWindowRawDeviceIds = new Set();
    this.sharingDisplay = false;
    this.sharingScreen = false;
    let suppressNotifications = false;

    // First, go through the streams and collect the counts on things
    // like the total number of shared windows, and whether or not we're
    // sharing screens.
    for (let stream of this._streams) {
      let { state } = stream;
      suppressNotifications |= state.suppressNotifications;

      for (let device of state.devices) {
        let mediaSource = device.mediaSource;

        if (mediaSource == "window" || mediaSource == "screen") {
          this.sharingDisplay = true;
        }

        if (!device.scary) {
          continue;
        }

        if (mediaSource == "window") {
          sharedWindowRawDeviceIds.add(device.rawId);
        } else if (mediaSource == "screen") {
          this.sharingScreen = true;
        }

        // If the user has granted a particular site the ability
        // to get a stream from a window or screen, we will
        // presume that it's exempt from the tab switch warning.
        //
        // We use the permanentKey here so that the allowing of
        // the tab survives tab tear-in and tear-out.
        let browser = stream.topBrowsingContext.embedderElement;
        this.allowedSharedBrowsers.add(browser.permanentKey);
      }
    }

    // Next, go through the list of shared windows, and map them
    // to our browser windows so that we know which ones are shared.
    this.sharedBrowserWindows = new WeakSet();

    for (let win of BrowserWindowTracker.orderedWindows) {
      let rawDeviceId;
      try {
        rawDeviceId = win.windowUtils.webrtcRawDeviceId;
      } catch (e) {
        // This can theoretically throw if some of the underlying
        // window primitives don't exist. In that case, we can skip
        // to the next window.
        continue;
      }
      if (sharedWindowRawDeviceIds.has(rawDeviceId)) {
        this.sharedBrowserWindows.add(win);

        // If we've shared a window, then the initially selected tab
        // in that window should be exempt from tab switch warnings,
        // since it's already been shared.
        let selectedBrowser = win.gBrowser.selectedBrowser;
        this.allowedSharedBrowsers.add(selectedBrowser.permanentKey);

        sharingBrowserWindow = true;
      }
    }

    // If we weren't sharing a window or screen, and now are, bump
    // the sharingDisplaySessionId. We use this ID for Event
    // telemetry, and consider a transition from no shared displays
    // to some shared displays as a new session.
    if (!wasSharingDisplay && this.sharingDisplay) {
      this.sharingDisplaySessionId++;
    }

    // If we were adding a new display stream, record some Telemetry for
    // it with the most recent sharedDisplaySessionId. We do this separately
    // from the loops above because those take into account the pre-existing
    // streams that might already have been shared.
    if (aData.devices) {
      // The mixture of camelCase with under_score notation here is due to
      // an unfortunate collision of conventions between this file and
      // Event Telemetry.
      let silence_notifs = suppressNotifications ? "true" : "false";
      for (let device of aData.devices) {
        if (device.mediaSource == "screen") {
          this.recordEvent("share_display", "screen", {
            silence_notifs,
          });
        } else if (device.mediaSource == "window") {
          if (device.scary) {
            this.recordEvent("share_display", "browser_window", {
              silence_notifs,
            });
          } else {
            this.recordEvent("share_display", "window", {
              silence_notifs,
            });
          }
        }
      }
    }

    // Since we're not sharing a screen or browser window,
    // we can clear these state variables, which are used
    // to warn users on tab switching when sharing. These
    // are safe to reset even if we hadn't been sharing
    // the screen or browser window already.
    if (!this.sharingScreen && !sharingBrowserWindow) {
      this.allowedSharedBrowsers = new WeakSet();
      this.allowTabSwitchesForSession = false;
      this.tabSwitchCountForSession = 0;
    }

    if (
      Services.prefs.getBoolPref(
        "privacy.webrtc.allowSilencingNotifications",
        false
      )
    ) {
      let alertsService = Cc["@mozilla.org/alerts-service;1"]
        .getService(Ci.nsIAlertsService)
        .QueryInterface(Ci.nsIAlertsDoNotDisturb);
      alertsService.suppressForScreenSharing = suppressNotifications;
    }
  },

  /**
   * Remove all the streams associated with a given
   * browsing context.
   */
  forgetStreamsFromBrowserContext(aBrowsingContext) {
    for (let index = 0; index < webrtcUI._streams.length; ) {
      let stream = this._streams[index];
      if (stream.browsingContext == aBrowsingContext) {
        this._streams.splice(index, 1);
      } else {
        index++;
      }
    }

    // Remove the per-tab indicator if it no longer needs to be displayed.
    let topBC = aBrowsingContext.top;
    if (this.perTabIndicators.has(topBC)) {
      let tabState = this.getCombinedStateForBrowser(topBC);
      if (
        !tabState.showCameraIndicator &&
        !tabState.showMicrophoneIndicator &&
        !tabState.showScreenSharingIndicator
      ) {
        this.perTabIndicators.delete(topBC);
      }
    }

    this.updateGlobalIndicator();
  },

  updateIndicators(aTopBrowsingContext) {
    let tabState = this.getCombinedStateForBrowser(aTopBrowsingContext);

    let indicators;
    if (this.perTabIndicators.has(aTopBrowsingContext)) {
      indicators = this.perTabIndicators.get(aTopBrowsingContext);
    } else {
      indicators = {};
      this.perTabIndicators.set(aTopBrowsingContext, indicators);
    }

    indicators.showCameraIndicator = tabState.showCameraIndicator;
    indicators.showMicrophoneIndicator = tabState.showMicrophoneIndicator;
    indicators.showScreenSharingIndicator = tabState.showScreenSharingIndicator;
    this.updateGlobalIndicator();

    return tabState;
  },

  swapBrowserForNotification(aOldBrowser, aNewBrowser) {
    for (let stream of this._streams) {
      if (stream.browser == aOldBrowser) {
        stream.browser = aNewBrowser;
      }
    }
  },

  forgetActivePermissionsFromBrowser(aBrowser) {
    this.activePerms.delete(aBrowser.outerWindowID);
  },

  showSharingDoorhanger(aActiveStream) {
    let browserWindow = aActiveStream.browser.ownerGlobal;
    if (aActiveStream.tab) {
      browserWindow.gBrowser.selectedTab = aActiveStream.tab;
    } else {
      aActiveStream.browser.focus();
    }
    browserWindow.focus();
    let identityBox = browserWindow.document.getElementById("identity-box");
    if (AppConstants.platform == "macosx" && !Services.focus.activeWindow) {
      browserWindow.addEventListener(
        "activate",
        function() {
          Services.tm.dispatchToMainThread(function() {
            identityBox.click();
          });
        },
        { once: true }
      );
      Cc["@mozilla.org/widget/macdocksupport;1"]
        .getService(Ci.nsIMacDockSupport)
        .activateApplication(true);
      return;
    }
    identityBox.click();
  },

  updateWarningLabel(aMenuList) {
    let type = aMenuList.selectedItem.getAttribute("devicetype");
    let document = aMenuList.ownerDocument;
    document.getElementById("webRTC-all-windows-shared").hidden =
      type != "screen";
  },

  // Add-ons can override stock permission behavior by doing:
  //
  //   webrtcUI.addPeerConnectionBlocker(function(aParams) {
  //     // new permission checking logic
  //   }));
  //
  // The blocking function receives an object with origin, callID, and windowID
  // parameters.  If it returns the string "deny" or a Promise that resolves
  // to "deny", the connection is immediately blocked.  With any other return
  // value (though the string "allow" is suggested for consistency), control
  // is passed to other registered blockers.  If no registered blockers block
  // the connection (or of course if there are no registered blockers), then
  // the connection is allowed.
  //
  // Add-ons may also use webrtcUI.on/off to listen to events without
  // blocking anything:
  //   peer-request-allowed is emitted when a new peer connection is
  //                        established (and not blocked).
  //   peer-request-blocked is emitted when a peer connection request is
  //                        blocked by some blocking connection handler.
  //   peer-request-cancel is emitted when a peer-request connection request
  //                       is canceled.  (This would typically be used in
  //                       conjunction with a blocking handler to cancel
  //                       a user prompt or other work done by the handler)
  addPeerConnectionBlocker(aCallback) {
    this.peerConnectionBlockers.add(aCallback);
  },

  removePeerConnectionBlocker(aCallback) {
    this.peerConnectionBlockers.delete(aCallback);
  },

  on(...args) {
    return this.emitter.on(...args);
  },

  off(...args) {
    return this.emitter.off(...args);
  },

  getHostOrExtensionName(uri, href) {
    let host;
    try {
      if (!uri) {
        uri = Services.io.newURI(href);
      }

      let addonPolicy = WebExtensionPolicy.getByURI(uri);
      host = addonPolicy ? addonPolicy.name : uri.host;
    } catch (ex) {}

    if (!host) {
      if (uri && uri.scheme.toLowerCase() == "about") {
        // For about URIs, just use the full spec, without any #hash parts.
        host = uri.specIgnoringRef;
      } else {
        // This is unfortunate, but we should display *something*...
        const kBundleURI = "chrome://browser/locale/browser.properties";
        let bundle = Services.strings.createBundle(kBundleURI);
        host = bundle.GetStringFromName("getUserMedia.sharingMenuUnknownHost");
      }
    }
    return host;
  },

  updateGlobalIndicator() {
    for (let chromeWin of Services.wm.getEnumerator("navigator:browser")) {
      if (this.showGlobalIndicator) {
        showOrCreateMenuForWindow(chromeWin);
      } else {
        let doc = chromeWin.document;
        let existingMenu = doc.getElementById("tabSharingMenu");
        if (existingMenu) {
          existingMenu.hidden = true;
        }
        if (AppConstants.platform == "macosx") {
          let separator = doc.getElementById("tabSharingSeparator");
          if (separator) {
            separator.hidden = true;
          }
        }
      }
    }

    if (this.showGlobalIndicator) {
      if (!gIndicatorWindow) {
        gIndicatorWindow = getGlobalIndicator();
      } else {
        try {
          gIndicatorWindow.updateIndicatorState();
        } catch (err) {
          Cu.reportError(
            `error in gIndicatorWindow.updateIndicatorState(): ${err.message}`
          );
        }
      }
    } else if (gIndicatorWindow) {
      gIndicatorWindow.close();
      gIndicatorWindow = null;
    }
  },

  getWindowShareState(window) {
    if (this.sharingScreen) {
      return this.SHARING_SCREEN;
    } else if (this.sharedBrowserWindows.has(window)) {
      return this.SHARING_WINDOW;
    }
    return this.SHARING_NONE;
  },

  tabAddedWhileSharing(tab) {
    this.allowedSharedBrowsers.add(tab.linkedBrowser.permanentKey);
  },

  shouldShowSharedTabWarning(tab) {
    if (!tab || !tab.linkedBrowser) {
      return false;
    }

    let browser = tab.linkedBrowser;
    // We want the user to be able to switch to one tab after starting
    // to share their window or screen. The presumption here is that
    // most users will have a single window with multiple tabs, where
    // the selected tab will be the one with the screen or window
    // sharing web application, and it's most likely that the contents
    // that the user wants to share are in another tab that they'll
    // switch to immediately upon sharing. These presumptions are based
    // on research that our user research team did with users using
    // video conferencing web applications.
    if (!this.tabSwitchCountForSession) {
      this.allowedSharedBrowsers.add(browser.permanentKey);
    }

    this.tabSwitchCountForSession++;
    let shouldShow =
      !this.allowTabSwitchesForSession &&
      !this.allowedSharedBrowsers.has(browser.permanentKey);

    if (shouldShow) {
      this.recordEvent("tab_switch_warning", "tab_switch_warning");
    }

    return shouldShow;
  },

  allowSharedTabSwitch(tab, allowForSession) {
    let browser = tab.linkedBrowser;
    let gBrowser = browser.getTabBrowser();
    this.allowedSharedBrowsers.add(browser.permanentKey);
    gBrowser.selectedTab = tab;
    this.allowTabSwitchesForSession = allowForSession;

    if (allowForSession) {
      this.recordEvent("allow_all_tabs", "allow_all_tabs");
    }
  },

  recordEvent(type, object, args = {}) {
    Services.telemetry.recordEvent(
      "webrtc.ui",
      type,
      object,
      this.sharingDisplaySessionId.toString(),
      args
    );
  },
};

function getGlobalIndicator() {
  if (!webrtcUI.useLegacyGlobalIndicator) {
    const INDICATOR_CHROME_URI =
      "chrome://browser/content/webrtcIndicator.xhtml";
    let features = "chrome,titlebar=no,alwaysontop,minimizable=yes";

    /* Don't use dialog on Gtk as it adds extra border and titlebar to indicator */
    if (!AppConstants.MOZ_WIDGET_GTK) {
      features += ",dialog=yes";
    }

    return Services.ww.openWindow(
      null,
      INDICATOR_CHROME_URI,
      "_blank",
      features,
      []
    );
  }

  if (AppConstants.platform != "macosx") {
    const LEGACY_INDICATOR_CHROME_URI =
      "chrome://browser/content/webrtcLegacyIndicator.xhtml";
    const features = "chrome,dialog=yes,titlebar=no,popup=yes";

    return Services.ww.openWindow(
      null,
      LEGACY_INDICATOR_CHROME_URI,
      "_blank",
      features,
      []
    );
  }

  return new MacOSWebRTCStatusbarIndicator();
}

/**
 * Controls the visibility of screen, camera and microphone sharing indicators
 * in the macOS global menu bar. This class should only ever be instantiated
 * on macOS.
 *
 * The public methods on this class intentionally match the interface for the
 * WebRTC global sharing indicator, because the MacOSWebRTCStatusbarIndicator
 * acts as the indicator when in the legacy indicator configuration.
 */
class MacOSWebRTCStatusbarIndicator {
  constructor() {
    this._camera = null;
    this._microphone = null;
    this._screen = null;

    this._hiddenDoc = Services.appShell.hiddenDOMWindow.document;
    this._statusBar = Cc["@mozilla.org/widget/macsystemstatusbar;1"].getService(
      Ci.nsISystemStatusBar
    );

    this.updateIndicatorState();
  }

  /**
   * Public method that will determine the most appropriate
   * set of indicators to show, and then show them or hide
   * them as necessary.
   */
  updateIndicatorState() {
    this._setIndicatorState("Camera", webrtcUI.showCameraIndicator);
    this._setIndicatorState("Microphone", webrtcUI.showMicrophoneIndicator);
    this._setIndicatorState("Screen", webrtcUI.showScreenSharingIndicator);
  }

  /**
   * Public method that will hide all indicators.
   */
  close() {
    this._setIndicatorState("Camera", false);
    this._setIndicatorState("Microphone", false);
    this._setIndicatorState("Screen", false);
  }

  handleEvent(event) {
    switch (event.type) {
      case "popupshowing": {
        this._popupShowing(event);
        break;
      }
      case "popuphiding": {
        this._popupHiding(event);
        break;
      }
      case "command": {
        this._command(event);
        break;
      }
    }
  }

  /**
   * Handler for command events fired by the <menuitem> elements
   * inside any of the indicator <menu>'s.
   *
   * @param {Event} aEvent - The command event for the <menuitem>.
   */
  _command(aEvent) {
    webrtcUI.showSharingDoorhanger(aEvent.target.stream);
  }

  /**
   * Handler for the popupshowing event for one of the status
   * bar indicator menus.
   *
   * @param {Event} aEvent - The popupshowing event for the <menu>.
   */
  _popupShowing(aEvent) {
    let menu = aEvent.target;
    let type = menu.getAttribute("type");
    let activeStreams;
    if (type == "Camera") {
      activeStreams = webrtcUI.getActiveStreams(true, false, false);
    } else if (type == "Microphone") {
      activeStreams = webrtcUI.getActiveStreams(false, true, false);
    } else if (type == "Screen") {
      activeStreams = webrtcUI.getActiveStreams(false, false, true);
      type = webrtcUI.showScreenSharingIndicator;
    }

    let bundle = Services.strings.createBundle(
      "chrome://browser/locale/webrtcIndicator.properties"
    );

    if (activeStreams.length == 1) {
      let stream = activeStreams[0];

      let menuitem = menu.ownerDocument.createXULElement("menuitem");
      let labelId = "webrtcIndicator.sharing" + type + "With.menuitem";
      let label = stream.browser.contentTitle || stream.uri;
      menuitem.setAttribute(
        "label",
        bundle.formatStringFromName(labelId, [label])
      );
      menuitem.setAttribute("disabled", "true");
      menu.appendChild(menuitem);

      menuitem = menu.ownerDocument.createXULElement("menuitem");
      menuitem.setAttribute(
        "label",
        bundle.GetStringFromName("webrtcIndicator.controlSharing.menuitem")
      );
      menuitem.stream = stream;
      menuitem.addEventListener("command", this);

      menu.appendChild(menuitem);
      return true;
    }

    // We show a different menu when there are several active streams.
    let menuitem = menu.ownerDocument.createXULElement("menuitem");
    let labelId = "webrtcIndicator.sharing" + type + "WithNTabs.menuitem";
    let count = activeStreams.length;
    let label = PluralForm.get(
      count,
      bundle.GetStringFromName(labelId)
    ).replace("#1", count);
    menuitem.setAttribute("label", label);
    menuitem.setAttribute("disabled", "true");
    menu.appendChild(menuitem);

    for (let stream of activeStreams) {
      let item = menu.ownerDocument.createXULElement("menuitem");
      labelId = "webrtcIndicator.controlSharingOn.menuitem";
      label = stream.browser.contentTitle || stream.uri;
      item.setAttribute("label", bundle.formatStringFromName(labelId, [label]));
      item.stream = stream;
      item.addEventListener("command", this);
      menu.appendChild(item);
    }

    return true;
  }

  /**
   * Handler for the popuphiding event for one of the status
   * bar indicator menus.
   *
   * @param {Event} aEvent - The popuphiding event for the <menu>.
   */
  _popupHiding(aEvent) {
    let menu = aEvent.target;
    while (menu.firstChild) {
      menu.firstChild.remove();
    }
  }

  /**
   * Updates the status bar to show or hide a screen, camera or
   * microphone indicator.
   *
   * @param {String} aName - One of the following: "screen", "camera",
   *   "microphone"
   * @param {boolean} aState - True to show the indicator for the aName
   *   type of stream, false ot hide it.
   */
  _setIndicatorState(aName, aState) {
    let field = "_" + aName.toLowerCase();
    if (aState && !this[field]) {
      let menu = this._hiddenDoc.createXULElement("menu");
      menu.setAttribute("id", "webRTC-sharing" + aName + "-menu");

      // The CSS will only be applied if the menu is actually inserted in the DOM.
      this._hiddenDoc.documentElement.appendChild(menu);

      this._statusBar.addItem(menu);

      let menupopup = this._hiddenDoc.createXULElement("menupopup");
      menupopup.setAttribute("type", aName);
      menupopup.addEventListener("popupshowing", this);
      menupopup.addEventListener("popuphiding", this);
      menupopup.addEventListener("command", this);
      menu.appendChild(menupopup);

      this[field] = menu;
    } else if (this[field] && !aState) {
      this._statusBar.removeItem(this[field]);
      this[field].remove();
      this[field] = null;
    }
  }
}

function onTabSharingMenuPopupShowing(e) {
  let streams = webrtcUI.getActiveStreams(true, true, true);
  for (let streamInfo of streams) {
    let stringName = "getUserMedia.sharingMenu";
    let types = streamInfo.types;
    if (types.camera) {
      stringName += "Camera";
    }
    if (types.microphone) {
      stringName += "Microphone";
    }
    if (types.screen) {
      stringName += types.screen;
    }

    let doc = e.target.ownerDocument;
    let bundle = doc.defaultView.gNavigatorBundle;

    let origin = webrtcUI.getHostOrExtensionName(null, streamInfo.uri);
    let menuitem = doc.createXULElement("menuitem");
    menuitem.setAttribute(
      "label",
      bundle.getFormattedString(stringName, [origin])
    );
    menuitem.stream = streamInfo;
    menuitem.addEventListener("command", onTabSharingMenuPopupCommand);
    e.target.appendChild(menuitem);
  }
}

function onTabSharingMenuPopupHiding(e) {
  while (this.lastChild) {
    this.lastChild.remove();
  }
}

function onTabSharingMenuPopupCommand(e) {
  webrtcUI.showSharingDoorhanger(e.target.stream);
}

function showOrCreateMenuForWindow(aWindow) {
  let document = aWindow.document;
  let menu = document.getElementById("tabSharingMenu");
  if (!menu) {
    let stringBundle = aWindow.gNavigatorBundle;
    menu = document.createXULElement("menu");
    menu.id = "tabSharingMenu";
    let labelStringId = "getUserMedia.sharingMenu.label";
    menu.setAttribute("label", stringBundle.getString(labelStringId));

    let container, insertionPoint;
    if (AppConstants.platform == "macosx") {
      container = document.getElementById("windowPopup");
      insertionPoint = document.getElementById("sep-window-list");
      let separator = document.createXULElement("menuseparator");
      separator.id = "tabSharingSeparator";
      container.insertBefore(separator, insertionPoint);
    } else {
      let accesskeyStringId = "getUserMedia.sharingMenu.accesskey";
      menu.setAttribute("accesskey", stringBundle.getString(accesskeyStringId));
      container = document.getElementById("main-menubar");
      insertionPoint = document.getElementById("helpMenu");
    }
    let popup = document.createXULElement("menupopup");
    popup.id = "tabSharingMenuPopup";
    popup.addEventListener("popupshowing", onTabSharingMenuPopupShowing);
    popup.addEventListener("popuphiding", onTabSharingMenuPopupHiding);
    menu.appendChild(popup);
    container.insertBefore(menu, insertionPoint);
  } else {
    menu.hidden = false;
    if (AppConstants.platform == "macosx") {
      document.getElementById("tabSharingSeparator").hidden = false;
    }
  }
}

var gIndicatorWindow = null;