-
Notifications
You must be signed in to change notification settings - Fork 2
/
background.js
431 lines (380 loc) · 13 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
/*
# 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';
gLogContext = 'BG';
const gOpeningTabs = [];
const gCreatingTabs = new Set();
const gTrackedWindows = new Set();
let gAggregateTabsMatchedPattern = null;
let gAggregateTabsFromMatchedPattern = null;
let gDoNotAggregateTabsMatchedPattern = null;
let gDoNotAggregateTabsFromMatchedPattern = null;
configs.$loaded.then(() => {
updateAggregateTabsMatchedPattern();
updateAggregateTabsFromMatchedPattern();
updateDoNotAggregateTabsMatchedPattern();
updateDoNotAggregateTabsFromMatchedPattern();
});
configs.$addObserver(key => {
switch (key) {
case 'aggregateTabsMatchedPattern':
updateAggregateTabsMatchedPattern();
break;
case 'aggregateTabsFromMatchedPattern':
updateAggregateTabsFromMatchedPattern();
break;
case 'doNotAggregateTabsMatchedPattern':
updateDoNotAggregateTabsMatchedPattern();
break;
case 'doNotAggregateTabsFromMatchedPattern':
updateDoNotAggregateTabsFromMatchedPattern();
break;
}
});
function updateAggregateTabsMatchedPattern() {
try {
const source = (configs.aggregateTabsMatchedPattern || '').trim();
gAggregateTabsMatchedPattern = source && new RegExp(source, 'i');
}
catch(_e) {
gAggregateTabsMatchedPattern = null;
}
}
function updateAggregateTabsFromMatchedPattern() {
try {
const source = (configs.aggregateTabsFromMatchedPattern || '').trim();
gAggregateTabsFromMatchedPattern = source && new RegExp(source, 'i');
}
catch(_e) {
gAggregateTabsFromMatchedPattern = null;
}
}
function updateDoNotAggregateTabsMatchedPattern() {
try {
const source = (configs.doNotAggregateTabsMatchedPattern || '').trim();
gDoNotAggregateTabsMatchedPattern = source && new RegExp(source, 'i');
}
catch(_e) {
gDoNotAggregateTabsMatchedPattern = null;
}
}
function updateDoNotAggregateTabsFromMatchedPattern() {
try {
const source = (configs.doNotAggregateTabsFromMatchedPattern || '').trim();
gDoNotAggregateTabsFromMatchedPattern = source && new RegExp(source, 'i');
}
catch(_e) {
gDoNotAggregateTabsFromMatchedPattern = null;
}
}
const kPERSISTENT_ID = 'persistent-id';
function handleMissingTabError(error) {
if (!error ||
!error.message ||
error.message.indexOf('Invalid tab ID:') != 0)
throw error;
// otherwise, this error is caused from a tab already closed.
// we just ignore it.
//console.log('Invalid Tab ID error on: ' + error.stack);
}
async function getUniqueTabId(tabId) {
let originalId = null;
let originalTabId = null;
let duplicated = false;
let oldId = await browser.sessions.getTabValue(tabId, kPERSISTENT_ID);
if (oldId && !oldId.tabId) // ignore broken information!
oldId = null;
if (oldId) {
// If the tab detected from stored tabId is different, it is duplicated tab.
try {
const tabWithOldId = await browser.tabs.get(oldId.tabId);
if (!tabWithOldId)
throw new Error(`Invalid tab ID: ${oldId.tabId}`);
originalId = await browser.sessions.getTabValue(oldId.tabId, kPERSISTENT_ID);
originalId = originalId && originalId.id;
duplicated = tabWithOldId.id != tabId && originalId == oldId.id;
if (duplicated)
originalTabId = oldId.tabId;
else
throw new Error(`Invalid tab ID: ${oldId.tabId}`);
}
catch(e) {
handleMissingTabError(e);
// It fails if the tab doesn't exist.
// There is no live tab for the tabId, thus
// this seems to be a tab restored from session.
// We need to update the related tab id.
await browser.sessions.setTabValue(tabId, kPERSISTENT_ID, {
id: oldId.id,
tabId
});
return {
id: oldId.id,
originalId: null,
originalTabId: oldId.tabId,
restored: true
};
}
}
const randomValue = Math.floor(Math.random() * 1000);
const id = `tab-${Date.now()}-${randomValue}`;
// tabId is for detecttion of duplicated tabs
await browser.sessions.setTabValue(tabId, kPERSISTENT_ID, { id, tabId });
return { id, originalId, originalTabId, duplicated };
}
browser.tabs.onCreated.addListener(async newTab => {
log('onCreated: tab: ', newTab);
const isNewWindow = gTrackedWindows.has(newTab.windowId);
gTrackedWindows.add(newTab.windowId);
gCreatingTabs.add(newTab.id);
setTimeout(async () => {
const tab = await browser.tabs.get(newTab.id);
if (!gCreatingTabs.has(newTab.id) ||
tab.url != newTab.url ||
tab.status != 'complete' ||
isNewWindow)
return;
gCreatingTabs.delete(newTab.id);
log('delayed onCreated: tab: ', tab);
tryAggregateTab(tab, {
excludeLastTab: true
});
}, 100);
gOpeningTabs.push(newTab.id);
await wait(configs.delayForMultipleNewTabs);
if (gOpeningTabs.length > 1 &&
Date.now() - gLsatCreatedAt < configs.delayForNewWindow) {
log(`tab ${newTab.id}: do nothing because multiple tabs are restored in an existing window`);
await wait(100);
gOpeningTabs.splice(gOpeningTabs.indexOf(newTab.id), 1);
return;
}
gOpeningTabs.splice(gOpeningTabs.indexOf(newTab.id), 1);
if (Date.now() - gCreatedAt.get(newTab.windowId) < configs.delayForNewWindow) {
log(`tab ${newTab.id}: do nothing because this window is opened with the tab explicitly (maybe a restored window)`);
return;
}
if (isNewWindow) {
log('ignore initial tab of a new window');
return;
}
const bookmarked = await isBookmarked(newTab);
if (!bookmarked &&
newTab.url == 'about:blank') {
log('ignore loading tab');
return;
}
tryAggregateTab(newTab, {
excludeLastTab: true,
bookmarked
});
});
browser.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
if (!changeInfo.url)
return;
if (gCreatingTabs.has(tabId)) {
// New tab opened from command line is initially opened with "about:blank"
// and loaded the requested URL after that. We need to ignore such a
// "complete" event.
if (changeInfo.status == 'complete' &&
changeInfo.url == 'about:blank')
return;
log('delayed onCreated (onUpdated): tab: ', tab);
gCreatingTabs.delete(tabId);
tryAggregateTab(tab, {
excludeLastTab: true
});
return;
}
log('checking for loading in an existing tab: ', { tab: tab, changeInfo: changeInfo });
log(`tab ${tab.id}: window.width = ${window.width}`);
if (!tab.active ||
!configs.redirectLoadingInCurrentTab ||
window.width >= configs.redirectLoadingInCurrentTabMinWindowWidth)
return;
const mainWindow = await getRedirectTargetWindowForTab(tab);
if (!mainWindow)
return;
browser.tabs.create({
url: changeInfo.url,
active: true,
index: mainWindow.tabs.length,
windowId: mainWindow.id
});
});
const gCreatedAt = new Map();
const gLastActive = new Map();
let gLsatCreatedAt = 0;
browser.windows.onCreated.addListener(window => {
const now = Date.now();
gCreatedAt.set(window.id, now);
gLastActive.set(window.id, now);
gLsatCreatedAt = now;
});
browser.windows.onFocusChanged.addListener(windowId => {
gLastActive.set(windowId, Date.now());
});
browser.windows.onRemoved.addListener(windowId => {
gCreatedAt.delete(windowId);
gLastActive.delete(windowId);
gTrackedWindows.delete(windowId);
});
async function tryAggregateTab(tab, { bookmarked, ...options } = {}) {
log('tryAggregateTab ', { tab, bookmarked, options });
const shouldBeAggregated = await shouldAggregateTab(tab, { bookmarked });
if (!shouldBeAggregated)
return;
const mainWindow = await getRedirectTargetWindowForTab(tab, {
excludeLastTab: true
});
if (!mainWindow)
return;
await browser.tabs.move([tab.id], {
index: mainWindow.tabs.length,
windowId: mainWindow.id
});
browser.tabs.update(tab.id, { active: true });
}
async function shouldAggregateTab(tab, { bookmarked } = {}) {
const opener = tab.openerTabId && await browser.tabs.get(tab.openerTabId);
let shouldBeAggregated = null;
if (opener) {
log('shouldAggregateTab: has opener');
if (opener.pinned) {
shouldBeAggregated = configs.aggregateTabsFromPinned;
log('pinned opener, should aggregate = ', shouldBeAggregated);
}
else {
shouldBeAggregated = configs.aggregateTabsFromUnpinned;
log('unpinned opener, should aggregate = ', shouldBeAggregated);
}
if (configs.aggregateTabsFromMatched) {
if (gAggregateTabsFromMatchedPattern &&
gAggregateTabsFromMatchedPattern.test(opener.url))
shouldBeAggregated = true;
log('matched opener, should aggregate = ', { shouldBeAggregated, gAggregateTabsFromMatchedPattern, url: opener.url });
}
if (configs.doNotAggregateTabsFromMatched) {
if (gDoNotAggregateTabsFromMatchedPattern &&
gDoNotAggregateTabsFromMatchedPattern.test(opener.url))
shouldBeAggregated = false;
log('matched opener for exception, should aggregate = ', { shouldBeAggregated, gDoNotAggregateTabsFromMatchedPattern, url: opener.url });
}
}
if (configs.aggregateTabsMatched) {
if (gAggregateTabsMatchedPattern &&
gAggregateTabsMatchedPattern.test(tab.url))
shouldBeAggregated = true;
log('matched tab, should aggregate = ', { shouldBeAggregated, gAggregateTabsMatchedPattern, url: tab.url });
}
if (configs.doNotAggregateTabsMatched) {
if (gDoNotAggregateTabsMatchedPattern &&
gDoNotAggregateTabsMatchedPattern.test(tab.url))
shouldBeAggregated = false;
log('matched tab for exception, should aggregate = ', { shouldBeAggregated, gDoNotAggregateTabsMatchedPattern, url: tab.url });
}
if (bookmarked === undefined ? (await isBookmarked(tab)) : bookmarked) {
shouldBeAggregated = configs.aggregateTabsForBookmarked;
log('bookmarked url, should aggregate = ', { shouldBeAggregated, url: tab.url });
}
if (shouldBeAggregated &&
(!configs.aggregateDuplicatedTabs ||
!configs.aggregateRestoredTabs)) {
const uniqueId = await getUniqueTabId(tab.id);
if (uniqueId.duplicated &&
!configs.aggregateDuplicatedTabs) {
log('do not aggregate duplicated tab');
shouldBeAggregated = false;
}
if (uniqueId.restored &&
!configs.aggregateRestoredTabs) {
log('do not aggregate restored tab');
shouldBeAggregated = false;
}
}
if (shouldBeAggregated !== null)
return shouldBeAggregated;
log('default case, should aggregate = ', configs.aggregateTabsAll);
return configs.aggregateTabsAll;
}
async function isBookmarked(tab) {
try {
const bookmarks = (await Promise.all([
//browser.bookmarks.search({ url: tab.url }),
(async () => {
try {
const bookmarks = await browser.bookmarks.search({ url: `http://${tab.title}` });
return bookmarks;
}
catch(_e) {
}
return [];
})(),
(async () => {
try {
const bookmarks = await browser.bookmarks.search({ url: `https://${tab.title}` });
return bookmarks;
}
catch(_e) {
}
return [];
})()
])).flat();
return bookmarks.length > 0;
}
catch(_e) {
}
return false;
}
async function getRedirectTargetWindowForTab(tab, options = {}) {
log(`getRedirectTargetWindowForTab: id = ${tab.id}`, tab);
const windows = (await browser.windows.getAll({
populate: true,
windowTypes: ['normal']
})).filter(window => window.incognito == tab.incognito);
log('windows: ', windows);
if (windows.length <= 1) {
log('do nothing because there is only one window');
return null;
}
const sourceWindow = windows.filter(window => window.id == tab.windowId)[0];
log('sourceWindow: ', sourceWindow);
if (options.excludeLastTab &&
sourceWindow.tabs.length <= 1) {
log('do nothing because it is a new window');
return null;
}
const mainWindow = findMainWindowFrom(windows);
log('mainWindow: ', mainWindow.id);
if (tab.windowId == mainWindow.id) {
log('do nothing because it is the main window');
return null;
}
return mainWindow;
}
const comparers = {
wider: (a, b) => b.width - a.width,
taller: (a, b) => b.height - a.height,
larger: (a, b) => (b.width * b.height) - (a.width * a.height),
muchTabs: (a, b) => b.tabs.length - a.tabs.length,
recent: (a, b) => (gLastActive.get(b) || 0) - (gLastActive.get(a) || 0),
};
function findMainWindowFrom(windows) {
windows = windows.slice(0).sort((a, b) => {
for (let name of configs.activeComparers) {
const result = comparers[name](a, b);
const acceptableFudgeFactor = configs.acceptableFudgeFactors[name] || 0;
log('findMainWindowFrom: sorting ', { name, a: a.id, b: b.id, result, acceptableFudgeFactor });
if (Math.abs(result) <= acceptableFudgeFactor)
continue;
if (result !== 0)
return result;
}
return 0;
});
log('findMainWindowFrom: sorted windows: ', windows);
return windows[0];
}