multi-account-containers/index.js

661 lines
20 KiB
JavaScript

/* 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 XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
const HIDE_MENU_TIMEOUT = 1000;
const IDENTITY_COLORS = ["blue", "turquoise", "green", "yellow", "orange", "red", "pink", "purple"];
const { attachTo } = require("sdk/content/mod");
const { ContextualIdentityService } = require("resource://gre/modules/ContextualIdentityService.jsm");
const { getFavicon } = require("sdk/places/favicon");
const self = require("sdk/self");
const { Style } = require("sdk/stylesheet/style");
const tabs = require("sdk/tabs");
const tabsUtils = require("sdk/tabs/utils");
const { viewFor } = require("sdk/view/core");
const webExtension = require("sdk/webextension");
const windows = require("sdk/windows");
const windowUtils = require("sdk/window/utils");
// ----------------------------------------------------------------------------
// ContainerService
const ContainerService = {
_identitiesState: {},
_windowMap: {},
init() {
// Enabling preferences
const prefs = [
[ "privacy.userContext.enabled", true ],
[ "privacy.userContext.ui.enabled", true ],
[ "privacy.usercontext.about_newtab_segregation.enabled", true ],
[ "privacy.usercontext.longPressBehavior", 1 ]
];
const prefService = require("sdk/preferences/service");
prefs.forEach((pref) => {
prefService.set(pref[0], pref[1]);
});
// Message routing
// only these methods are allowed. We have a 1:1 mapping between messages
// and methods. These methods must return a promise.
const methods = [
"hideTabs",
"showTabs",
"sortTabs",
"getTabs",
"showTab",
"openTab",
"moveTabsToWindow",
"queryIdentities",
"getIdentity",
"createIdentity",
"removeIdentity",
"updateIdentity",
];
// Map of identities.
ContextualIdentityService.getIdentities().forEach(identity => {
this._identitiesState[identity.userContextId] = {
hiddenTabUrls: [],
openTabs: 0
};
});
// It can happen that this jsm is loaded after the opening a container tab.
for (let tab of tabs) { // eslint-disable-line prefer-const
const userContextId = this._getUserContextIdFromTab(tab);
if (userContextId) {
++this._identitiesState[userContextId].openTabs;
}
}
tabs.on("open", tab => {
const userContextId = this._getUserContextIdFromTab(tab);
if (userContextId) {
++this._identitiesState[userContextId].openTabs;
}
this._hideAllPanels();
});
tabs.on("close", tab => {
const userContextId = this._getUserContextIdFromTab(tab);
if (userContextId && this._identitiesState[userContextId].openTabs) {
--this._identitiesState[userContextId].openTabs;
}
this._hideAllPanels();
});
tabs.on("activate", () => {
this._hideAllPanels();
});
// Modify CSS and other stuff for each window.
this.configureWindows();
windows.browserWindows.on("open", window => {
this.configureWindow(viewFor(window));
});
windows.browserWindows.on("close", window => {
this.closeWindow(viewFor(window));
});
// WebExtension startup
webExtension.startup().then(api => {
api.browser.runtime.onMessage.addListener((message, sender, sendReply) => {
if ("method" in message && methods.indexOf(message.method) !== -1) {
sendReply(this[message.method](message));
}
});
}).catch(() => {
throw new Error("WebExtension startup failed. Unable to continue.");
});
},
// utility methods
_convert(identity) {
// In FF 50-51, the icon is the full path, in 52 and following
// releases, we have IDs to be used with a svg file. In this function
// we map URLs to svg IDs.
let image, color;
if (identity.icon === "fingerprint" ||
identity.icon === "chrome://browser/skin/usercontext/personal.svg") {
image = "fingerprint";
} else if (identity.icon === "briefcase" ||
identity.icon === "chrome://browser/skin/usercontext/work.svg") {
image = "briefcase";
} else if (identity.icon === "dollar" ||
identity.icon === "chrome://browser/skin/usercontext/banking.svg") {
image = "dollar";
} else if (identity.icon === "cart" ||
identity.icon === "chrome://browser/skin/usercontext/shopping.svg") {
image = "cart";
} else {
image = "circle";
}
if (identity.color === "#00a7e0") {
color = "blue";
} else if (identity.color === "#f89c24") {
color = "orange";
} else if (identity.color === "#7dc14c") {
color = "green";
} else if (identity.color === "#ee5195") {
color = "pink";
} else if (IDENTITY_COLORS.indexOf(identity.color) !== -1) {
color = identity.color;
} else {
color = "";
}
return {
name: ContextualIdentityService.getUserContextLabel(identity.userContextId),
image,
color,
userContextId: identity.userContextId,
hasHiddenTabs: !!this._identitiesState[identity.userContextId].hiddenTabUrls.length,
hasOpenTabs: !!this._identitiesState[identity.userContextId].openTabs
};
},
_getUserContextIdFromTab(tab) {
return parseInt(viewFor(tab).getAttribute("usercontextid") || 0, 10);
},
_createTabObject(tab) {
return { title: tab.title, url: tab.url, id: tab.id, active: true };
},
_containerTabIterator(userContextId, cb) {
for (let tab of tabs) { // eslint-disable-line prefer-const
if (userContextId === this._getUserContextIdFromTab(tab)) {
cb(tab);
}
}
},
// Tabs management
hideTabs(args) {
return new Promise((resolve, reject) => {
if (!("userContextId" in args)) {
reject("hideTabs must be called with userContextId argument.");
return;
}
this._containerTabIterator(args.userContextId, tab => {
const object = this._createTabObject(tab);
// This tab is going to be closed. Let's mark this tabObject as
// non-active.
object.active = false;
getFavicon(object.url).then(url => {
object.favicon = url;
}).catch(() => {
object.favicon = "";
});
this._identitiesState[args.userContextId].hiddenTabUrls.push(object);
tab.close();
});
resolve(null);
});
},
showTabs(args) {
if (!("userContextId" in args)) {
return Promise.reject("showTabs must be called with userContextId argument.");
}
const promises = [];
for (let object of this._identitiesState[args.userContextId].hiddenTabUrls) { // eslint-disable-line prefer-const
promises.push(this.openTab({ userContextId: args.userContextId, url: object.url }));
}
this._identitiesState[args.userContextId].hiddenTabUrls = [];
return Promise.all(promises);
},
sortTabs() {
return new Promise(resolve => {
for (let window of windows.browserWindows) { // eslint-disable-line prefer-const
// First the pinned tabs, then the normal ones.
this._sortTabsInternal(window, true);
this._sortTabsInternal(window, false);
}
resolve(null);
});
},
_sortTabsInternal(window, pinnedTabs) {
// From model to XUL window.
const xulWindow = viewFor(window);
const tabs = tabsUtils.getTabs(xulWindow);
let pos = 0;
// Let's collect UCIs/tabs for this window.
const map = new Map;
for (let tab of tabs) { // eslint-disable-line prefer-const
if (pinnedTabs && !tabsUtils.isPinned(tab)) {
// We don't have, or we already handled all the pinned tabs.
break;
}
if (!pinnedTabs && tabsUtils.isPinned(tab)) {
// pinned tabs must be consider as taken positions.
++pos;
continue;
}
const userContextId = this._getUserContextIdFromTab(tab);
if (!map.has(userContextId)) {
map.set(userContextId, []);
}
map.get(userContextId).push(tab);
}
// Let's sort the map.
const sortMap = new Map([...map.entries()].sort((a, b) => a[0] > b[0]));
// Let's move tabs.
sortMap.forEach(tabs => {
for (let tab of tabs) { // eslint-disable-line prefer-const
xulWindow.gBrowser.moveTabTo(tab, pos++);
}
});
},
getTabs(args) {
return new Promise((resolve, reject) => {
if (!("userContextId" in args)) {
reject("getTabs must be called with userContextId argument.");
return;
}
const list = [];
this._containerTabIterator(args.userContextId, tab => {
list.push(this._createTabObject(tab));
});
const promises = [];
for (let object of list) { // eslint-disable-line prefer-const
promises.push(getFavicon(object.url).then(url => {
object.favicon = url;
}).catch(() => {
object.favicon = "";
}));
}
Promise.all(promises).then(() => {
resolve(list.concat(this._identitiesState[args.userContextId].hiddenTabUrls));
}).catch((e) => {
reject(e);
});
});
},
showTab(args) {
return new Promise((resolve, reject) => {
if (!("tabId" in args)) {
reject("showTab must be called with tabId argument.");
return;
}
for (let tab of tabs) { // eslint-disable-line prefer-const
if (tab.id === args.tabId) {
tab.window.activate();
tab.activate();
break;
}
}
resolve(null);
});
},
moveTabsToWindow(args) {
return new Promise((resolve, reject) => {
if (!("userContextId" in args)) {
reject("moveTabsToWindow must be called with userContextId argument.");
return;
}
// Let's create a list of the tabs.
const list = [];
this._containerTabIterator(args.userContextId, tab => {
list.push(tab);
});
// Nothing to do
if (list.length === 0) {
resolve(null);
return;
}
windows.browserWindows.open({
url: "about:blank",
onOpen: window => {
const newBrowserWindow = viewFor(window);
// Let's move the tab to the new window.
for (let tab of list) { // eslint-disable-line prefer-const
const newTab = newBrowserWindow.gBrowser.addTab("about:blank");
newBrowserWindow.gBrowser.swapBrowsersAndCloseOther(newTab, viewFor(tab));
// swapBrowsersAndCloseOther is an internal method of gBrowser
// an it's not supported by addon SDK. This means that we
// don't receive an 'open' event, but only the 'close' one.
// We have to force a +1 in our tab counter.
++this._identitiesState[args.userContextId].openTabs;
}
// Let's close all the normal tab in the new window. In theory it
// should be only the first tab, but maybe there are addons doing
// crazy stuff.
for (let tab of window.tabs) { // eslint-disable-line prefer-const
const userContextId = this._getUserContextIdFromTab(tab);
if (args.userContextId !== userContextId) {
newBrowserWindow.gBrowser.removeTab(viewFor(tab));
}
}
resolve(null);
},
});
});
},
openTab(args) {
return new Promise(resolve => {
const browserWin = windowUtils.getMostRecentBrowserWindow();
// This should not really happen.
if (!browserWin || !browserWin.gBrowser) {
return Promise.resolve(false);
}
let userContextId = 0;
if ("userContextId" in args) {
userContextId = args.userContextId;
}
const tab = browserWin.gBrowser.addTab(args.url || null, { userContextId });
browserWin.gBrowser.selectedTab = tab;
resolve(true);
});
},
// Identities management
queryIdentities() {
return new Promise(resolve => {
const identities = [];
ContextualIdentityService.getIdentities().forEach(identity => {
const convertedIdentity = this._convert(identity);
identities.push(convertedIdentity);
});
resolve(identities);
});
},
getIdentity(args) {
if (!("userContextId" in args)) {
return Promise.reject("getIdentity must be called with userContextId argument.");
}
const identity = ContextualIdentityService.getIdentityFromId(args.userContextId);
return Promise.resolve(identity ? this._convert(identity) : null);
},
createIdentity(args) {
for (let arg of [ "name", "color", "icon"]) { // eslint-disable-line prefer-const
if (!(arg in args)) {
return Promise.reject("createIdentity must be called with " + arg + " argument.");
}
}
// FIXME: icon and color conversion based on FF version.
const identity = ContextualIdentityService.create(args.name, args.icon, args.color);
this._identitiesState[identity.userContextId] = {
hiddenTabUrls: [],
openTabs: 0
};
this._refreshNeeded();
return Promise.resolve(this._convert(identity));
},
updateIdentity(args) {
if (!("userContextId" in args)) {
return Promise.reject("updateIdentity must be called with userContextId argument.");
}
const identity = ContextualIdentityService.getIdentityFromId(args.userContextId);
for (let arg of [ "name", "color", "icon"]) { // eslint-disable-line prefer-const
if ((arg in args)) {
identity[arg] = args[arg];
}
}
// FIXME: icon and color conversion based on FF version.
const updated = ContextualIdentityService.update(args.userContextId,
identity.name,
identity.icon,
identity.color);
this._refreshNeeded();
return Promise.resolve(updated);
},
removeIdentity(args) {
if (!("userContextId" in args)) {
return Promise.reject("removeIdentity must be called with userContextId argument.");
}
this._containerTabIterator(args.userContextId, tab => {
tab.close();
});
const removed = ContextualIdentityService.remove(args.userContextId);
this._refreshNeeded();
return Promise.resolve(removed);
},
// Styling the window
configureWindows() {
for (let window of windows.browserWindows) { // eslint-disable-line prefer-const
this.configureWindow(viewFor(window));
}
},
configureWindow(window) {
const id = windowUtils.getInnerId(window);
if (!(id in this._windowMap)) {
this._windowMap[id] = new ContainerWindow(window);
}
this._windowMap[id].configure();
},
closeWindow(window) {
const id = windowUtils.getInnerId(window);
delete this._windowMap[id];
},
_refreshNeeded() {
// FIXME: color/name propagation
this.configureWindows();
},
_hideAllPanels() {
for (let id in this._windowMap) { // eslint-disable-line prefer-const
this._windowMap[id].hidePanel();
}
},
};
// ----------------------------------------------------------------------------
// ContainerWindow
// This object is used to configure a single window.
function ContainerWindow(window) {
this._init(window);
}
ContainerWindow.prototype = {
_window: null,
_panelElement: null,
_timeoutId: 0,
_init(window) {
this._window = window;
const style = Style({ uri: self.data.url("usercontext.css") });
attachTo(style, this._window);
},
configure() {
const tabsElement = this._window.document.getElementById("tabbrowser-tabs");
const button = this._window.document.getAnonymousElementByAttribute(tabsElement, "anonid", "tabs-newtab-button");
// Let's remove the tooltip because it can go over our panel.
button.setAttribute("tooltip", "");
// Let's remove all the previous panels.
if (this._panelElement) {
this._panelElement.remove();
}
this._panelElement = this._window.document.createElementNS(XUL_NS, "panel");
this._panelElement.setAttribute("id", "new-tab-overlay");
button.after(this._panelElement);
this._panelElement.hidden = true;
this._repositionPopup();
ContainerService.queryIdentities().then(identities => {
identities.forEach(identity => {
const menuItemElement = this._window.document.createElementNS(XUL_NS, "menuitem");
this._panelElement.appendChild(menuItemElement);
menuItemElement.className = "menuitem-iconic";
menuItemElement.setAttribute("label", identity.name);
menuItemElement.setAttribute("data-usercontextid", identity.userContextId);
menuItemElement.setAttribute("data-identity-icon", identity.image);
menuItemElement.setAttribute("data-identity-color", identity.color);
menuItemElement.addEventListener("command", e => {
ContainerService.openTab({userContextId: identity.userContextId});
e.stopPropagation();
});
//Command isn't working probably because I'm in a panel
menuItemElement.addEventListener("click", e => {
ContainerService.openTab({userContextId: identity.userContextId});
e.stopPropagation();
});
menuItemElement.addEventListener("mouseover", () => {
this._cleanTimeout();
});
menuItemElement.addEventListener("mouseout", () => {
this._createTimeout();
});
this._panelElement.appendChild(menuItemElement);
});
}).catch(() => {
this.hidePanel();
});
button.addEventListener("click", () => {
this._panelElement.hidden = false;
});
button.addEventListener("mouseover", () => {
this._repositionPopup();
this._panelElement.hidden = false;
});
button.addEventListener("mouseout", () => {
this._createTimeout();
});
this._panelElement.addEventListener("mouseout", (e) => {
if (e.target !== this._panelElement) {
this._createTimeout();
return;
}
this._repositionPopup();
});
},
// This function puts the popup in the correct place.
_repositionPopup() {
const tabsElement = this._window.document.getElementById("tabbrowser-tabs");
const button = this._window.document.getAnonymousElementByAttribute(tabsElement, "anonid", "tabs-newtab-button");
const size = button.getBoxQuads()[0];
const innerWindow = tabsElement.getBoxQuads()[0];
const panelElementWidth = 200;
// 1/4th of the way past the left hand side of the new tab button
// This seems to line up nicely with the left of the +
const offset = ((size.p3.x - size.p4.x) / 4);
let left = size.p4.x + offset;
if (left + panelElementWidth > innerWindow.p2.x) {
left -= panelElementWidth - offset;
}
this._panelElement.style.left = left + "px";
this._panelElement.style.top = size.p4.y + "px";
},
// This timer is used to hide the panel auto-magically if it's not used in
// the following X seconds. This is need to avoid the leaking of the panel
// when the mouse goes out of of the 'plus' button.
_createTimeout() {
this._cleanTimeout();
this._timeoutId = this._window.setTimeout(() => {
this.hidePanel();
this._timeoutId = 0;
}, HIDE_MENU_TIMEOUT);
},
_cleanTimeout() {
if (this._timeoutId) {
this._window.clearTimeout(this._timeoutId);
this._timeoutId = 0;
}
},
hidePanel() {
this._cleanTimeout();
this._panelElement.hidden = true;
},
};
// ----------------------------------------------------------------------------
// Let's start :)
ContainerService.init();