Merge pull request #43 from bakulf/cleanup_methods

for #33: 51 support and #11 and much more.
This commit is contained in:
Andrea Marchesini 2017-01-09 12:14:42 +01:00 committed by GitHub
commit 0a1661d32f
4 changed files with 276 additions and 250 deletions

View file

@ -14,7 +14,7 @@ details](https://docs.google.com/document/d/1WQdHTVXROk7dYkSFluc6_hS44tqZjIrG9I-
## Requirements ## Requirements
* node 7+ (for jpm) * node 7+ (for jpm)
* Firefox 52+ (For now; aiming at Firefox 51+) * Firefox 51+
## Run it ## Run it
@ -53,7 +53,7 @@ The only way to run the experiment is using an [unbranded version build](https:/
1. `git clone git@github.com:mozilla/testpilot-containers.git` 1. `git clone git@github.com:mozilla/testpilot-containers.git`
2. `cd testpilot-containers` 2. `cd testpilot-containers`
3. `npm install` 3. `npm install`
4. `./node_modules/.bin/jpm run -p /Path/To/Firefox/Profiles/{junk}.addon_dev -b FirefoxDeveloperEdition` (where FirefoxDeveloperEdition might be: ~/<reponame>/obj-x86_64-pc-linux-gnu/dist/bin/firefox) 4. `./node_modules/.bin/jpm run -p /Path/To/Firefox/Profiles/{junk}.addon_dev -b FirefoxBeta` (where FirefoxBeta might be: ~/<reponame>/obj-x86_64-pc-linux-gnu/dist/bin/firefox or ~/<downloadedFirefoxBeta>/firefox)
Check out the [Browser Toolbox](https://developer.mozilla.org/en-US/docs/Tools/Browser_Toolbox) for more information about debugging add-on code. Check out the [Browser Toolbox](https://developer.mozilla.org/en-US/docs/Tools/Browser_Toolbox) for more information about debugging add-on code.

347
index.js
View file

@ -1,208 +1,213 @@
/* global require */ /* global require */
const {ContextualIdentityService} = require('resource://gre/modules/ContextualIdentityService.jsm'); const {ContextualIdentityService} = require('resource://gre/modules/ContextualIdentityService.jsm');
const { Cc, Ci, Cu, Cr } = require('chrome');
const tabs = require('sdk/tabs'); const tabs = require('sdk/tabs');
const webExtension = require('sdk/webextension'); const webExtension = require('sdk/webextension');
const { viewFor } = require("sdk/view/core");
var windowUtils = require('sdk/window/utils');
var tabsUtils = require('sdk/tabs/utils');
/* Let's start enabling Containers */ let ContainerService =
var prefs = [ {
[ "privacy.userContext.enabled", true ], _identitiesState: {},
[ "privacy.userContext.ui.enabled", true ],
[ "privacy.usercontext.about_newtab_segregation.enabled", true ],
[ "privacy.usercontext.longPressBehavior", 1 ]
];
const prefService = require("sdk/preferences/service"); init() {
prefs.forEach((pref) => { // Enabling preferences
prefService.set(pref[0], pref[1]);
});
const CONTAINER_STORE = 'firefox-container-'; let prefs = [
[ "privacy.userContext.enabled", true ],
[ "privacy.userContext.ui.enabled", true ],
[ "privacy.usercontext.about_newtab_segregation.enabled", true ],
[ "privacy.usercontext.longPressBehavior", 1 ]
];
const identitiesState = { const prefService = require("sdk/preferences/service");
}; prefs.forEach((pref) => {
prefService.set(pref[0], pref[1]);
});
function getCookieStoreIdForContainer(containerId) { // Message routing
return CONTAINER_STORE + containerId;
}
function convert(identity) { // only these methods are allowed. We have a 1:1 mapping between messages
const cookieStoreId = getCookieStoreIdForContainer(identity.userContextId); // and methods. These methods must return a promise.
let hiddenTabUrls = []; let methods = [
'hideTabs',
'showTabs',
'sortTabs',
'openTab',
'queryIdentities',
'getIdentity',
];
if (cookieStoreId in identitiesState) { // Map of identities.
hiddenTabUrls = identitiesState[cookieStoreId].hiddenTabUrls; ContextualIdentityService.getIdentities().forEach(identity => {
} this._identitiesState[identity.userContextId] = {
const result = { hiddenTabUrls: [],
name: ContextualIdentityService.getUserContextLabel(identity.userContextId), openTabs: 0,
icon: identity.icon, };
color: identity.color, });
cookieStoreId: cookieStoreId,
hiddenTabUrls: hiddenTabUrls
};
return result; // It can happen that this jsm is loaded after the opening a container tab.
} for (let tab of tabs) {
let xulTab = viewFor(tab);
function isContainerCookieStoreId(storeId) { let userContextId = parseInt(xulTab.getAttribute('usercontextid') || 0, 10);
return storeId !== null && storeId.startsWith(CONTAINER_STORE); if (userContextId) {
} ++this._identitiesState[userContextId].openTabs;
}
function getContainerForCookieStoreId(storeId) {
if (!isContainerCookieStoreId(storeId)) {
return null;
}
const containerId = storeId.substring(CONTAINER_STORE.length);
if (ContextualIdentityService.getIdentityFromId(containerId)) {
return parseInt(containerId, 10);
}
return null;
}
function getContainer(cookieStoreId) {
const containerId = getContainerForCookieStoreId(cookieStoreId);
if (!containerId) {
return Promise.resolve(null);
}
const identity = ContextualIdentityService.getIdentityFromId(containerId);
return Promise.resolve(convert(identity));
}
function queryContainers(details) {
const identities = [];
ContextualIdentityService.getIdentities().forEach(identity=> {
if (details && details.name &&
ContextualIdentityService.getUserContextLabel(identity.userContextId) !== details.name) {
return;
} }
const convertedIdentity = convert(identity); tabs.on("open", tab => {
let xulTab = viewFor(tab);
let userContextId = parseInt(xulTab.getAttribute('usercontextid') || 0, 10);
if (userContextId) {
++this._identitiesState[userContextId].openTabs;
}
});
identities.push(convertedIdentity); tabs.on("close", tab => {
if (!(convertedIdentity.cookieStoreId in identitiesState)) { let xulTab = viewFor(tab);
identitiesState[convertedIdentity.cookieStoreId] = {hiddenTabUrls: []}; let userContextId = parseInt(xulTab.getAttribute('usercontextid') || 0, 10);
if (userContextId && this._identitiesState[userContextId].openTabs) {
--this._identitiesState[userContextId].openTabs;
}
});
// 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));
}
});
});
},
// utility methods
_convert(identity) {
return {
name: ContextualIdentityService.getUserContextLabel(identity.userContextId),
icon: identity.icon,
color: identity.color,
userContextId: identity.userContextId,
hasHiddenTabs: !!this._identitiesState[identity.userContextId].hiddenTabUrls.length,
hasOpenTabs: !!this._identitiesState[identity.userContextId].openTabs,
};
},
// Tabs management
hideTabs(args) {
return new Promise((resolve, reject) => {
for (let tab of tabs) {
let xulTab = viewFor(tab);
let userContextId = parseInt(xulTab.getAttribute('usercontextid') || 0, 10);
if ("userContextId" in args && args.userContextId != userContextId) {
continue;
}
this._identitiesState[args.userContextId].hiddenTabUrls.push(tab.url);
tab.close();
}
resolve(null);
});
},
showTabs(args) {
let promises = [];
for (let url of this._identitiesState[args.userContextId].hiddenTabUrls) {
promises.push(this.openTab({ userContextId: args.userContextId, url }));
} }
});
return Promise.resolve(identities); this._identitiesState[args.userContextId].hiddenTabUrls = [];
}
function createContainer(details) { return Promise.all(promises);
const identity = ContextualIdentityService.create(details.name, },
details.icon,
details.color);
return Promise.resolve(convert(identity)); sortTabs(args) {
} return new Promise((resolve, reject) => {
let windows = windowUtils.windows('navigator:browser', {includePrivate:false});
for (let window of windows) {
let tabs = tabsUtils.getTabs(window);
function updateContainer(cookieStoreId, details) { let pos = 0;
const containerId = getContainerForCookieStoreId(cookieStoreId);
if (!containerId) { // Let's collect UCIs/tabs for this window.
return Promise.resolve(null); let map = new Map;
} for (let tab of tabs) {
if (tabsUtils.isPinned(tab)) {
// pinned tabs must be consider as taken positions.
++pos;
continue;
}
const identity = ContextualIdentityService.getIdentityFromId(containerId); let userContextId = parseInt(tab.getAttribute('usercontextid') || 0, 10);
if (!map.has(userContextId)) {
map.set(userContextId, []);
}
map.get(userContextId).push(tab);
}
if (!identity) { // Let's sort the map.
return Promise.resolve(null); let sortMap = new Map([...map.entries()].sort((a, b) => a[0] > b[0]));
}
if (details.name !== null) { // Let's move tabs.
identity.name = details.name; for (let [userContextId, tabs] of sortMap) {
} for (let tab of tabs) {
window.gBrowser.moveTabTo(tab, pos++);
}
}
}
if (details.color !== null) { resolve(null);
identity.color = details.color; });
} },
if (details.icon !== null) { openTab(args) {
identity.icon = details.icon; return new Promise((resolve, reject) => {
} let browserWin = windowUtils.getMostRecentBrowserWindow();
if (!ContextualIdentityService.update(identity.userContextId, // This should not really happen.
identity.name, identity.icon, if (!browserWin || !browserWin.gBrowser) {
identity.color)) { return Promise.resolve(false);
return Promise.resolve(null); }
}
return Promise.resolve(convert(identity)); let userContextId = 0;
} if ('userContextId' in args) {
userContextId = args.userContextId;
}
function removeContainer(cookieStoreId) { let tab = browserWin.gBrowser.addTab(args.url || null,
const containerId = getContainerForCookieStoreId(cookieStoreId); { userContextId: userContextId })
browserWin.gBrowser.selectedTab = tab;
resolve(true);
});
},
if (!containerId) { // Identities management
return Promise.resolve(null);
}
const identity = ContextualIdentityService.getIdentityFromId(containerId); queryIdentities(args) {
return new Promise((resolve, reject) => {
let identities = [];
if (!identity) { ContextualIdentityService.getIdentities().forEach(identity => {
return Promise.resolve(null); let convertedIdentity = this._convert(identity);
} identities.push(convertedIdentity);
});
// We have to create the identity object before removing it. resolve(identities);
const convertedIdentity = convert(identity); });
},
if (!ContextualIdentityService.remove(identity.userContextId)) { getIdentity(args) {
return Promise.resolve(null); let identity = ContextualIdentityService.getIdentityFromId(args.userContextId);
} return Promise.resolve(identity ? this._convert(identity) : null);
},
return Promise.resolve(convertedIdentity);
}
const contextualIdentities = {
get: getContainer,
query: queryContainers,
create: createContainer,
update: updateContainer,
remove: removeContainer
}; };
function handleWebExtensionMessage(message, sender, sendReply) { ContainerService.init();
switch (message.method) {
case 'query':
sendReply(contextualIdentities.query(message.arguments));
break;
case 'hide':
identitiesState[message.cookieStoreId].hiddenTabUrls = message.tabUrlsToSave;
break;
case 'show':
sendReply(identitiesState[message.cookieStoreId].hiddenTabUrls);
identitiesState[message.cookieStoreId].hiddenTabUrls = [];
break;
case 'get':
sendReply(contextualIdentities.get(message.arguments));
break;
case 'create':
sendReply(contextualIdentities.create(message.arguments));
break;
case 'update':
sendReply(contextualIdentities.update(message.arguments));
break;
case 'remove':
sendReply(contextualIdentities.remove(message.arguments));
break;
case 'getIdentitiesState':
sendReply(identitiesState);
break;
case 'open-containers-preferences':
tabs.open('about:preferences#containers');
sendReply({content: 'opened'});
break;
}
}
webExtension.startup().then(api=> {
const {browser} = api;
browser.runtime.onMessage.addListener(handleWebExtensionMessage);
});

View file

@ -98,21 +98,21 @@ table.unstriped tbody tr {
} }
[data-identity-icon="fingerprint"] { [data-identity-icon="fingerprint"] {
--identity-icon: url("chrome://browser/content/usercontext.svg#fingerprint"); --identity-icon: url("/img/usercontext.svg#fingerprint");
} }
[data-identity-icon="briefcase"] { [data-identity-icon="briefcase"] {
--identity-icon: url("chrome://browser/content/usercontext.svg#briefcase"); --identity-icon: url("/img/usercontext.svg#briefcase");
} }
[data-identity-icon="dollar"] { [data-identity-icon="dollar"] {
--identity-icon: url("chrome://browser/content/usercontext.svg#dollar"); --identity-icon: url("/img/usercontext.svg#dollar");
} }
[data-identity-icon="cart"] { [data-identity-icon="cart"] {
--identity-icon: url("chrome://browser/content/usercontext.svg#cart"); --identity-icon: url("/img/usercontext.svg#cart");
} }
[data-identity-icon="circle"] { [data-identity-icon="circle"] {
--identity-icon: url("chrome://browser/content/usercontext.svg#circle"); --identity-icon: url("/img/usercontext.svg#circle");
} }

View file

@ -2,42 +2,67 @@
const CONTAINER_HIDE_SRC = '/img/container-hide.svg'; const CONTAINER_HIDE_SRC = '/img/container-hide.svg';
const CONTAINER_UNHIDE_SRC = '/img/container-unhide.svg'; const CONTAINER_UNHIDE_SRC = '/img/container-unhide.svg';
function hideContainerTabs(containerId) { function showOrHideContainerTabs(userContextId, hasHiddenTabs) {
const tabIdsToRemove = []; return new Promise((resolve, reject) => {
const tabUrlsToSave = []; const hideorshowIcon = document.querySelector(`#uci-${userContextId}-hideorshow-icon`);
const hideorshowIcon = document.querySelector(`#${containerId}-hideorshow-icon`);
browser.tabs.query({cookieStoreId: containerId}).then(tabs=> {
tabs.forEach(tab=> {
tabIdsToRemove.push(tab.id);
tabUrlsToSave.push(tab.url);
});
browser.runtime.sendMessage({ browser.runtime.sendMessage({
method: 'hide', method: hasHiddenTabs ? 'showTabs' : 'hideTabs',
cookieStoreId: containerId, userContextId: userContextId
tabUrlsToSave: tabUrlsToSave }).then(() => {
}).then(()=> { return browser.runtime.sendMessage({
browser.tabs.remove(tabIdsToRemove); method: 'getIdentity',
hideorshowIcon.src = CONTAINER_UNHIDE_SRC; userContextId: userContextId
}); });
}).then((identity) => {
if (!identity.hasHiddenTabs && !identity.hasOpenTabs) {
hideorshowIcon.style.display = "none";
} else {
hideorshowIcon.style.display = "";
}
hideorshowIcon.src = hasHiddenTabs ? CONTAINER_HIDE_SRC : CONTAINER_UNHIDE_SRC;
}).then(resolve);
}); });
} }
function showContainerTabs(containerId) { // In FF 50-51, the icon is the full path, in 52 and following releases, we
const hideorshowIcon = document.querySelector(`#${containerId}-hideorshow-icon`); // have IDs to be used with a svg file. In this function we map URLs to svg IDs.
function getIconAndColorForIdentity(identity) {
let image, color;
browser.runtime.sendMessage({ if (identity.icon == "fingerprint" ||
method: 'show', identity.icon == "chrome://browser/skin/usercontext/personal.svg") {
cookieStoreId: containerId image = "fingerprint";
}).then(hiddenTabUrls=> { } else if (identity.icon == "briefcase" ||
hiddenTabUrls.forEach(url=> { identity.icon == "chrome://browser/skin/usercontext/work.svg") {
browser.tabs.create({ image = "briefcase";
url: url, } else if (identity.icon == "dollar" ||
cookieStoreId: containerId identity.icon == "chrome://browser/skin/usercontext/banking.svg") {
}); image = "dollar";
}); } else if (identity.icon == "cart" ||
}); identity.icon == "chrome://browser/skin/usercontext/shopping.svg") {
hideorshowIcon.src = CONTAINER_HIDE_SRC; 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 (["blue", "turquoise", "green", "yellow", "orange", "red",
"pink", "purple"].indexOf(identity.color) != -1) {
color = identity.color;
} else {
color = "";
}
return { image, color };
} }
if (localStorage.getItem('onboarded2')) { if (localStorage.getItem('onboarded2')) {
@ -67,21 +92,24 @@ document.querySelector('#onboarding-done-button').addEventListener('click', ()=>
document.querySelector('#container-panel').classList.remove('hide'); document.querySelector('#container-panel').classList.remove('hide');
}); });
browser.runtime.sendMessage({method: 'query'}).then(identities=> { browser.runtime.sendMessage({method: 'queryIdentities'}).then(identities=> {
const identitiesListElement = document.querySelector('.identities-list'); const identitiesListElement = document.querySelector('.identities-list');
identities.forEach(identity=> { identities.forEach(identity=> {
let hideOrShowIconSrc = CONTAINER_HIDE_SRC; let hideOrShowIconSrc = CONTAINER_HIDE_SRC;
if (identity.hiddenTabUrls.length) { if (identity.hasHiddenTabs) {
hideOrShowIconSrc = CONTAINER_UNHIDE_SRC; hideOrShowIconSrc = CONTAINER_UNHIDE_SRC;
} }
let {image, color} = getIconAndColorForIdentity(identity);
const identityRow = ` const identityRow = `
<tr data-identity-cookie-store-id="${identity.cookieStoreId}" > <tr data-identity-cookie-store-id="${identity.userContextId}" >
<td> <td>
<div class="userContext-icon" <div class="userContext-icon"
data-identity-icon="${identity.icon}" data-identity-icon="${image}"
data-identity-color="${identity.color}"> data-identity-color="${color}">
</div> </div>
</td> </td>
<td>${identity.name}</td> <td>${identity.name}</td>
@ -94,8 +122,8 @@ browser.runtime.sendMessage({method: 'query'}).then(identities=> {
<td class="hideorshow" > <td class="hideorshow" >
<img <img
title="Hide or show ${identity.name} container tabs" title="Hide or show ${identity.name} container tabs"
data-identity-cookie-store-id="${identity.cookieStoreId}" data-identity-cookie-store-id="${identity.userContextId}"
id="${identity.cookieStoreId}-hideorshow-icon" id="uci-${identity.userContextId}-hideorshow-icon"
class="icon hideorshow-icon" class="icon hideorshow-icon"
src="${hideOrShowIconSrc}" src="${hideOrShowIconSrc}"
/> />
@ -104,61 +132,54 @@ browser.runtime.sendMessage({method: 'query'}).then(identities=> {
</tr>`; </tr>`;
identitiesListElement.innerHTML += identityRow; identitiesListElement.innerHTML += identityRow;
// No tabs, no icon.
if (!identity.hasHiddenTabs && !identity.hasOpenTabs) {
const hideorshowIcon = document.querySelector(`#uci-${identity.userContextId}-hideorshow-icon`);
hideorshowIcon.style.display = "none";
}
}); });
const rows = identitiesListElement.querySelectorAll('tr'); const rows = identitiesListElement.querySelectorAll('tr');
rows.forEach(row=> { rows.forEach(row=> {
row.addEventListener('click', e=> { row.addEventListener('click', e=> {
const containerId = e.target.parentElement.parentElement.dataset.identityCookieStoreId; const userContextId = e.target.parentElement.parentElement.dataset.identityCookieStoreId;
if (e.target.matches('.hideorshow-icon')) { if (e.target.matches('.hideorshow-icon')) {
browser.runtime.sendMessage({method: 'getIdentitiesState'}).then(identitiesState=> { browser.runtime.sendMessage({
if (identitiesState[containerId].hiddenTabUrls.length) { method: 'getIdentity',
showContainerTabs(containerId); userContextId
} else { }).then(identity=> {
hideContainerTabs(containerId); showOrHideContainerTabs(userContextId, identity.hasHiddenTabs);
}
}); });
} else if (e.target.matches('.newtab-icon')) { } else if (e.target.matches('.newtab-icon')) {
browser.tabs.create({cookieStoreId: containerId}); showOrHideContainerTabs(userContextId, true).then(() => {
window.close(); browser.runtime.sendMessage({
method: 'openTab',
userContextId: userContextId})
.then(() => {
window.close();
});
});
} }
}); });
}); });
}); });
document.querySelector('#edit-containers-link').addEventListener('click', ()=> { document.querySelector('#edit-containers-link').addEventListener('click', ()=> {
browser.runtime.sendMessage({method: 'open-containers-preferences'}).then(()=> { browser.runtime.sendMessage({
method: 'openTab',
url: "about:preferences#containers"
}).then(()=> {
window.close(); window.close();
}); });
}); });
function moveTabs(sortedTabsArray) {
let positionIndex = 0;
sortedTabsArray.forEach(tabID=> {
browser.tabs.move(tabID, {index: positionIndex});
positionIndex++;
});
}
document.querySelector('#sort-containers-link').addEventListener('click', ()=> { document.querySelector('#sort-containers-link').addEventListener('click', ()=> {
browser.runtime.sendMessage({method: 'query'}).then(identities=> { browser.runtime.sendMessage({
identities.unshift({cookieStoreId: 'firefox-default'}); method: 'sortTabs'
}).then(()=> {
browser.tabs.query({}).then(tabsArray=> { window.close();
const sortedTabsArray = [];
identities.forEach(identity=> {
tabsArray.forEach(tab=> {
if (tab.cookieStoreId === identity.cookieStoreId) {
sortedTabsArray.push(tab.id);
}
});
});
moveTabs(sortedTabsArray);
});
}); });
}); });