-
Notifications
You must be signed in to change notification settings - Fork 272
/
api-tabs-listener.js
1059 lines (920 loc) · 35.9 KB
/
api-tabs-listener.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
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
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is the Tree Style Tab.
*
* The Initial Developer of the Original Code is YUKI "Piro" Hiroshi.
* Portions created by the Initial Developer are Copyright (C) 2011-2020
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): YUKI "Piro" Hiroshi <piro.outsider.reflex@gmail.com>
* wanabe <https://github.com/wanabe>
* Tetsuharu OHZEKI <https://github.com/saneyuki>
* Xidorn Quan <https://github.com/upsuper> (Firefox 40+ support)
* lv7777 (https://github.com/lv7777)
*
* ***** END LICENSE BLOCK ******/
'use strict';
import {
log as internalLogger,
dumpTab,
toLines,
configs
} from '/common/common.js';
import * as Constants from '/common/constants.js';
import * as ApiTabs from '/common/api-tabs.js';
import * as TabsStore from '/common/tabs-store.js';
import * as TabsUpdate from '/common/tabs-update.js';
import * as TabsInternalOperation from '/common/tabs-internal-operation.js';
import * as TreeBehavior from '/common/tree-behavior.js';
import * as SidebarConnection from '/common/sidebar-connection.js';
import Tab from '/common/Tab.js';
import Window from '/common/Window.js';
import * as Tree from './tree.js';
function log(...args) {
internalLogger('background/api-tabs-listener', ...args);
}
function logUpdated(...args) {
internalLogger('common/tabs-update', ...args);
}
let mAppIsActive = false;
export function init() {
browser.tabs.onActivated.addListener(onActivated);
browser.tabs.onUpdated.addListener(onUpdated);
browser.tabs.onHighlighted.addListener(onHighlighted);
browser.tabs.onCreated.addListener(onCreated);
browser.tabs.onRemoved.addListener(onRemoved);
browser.tabs.onMoved.addListener(onMoved);
browser.tabs.onAttached.addListener(onAttached);
browser.tabs.onDetached.addListener(onDetached);
browser.windows.onCreated.addListener(onWindowCreated);
browser.windows.onRemoved.addListener(onWindowRemoved);
browser.windows.getAll({}).then(windows => {
mAppIsActive = windows.some(window => window.focused);
});
}
let mPromisedStartedResolver;
let mPromisedStarted = new Promise((resolve, _reject) => {
mPromisedStartedResolver = resolve;
});
export function destroy() {
mPromisedStartedResolver = undefined;
mPromisedStarted = undefined;
browser.tabs.onActivated.removeListener(onActivated);
browser.tabs.onUpdated.removeListener(onUpdated);
browser.tabs.onHighlighted.removeListener(onHighlighted);
browser.tabs.onCreated.removeListener(onCreated);
browser.tabs.onRemoved.removeListener(onRemoved);
browser.tabs.onMoved.removeListener(onMoved);
browser.tabs.onAttached.removeListener(onAttached);
browser.tabs.onDetached.removeListener(onDetached);
browser.windows.onCreated.removeListener(onWindowCreated);
browser.windows.onRemoved.removeListener(onWindowRemoved);
}
export function start() {
if (!mPromisedStartedResolver)
return;
mPromisedStartedResolver();
mPromisedStartedResolver = undefined;
mPromisedStarted = undefined;
}
const mTabOperationQueue = [];
function addTabOperationQueue() {
let onCompleted;
const previous = mTabOperationQueue[mTabOperationQueue.length - 1];
const queue = new Promise((resolve, _aReject) => {
onCompleted = resolve;
});
queue.then(() => {
mTabOperationQueue.splice(mTabOperationQueue.indexOf(queue), 1);
});
mTabOperationQueue.push(queue);
return [onCompleted, previous];
}
function warnTabDestroyedWhileWaiting(tabId, tab) {
if (configs.debug)
console.log(`WARNING: tab ${tabId} is destroyed while waiting. `, tab, new Error().stack);
}
async function onActivated(activeInfo) {
if (mPromisedStarted)
await mPromisedStarted;
TabsStore.activeTabInWindow.set(activeInfo.windowId, Tab.get(activeInfo.tabId));
const [onCompleted, previous] = addTabOperationQueue();
if (!configs.acceleratedTabOperations && previous)
await previous;
try {
const window = Window.init(activeInfo.windowId);
const byInternalOperation = window.internalFocusCount > 0;
if (byInternalOperation)
window.internalFocusCount--;
const silently = window.internalSilentlyFocusCount > 0;
if (silently)
window.internalSilentlyFocusCount--;
const byTabDuplication = parseInt(window.duplicatingTabsCount) > 0;
if (!Tab.isTracked(activeInfo.tabId))
await Tab.waitUntilTracked(activeInfo.tabId, { element: !!TabsStore.getCurrentWindowId() });
const newActiveTab = Tab.get(activeInfo.tabId);
if (!newActiveTab ||
!TabsStore.ensureLivingTab(newActiveTab)) {
warnTabDestroyedWhileWaiting(activeInfo.tabId);
onCompleted();
return;
}
log('tabs.onActivated: ', newActiveTab);
const oldActiveTabs = TabsInternalOperation.setTabActive(newActiveTab);
const byActiveTabRemove = !activeInfo.previousTabId;
if (!TabsStore.ensureLivingTab(newActiveTab)) { // it can be removed while waiting
onCompleted();
warnTabDestroyedWhileWaiting(activeInfo.tabId);
return;
}
let focusOverridden = Tab.onActivating.dispatch(newActiveTab, {
...activeInfo,
byActiveTabRemove,
byTabDuplication,
byInternalOperation,
silently
});
// don't do await if not needed, to process things synchronously
if (focusOverridden instanceof Promise)
focusOverridden = await focusOverridden;
focusOverridden = focusOverridden === false;
if (focusOverridden) {
onCompleted();
return;
}
if (!TabsStore.ensureLivingTab(newActiveTab)) { // it can be removed while waiting
onCompleted();
warnTabDestroyedWhileWaiting(activeInfo.tabId);
return;
}
const onActivatedReuslt = Tab.onActivated.dispatch(newActiveTab, {
...activeInfo,
oldActiveTabs,
byActiveTabRemove,
byTabDuplication,
byInternalOperation,
silently
});
// don't do await if not needed, to process things synchronously
if (onActivatedReuslt instanceof Promise)
await onActivatedReuslt;
SidebarConnection.sendMessage({
type: Constants.kCOMMAND_NOTIFY_TAB_ACTIVATED,
windowId: activeInfo.windowId,
tabId: activeInfo.tabId
});
onCompleted();
}
catch(e) {
console.log(e);
onCompleted();
}
}
async function onUpdated(tabId, changeInfo, tab) {
if (mPromisedStarted)
await mPromisedStarted;
if (!Tab.isTracked(tabId))
await Tab.waitUntilTracked(tabId, { element: !!TabsStore.getCurrentWindowId() });
const [onCompleted, previous] = addTabOperationQueue();
if (!configs.acceleratedTabOperations && previous)
await previous;
try {
const updatedTab = Tab.get(tabId);
if (!updatedTab ||
!TabsStore.ensureLivingTab(updatedTab)) {
onCompleted();
warnTabDestroyedWhileWaiting(tabId, updatedTab);
return;
}
logUpdated('tabs.onUpdated ', tabId, changeInfo, tab, updatedTab);
const oldState = {};
if ('url' in changeInfo) {
changeInfo.previousUrl = updatedTab.url;
}
/*
Updated openerTabId is not notified via tabs.onUpdated due to
https://bugzilla.mozilla.org/show_bug.cgi?id=1409262 , so it can be
notified with delay as a part of the complete tabs.Tab object,
"tab" given to this handler. To prevent unexpected tree brekage,
we should apply updated openerTabId only when it is modified at
outside of TST (in other words, by any other addon.)
*/
for (const key of Object.keys(changeInfo)) {
if (key == 'index')
continue;
if ('key' in updatedTab)
oldState[key] = updatedTab[key];
updatedTab[key] = changeInfo[key];
}
if (changeInfo.url ||
changeInfo.status == 'complete') {
// On some edge cases internally changed "favIconUrl" is not
// notified, so we need to check actual favIconUrl manually.
// Known cases are:
// * Transition from "about:privatebrowsing" to "about:blank"
// https://github.com/piroor/treestyletab/issues/1916
// * Reopen tab by Ctrl-Shift-T
browser.tabs.get(tabId).then(tab => {
if (tab.favIconUrl != updatedTab.favIconUrl)
onUpdated(tabId, { favIconUrl: tab.favIconUrl }, tab);
}).catch(ApiTabs.createErrorSuppressor());
}
if (configs.enableWorkaroundForBug1409262 &&
tab.openerTabId != updatedTab.$TST.updatedOpenerTabId) {
logUpdated(`openerTabId of ${tabId} is changed by someone!: ${updatedTab.$TST.updatedOpenerTabId} => ${tab.openerTabId}`);
updatedTab.$TST.updatedOpenerTabId = updatedTab.openerTabId = changeInfo.openerTabId = tab.openerTabId;
}
TabsUpdate.updateTab(updatedTab, changeInfo, { tab, old: oldState });
const onUpdatedResult = Tab.onUpdated.dispatch(updatedTab, changeInfo);
// don't do await if not needed, to process things synchronously
if (onUpdatedResult instanceof Promise)
await onUpdatedResult;
onCompleted();
}
catch(e) {
console.log(e);
onCompleted();
}
}
const mTabsHighlightedTimers = new Map();
const mLastHighlightedCount = new Map();
async function onHighlighted(highlightInfo) {
if (mPromisedStarted)
await mPromisedStarted;
let timer = mTabsHighlightedTimers.get(highlightInfo.windowId);
if (timer)
clearTimeout(timer);
if ((mLastHighlightedCount.get(highlightInfo.windowId) || 0) <= 1 &&
highlightInfo.tabIds.length == 1) {
// simple active tab switching
TabsUpdate.updateTabsHighlighted(highlightInfo);
SidebarConnection.sendMessage({
type: Constants.kCOMMAND_NOTIFY_HIGHLIGHTED_TABS_CHANGED,
windowId: highlightInfo.windowId,
tabIds: highlightInfo.tabIds
});
return;
}
timer = setTimeout(() => {
mTabsHighlightedTimers.delete(highlightInfo.windowId);
TabsUpdate.updateTabsHighlighted(highlightInfo);
mLastHighlightedCount.set(highlightInfo.windowId, highlightInfo.tabIds.length);
SidebarConnection.sendMessage({
type: Constants.kCOMMAND_NOTIFY_HIGHLIGHTED_TABS_CHANGED,
windowId: highlightInfo.windowId,
tabIds: highlightInfo.tabIds
});
}, configs.delayToApplyHighlightedState);
mTabsHighlightedTimers.set(highlightInfo.windowId, timer);
}
async function onCreated(tab) {
if (mPromisedStarted)
await mPromisedStarted;
log('tabs.onCreated: ', dumpTab(tab));
return onNewTabTracked(tab, { type: 'onCreated' });
}
async function onNewTabTracked(tab, info) {
const window = Window.init(tab.windowId);
const positionedBySelf = window.toBeOpenedTabsWithPositions > 0;
const duplicatedInternally = window.duplicatingTabsCount > 0;
const maybeOrphan = window.toBeOpenedOrphanTabs > 0;
const activeTab = Tab.getActiveTab(window.id);
const fromExternal = !mAppIsActive;
const initialOpenerTabId = tab.openerTabId;
// New tab's index can become invalid because the value of "index" is same to
// the one given to browser.tabs.create() (new tab) or the original index
// (restored tab) instead of its actual index.
// (By the way, any pinned tab won't be opened after the first unpinned tab,
// and any unpinned tab won't be opened before the last pinned tab. On such
// cases Firefox automatically fixup the index regardless they are newly
// opened ore restored, so we don't need to care such cases.)
// See also:
// https://github.com/piroor/treestyletab/issues/2131
// https://github.com/piroor/treestyletab/issues/2216
// https://bugzilla.mozilla.org/show_bug.cgi?id=1541748
tab.index = Math.max(0, Math.min(tab.index, window.tabs.size));
tab.reindexedBy = `onNewTabTracked (${tab.index})`;
// New tab from a bookmark always have its URL as the title
// (but the scheme part is missing.)
tab.$possibleInitialUrl = tab.title;
// We need to track new tab after getting old active tab. Otherwise, this
// operation updates the latest active tab in the window amd it becomes
// impossible to know which tab was previously active.
tab = Tab.track(tab);
if (info.type == 'onCreated')
tab.$TST.addState(Constants.kTAB_STATE_CREATING);
const mayBeReplacedWithContainer = tab.$TST.mayBeReplacedWithContainer;
log(`onNewTabTracked(i${dumpTab(tab)}): `, tab, { window, positionedBySelf, mayBeReplacedWithContainer, duplicatedInternally, maybeOrphan, activeTab });
Tab.onBeforeCreate.dispatch(tab, {
positionedBySelf,
mayBeReplacedWithContainer,
maybeOrphan,
activeTab,
fromExternal
});
if (Tab.needToWaitTracked(tab.windowId, { exceptionTabId: tab.id }))
await Tab.waitUntilTrackedAll(tab.windowId, { exceptionTabId: tab.id });
const [onCompleted, previous] = addTabOperationQueue();
if (!configs.acceleratedTabOperations && previous)
await previous;
log(`onNewTabTracked(${dumpTab(tab)}): start to create tab element`);
// Cached tree information may be expired when there are multiple new tabs
// opened at just same time and some of others are attached on listeners of
// "onCreating" and other points. Thus we need to refresh cached information
// dynamically.
// See also: https://github.com/piroor/treestyletab/issues/2419
let treeForActionDetection;
const onTreeModified = (_child, _info) => {
if (!treeForActionDetection ||
!TabsStore.ensureLivingTab(tab))
return;
treeForActionDetection = Tree.snapshotForActionDetection(tab);
log('Tree modification is detected while waiting. Cached tree for action detection is updated: ', treeForActionDetection);
};
// We should refresh ceched information only when tabs are creaetd and
// attached, because the cacheed information was originally introduced for
// failsafe around problems from tabs closed while waiting.
Tree.onAttached.addListener(onTreeModified);
try {
tab = Tab.init(tab, { inBackground: false });
const nextTab = Tab.getTabAt(window.id, tab.index);
// We need to update "active" state of a new active tab immediately.
// Attaching of initial child tab (this new tab may become it) to an
// existing tab may produce collapsing of existing tree, and a
// collapsing tree may have the old active tab. On such cases TST
// tries to move focus to a nearest visible ancestor, instead of this
// new active tab.
// See also: https://github.com/piroor/treestyletab/issues/2155
if (tab.active)
TabsInternalOperation.setTabActive(tab);
const uniqueId = await tab.$TST.promisedUniqueId;
if (!TabsStore.ensureLivingTab(tab)) { // it can be removed while waiting
onCompleted(uniqueId);
tab.$TST.rejectOpened();
Tab.untrack(tab.id);
warnTabDestroyedWhileWaiting(tab.id, tab);
return;
}
TabsUpdate.updateTab(tab, tab, {
forceApply: true
});
const duplicated = duplicatedInternally || uniqueId.duplicated;
const restored = uniqueId.restored;
const skipFixupTree = !nextTab;
const maybeNeedToFixupTree = (
(info.mayBeReplacedWithContainer ||
(!duplicated &&
!restored &&
!skipFixupTree)) &&
!info.positionedBySelf
);
// Tabs can be removed and detached while waiting, so cache them here for `detectTabActionFromNewPosition()`.
// This operation takes too much time so it should be skipped if unnecessary.
// See also: https://github.com/piroor/treestyletab/issues/2278#issuecomment-521534290
treeForActionDetection = maybeNeedToFixupTree ? Tree.snapshotForActionDetection(tab) : null;
if (positionedBySelf)
window.toBeOpenedTabsWithPositions--;
if (maybeOrphan)
window.toBeOpenedOrphanTabs--;
if (duplicatedInternally)
window.duplicatingTabsCount--;
if (restored) {
window.restoredCount = window.restoredCount || 0;
window.restoredCount++;
if (!window.allTabsRestored) {
log(`onNewTabTracked(${dumpTab(tab)}): Maybe starting to restore window`);
window.allTabsRestored = new Promise((resolve, _aReject) => {
let lastCount = window.restoredCount;
const timer = setInterval(() => {
if (lastCount != window.restoredCount) {
lastCount = window.restoredCount;
return;
}
clearTimeout(timer);
window.allTabsRestored = null;
window.restoredCount = 0;
log('All tabs are restored');
resolve(lastCount);
}, 200);
});
window.allTabsRestored = Tab.onWindowRestoring.dispatch(tab.windowId);
}
SidebarConnection.sendMessage({
type: Constants.kCOMMAND_NOTIFY_TAB_RESTORING,
tabId: tab.id,
windowId: tab.windowId
});
await window.allTabsRestored;
log(`onNewTabTracked(${dumpTab(tab)}): continued for restored tab`);
}
if (!TabsStore.ensureLivingTab(tab)) {
log(`onNewTabTracked(${dumpTab(tab)}): => aborted`);
onCompleted(uniqueId);
tab.$TST.rejectOpened();
Tab.untrack(tab.id);
warnTabDestroyedWhileWaiting(tab.id, tab);
Tree.onAttached.removeListener(onTreeModified);
return;
}
let moved = Tab.onCreating.dispatch(tab, {
positionedBySelf,
mayBeReplacedWithContainer,
maybeOrphan,
restored,
duplicated,
duplicatedInternally,
activeTab,
fromExternal
});
// don't do await if not needed, to process things synchronously
if (moved instanceof Promise)
moved = await moved;
moved = moved === false;
if (!TabsStore.ensureLivingTab(tab)) {
log(`onNewTabTracked(${dumpTab(tab)}): => aborted`);
onCompleted(uniqueId);
tab.$TST.rejectOpened();
Tab.untrack(tab.id);
warnTabDestroyedWhileWaiting(tab.id, tab);
Tree.onAttached.removeListener(onTreeModified);
return;
}
SidebarConnection.sendMessage({
type: Constants.kCOMMAND_NOTIFY_TAB_CREATING,
windowId: tab.windowId,
tabId: tab.id,
tab: tab.$TST.sanitized,
order: window.order,
maybeMoved: moved
});
log(`onNewTabTracked(${dumpTab(tab)}): moved = `, moved);
if (TabsStore.ensureLivingTab(tab)) { // it can be removed while waiting
window.openingTabs.add(tab.id);
setTimeout(() => {
if (!TabsStore.windows.get(tab.windowId)) // it can be removed while waiting
return;
window.openingTabs.delete(tab.id);
}, 0);
}
if (!TabsStore.ensureLivingTab(tab)) { // it can be removed while waiting
onCompleted(uniqueId);
tab.$TST.rejectOpened();
Tab.untrack(tab.id);
warnTabDestroyedWhileWaiting(tab.id, tab);
Tree.onAttached.removeListener(onTreeModified);
return;
}
log(`onNewTabTracked(${dumpTab(tab)}): uniqueId = `, uniqueId);
Tab.onCreated.dispatch(tab, {
positionedBySelf,
mayBeReplacedWithContainer,
movedBySelfWhileCreation: moved,
skipFixupTree,
restored,
duplicated,
duplicatedInternally,
originalTab: duplicated && Tab.get(uniqueId.originalTabId),
treeForActionDetection,
fromExternal
});
tab.$TST.resolveOpened();
SidebarConnection.sendMessage({
type: Constants.kCOMMAND_NOTIFY_TAB_CREATED,
windowId: tab.windowId,
tabId: tab.id,
active: tab.active,
maybeMoved: moved
});
if (!duplicated &&
restored) {
tab.$TST.addState(Constants.kTAB_STATE_RESTORED);
Tab.onRestored.dispatch(tab);
checkRecycledTab(window.id);
}
onCompleted(uniqueId);
tab.$TST.removeState(Constants.kTAB_STATE_CREATING);
// tab can be changed while creating!
const renewedTab = await browser.tabs.get(tab.id).catch(ApiTabs.createErrorHandler());
if (!renewedTab)
throw new Error(`tab ${tab.id} is closed while tracking`);
const updatedOpenerTabId = tab.openerTabId;
const changedProps = {};
for (const key of Object.keys(renewedTab)) {
if (tab[key] != renewedTab[key])
changedProps[key] = renewedTab[key];
}
// When the active tab is duplicated, Firefox creates a duplicated tab
// with its `openerTabId` filled with the ID of the source tab.
// It is the `initialOpenerTabId`.
// On the other hand, TST may attach the duplicated tab to any other
// parent while it is initializing, based on a configuration
// `configs.autoAttachOnDuplicated`. It is the `updatedOpenerTabId`.
// At this scenario `renewedTab.openerTabId` becomes `initialOpenerTabId`
// and `updatedOpenerTabId` is lost.
// Thus we need to re-apply `updatedOpenerTabId` as the `openerTabId` of
// the tab again, to keep the tree structure managed by TST.
// See also: https://github.com/piroor/treestyletab/issues/2388
if (duplicated &&
tab.active &&
'openerTabId' in changedProps &&
changedProps.openerTabId == initialOpenerTabId &&
changedProps.openerTabId != updatedOpenerTabId) {
delete changedProps.openerTabId;
browser.tabs.update(tab.id, { openerTabId: updatedOpenerTabId });
}
if (Object.keys(renewedTab).length > 0)
onUpdated(tab.id, changedProps, renewedTab);
const currentActiveTab = Tab.getActiveTab(tab.windowId);
if (renewedTab.active &&
currentActiveTab.id != tab.id)
onActivated({
tabId: tab.id,
windowId: tab.windowId,
previousTabId: currentActiveTab.id
});
tab.$TST.memorizeNeighbors();
if (tab.$TST.unsafePreviousTab)
tab.$TST.unsafePreviousTab.$TST.memorizeNeighbors();
if (tab.$TST.unsafeNextTab)
tab.$TST.unsafeNextTab.$TST.memorizeNeighbors();
Tree.onAttached.removeListener(onTreeModified);
return tab;
}
catch(e) {
console.log(e, e.stack);
onCompleted();
tab.$TST.removeState(Constants.kTAB_STATE_CREATING);
Tree.onAttached.removeListener(onTreeModified);
}
}
// "Recycled tab" is an existing but reused tab for session restoration.
function checkRecycledTab(windowId) {
const possibleRecycledTabs = Tab.getRecycledTabs(windowId);
log(`Detecting recycled tabs`);
for (const tab of possibleRecycledTabs) {
if (!TabsStore.ensureLivingTab(tab))
continue;
const currentId = tab.$TST.uniqueId.id;
tab.$TST.updateUniqueId().then(uniqueId => {
if (!TabsStore.ensureLivingTab(tab) ||
!uniqueId.restored ||
uniqueId.id == currentId ||
Constants.kTAB_STATE_RESTORED in tab.$TST.states)
return;
log('A recycled tab is detected: ', dumpTab(tab));
tab.$TST.addState(Constants.kTAB_STATE_RESTORED);
Tab.onRestored.dispatch(tab);
});
}
}
async function onRemoved(tabId, removeInfo) {
if (mPromisedStarted)
await mPromisedStarted;
log('tabs.onRemoved: ', tabId, removeInfo);
const window = Window.init(removeInfo.windowId);
const byInternalOperation = window.internalClosingTabs.has(tabId);
if (byInternalOperation)
window.internalClosingTabs.delete(tabId);
if (Tab.needToWaitTracked(removeInfo.windowId))
await Tab.waitUntilTrackedAll(removeInfo.windowId);
const [onCompleted, previous] = addTabOperationQueue();
if (!configs.acceleratedTabOperations && previous)
await previous;
try {
const oldTab = Tab.get(tabId);
if (!oldTab) {
onCompleted();
return;
}
log('tabs.onRemoved, tab is found: ', oldTab);
const nearestTabs = [oldTab.$TST.unsafePreviousTab, oldTab.$TST.unsafeNextTab];
// remove from "highlighted tabs" cache immediately, to prevent misdetection for "multiple highlighted".
TabsStore.removeHighlightedTab(oldTab);
TabsStore.removeGroupTab(oldTab);
TabsStore.addRemovedTab(oldTab);
removeInfo = {
...removeInfo,
byInternalOperation,
oldChildren: oldTab.$TST.children,
oldParent: oldTab.$TST.parent
};
if (!removeInfo.isWindowClosing) {
const closeParentBehavior = TreeBehavior.getCloseParentBehaviorForTabWithSidebarOpenState(oldTab, removeInfo);
if (closeParentBehavior != Constants.kCLOSE_PARENT_BEHAVIOR_CLOSE_ALL_CHILDREN &&
oldTab.$TST.subtreeCollapsed)
Tree.collapseExpandSubtree(oldTab, {
collapsed: false
});
SidebarConnection.sendMessage({
type: Constants.kCOMMAND_NOTIFY_TAB_REMOVING,
windowId: oldTab.windowId,
tabId: oldTab.id,
isWindowClosing: removeInfo.isWindowClosing,
byInternalOperation
});
}
const onRemovingResult = Tab.onRemoving.dispatch(oldTab, {
...removeInfo,
byInternalOperation
});
// don't do await if not needed, to process things synchronously
if (onRemovingResult instanceof Promise)
await onRemovingResult;
// The removing tab may be attached to tree/someone attached to the removing tab.
// We need to clear them by onRemoved handlers.
removeInfo.oldChildren = oldTab.$TST.children;
removeInfo.oldParent = oldTab.$TST.parent;
oldTab.$TST.addState(Constants.kTAB_STATE_REMOVING);
TabsStore.addRemovingTab(oldTab);
TabsStore.windows.get(removeInfo.windowId).detachTab(oldTab.id, {
toBeRemoved: true
});
const onRemovedReuslt = Tab.onRemoved.dispatch(oldTab, removeInfo);
// don't do await if not needed, to process things synchronously
if (onRemovedReuslt instanceof Promise)
await onRemovedReuslt;
SidebarConnection.sendMessage({
type: Constants.kCOMMAND_NOTIFY_TAB_REMOVED,
windowId: oldTab.windowId,
tabId: oldTab.id,
isWindowClosing: removeInfo.isWindowClosing,
byInternalOperation
});
oldTab.$TST.destroy();
for (const tab of nearestTabs) {
if (!tab || !tab.$TST)
continue;
tab.$TST.memorizeNeighbors();
}
onCompleted();
}
catch(e) {
console.log(e);
onCompleted();
}
}
async function onMoved(tabId, moveInfo) {
if (mPromisedStarted)
await mPromisedStarted;
const window = Window.init(moveInfo.windowId);
// Firefox may move the tab between TabsMove.moveTabsInternallyBefore/After()
// and TabsMove.syncTabsPositionToApiTabs(). We should treat such a movement
// as an "internal" operation also, because we need to suppress "move back"
// and other fixup operations around tabs moved by foreign triggers, on such
// cases. Don't mind, the tab will be rearranged again by delayed
// TabsMove.syncTabsPositionToApiTabs() anyway!
const maybeInternalOperation = window.internalMovingTabs.has(tabId);
if (!Tab.isTracked(tabId))
await Tab.waitUntilTracked(tabId, { element: !!TabsStore.getCurrentWindowId() });
if (Tab.needToWaitMoved(moveInfo.windowId))
await Tab.waitUntilMovedAll(moveInfo.windowId);
const [onCompleted, previous] = addTabOperationQueue();
if (!configs.acceleratedTabOperations && previous)
await previous;
try {
const finishMoving = Tab.get(tabId).$TST.startMoving();
const completelyMoved = () => { finishMoving(); onCompleted() };
/* When a tab is pinned, tabs.onMoved may be notified before
tabs.onUpdated(pinned=true) is notified. As the result,
descendant tabs are unexpectedly moved to the top of the
tab bar to follow their parent pinning tab. To avoid this
problem, we have to wait for a while with this "async" and
do following processes after the tab is completely pinned. */
const movedTab = Tab.get(tabId);
if (!movedTab) {
if (maybeInternalOperation)
window.internalMovingTabs.delete(tabId);
completelyMoved();
warnTabDestroyedWhileWaiting(tabId, movedTab);
return;
}
let oldPreviousTab = movedTab.hidden ? movedTab.$TST.unsafePreviousTab : movedTab.$TST.previousTab;
let oldNextTab = movedTab.hidden ? movedTab.$TST.unsafeNextTab : movedTab.$TST.nextTab;
if (movedTab.index != moveInfo.toIndex) { // already moved
oldPreviousTab = Tab.getTabAt(moveInfo.windowId, moveInfo.toIndex < moveInfo.fromIndex ? moveInfo.fromIndex : moveInfo.fromIndex - 1);
oldNextTab = Tab.getTabAt(moveInfo.windowId, moveInfo.toIndex < moveInfo.fromIndex ? moveInfo.fromIndex + 1 : moveInfo.fromIndex);
}
let alreadyMoved = false;
if (window.alreadyMovedTabs.has(tabId)) {
window.alreadyMovedTabs.delete(tabId);
alreadyMoved = true;
}
const extendedMoveInfo = {
...moveInfo,
byInternalOperation: maybeInternalOperation,
alreadyMoved,
oldPreviousTab,
oldNextTab,
isSubstantiallyMoved: movedTab.$TST.isSubstantiallyMoved
};
log('tabs.onMoved: ', movedTab, extendedMoveInfo);
let canceled = Tab.onMoving.dispatch(movedTab, extendedMoveInfo);
// don't do await if not needed, to process things synchronously
if (canceled instanceof Promise)
await canceled;
canceled = canceled === false;
if (!canceled &&
TabsStore.ensureLivingTab(movedTab)) { // it is removed while waiting
let newNextIndex = extendedMoveInfo.toIndex;
if (extendedMoveInfo.fromIndex < newNextIndex)
newNextIndex++;
const nextTab = Tab.getTabAt(moveInfo.windowId, newNextIndex);
extendedMoveInfo.nextTab = nextTab;
if (!alreadyMoved &&
movedTab.$TST.nextTab != nextTab) {
if (nextTab) {
if (nextTab.index > movedTab.index)
movedTab.index = nextTab.index - 1;
else
movedTab.index = nextTab.index;
}
else {
movedTab.index = window.tabs.size - 1
}
movedTab.reindexedBy = `tabs.onMoved (${movedTab.index})`;
window.trackTab(movedTab);
log('Tab nodes rearranged by tabs.onMoved listener:\n'+(!configs.debug ? '' :
toLines(Array.from(window.getOrderedTabs()),
tab => ` - ${tab.index}: ${tab.id}${tab.id == movedTab.id ? '[MOVED]' : ''}`)),
{ moveInfo });
}
const onMovedResult = Tab.onMoved.dispatch(movedTab, extendedMoveInfo);
// don't do await if not needed, to process things synchronously
if (onMovedResult instanceof Promise)
await onMovedResult;
if (!alreadyMoved)
SidebarConnection.sendMessage({
type: Constants.kCOMMAND_NOTIFY_TAB_MOVED,
windowId: movedTab.windowId,
tabId: movedTab.id,
newIndex: movedTab.index,
nextTabId: nextTab && nextTab.id
});
}
if (maybeInternalOperation)
window.internalMovingTabs.delete(tabId);
completelyMoved();
movedTab.$TST.memorizeNeighbors();
if (movedTab.$TST.unsafePreviousTab)
movedTab.$TST.unsafePreviousTab.$TST.memorizeNeighbors();
if (movedTab.$TST.unsafeNextTab)
movedTab.$TST.unsafeNextTab.$TST.memorizeNeighbors();
if (oldPreviousTab)
oldPreviousTab.$TST.memorizeNeighbors();
if (oldNextTab)
oldNextTab.$TST.memorizeNeighbors();
}
catch(e) {
console.log(e);
onCompleted();
}
}
const mTreeInfoForTabsMovingAcrossWindows = new Map();
async function onAttached(tabId, attachInfo) {
if (mPromisedStarted)
await mPromisedStarted;
const [onCompleted, previous] = addTabOperationQueue();
if (!configs.acceleratedTabOperations && previous)
await previous;
try {
log('tabs.onAttached, id: ', tabId, attachInfo);
const tab = Tab.get(tabId);
const attachedTab = await browser.tabs.get(tabId).catch(ApiTabs.createErrorHandler());
if (!attachedTab) {
onCompleted();
return;
}
if (tab) {
tab.windowId = attachInfo.newWindowId
tab.index = attachedTab.index;
tab.reindexedBy = `tabs.onAttached (${tab.index})`;
}
TabsInternalOperation.clearOldActiveStateInWindow(attachInfo.newWindowId);
const info = {
...attachInfo,
...mTreeInfoForTabsMovingAcrossWindows.get(tabId)
};
mTreeInfoForTabsMovingAcrossWindows.delete(tabId);
const window = TabsStore.windows.get(attachInfo.newWindowId);
await onNewTabTracked(tab, { type: 'onAttached' });
const byInternalOperation = window.toBeAttachedTabs.has(tab.id);
if (byInternalOperation)
window.toBeAttachedTabs.delete(tab.id);
info.byInternalOperation = info.byInternalOperation || byInternalOperation;
if (!byInternalOperation) { // we should process only tabs attached by others.
const onAttachedResult = Tab.onAttached.dispatch(tab, info);
// don't do await if not needed, to process things synchronously
if (onAttachedResult instanceof Promise)
await onAttachedResult;
}
SidebarConnection.sendMessage({
type: Constants.kCOMMAND_NOTIFY_TAB_ATTACHED_TO_WINDOW,
windowId: attachInfo.newWindowId,
tabId
});
onCompleted();
}
catch(e) {
console.log(e);
onCompleted();
}
}
async function onDetached(tabId, detachInfo) {
if (mPromisedStarted)
await mPromisedStarted;
const [onCompleted, previous] = addTabOperationQueue();
if (!configs.acceleratedTabOperations && previous)
await previous;
try {
log('tabs.onDetached, id: ', tabId, detachInfo);
const oldTab = Tab.get(tabId);
if (!oldTab) {
onCompleted();
return;
}
const oldWindow = TabsStore.windows.get(detachInfo.oldWindowId);
const byInternalOperation = oldWindow.toBeDetachedTabs.has(tabId);
if (byInternalOperation)
oldWindow.toBeDetachedTabs.delete(tabId);
const descendants = oldTab.$TST.descendants;
const info = {
...detachInfo,
byInternalOperation,
windowId: detachInfo.oldWindowId,
structure: TreeBehavior.getTreeStructureFromTabs([oldTab, ...descendants]),
descendants
};
const alreadyMovedAcrossWindows = Array.from(mTreeInfoForTabsMovingAcrossWindows.values(), info => info.descendants.map(tab => tab.id)).some(tabIds => tabIds.includes(tabId));
if (!alreadyMovedAcrossWindows)
mTreeInfoForTabsMovingAcrossWindows.set(tabId, info);
if (!byInternalOperation) // we should process only tabs detached by others.
Tab.onDetached.dispatch(oldTab, info);
SidebarConnection.sendMessage({
type: Constants.kCOMMAND_NOTIFY_TAB_DETACHED_FROM_WINDOW,
windowId: detachInfo.oldWindowId,
tabId,
wasPinned: oldTab.pinned
});
TabsStore.addRemovedTab(oldTab);
oldWindow.detachTab(oldTab.id, {