-
Notifications
You must be signed in to change notification settings - Fork 55
/
background.js
503 lines (414 loc) · 16.5 KB
/
background.js
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
'use strict';
import { loadOptions } from "./_share/options.js";
const manifest = browser.runtime.getManifest();
window.backgroundState = {
openingView: false,
openingBackup: false,
};
/** Modulo in javascript does not behave like modulo in mathematics when x is negative.
* Following code is based from this:
* https://stackoverflow.com/questions/4467539/javascript-modulo-gives-a-negative-result-for-negative-numbers */
function mod(x, n) {
return (x % n + n) % n;
}
function addRefreshMenuItem() {
browser.menus.remove("refresh-groups");
browser.menus.remove("refresh-spacer");
browser.menus.create({
id: "refresh-spacer",
type: "separator",
parentId: "send-tab",
contexts: ["tab"]
});
browser.menus.create({
id: "refresh-groups",
title: browser.i18n.getMessage('refreshGroups'),
parentId: "send-tab",
contexts: ["tab"]
});
}
async function createMenuList() {
let windowId = (await browser.windows.getCurrent()).id;
let groups = (await browser.sessions.getWindowValue(windowId, 'groups'));
browser.menus.removeAll();
browser.menus.create({
id: "send-tab",
title: browser.i18n.getMessage('sendTab'),
contexts: ["tab"]
});
for (var i in groups) {
browser.menus.create({
id: groups[i].id.toString(),
title: groups[i].id + ": " + groups[i].name,
parentId: "send-tab",
contexts: ["tab"]
});
}
addRefreshMenuItem();
}
createMenuList();
browser.runtime.onMessage.addListener(changeMenu);
function changeMenu(message) {
switch (message.action) {
case "createMenuItem":
browser.menus.create({
id: message.groupId,
title: message.groupId + ": " + message.groupName,
parentId: "send-tab",
contexts: ["tab"]
});
addRefreshMenuItem(); // move refresh menu to end
break;
case "removeMenuItem":
browser.menus.remove(message.groupId);
break;
case "updateMenuItem":
browser.menus.update(message.groupId, {title: message.groupId + ": " + message.groupName});
}
}
async function moveTab(tabId, groupId) {
let windowId = (await browser.windows.getCurrent()).id;
await browser.sessions.setTabValue(tabId, 'groupId', groupId);
let toIndex = -1;
await browser.tabs.move(tabId, {index: toIndex});
let activeGroup = (await browser.sessions.getWindowValue(windowId, 'activeGroup'));
await toggleVisibleTabs(activeGroup);
}
async function menuClicked(info, tab) {
let windowId = (await browser.windows.getCurrent()).id;
switch (info.menuItemId) {
case "refresh-groups":
let groups = (await browser.sessions.getWindowValue(windowId, 'groups'));
browser.menus.removeAll();
createMenuList();
break;
default:
// see if we're sending multiple tabs
let tabs = await browser.tabs.query({highlighted: true });
// if you select multiple tabs, your active tab is selected as well and needs to be filtered out
if (tabs.length > 1) {
let activeTabId = (await browser.tabs.query({active: true}))[0].id;
for (let i in tabs) {
let tabId = tabs[i].id;
if (tabId != activeTabId) {
moveTab(tabId, info.menuItemId);
}
}
}
// otherwise just use the tab where the menu was clicked from
// if you don't do multiselect, but just right click, the tab isn't actually highlighted
else {
let activeTabId = (await browser.tabs.query({active: true}))[0].id;
if (activeTabId === tab.id) {
let visibleTabs = (await browser.tabs.query({hidden: false}));
// find position of active tab among visible tabs
let tabIndex = 0;
for (let i in visibleTabs) {
if (visibleTabs[i].id === tab.id) {
tabIndex = parseInt(i);
break;
}
}
// find neighboring tab and make it the active tab
let newActiveTab = tab;
if (visibleTabs[tabIndex-1] !== undefined) {
newActiveTab = visibleTabs[tabIndex-1];
} else if (visibleTabs[tabIndex+1] !== undefined) {
newActiveTab = visibleTabs[tabIndex+1]
}
await browser.tabs.update(newActiveTab.id, {active: true});
}
moveTab(tab.id, info.menuItemId);
}
}
}
browser.menus.onClicked.addListener(menuClicked);
async function triggerCommand(command) {
const options = await loadOptions();
if (options["shortcut"][command].disabled) {
// Doesn't execute disabled command
return;
}
if (command === "activate-next-group") {
await changeActiveGroupBy(1);
} else if (command === "activate-previous-group") {
await changeActiveGroupBy(-1);
} else if (command === "toggle-panorama-view") {
await toggleView();
}
}
/** Shift current active group by offset */
async function changeActiveGroupBy(offset) {
const windowId = (await browser.windows.getCurrent()).id;
const groups = await browser.sessions.getWindowValue(windowId, 'groups');
let activeGroup = (await browser.sessions.getWindowValue(windowId, 'activeGroup'));
let activeIndex = groups.findIndex(function (group) { return group.id === activeGroup; });
let newIndex = activeIndex + offset;
activeGroup = groups[mod(newIndex, groups.length)].id;
await browser.sessions.setWindowValue(windowId, 'activeGroup', activeGroup);
await toggleVisibleTabs(activeGroup, true);
}
/** Open the Panorama View tab, or return to the last open tab if Panorama View is currently open */
async function toggleView() {
let extTabs = await browser.tabs.query({url: browser.extension.getURL("view.html"), currentWindow: true});
if (extTabs.length > 0) {
let currentTab = (await browser.tabs.query({active: true, currentWindow: true}))[0];
// switch to last accessed tab in window
if (extTabs[0].id == currentTab.id) {
let tabs = await browser.tabs.query({currentWindow: true});
tabs.sort((tabA, tabB) => tabB.lastAccessed - tabA.lastAccessed);
// skip first tab which will be the panorama view
if (tabs.length > 1) {
await browser.tabs.update(tabs[1].id, {active: true});
}
// switch to Panorama View tab
} else {
await browser.tabs.update(extTabs[0].id, {active: true});
}
} else { // if there is no Panorama View tab, make one
window.backgroundState.openingView = true;
await browser.tabs.create({url: "/view.html", active: true});
}
}
/** Callback function which will be called whenever a tab is opened */
async function tabCreated(tab) {
if(window.backgroundState.openingBackup) {
return;
}
if(!window.backgroundState.openingView) {
// Normal case: everything except the Panorama View tab
// If the tab does not have a group, set its group to the current group
let tabGroupId = await browser.sessions.getTabValue(tab.id, 'groupId');
if(tabGroupId === undefined) {
let activeGroup = undefined;
while(activeGroup === undefined) {
activeGroup = await browser.sessions.getWindowValue(tab.windowId, 'activeGroup');
}
await browser.sessions.setTabValue(tab.id, 'groupId', activeGroup);
}
}else{
// Opening the Panorama View tab
// Make sure it's in the special group
window.backgroundState.openingView = false;
await browser.sessions.setTabValue(tab.id, 'groupId', -1);
}
}
async function tabAttached(tabId, attachInfo) {
let tab = await browser.tabs.get(tabId);
await tabCreated(tab);
}
async function tabDetached(tabId, detachInfo) {
await browser.sessions.removeTabValue(tabId, 'groupId');
}
/** Callback function which will be called whenever the user switches tabs.
* This callback needed for properly switch between groups, when current tab
* is from another group (or is Panorama Tab Groups tab).
*/
async function tabActivated(activeInfo) {
let tab = await browser.tabs.get(activeInfo.tabId);
if(tab.pinned) {
return;
}
// Set the window's active group to the new active tab's group
// If this is a newly-created tab, tabCreated() might not have set a
// groupId yet, so retry until it does.
let activeGroup = undefined;
while (activeGroup === undefined) {
activeGroup = await browser.sessions.getTabValue(activeInfo.tabId, 'groupId');
}
if(activeGroup != -1) {
// activated tab is not Panorama View tab
await browser.sessions.setWindowValue(tab.windowId, 'activeGroup', activeGroup);
}
await toggleVisibleTabs(activeGroup);
}
async function toggleVisibleTabs(activeGroup, noTabSelected) {
// Show and hide the appropriate tabs
const tabs = await browser.tabs.query({currentWindow: true});
let showTabIds = [];
let hideTabIds = [];
let showTabs = [];
await Promise.all(tabs.map(async(tab) => {
try{
let groupId = await browser.sessions.getTabValue(tab.id, 'groupId');
if(groupId != activeGroup) {
hideTabIds.push(tab.id)
}else{
showTabIds.push(tab.id)
showTabs.push(tab)
}
} catch {
//The tab has probably been closed, this should be safe to ignore
}
}));
if(noTabSelected) {
showTabs.sort((tabA, tabB) => tabB.lastAccessed - tabA.lastAccessed);
await browser.tabs.update(showTabs[0].id, {active: true});
}
await browser.tabs.hide(hideTabIds);
await browser.tabs.show(showTabIds);
if (activeGroup >= 0) {
let window = await browser.windows.getLastFocused();
await setActionTitle(window.id, activeGroup);
}
}
/** Set extension icon tooltip and numGroups to icon **/
async function setActionTitle(windowId, activeGroup = null) {
let name;
let groups = await browser.sessions.getWindowValue(windowId, 'groups');
if(activeGroup === null) {
activeGroup = await browser.sessions.getWindowValue(windowId, 'activeGroup');
}
for (var i in groups) {
if (groups[i].id == activeGroup) {
name = groups[i].name;
}
}
browser.browserAction.setTitle({title: `Active Group: ${name}`, 'windowId': windowId});
browser.browserAction.setBadgeText({text: String(groups.length), windowId: windowId});
browser.browserAction.setBadgeBackgrounColor({color: "#666666"});
}
/** Make sure each window has a group */
async function setupWindows() {
const windows = await browser.windows.getAll({});
for (const window of windows) {
await createGroupInWindowIfMissing(window);
}
}
/** Get a new UID for a group */
async function newGroupUid(windowId) {
let groupIndex = await browser.sessions.getWindowValue(windowId, 'groupIndex');
let uid = groupIndex || 0;
let newGroupIndex = uid + 1;
await browser.sessions.setWindowValue(windowId, 'groupIndex', newGroupIndex);
return uid;
}
/** Checks that group is missing before creating new one in window
* This makes sure existing/restored windows are not reinitialized.
* For example, windows that are restored by user (e.g. Ctrl+Shift+N) will
* trigger the onCreated event but still have the existing group data.
*/
async function createGroupInWindowIfMissing(browserWindow) {
let groups = await browser.sessions.getWindowValue(browserWindow.id, 'groups');
if (!groups || !groups.length) {
console.log(`No groups found for window ${browserWindow.id}!`);
await createGroupInWindow(browserWindow);
}
browser.browserAction.setTitle({title: `Active Group: Unnamed group`, 'windowId': browserWindow.id});
browser.browserAction.setBadgeText({text: '1', windowId: browserWindow.id});
browser.browserAction.setBadgeBackgroundColor({color: "#666666"});
}
/** Create the first group in a window
* This handles new windows and, during installation, existing windows
* that do not yet have a group */
async function createGroupInWindow(browserWindow) {
if(window.backgroundState.openingBackup) {
console.log('Skipping creation of groups since we are opening backup');
return;
}
let groupId = await newGroupUid(browserWindow.id);
let groups = [{
id: groupId,
name: groupId + ": " + browser.i18n.getMessage("defaultGroupName"),
containerId: 'firefox-default',
rect: {x: 0, y: 0, w: 0.5, h: 0.5},
lastMoved: (new Date).getTime(),
}];
await browser.sessions.setWindowValue(browserWindow.id, 'groups', groups);
await browser.sessions.setWindowValue(browserWindow.id, 'activeGroup', groupId);
}
/** Put any tabs that do not have a group into the active group */
async function salvageGrouplessTabs() {
// make array of all groups for quick look-up
let windows = {};
const _windows = await browser.windows.getAll({});
for(const window of _windows) {
windows[window.id] = {groups: null};
windows[window.id].groups = await browser.sessions.getWindowValue(window.id, 'groups');
}
// check all tabs
const tabs = await browser.tabs.query({});
for(const tab of tabs) {
let groupId = await browser.sessions.getTabValue(tab.id, 'groupId');
let groupExists = false;
for(let i in windows[tab.windowId].groups) {
if(windows[tab.windowId].groups[i].id == groupId) {
groupExists = true;
break;
}
}
if(!groupExists && groupId != -1) {
let activeGroup = await browser.sessions.getWindowValue(tab.windowId, 'activeGroup');
await browser.sessions.setTabValue(tab.id, 'groupId', activeGroup);
}
}
}
async function init() {
console.log('Initializing Panorama Tab View');
await setupWindows();
await salvageGrouplessTabs();
console.log('Finished setup');
await migrate(); //keep until everyone are on 0.8.0
browser.commands.onCommand.addListener(triggerCommand);
browser.browserAction.onClicked.addListener(toggleView);
browser.windows.onCreated.addListener(createGroupInWindowIfMissing);
browser.tabs.onCreated.addListener(tabCreated);
browser.tabs.onAttached.addListener(tabAttached);
browser.tabs.onDetached.addListener(tabDetached);
browser.tabs.onActivated.addListener(tabActivated);
}
init();
// migrate to transformable groups
async function migrate() {
const windows = await browser.windows.getAll({});
for(const window of windows) {
let groups = await browser.sessions.getWindowValue(window.id, 'groups');
if(groups[0].lastMoved !== undefined) {
return;
}
let pitchX = 4;
let pitchY = 2;
if(groups.length > 8) {
pitchX = 6;
pitchY = 3;
}else if(groups.length > 18) {
pitchX = 8;
pitchY = 4;
}
for(let i in groups) {
groups[i].rect = {
x: (1/pitchX) * (i % pitchX),
y: (1/pitchY) * Math.floor(i / pitchX),
w: 1/pitchX,
h: 1/pitchY,
};
groups[i].lastMoved = (new Date).getTime();
}
await browser.sessions.setWindowValue(window.id, 'groups', groups);
}
}
function handleMessage(message, sender) {
if (message === "toggle-panorama-view") {
toggleView();
}
else if (message == "activate-next-group") {
triggerCommand("activate-next-group");
}
else if (message == "activate-previous-group") {
triggerCommand("activate-previous-group");
}
}
browser.runtime.onMessageExternal.addListener(handleMessage);
/*
* Handle upboarding
*/
function onRuntimeInstallNotification(details) {
if (details.temporary) return;
// Open new tab to the release notes after update
if (details.reason === 'update') {
browser.tabs.create({
url: `https://github.com/projectdelphai/panorama-tab-groups/releases/tag/${manifest.version}`
});
}
}
browser.runtime.onInstalled.addListener(onRuntimeInstallNotification);