forked from gswch/fx-BarTab
/
prototypes.js
1060 lines (921 loc) · 31.1 KB
/
prototypes.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
const EXPORTED_SYMBOLS = ["BarTabHandler",
"BarTabUtils"];
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
/*
* This handler attaches to the tabbrowser. It listens to various tab
* related events to prevent tabs from loading or to load them upon
* the user's request (e.g. automatic timer or context menu item).
*
* This object provides a small public API (see below) to perform
* these tasks programatically, too. You may obtain a reference to it
* via tabbrowser.BarTabHandler.
*/
function BarTabHandler() {}
BarTabHandler.prototype = {
init: function(aTabBrowser) {
aTabBrowser.BarTabHandler = this;
this.tabbrowser = aTabBrowser;
let document = aTabBrowser.ownerDocument;
this.l10n = document.getElementById('bartab-strings');
aTabBrowser.tabContainer.addEventListener('SSTabRestoring', this, false);
aTabBrowser.tabContainer.addEventListener('TabOpen', this, false);
aTabBrowser.tabContainer.addEventListener('TabSelect', this, false);
aTabBrowser.tabContainer.addEventListener('TabClose', this, false);
(new BarTabTimer()).init(aTabBrowser);
// We need an event listener for the context menu so that we can
// adjust the label of the whitelist menu item
let popup = aTabBrowser.tabContainer.contextMenu;
if (!popup) {
// In Firefox <4, the tab context menu lives inside the
// tabbrowser.
popup = document.getAnonymousElementByAttribute(
aTabBrowser, "anonid", "tabContextMenu");
let before = document.getAnonymousElementByAttribute(
aTabBrowser, "id", "context_openTabInWindow");
["context_BarTabUnloadTab",
"context_BarTabUnloadOtherTabs",
"context_BarTabNeverUnload",
"context_BarTabSeparator"].forEach(function (menuitemid) {
let menuitem = document.getElementById(menuitemid);
popup.insertBefore(menuitem, before);
});
}
popup.addEventListener('popupshowing', this, false);
},
/*** Event handlers ***/
handleEvent: function(aEvent) {
switch (aEvent.type) {
case 'SSTabRestoring':
this.onTabRestoring(aEvent);
return;
case 'TabOpen':
this.onTabOpen(aEvent);
return;
case 'TabSelect':
this.onTabSelect(aEvent);
return;
case 'TabClose':
this.onTabClose(aEvent);
return;
case 'popupshowing':
this.onPopupShowing(aEvent);
return;
}
},
/*
* Hook into newly opened tabs if the user wants to prevent tabs
* opened in the background from loading. (If this tab ends up not
* being in the background after all, 'onTabSelect' will take care
* of loading the tab.)
*/
onTabOpen: function(aEvent) {
var tab = aEvent.originalTarget;
if (tab.selected || !BarTabUtils.getPref("loadBackgroundTabs")) {
return;
}
tab.setAttribute("ontab", "true");
(new BarTabWebProgressListener()).hook(tab);
(new BarTabWebNavigation()).hook(tab);
},
/*
* Listen to the 'SSTabRestoring' event from the nsISessionStore
* service and hook into restored tabs if the user wants to prevent
* restored tabs from loading.
*/
onTabRestoring: function(aEvent) {
let tab = aEvent.originalTarget;
if (tab.selected || tab.getAttribute("ontab") == "true") {
return;
}
tab.setAttribute("ontab", "true");
(new BarTabRestoreProgressListener()).hook(tab);
},
onTabSelect: function(aEvent) {
var tab = aEvent.originalTarget;
if (tab.getAttribute("ontab") != "true") {
return;
}
// Always load a blank page immediately
let uri = tab.linkedBrowser.webNavigation.currentURI;
if (!uri || (uri.spec == "about:blank")) {
this.loadTab(tab);
return;
}
let delay = BarTabUtils.getPref("loadOnSelectDelay");
if (!delay) {
// Load immediately
this.loadTab(tab);
return;
}
// Load after delay
let window = tab.ownerDocument.defaultView;
let self = this;
window.setTimeout(function() {
if (tab.selected) {
self.loadTab(tab);
}
}, delay);
},
onTabClose: function(aEvent) {
if (!BarTabUtils.getPref("findClosestLoadedTab")) {
return;
}
let tab = aEvent.originalTarget;
if (!tab.selected) {
return;
}
let activeTab = this.findClosestLoadedTab(tab);
if (activeTab) {
this.tabbrowser.selectedTab = activeTab;
}
},
onPopupShowing: function(aEvent) {
var document = aEvent.target.ownerDocument;
var tab = document.popupNode.localName == "tab" ?
document.popupNode : this.tabbrowser.selectedTab;
var neverunload = document.getElementById("context_BarTabNeverUnload");
var unloadtab = document.getElementById("context_BarTabUnloadTab");
let host;
try {
host = tab.linkedBrowser.currentURI.host;
} catch (ex) {
// Most likely uri.host doesn't exist which probably means
// whitelisting doesn't make sense on this tab. Set empty
// host so we don't show the menu item
host = '';
}
if (!host) {
neverunload.setAttribute("hidden", "true");
unloadtab.removeAttribute("disabled");
return;
}
let label = this.l10n.getFormattedString('neverUnload', [host]);
neverunload.setAttribute("label", label);
neverunload.removeAttribute("hidden");
if (BarTabUtils.whiteListed(tab.linkedBrowser.currentURI)) {
neverunload.setAttribute("checked", "true");
unloadtab.setAttribute("disabled", "true");
return;
}
neverunload.removeAttribute("checked");
if (tab.getAttribute("ontab") == "true") {
unloadtab.setAttribute("disabled", "true");
} else {
unloadtab.removeAttribute("disabled");
}
},
/*** Public API ***/
loadTab: function(aTab) {
if (aTab.getAttribute("ontab") != "true") {
return;
}
aTab.removeAttribute("ontab");
aTab.linkedBrowser.webNavigation._resume();
},
unloadTab: function(aTab) {
// Ignore tabs that are already unloaded or are on the host whitelist.
if (aTab.getAttribute("ontab") == "true") {
return;
}
if (BarTabUtils.whiteListed(aTab.linkedBrowser.currentURI)) {
return;
}
let tabbrowser = this.tabbrowser;
// Make sure that we're not on this tab. If we are, find the
// closest tab that isn't on the bar tab.
if (aTab.selected) {
let activeTab = this.findClosestLoadedTab(aTab);
if (activeTab) {
tabbrowser.selectedTab = activeTab;
}
}
var sessionstore = BarTabUtils.mSessionStore;
var state = sessionstore.getTabState(aTab);
var newtab = tabbrowser.addTab(null, {skipAnimation: true});
// The user might not have 'extensions.bartab.loadRestoredTabs'
// set to 1 but still wants to unload this tab. That's why we
// need to make sure we hook into the new tab before restoring
// the tab state.
if (newtab.getAttribute("ontab") != "true") {
newtab.setAttribute("ontab", "true");
(new BarTabWebProgressListener()).hook(newtab);
(new BarTabWebNavigation()).hook(newtab);
}
sessionstore.setTabState(newtab, state);
// Move the new tab next to the one we're removing, but not in
// front of it as that confuses Tree Style Tab.
tabbrowser.moveTabTo(newtab, aTab._tPos + 1);
// Restore tree when using Tree Style Tab
if (tabbrowser.treeStyleTab) {
let parent = tabbrowser.treeStyleTab.getParentTab(aTab);
if (parent) {
tabbrowser.treeStyleTab.attachTabTo(newtab, parent,
{dontAnimate: true, insertBefore: aTab.nextSibling});
}
let children = tabbrowser.treeStyleTab.getChildTabs(aTab);
children.forEach(function(aChild) {
tabbrowser.treeStyleTab.attachTabTo(
aChild, newtab, {dontAnimate: true});
});
}
// Close the original tab. We're taking the long way round to
// ensure the nsISessionStore service won't save this in the
// recently closed tabs.
let check = tabbrowser._beginRemoveTab(aTab, true, null, false);
if (typeof check == "boolean" && check) {
// Firefox 4.0
tabbrowser._endRemoveTab(aTab);
return;
}
tabbrowser._endRemoveTab(check);
},
unloadOtherTabs: function(aTab) {
var tabbrowser = this.tabbrowser;
// Make sure we're sitting on the tab that isn't going to be unloaded.
if (tabbrowser.selectedTab != aTab) {
tabbrowser.selectedTab = aTab;
}
// unloadTab() mutates the tabs so the only sane thing to do is to
// copy the list of tabs now and then work off that list.
var tabs = [];
for (let i = 0; i < tabbrowser.mTabs.length; i++) {
tabs.push(tabbrowser.mTabs[i]);
}
var self = this;
tabs.forEach(function(tab) {
if (tab != aTab) {
self.unloadTab(tab);
}
});
},
toggleWhitelist: function(aTab) {
var uri = aTab.linkedBrowser.currentURI;
try {
var host = uri.host;
} catch(ex) {
// Most likely uri.host doesn't exist. Ignore then.
return;
}
let whitelist = BarTabUtils.getWhitelist();
let index = whitelist.indexOf(host);
if (index == -1) {
whitelist.push(host);
} else {
whitelist.splice(index, 1);
}
BarTabUtils.setWhitelist(whitelist);
},
/*
* In relation to a given tab, find the closest tab that is loaded.
* Note: if there's no such tab available, this will return unloaded
* tabs as a last resort.
*/
findClosestLoadedTab: function(aTab) {
var tabbrowser = this.tabbrowser;
// Shortcut: if this is the only tab available, we're not going to
// find another active one, are we...
if (tabbrowser.mTabs.length == 1) {
return null;
}
// The most obvious choice would be the owner tab, if it's active.
if (aTab.owner
&& BarTabUtils.mPrefs.getBoolPref("browser.tabs.selectOwnerOnClose")
&& aTab.owner.getAttribute("ontab") != "true") {
return aTab.owner;
}
// Otherwise walk the tab list and see if we can find an active one.
let i = 1;
while ((aTab._tPos - i >= 0) ||
(aTab._tPos + i < tabbrowser.mTabs.length)) {
if (aTab._tPos + i < tabbrowser.mTabs.length) {
if (tabbrowser.mTabs[aTab._tPos+i].getAttribute("ontab") != "true") {
return tabbrowser.mTabs[aTab._tPos+i];
}
}
if (aTab._tPos - i >= 0) {
if (tabbrowser.mTabs[aTab._tPos-i].getAttribute("ontab") != "true") {
return tabbrowser.mTabs[aTab._tPos-i];
}
}
i++;
}
// Fallback: there isn't an active tab available, so we're going
// to have to nominate a non-active one.
if (aTab.owner
&& BarTabUtils.mPrefs.getBoolPref("browser.tabs.selectOwnerOnClose")) {
return aTab.owner;
}
if (aTab.nextSibling) {
return aTab.nextSibling;
}
return aTab.previousSibling;
}
};
/*
* A wrapping implementation of nsIWebNavigation.
*
* It can install itself as the webNavigation property of a tab's
* browser object, replacing and wrapping around the original
* implementation. Once it has done so, it will defer all URI loading
* until the tab is no longer marked as 'ontab'.
*
* This provides a new method on top of nsIWebNavigation called
* 'resume()' which allows you to resume the operation that was
* deferred.
*/
function BarTabWebNavigation () {}
BarTabWebNavigation.prototype = {
/*
* Install ourself as browser's webNavigation. This needs to be
* passed the tab object (rather than just its associated browser
* object) because we need to be able to read and change tab's
* 'ontab' attribute.
*/
hook: function (aTab) {
this._tab = aTab;
this._original = aTab.linkedBrowser.webNavigation;
var self = this;
aTab.linkedBrowser.__defineGetter__('webNavigation', function () {
return self;
});
},
/*
* Restore the browser's original webNavigation.
*/
unhook: function () {
if (this._tab._barTabProgressListener) {
this._tab._barTabProgressListener.unhook();
}
delete this._gotoindex;
delete this._loaduri_args;
delete this._referringuri;
if (this._tab.linkedBrowser.webNavigation === this) {
// This will delete the instance getter for 'webNavigation',
// thus revealing the original implementation.
delete this._tab.linkedBrowser.webNavigation;
}
delete this._original;
delete this._tab;
},
/*
* This will be replaced with either _resumeGotoIndex or _resumeLoadURI,
* unless it's a blank tab. For the latter case we make sure we'll
* unhook ourselves.
*/
_resume: function () {
this.unhook();
},
_unfakeDocshellURI: function () {
// No longer lie about the URI. Otherwise the docshell might
// not want to load the page (especially seems to happen with
// fragment URIs).
var blankURI = BarTabUtils.makeURI("about:blank");
this._tab.linkedBrowser.docShell.setCurrentURI(blankURI);
},
/*** Hook into gotoIndex() ***/
gotoIndex: function (aIndex) {
if (this._tab.getAttribute("ontab") == "true") {
return this._pauseGotoIndex(aIndex);
}
return this._original.gotoIndex(aIndex);
},
_pauseGotoIndex: function (aIndex) {
var history = this._original.sessionHistory;
var entry = history.getEntryAtIndex(aIndex, false);
if (BarTabUtils.whiteListed(entry.URI)) {
this._tab.removeAttribute("ontab");
return this._original.gotoIndex(aIndex);
}
this._tab.removeAttribute("busy");
this._tab.label = entry.title;
let window = this._tab.ownerDocument.defaultView;
window.setTimeout(BarTabUtils.setIcon, 0, this._tab, entry.URI);
// Fake the docshell's currentURI. (This will also affect
// window.location etc.)
this._tab.linkedBrowser.docShell.setCurrentURI(entry.URI);
this._referringuri = entry.referrerURI;
this._gotoindex = aIndex;
this._resume = this._resumeGotoIndex;
},
_resumeGotoIndex: function () {
var index = this._gotoindex;
var original = this._original;
this._unfakeDocshellURI();
this.unhook();
return original.gotoIndex(index);
},
/*** Hook into loadURI() ***/
loadURI: function (aURI) {
// Allow about:blank to load without any side effects.
if (aURI
&& (aURI != "about:blank")
&& (this._tab.getAttribute("ontab") == "true")) {
return this._pauseLoadURI.apply(this, arguments);
}
return this._original.loadURI.apply(this._original, arguments);
},
_pauseLoadURI: function (aURI, aLoadFlags, aReferrer) {
var uri = BarTabUtils.makeURI(aURI);
if (BarTabUtils.whiteListed(uri)) {
let original = this._original;
this._tab.removeAttribute("ontab");
this.unhook();
return original.loadURI.apply(original, arguments);
}
this._tab.removeAttribute("busy");
let window = this._tab.ownerDocument.defaultView;
if (aReferrer) {
// Fake the docshell's currentURI. (This will also affect
// window.location etc.)
this._tab.linkedBrowser.docShell.setCurrentURI(uri);
window.setTimeout(BarTabUtils.setTitleAndIcon, 0, this._tab, uri);
} else {
// If there's no referrer, it's likely that we were opened
// from an external application which somehow sets up things
// like tab title and currentURI later. Avoid the race
// with an increased timeout.
window.setTimeout(this._tab.linkedBrowser.docShell.setCurrentURI,
100, uri);
window.setTimeout(BarTabUtils.setTitleAndIcon, 100, this._tab, uri);
}
if (aReferrer instanceof Ci.nsIURI) {
this._referringuri = aReferrer.clone();
}
this._loaduri_args = arguments;
this._resume = this._resumeLoadURI;
},
_resumeLoadURI: function () {
var args = this._loaduri_args;
var original = this._original;
this._unfakeDocshellURI();
this.unhook();
return original.loadURI.apply(original, args);
},
/*** Behaviour changed for unloaded tabs. ***/
get referringURI() {
if (this._referringuri) {
return this._referringuri.clone();
}
return this._original.currentURI;
},
reload: function(aReloadFlags) {
if (this._tab.getAttribute("ontab") == "true") {
this._tab.removeAttribute("ontab");
//TODO should we patch aReloadFlags into this._loaduri_args?
return this._resume();
}
return this._original.reload(aReloadFlags);
},
QueryInterface: function(aIID) {
if (Ci.nsISupports.equals(aIID) || Ci.nsIWebNavigation.equals(aIID)) {
return this;
}
return this._original.QueryInterface(aIID);
},
/*** These methods and properties are simply passed through. ***/
goBack: function () {
return this._original.goBack();
},
goForward: function () {
return this._original.goForward();
},
stop: function(aStopFlags) {
return this._original.stop(aStopFlags);
},
get currentURI() {
return this._original.currentURI;
},
get canGoBack() {
return this._original.canGoBack;
},
get canGoForward() {
return this._original.canGoForward;
},
get document() {
return this._original.document;
},
get sessionHistory() {
return this._original.sessionHistory;
}
};
/*
* Progress listener for tabs that are being restored but haven't
* loaded yet.
*/
function BarTabRestoreProgressListener () {}
BarTabRestoreProgressListener.prototype = {
hook: function (aTab) {
this._tab = aTab;
aTab._barTabRestoreProgressListener = this;
aTab.linkedBrowser.webProgress.addProgressListener(
this, Ci.nsIWebProgress.NOTIFY_STATE_NETWORK);
},
unhook: function () {
this._tab.linkedBrowser.webProgress.removeProgressListener(this);
delete this._tab._barTabRestoreProgressListener;
delete this._tab;
},
/*** nsIWebProgressListener ***/
onStateChange: function (aWebProgress, aRequest, aStateFlags, aStatus) {
this._tab.removeAttribute("ontab");
this.unhook();
},
onProgressChange: function () {},
onLocationChange: function () {},
onStatusChange: function () {},
onSecurityChange: function () {},
QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
Ci.nsISupportsWeakReference,
Ci.nsISupports])
};
/*
* Progress listener that stops the loading of tabs that are opened in
* the background and whose contents is loaded by C++ code. This
* occurs for instance when the 'browser.tabs.loadDivertedInBackground'
* preference is enabled (because links are always opened by docshell code).
*/
function BarTabWebProgressListener () {}
BarTabWebProgressListener.prototype = {
hook: function (aTab) {
this._tab = aTab;
aTab._barTabProgressListener = this;
aTab.linkedBrowser.webProgress.addProgressListener(
this, Ci.nsIWebProgress.NOTIFY_ALL);
},
unhook: function () {
this._tab.linkedBrowser.webProgress.removeProgressListener(this);
delete this._tab._barTabProgressListener;
delete this._tab;
},
/*** nsIWebProgressListener ***/
onStateChange: function (aWebProgress, aRequest, aStateFlags, aStatus) {
if (!aRequest) {
return;
}
if (!(aStateFlags & Ci.nsIWebProgressListener.STATE_START)
|| !(aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK)
|| (aStateFlags & Ci.nsIWebProgressListener.STATE_RESTORING)) {
return;
}
if (this._tab.getAttribute("ontab") != "true") {
return;
}
// Allow about:blank and wyciwyg URIs to load without any side effects.
let uri = aRequest.QueryInterface(Ci.nsIChannel).URI;
if ((uri.spec == "about:blank") || (uri.scheme == "wyciwyg")) {
return;
}
// Allow whitelisted URIs to load.
let browser = this._tab.linkedBrowser;
if (BarTabUtils.whiteListed(uri)) {
this._tab.removeAttribute("ontab");
// webNavigation.unhook() will call our unhook.
browser.webNavigation.unhook();
return;
}
// If it's an HTTP request, we want to set the right referrer.
// And if it's a POST request on top of that, we want to make
// sure we reuse the post data.
let httpChannel;
try {
httpChannel = aRequest.QueryInterface(Ci.nsIHttpChannel);
} catch (ex) {
// Ignore.
}
let referrer;
let postData;
if (httpChannel) {
referrer = httpChannel.referrer;
let uploadChannel = httpChannel.QueryInterface(Ci.nsIUploadChannel);
// uploadStream will be null or an nsIInputStream.
postData = uploadChannel.uploadStream;
}
// Defer the loading. Do this async so that other
// nsIWebProgressListeners have a chance to update the UI
// before _pauseLoadURI overwrites it all again.
browser.stop();
let flags = Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
let window = this._tab.ownerDocument.defaultView;
window.setTimeout(function () {
browser.webNavigation._pauseLoadURI(
uri.spec, flags, referrer, postData, null);
}, 0);
},
onProgressChange: function () {},
onLocationChange: function () {},
onStatusChange: function () {},
onSecurityChange: function () {},
QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener,
Ci.nsISupportsWeakReference,
Ci.nsISupports])
};
/*
* A timer that keeps track of how long ago each tab was last visited.
* If that time reaches a user-defined value, it unloads the tab in
* question. (The actual implementation works differently. It uses
* setTimeout, of course).
*/
function BarTabTimer() {}
BarTabTimer.prototype = {
init: function(aTabBrowser) {
this.tabbrowser = aTabBrowser;
aTabBrowser.tabContainer.addEventListener('TabOpen', this, false);
aTabBrowser.tabContainer.addEventListener('TabSelect', this, false);
aTabBrowser.tabContainer.addEventListener('TabClose', this, false);
this.previousTab = null;
this.selectedTab = aTabBrowser.selectedTab;
},
handleEvent: function(event) {
switch (event.type) {
case 'TabOpen':
this.onTabOpen(event);
return;
case 'TabSelect':
this.onTabSelect(event);
return;
case 'TabClose':
this.onTabClose(event);
return;
}
},
onTabOpen: function(aEvent) {
var tab = aEvent.originalTarget;
if (tab.selected
|| (BarTabUtils.getPref("loadBackgroundTabs") == 1)) {
return;
}
this.startTimer(tab);
},
onTabClose: function(event) {
this.clearTimer(event.originalTarget);
if (event.originalTarget == this.selectedTab) {
this.selectedTab = null;
};
if (event.originalTarget == this.previousTab) {
this.previousTab = null;
};
},
onTabSelect: function(event) {
this.previousTab = this.selectedTab;
this.selectedTab = event.originalTarget;
if (this.previousTab) {
// The previous tab may not be available because it has
// been closed.
this.startTimer(this.previousTab);
}
this.clearTimer(this.selectedTab);
},
startTimer: function(aTab) {
if (!BarTabUtils.getPref("unloadAfterTimeout")) {
return;
}
if (aTab.getAttribute("ontab") == "true") {
return;
}
if (aTab._barTabTimer) {
this.clearTimer(aTab);
}
let secs = BarTabUtils.getPref("timeoutValue")
* BarTabUtils.getPref("timeoutUnit");
let window = aTab.ownerDocument.defaultView;
// Allow 'this' to leak into the inline function
let self = this;
aTab._barTabTimer = window.setTimeout(function() {
// The timer will be removed automatically since
// unloadTab() will close and replace the original tab.
self.tabbrowser.BarTabHandler.unloadTab(aTab, self.tabbrowser);
}, secs*1000);
},
clearTimer: function(aTab) {
var window = aTab.ownerDocument.defaultView;
window.clearTimeout(aTab._barTabTimer);
aTab._barTabTimer = null;
}
};
var BarTabUtils = {
/*
* Create a new URI object.
*/
makeURI: function(aURL, aOriginCharset, aBaseURI) {
return this.mIO.newURI(aURL, aOriginCharset, aBaseURI);
},
/*
* Find and set the tab's favicon for a given URI.
*/
setIcon: function(aTab, aURI) {
try {
let iconURI = BarTabUtils.mFavicon.getFaviconForPage(aURI);
aTab.setAttribute("image", iconURI.spec);
} catch (ex) {
// No favicon found. Perhaps it's a URL with an anchor?
// Firefox doesn't always store favicons for those.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=420605
aURI = BarTabUtils.stripFragmentFromURI(aURI);
if (aURI) {
BarTabUtils.setIcon(aTab, aURI);
}
}
},
/*
* Set a tab's title and favicon given a URI by querying the history
* service.
*/
setTitleAndIcon: function(aTab, aURI) {
// See if we have title, favicon in stock for it. This should
// definitely work for restored tabs as they're in the history
// database.
let info = BarTabUtils.getInfoFromHistory(aURI);
if (!info) {
aTab.label = BarTabUtils.titleFromURI(aURI);
return;
}
// Firefox cripples nsINavHistoryService entries for fragment links.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=503832
// Try to work around that by stripping the fragment from the URI.
if (!info.icon) {
let uri = BarTabUtils.stripFragmentFromURI(aURI);
if (uri) {
let anchorinfo = BarTabUtils.getInfoFromHistory(uri);
if (anchorinfo) {
info = anchorinfo;
}
}
}
aTab.setAttribute("image", info.icon);
if (info.title) {
aTab.label = info.title;
} else {
aTab.label = BarTabUtils.titleFromURI(aURI);
}
},
/*
* Strip the fragment from a URI. Returns a new URI object, or null
* if the URI didn't contain a fragment.
*/
stripFragmentFromURI: function(aURI) {
var anchor = aURI.path.indexOf('#');
if (anchor == -1) {
return null;
}
let uri = aURI.clone();
uri.path = uri.path.substr(0, anchor);
return uri;
},
/*
* Derive a title from a URI by stripping the protocol and potentially
* "www.", so "http://www.mozilla.org" would become "mozilla.org".
*/
titleFromURI: function(aURI) {
try {
let hostPort = aURI.hostPort;
let path = aURI.path;
if (hostPort.substr(0, 4) == "www.") {
hostPort = hostPort.substr(4);
}
if (path == "/") {
path = "";
}
return hostPort + path;
} catch (ex) {
// Most likely aURI.hostPort and aURI.path failed.
// Let's handle this gracefully.
return aURI.spec;
}
},
/*
* Get information about a URI from the history service,
* e.g. title, favicon, ...
*/
getInfoFromHistory: function(aURI) {
var history = BarTabUtils.mHistory;
var options = history.getNewQueryOptions();
options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_HISTORY;
options.maxResults = 1;
var query = history.getNewQuery();
query.uri = aURI;
var result = history.executeQuery(query, options);
result.root.containerOpen = true;
if (!result.root.childCount) {
return null;
}
return result.root.getChild(0);
},
getPref: function(aPref, aDefaultValue) {
let branch = BarTabUtils.mPrefBranch;
switch (branch.getPrefType(aPref)) {
case Ci.nsIPrefBranch.PREF_STRING:
return branch.getComplexValue(aPref, Ci.nsISupportsString).data;
case Ci.nsIPrefBranch.PREF_INT:
return branch.getIntPref(aPref);
case Ci.nsIPrefBranch.PREF_BOOL:
return branch.getBoolPref(aPref);
case Ci.nsIPrefBranch.PREF_INVALID:
return aDefaultValue;
default:
// This should never happen.
throw "Error getting pref " + aPref + "!\n";
}
},
migratePrefs: function() {
if (this.getPref("migrated")) {
return;
}
// Grab the list of old pref names
let newBranch = BarTabUtils.mPrefBranch;
let oldBranch = BarTabUtils.mPrefs.getBranch("extensions.bartap.");
let oldPrefNames = oldBranch.getChildList("", {});
let value;
for each (let pref in oldPrefNames) {
switch (pref) {
case "tapBackgroundTabs":
value = oldBranch.getBoolPref(pref);
newBranch.setIntPref("loadBackgroundTabs", 0+value);
break;
case "tapAfterTimeout":
value = oldBranch.getBoolPref(pref);
newBranch.setBoolPref("unloadAfterTimeout", value);
break;
case "loadOnSelect":
value = oldBranch.getBoolPref(pref);
if (value) {
value = oldBranch.getBoolPref("loadOnSelectDelay");
}
newBranch.setIntPref("loadOnSelectDelay", 0+value);
break;
case "loadOnSelectDelay":
break;
case "findClosestUntappedTab":
value = oldBranch.getBoolPref(pref);
newBranch.setBoolPref("findClosestLoadedTab", value);
break;
case "hostWhitelist":
value = oldBranch.getCharPref(pref);
newBranch.setCharPref("whitelist", value);
break;
default:
value = oldBranch.getIntPref(pref);
newBranch.setIntPref(pref, value);
}
}
oldBranch.deleteBranch("");
newBranch.setBoolPref("migrated", true);
},