This repository has been archived by the owner on Apr 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 305
/
nsBrowserGlue.js
1751 lines (1550 loc) · 71.7 KB
/
nsBrowserGlue.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
# -*- indent-tabs-mode: nil -*-
# 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/.
const Ci = Components.interfaces;
const Cc = Components.classes;
const Cr = Components.results;
const Cu = Components.utils;
const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource:///modules/SignInToWebsite.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
"resource://gre/modules/AddonManager.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
"resource://gre/modules/NetUtil.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "UserAgentOverrides",
"resource://gre/modules/UserAgentOverrides.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "BookmarkHTMLUtils",
"resource://gre/modules/BookmarkHTMLUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "webappsUI",
"resource:///modules/webappsUI.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PageThumbs",
"resource:///modules/PageThumbs.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NewTabUtils",
"resource:///modules/NewTabUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "BrowserNewTabPreloader",
"resource:///modules/BrowserNewTabPreloader.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PdfJs",
"resource://pdf.js/PdfJs.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "webrtcUI",
"resource:///modules/webrtcUI.jsm");
const PREF_PLUGINS_NOTIFYUSER = "plugins.update.notifyUser";
const PREF_PLUGINS_UPDATEURL = "plugins.update.url";
// We try to backup bookmarks at idle times, to avoid doing that at shutdown.
// Number of idle seconds before trying to backup bookmarks. 15 minutes.
const BOOKMARKS_BACKUP_IDLE_TIME = 15 * 60;
// Minimum interval in milliseconds between backups.
const BOOKMARKS_BACKUP_INTERVAL = 86400 * 1000;
// Maximum number of backups to create. Old ones will be purged.
const BOOKMARKS_BACKUP_MAX_BACKUPS = 10;
// Factory object
const BrowserGlueServiceFactory = {
_instance: null,
createInstance: function BGSF_createInstance(outer, iid) {
if (outer != null)
throw Components.results.NS_ERROR_NO_AGGREGATION;
return this._instance == null ?
this._instance = new BrowserGlue() : this._instance;
}
};
// Constructor
function BrowserGlue() {
XPCOMUtils.defineLazyServiceGetter(this, "_idleService",
"@mozilla.org/widget/idleservice;1",
"nsIIdleService");
XPCOMUtils.defineLazyGetter(this, "_distributionCustomizer", function() {
Cu.import("resource:///modules/distribution.js");
return new DistributionCustomizer();
});
XPCOMUtils.defineLazyGetter(this, "_sanitizer",
function() {
let sanitizerScope = {};
Services.scriptloader.loadSubScript("chrome://browser/content/sanitize.js", sanitizerScope);
return sanitizerScope.Sanitizer;
});
this._init();
}
#ifndef XP_MACOSX
# OS X has the concept of zero-window sessions and therefore ignores the
# browser-lastwindow-close-* topics.
#define OBSERVE_LASTWINDOW_CLOSE_TOPICS 1
#endif
BrowserGlue.prototype = {
_saveSession: false,
_isIdleObserver: false,
_isPlacesInitObserver: false,
_isPlacesLockedObserver: false,
_isPlacesShutdownObserver: false,
_isPlacesDatabaseLocked: false,
_migrationImportsDefaultBookmarks: false,
_setPrefToSaveSession: function BG__setPrefToSaveSession(aForce) {
if (!this._saveSession && !aForce)
return;
Services.prefs.setBoolPref("browser.sessionstore.resume_session_once", true);
// This method can be called via [NSApplication terminate:] on Mac, which
// ends up causing prefs not to be flushed to disk, so we need to do that
// explicitly here. See bug 497652.
Services.prefs.savePrefFile(null);
},
#ifdef MOZ_SERVICES_SYNC
_setSyncAutoconnectDelay: function BG__setSyncAutoconnectDelay() {
// Assume that a non-zero value for services.sync.autoconnectDelay should override
if (Services.prefs.prefHasUserValue("services.sync.autoconnectDelay")) {
let prefDelay = Services.prefs.getIntPref("services.sync.autoconnectDelay");
if (prefDelay > 0)
return;
}
// delays are in seconds
const MAX_DELAY = 300;
let delay = 3;
let browserEnum = Services.wm.getEnumerator("navigator:browser");
while (browserEnum.hasMoreElements()) {
delay += browserEnum.getNext().gBrowser.tabs.length;
}
delay = delay <= MAX_DELAY ? delay : MAX_DELAY;
Cu.import("resource://services-sync/main.js");
Weave.SyncScheduler.delayedAutoConnect(delay);
},
#endif
// nsIObserver implementation
observe: function BG_observe(subject, topic, data) {
switch (topic) {
case "xpcom-shutdown":
this._dispose();
break;
case "prefservice:after-app-defaults":
this._onAppDefaults();
break;
case "final-ui-startup":
this._onProfileStartup();
break;
case "browser-delayed-startup-finished":
this._onFirstWindowLoaded();
Services.obs.removeObserver(this, "browser-delayed-startup-finished");
break;
case "sessionstore-windows-restored":
this._onWindowsRestored();
break;
case "browser:purge-session-history":
// reset the console service's error buffer
Services.console.logStringMessage(null); // clear the console (in case it's open)
Services.console.reset();
break;
case "quit-application-requested":
this._onQuitRequest(subject, data);
break;
case "quit-application-granted":
// This pref must be set here because SessionStore will use its value
// on quit-application.
this._setPrefToSaveSession();
try {
let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"].
getService(Ci.nsIAppStartup);
appStartup.trackStartupCrashEnd();
} catch (e) {
Cu.reportError("Could not end startup crash tracking in quit-application-granted: " + e);
}
break;
#ifdef OBSERVE_LASTWINDOW_CLOSE_TOPICS
case "browser-lastwindow-close-requested":
// The application is not actually quitting, but the last full browser
// window is about to be closed.
this._onQuitRequest(subject, "lastwindow");
break;
case "browser-lastwindow-close-granted":
this._setPrefToSaveSession();
break;
#endif
#ifdef MOZ_SERVICES_SYNC
case "weave:service:ready":
this._setSyncAutoconnectDelay();
break;
case "weave:engine:clients:display-uri":
this._onDisplaySyncURI(subject);
break;
#endif
case "session-save":
this._setPrefToSaveSession(true);
subject.QueryInterface(Ci.nsISupportsPRBool);
subject.data = true;
break;
case "places-init-complete":
if (!this._migrationImportsDefaultBookmarks)
this._initPlaces(false);
Services.obs.removeObserver(this, "places-init-complete");
this._isPlacesInitObserver = false;
// no longer needed, since history was initialized completely.
Services.obs.removeObserver(this, "places-database-locked");
this._isPlacesLockedObserver = false;
break;
case "places-database-locked":
this._isPlacesDatabaseLocked = true;
// Stop observing, so further attempts to load history service
// will not show the prompt.
Services.obs.removeObserver(this, "places-database-locked");
this._isPlacesLockedObserver = false;
break;
case "places-shutdown":
if (this._isPlacesShutdownObserver) {
Services.obs.removeObserver(this, "places-shutdown");
this._isPlacesShutdownObserver = false;
}
// places-shutdown is fired when the profile is about to disappear.
this._onProfileShutdown();
break;
case "idle":
if (this._idleService.idleTime > BOOKMARKS_BACKUP_IDLE_TIME * 1000)
this._backupBookmarks();
break;
case "distribution-customization-complete":
Services.obs.removeObserver(this, "distribution-customization-complete");
// Customization has finished, we don't need the customizer anymore.
delete this._distributionCustomizer;
break;
case "browser-glue-test": // used by tests
if (data == "post-update-notification") {
if (Services.prefs.prefHasUserValue("app.update.postupdate"))
this._showUpdateNotification();
}
else if (data == "force-ui-migration") {
this._migrateUI();
}
else if (data == "force-distribution-customization") {
this._distributionCustomizer.applyPrefDefaults();
this._distributionCustomizer.applyCustomizations();
// To apply distribution bookmarks use "places-init-complete".
}
else if (data == "force-places-init") {
this._initPlaces(false);
}
break;
case "initial-migration-will-import-default-bookmarks":
this._migrationImportsDefaultBookmarks = true;
break;
case "initial-migration-did-import-default-bookmarks":
this._initPlaces(true);
break;
}
},
// initialization (called on application startup)
_init: function BG__init() {
let os = Services.obs;
os.addObserver(this, "xpcom-shutdown", false);
os.addObserver(this, "prefservice:after-app-defaults", false);
os.addObserver(this, "final-ui-startup", false);
os.addObserver(this, "browser-delayed-startup-finished", false);
os.addObserver(this, "sessionstore-windows-restored", false);
os.addObserver(this, "browser:purge-session-history", false);
os.addObserver(this, "quit-application-requested", false);
os.addObserver(this, "quit-application-granted", false);
#ifdef OBSERVE_LASTWINDOW_CLOSE_TOPICS
os.addObserver(this, "browser-lastwindow-close-requested", false);
os.addObserver(this, "browser-lastwindow-close-granted", false);
#endif
#ifdef MOZ_SERVICES_SYNC
os.addObserver(this, "weave:service:ready", false);
os.addObserver(this, "weave:engine:clients:display-uri", false);
#endif
os.addObserver(this, "session-save", false);
os.addObserver(this, "places-init-complete", false);
this._isPlacesInitObserver = true;
os.addObserver(this, "places-database-locked", false);
this._isPlacesLockedObserver = true;
os.addObserver(this, "distribution-customization-complete", false);
os.addObserver(this, "places-shutdown", false);
this._isPlacesShutdownObserver = true;
},
// cleanup (called on application shutdown)
_dispose: function BG__dispose() {
let os = Services.obs;
os.removeObserver(this, "xpcom-shutdown");
os.removeObserver(this, "prefservice:after-app-defaults");
os.removeObserver(this, "final-ui-startup");
os.removeObserver(this, "sessionstore-windows-restored");
os.removeObserver(this, "browser:purge-session-history");
os.removeObserver(this, "quit-application-requested");
os.removeObserver(this, "quit-application-granted");
#ifdef OBSERVE_LASTWINDOW_CLOSE_TOPICS
os.removeObserver(this, "browser-lastwindow-close-requested");
os.removeObserver(this, "browser-lastwindow-close-granted");
#endif
#ifdef MOZ_SERVICES_SYNC
os.removeObserver(this, "weave:service:ready", false);
os.removeObserver(this, "weave:engine:clients:display-uri", false);
#endif
os.removeObserver(this, "session-save");
if (this._isIdleObserver)
this._idleService.removeIdleObserver(this, BOOKMARKS_BACKUP_IDLE_TIME);
if (this._isPlacesInitObserver)
os.removeObserver(this, "places-init-complete");
if (this._isPlacesLockedObserver)
os.removeObserver(this, "places-database-locked");
if (this._isPlacesShutdownObserver)
os.removeObserver(this, "places-shutdown");
UserAgentOverrides.uninit();
webappsUI.uninit();
SignInToWebsiteUX.uninit();
webrtcUI.uninit();
},
_onAppDefaults: function BG__onAppDefaults() {
// apply distribution customizations (prefs)
// other customizations are applied in _onProfileStartup()
this._distributionCustomizer.applyPrefDefaults();
},
// profile startup handler (contains profile initialization routines)
_onProfileStartup: function BG__onProfileStartup() {
this._sanitizer.onStartup();
// check if we're in safe mode
if (Services.appinfo.inSafeMode) {
Services.ww.openWindow(null, "chrome://browser/content/safeMode.xul",
"_blank", "chrome,centerscreen,modal,resizable=no", null);
}
// apply distribution customizations
// prefs are applied in _onAppDefaults()
this._distributionCustomizer.applyCustomizations();
// handle any UI migration
this._migrateUI();
this._setUpUserAgentOverrides();
webappsUI.init();
PageThumbs.init();
NewTabUtils.init();
BrowserNewTabPreloader.init();
SignInToWebsiteUX.init();
PdfJs.init();
webrtcUI.init();
Services.obs.notifyObservers(null, "browser-ui-startup-complete", "");
},
_setUpUserAgentOverrides: function BG__setUpUserAgentOverrides() {
UserAgentOverrides.init();
if (Services.prefs.getBoolPref("general.useragent.complexOverride.moodle")) {
UserAgentOverrides.addComplexOverride(function (aHttpChannel, aOriginalUA) {
let cookies;
try {
cookies = aHttpChannel.getRequestHeader("Cookie");
} catch (e) { /* no cookie sent */ }
if (cookies && cookies.indexOf("MoodleSession") > -1)
return aOriginalUA.replace(/Gecko\/[^ ]*/, "Gecko/20100101");
return null;
});
}
},
// the first browser window has finished initializing
_onFirstWindowLoaded: function BG__onFirstWindowLoaded() {
#ifdef XP_WIN
// For windows seven, initialize the jump list module.
const WINTASKBAR_CONTRACTID = "@mozilla.org/windows-taskbar;1";
if (WINTASKBAR_CONTRACTID in Cc &&
Cc[WINTASKBAR_CONTRACTID].getService(Ci.nsIWinTaskbar).available) {
let temp = {};
Cu.import("resource://gre/modules/WindowsJumpLists.jsm", temp);
temp.WinTaskbarJumpList.startup();
}
#endif
},
// profile shutdown handler (contains profile cleanup routines)
_onProfileShutdown: function BG__onProfileShutdown() {
this._shutdownPlaces();
this._sanitizer.onShutdown();
PageThumbs.uninit();
BrowserNewTabPreloader.uninit();
},
// All initial windows have opened.
_onWindowsRestored: function BG__onWindowsRestored() {
// Show about:rights notification, if needed.
if (this._shouldShowRights()) {
this._showRightsNotification();
#ifdef MOZ_TELEMETRY_REPORTING
} else {
// Only show telemetry notification when about:rights notification is not shown.
this._showTelemetryNotification();
#endif
}
// Show update notification, if needed.
if (Services.prefs.prefHasUserValue("app.update.postupdate"))
this._showUpdateNotification();
// Load the "more info" page for a locked places.sqlite
// This property is set earlier by places-database-locked topic.
if (this._isPlacesDatabaseLocked) {
this._showPlacesLockedNotificationBox();
}
// If there are plugins installed that are outdated, and the user hasn't
// been warned about them yet, open the plugins update page.
if (Services.prefs.getBoolPref(PREF_PLUGINS_NOTIFYUSER))
this._showPluginUpdatePage();
// For any add-ons that were installed disabled and can be enabled offer
// them to the user.
let changedIDs = AddonManager.getStartupChanges(AddonManager.STARTUP_CHANGE_INSTALLED);
if (changedIDs.length > 0) {
let browser = this.getMostRecentBrowserWindow().gBrowser;
AddonManager.getAddonsByIDs(changedIDs, function(aAddons) {
aAddons.forEach(function(aAddon) {
// If the add-on isn't user disabled or can't be enabled then skip it.
if (!aAddon.userDisabled || !(aAddon.permissions & AddonManager.PERM_CAN_ENABLE))
return;
browser.selectedTab = browser.addTab("about:newaddon?id=" + aAddon.id);
})
});
}
let keywordURLUserSet = Services.prefs.prefHasUserValue("keyword.URL");
Services.telemetry.getHistogramById("FX_KEYWORD_URL_USERSET").add(keywordURLUserSet);
// Perform default browser checking.
var shell;
try {
shell = Components.classes["@mozilla.org/browser/shell-service;1"]
.getService(Components.interfaces.nsIShellService);
} catch (e) { }
if (shell) {
#ifdef DEBUG
let shouldCheck = false;
#else
let shouldCheck = shell.shouldCheckDefaultBrowser;
#endif
let willRecoverSession = false;
try {
let ss = Cc["@mozilla.org/browser/sessionstartup;1"].
getService(Ci.nsISessionStartup);
willRecoverSession =
(ss.sessionType == Ci.nsISessionStartup.RECOVER_SESSION);
}
catch (ex) { /* never mind; suppose SessionStore is broken */ }
if (shouldCheck &&
!shell.isDefaultBrowser(true, false) &&
!willRecoverSession) {
Services.tm.mainThread.dispatch(function() {
var win = this.getMostRecentBrowserWindow();
var brandBundle = win.document.getElementById("bundle_brand");
var shellBundle = win.document.getElementById("bundle_shell");
var brandShortName = brandBundle.getString("brandShortName");
var promptTitle = shellBundle.getString("setDefaultBrowserTitle");
var promptMessage = shellBundle.getFormattedString("setDefaultBrowserMessage",
[brandShortName]);
var checkboxLabel = shellBundle.getFormattedString("setDefaultBrowserDontAsk",
[brandShortName]);
var checkEveryTime = { value: shouldCheck };
var ps = Services.prompt;
var rv = ps.confirmEx(win, promptTitle, promptMessage,
ps.STD_YES_NO_BUTTONS,
null, null, null, checkboxLabel, checkEveryTime);
if (rv == 0) {
var claimAllTypes = true;
#ifdef XP_WIN
try {
// In Windows 8, the UI for selecting default protocol is much
// nicer than the UI for setting file type associations. So we
// only show the protocol association screen on Windows 8.
// Windows 8 is version 6.2.
let version = Cc["@mozilla.org/system-info;1"]
.getService(Ci.nsIPropertyBag2)
.getProperty("version");
claimAllTypes = (parseFloat(version) < 6.2);
} catch (ex) { }
#endif
shell.setDefaultBrowser(claimAllTypes, false);
}
shell.shouldCheckDefaultBrowser = checkEveryTime.value;
}.bind(this), Ci.nsIThread.DISPATCH_NORMAL);
}
}
},
_onQuitRequest: function BG__onQuitRequest(aCancelQuit, aQuitType) {
// If user has already dismissed quit request, then do nothing
if ((aCancelQuit instanceof Ci.nsISupportsPRBool) && aCancelQuit.data)
return;
// There are several cases where we won't show a dialog here:
// 1. There is only 1 tab open in 1 window
// 2. The session will be restored at startup, indicated by
// browser.startup.page == 3 or browser.sessionstore.resume_session_once == true
// 3. browser.warnOnQuit == false
// 4. The browser is currently in Private Browsing mode
//
// Otherwise these are the conditions and the associated dialogs that will be shown:
// 1. aQuitType == "lastwindow" or "quit" and browser.showQuitWarning == true
// - The quit dialog will be shown
// 2. aQuitType == "restart" && browser.warnOnRestart == true
// - The restart dialog will be shown
// 3. aQuitType == "lastwindow" && browser.tabs.warnOnClose == true
// - The "closing multiple tabs" dialog will be shown
//
// aQuitType == "lastwindow" is overloaded. "lastwindow" is used to indicate
// "the last window is closing but we're not quitting (a non-browser window is open)"
// and also "we're quitting by closing the last window".
var windowcount = 0;
var pagecount = 0;
var browserEnum = Services.wm.getEnumerator("navigator:browser");
let allWindowsPrivate = true;
while (browserEnum.hasMoreElements()) {
windowcount++;
var browser = browserEnum.getNext();
if (("gPrivateBrowsingUI" in browser) && !browser.gPrivateBrowsingUI.privateWindow)
allWindowsPrivate = false;
var tabbrowser = browser.document.getElementById("content");
if (tabbrowser)
pagecount += tabbrowser.browsers.length - tabbrowser._numPinnedTabs;
}
this._saveSession = false;
if (pagecount < 2)
return;
if (!aQuitType)
aQuitType = "quit";
var showPrompt = false;
var mostRecentBrowserWindow;
// browser.warnOnQuit is a hidden global boolean to override all quit prompts
// browser.showQuitWarning specifically covers quitting
// browser.warnOnRestart specifically covers app-initiated restarts where we restart the app
// browser.tabs.warnOnClose is the global "warn when closing multiple tabs" pref
var sessionWillBeRestored = Services.prefs.getIntPref("browser.startup.page") == 3 ||
Services.prefs.getBoolPref("browser.sessionstore.resume_session_once");
if (sessionWillBeRestored || !Services.prefs.getBoolPref("browser.warnOnQuit"))
return;
// On last window close or quit && showQuitWarning, we want to show the
// quit warning.
if (aQuitType != "restart" && Services.prefs.getBoolPref("browser.showQuitWarning")) {
showPrompt = true;
}
else if (aQuitType == "restart" && Services.prefs.getBoolPref("browser.warnOnRestart")) {
showPrompt = true;
}
else if (aQuitType == "lastwindow") {
// If aQuitType is "lastwindow" and we aren't showing the quit warning,
// we should show the window closing warning instead. warnAboutClosing
// tabs checks browser.tabs.warnOnClose and returns if it's ok to close
// the window. It doesn't actually close the window.
mostRecentBrowserWindow = Services.wm.getMostRecentWindow("navigator:browser");
aCancelQuit.data = !mostRecentBrowserWindow.gBrowser.warnAboutClosingTabs(true);
return;
}
// Never show a prompt inside private browsing mode
if (allWindowsPrivate)
return;
if (!showPrompt)
return;
var quitBundle = Services.strings.createBundle("chrome://browser/locale/quitDialog.properties");
var brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties");
var appName = brandBundle.GetStringFromName("brandShortName");
var quitTitleString = (aQuitType == "restart" ? "restart" : "quit") + "DialogTitle";
var quitDialogTitle = quitBundle.formatStringFromName(quitTitleString, [appName], 1);
var message;
if (aQuitType == "restart")
message = quitBundle.formatStringFromName("messageRestart",
[appName], 1);
else if (windowcount == 1)
message = quitBundle.formatStringFromName("messageNoWindows",
[appName], 1);
else
message = quitBundle.formatStringFromName("message",
[appName], 1);
var promptService = Services.prompt;
var flags = promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1 +
promptService.BUTTON_POS_0_DEFAULT;
var neverAsk = {value:false};
var button0Title, button2Title;
var button1Title = quitBundle.GetStringFromName("cancelTitle");
var neverAskText = quitBundle.GetStringFromName("neverAsk");
if (aQuitType == "restart")
button0Title = quitBundle.GetStringFromName("restartTitle");
else {
flags += promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_2;
button0Title = quitBundle.GetStringFromName("saveTitle");
button2Title = quitBundle.GetStringFromName("quitTitle");
}
// This wouldn't have been set above since we shouldn't be here for
// aQuitType == "lastwindow"
mostRecentBrowserWindow = Services.wm.getMostRecentWindow("navigator:browser");
var buttonChoice =
promptService.confirmEx(mostRecentBrowserWindow, quitDialogTitle, message,
flags, button0Title, button1Title, button2Title,
neverAskText, neverAsk);
switch (buttonChoice) {
case 2: // Quit
if (neverAsk.value)
Services.prefs.setBoolPref("browser.showQuitWarning", false);
break;
case 1: // Cancel
aCancelQuit.QueryInterface(Ci.nsISupportsPRBool);
aCancelQuit.data = true;
break;
case 0: // Save & Quit
this._saveSession = true;
if (neverAsk.value) {
if (aQuitType == "restart")
Services.prefs.setBoolPref("browser.warnOnRestart", false);
else {
// always save state when shutting down
Services.prefs.setIntPref("browser.startup.page", 3);
}
}
break;
}
},
/*
* _shouldShowRights - Determines if the user should be shown the
* about:rights notification. The notification should *not* be shown if
* we've already shown the current version, or if the override pref says to
* never show it. The notification *should* be shown if it's never been seen
* before, if a newer version is available, or if the override pref says to
* always show it.
*/
_shouldShowRights: function BG__shouldShowRights() {
// Look for an unconditional override pref. If set, do what it says.
// (true --> never show, false --> always show)
try {
return !Services.prefs.getBoolPref("browser.rights.override");
} catch (e) { }
// Ditto, for the legacy EULA pref.
try {
return !Services.prefs.getBoolPref("browser.EULA.override");
} catch (e) { }
#ifndef OFFICIAL_BUILD
// Non-official builds shouldn't shouldn't show the notification.
return false;
#endif
// Look to see if the user has seen the current version or not.
var currentVersion = Services.prefs.getIntPref("browser.rights.version");
try {
return !Services.prefs.getBoolPref("browser.rights." + currentVersion + ".shown");
} catch (e) { }
// Legacy: If the user accepted a EULA, we won't annoy them with the
// equivalent about:rights page until the version changes.
try {
return !Services.prefs.getBoolPref("browser.EULA." + currentVersion + ".accepted");
} catch (e) { }
// We haven't shown the notification before, so do so now.
return true;
},
_showRightsNotification: function BG__showRightsNotification() {
// Stick the notification onto the selected tab of the active browser window.
var win = this.getMostRecentBrowserWindow();
var browser = win.gBrowser; // for closure in notification bar callback
var notifyBox = browser.getNotificationBox();
var brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties");
var rightsBundle = Services.strings.createBundle("chrome://global/locale/aboutRights.properties");
var buttonLabel = rightsBundle.GetStringFromName("buttonLabel");
var buttonAccessKey = rightsBundle.GetStringFromName("buttonAccessKey");
var productName = brandBundle.GetStringFromName("brandFullName");
var notifyRightsText = rightsBundle.formatStringFromName("notifyRightsText", [productName], 1);
var buttons = [
{
label: buttonLabel,
accessKey: buttonAccessKey,
popup: null,
callback: function(aNotificationBar, aButton) {
browser.selectedTab = browser.addTab("about:rights");
}
}
];
// Set pref to indicate we've shown the notification.
var currentVersion = Services.prefs.getIntPref("browser.rights.version");
Services.prefs.setBoolPref("browser.rights." + currentVersion + ".shown", true);
var notification = notifyBox.appendNotification(notifyRightsText, "about-rights", null, notifyBox.PRIORITY_INFO_LOW, buttons);
notification.persistence = -1; // Until user closes it
},
_showUpdateNotification: function BG__showUpdateNotification() {
Services.prefs.clearUserPref("app.update.postupdate");
var um = Cc["@mozilla.org/updates/update-manager;1"].
getService(Ci.nsIUpdateManager);
try {
// If the updates.xml file is deleted then getUpdateAt will throw.
var update = um.getUpdateAt(0).QueryInterface(Ci.nsIPropertyBag);
}
catch (e) {
// This should never happen.
Cu.reportError("Unable to find update: " + e);
return;
}
var actions = update.getProperty("actions");
if (!actions || actions.indexOf("silent") != -1)
return;
var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"].
getService(Ci.nsIURLFormatter);
var browserBundle = Services.strings.createBundle("chrome://browser/locale/browser.properties");
var brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties");
var appName = brandBundle.GetStringFromName("brandShortName");
function getNotifyString(aPropData) {
var propValue = update.getProperty(aPropData.propName);
if (!propValue) {
if (aPropData.prefName)
propValue = formatter.formatURLPref(aPropData.prefName);
else if (aPropData.stringParams)
propValue = browserBundle.formatStringFromName(aPropData.stringName,
aPropData.stringParams,
aPropData.stringParams.length);
else
propValue = browserBundle.GetStringFromName(aPropData.stringName);
}
return propValue;
}
if (actions.indexOf("showNotification") != -1) {
let text = getNotifyString({propName: "notificationText",
stringName: "puNotifyText",
stringParams: [appName]});
let url = getNotifyString({propName: "notificationURL",
prefName: "startup.homepage_override_url"});
let label = getNotifyString({propName: "notificationButtonLabel",
stringName: "pu.notifyButton.label"});
let key = getNotifyString({propName: "notificationButtonAccessKey",
stringName: "pu.notifyButton.accesskey"});
let win = this.getMostRecentBrowserWindow();
let browser = win.gBrowser; // for closure in notification bar callback
let notifyBox = browser.getNotificationBox();
let buttons = [
{
label: label,
accessKey: key,
popup: null,
callback: function(aNotificationBar, aButton) {
browser.selectedTab = browser.addTab(url);
}
}
];
let notification = notifyBox.appendNotification(text, "post-update-notification",
null, notifyBox.PRIORITY_INFO_LOW,
buttons);
notification.persistence = -1; // Until user closes it
}
if (actions.indexOf("showAlert") == -1)
return;
let notifier;
try {
notifier = Cc["@mozilla.org/alerts-service;1"].
getService(Ci.nsIAlertsService);
}
catch (e) {
// nsIAlertsService is not available for this platform
return;
}
let title = getNotifyString({propName: "alertTitle",
stringName: "puAlertTitle",
stringParams: [appName]});
let text = getNotifyString({propName: "alertText",
stringName: "puAlertText",
stringParams: [appName]});
let url = getNotifyString({propName: "alertURL",
prefName: "startup.homepage_override_url"});
var self = this;
function clickCallback(subject, topic, data) {
// This callback will be called twice but only once with this topic
if (topic != "alertclickcallback")
return;
let win = self.getMostRecentBrowserWindow();
let browser = win.gBrowser;
browser.selectedTab = browser.addTab(data);
}
try {
// This will throw NS_ERROR_NOT_AVAILABLE if the notification cannot
// be displayed per the idl.
notifier.showAlertNotification(null, title, text,
true, url, clickCallback);
}
catch (e) {
}
},
#ifdef MOZ_TELEMETRY_REPORTING
_showTelemetryNotification: function BG__showTelemetryNotification() {
const PREF_TELEMETRY_PROMPTED = "toolkit.telemetry.prompted";
const PREF_TELEMETRY_ENABLED = "toolkit.telemetry.enabled";
const PREF_TELEMETRY_REJECTED = "toolkit.telemetry.rejected";
const PREF_TELEMETRY_INFOURL = "toolkit.telemetry.infoURL";
const PREF_TELEMETRY_SERVER_OWNER = "toolkit.telemetry.server_owner";
const PREF_TELEMETRY_ENABLED_BY_DEFAULT = "toolkit.telemetry.enabledByDefault";
const PREF_TELEMETRY_NOTIFIED_OPTOUT = "toolkit.telemetry.notifiedOptOut";
// This is used to reprompt users when privacy message changes
const TELEMETRY_PROMPT_REV = 2;
// Stick notifications onto the selected tab of the active browser window.
var win = this.getMostRecentBrowserWindow();
var tabbrowser = win.gBrowser;
var notifyBox = tabbrowser.getNotificationBox();
var browserBundle = Services.strings.createBundle("chrome://browser/locale/browser.properties");
var brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties");
var productName = brandBundle.GetStringFromName("brandFullName");
var serverOwner = Services.prefs.getCharPref(PREF_TELEMETRY_SERVER_OWNER);
function appendTelemetryNotification(message, buttons, hideclose) {
let notification = notifyBox.appendNotification(message, "telemetry", null,
notifyBox.PRIORITY_INFO_LOW,
buttons);
if (hideclose)
notification.setAttribute("hideclose", hideclose);
notification.persistence = -1; // Until user closes it
return notification;
}
function appendLearnMoreLink(notification) {
let XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
let link = notification.ownerDocument.createElementNS(XULNS, "label");
link.className = "text-link telemetry-text-link";
link.setAttribute("value", browserBundle.GetStringFromName("telemetryLinkLabel"));
let description = notification.ownerDocument.getAnonymousElementByAttribute(notification, "anonid", "messageText");
description.appendChild(link);
return link;
}
var telemetryEnabledByDefault = false;
try {
telemetryEnabledByDefault = Services.prefs.getBoolPref(PREF_TELEMETRY_ENABLED_BY_DEFAULT);
} catch(e) {}
if (telemetryEnabledByDefault) {
var telemetryNotifiedOptOut = false;
try {
telemetryNotifiedOptOut = Services.prefs.getBoolPref(PREF_TELEMETRY_NOTIFIED_OPTOUT);
} catch(e) {}
if (telemetryNotifiedOptOut)
return;
var telemetryPrompt = browserBundle.formatStringFromName("telemetryOptOutPrompt",
[productName, serverOwner, productName], 3);
Services.prefs.setBoolPref(PREF_TELEMETRY_NOTIFIED_OPTOUT, true);
let notification = appendTelemetryNotification(telemetryPrompt, null, false);
let link = appendLearnMoreLink(notification);
link.addEventListener('click', function() {
// Open the learn more url in a new tab
let url = Services.urlFormatter.formatURLPref("app.support.baseURL");
url += "how-can-i-help-submitting-performance-data";
tabbrowser.selectedTab = tabbrowser.addTab(url);
// Remove the notification on which the user clicked
notification.parentNode.removeNotification(notification, true);
}, false);
return;
}
var telemetryPrompted = null;
try {
telemetryPrompted = Services.prefs.getIntPref(PREF_TELEMETRY_PROMPTED);
} catch(e) {}
// If the user has seen the latest telemetry prompt, do not prompt again
// else clear old prefs and reprompt
if (telemetryPrompted === TELEMETRY_PROMPT_REV)
return;
Services.prefs.clearUserPref(PREF_TELEMETRY_PROMPTED);
Services.prefs.clearUserPref(PREF_TELEMETRY_ENABLED);
var telemetryPrompt = browserBundle.formatStringFromName("telemetryOptInPrompt", [productName, serverOwner], 2);
var buttons = [
{
label: browserBundle.GetStringFromName("telemetryYesButtonLabel2"),
accessKey: browserBundle.GetStringFromName("telemetryYesButtonAccessKey"),
popup: null,
callback: function(aNotificationBar, aButton) {
Services.prefs.setBoolPref(PREF_TELEMETRY_ENABLED, true);
}
},
{
label: browserBundle.GetStringFromName("telemetryNoButtonLabel"),
accessKey: browserBundle.GetStringFromName("telemetryNoButtonAccessKey"),
popup: null,
callback: function(aNotificationBar, aButton) {
Services.prefs.setBoolPref(PREF_TELEMETRY_REJECTED, true);
}
}
];
// Set pref to indicate we've shown the notification.
Services.prefs.setIntPref(PREF_TELEMETRY_PROMPTED, TELEMETRY_PROMPT_REV);
let notification = appendTelemetryNotification(telemetryPrompt, buttons, true);
let link = appendLearnMoreLink(notification);
link.addEventListener('click', function() {
// Open the learn more url in a new tab
tabbrowser.selectedTab = tabbrowser.addTab(Services.prefs.getCharPref(PREF_TELEMETRY_INFOURL));
// Remove the notification on which the user clicked
notification.parentNode.removeNotification(notification, true);
// Add a new notification to that tab, with no "Learn more" link
notifyBox = tabbrowser.getNotificationBox();
appendTelemetryNotification(telemetryPrompt, buttons, true);
}, false);
},
#endif
_showPluginUpdatePage: function BG__showPluginUpdatePage() {
Services.prefs.setBoolPref(PREF_PLUGINS_NOTIFYUSER, false);
var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"].
getService(Ci.nsIURLFormatter);
var updateUrl = formatter.formatURLPref(PREF_PLUGINS_UPDATEURL);
var win = this.getMostRecentBrowserWindow();
var browser = win.gBrowser;
browser.selectedTab = browser.addTab(updateUrl);
},
/**
* Initialize Places
* - imports the bookmarks html file if bookmarks database is empty, try to
* restore bookmarks from a JSON backup if the backend indicates that the
* database was corrupt.
*
* These prefs can be set up by the frontend:
*
* WARNING: setting these preferences to true will overwite existing bookmarks
*
* - browser.places.importBookmarksHTML
* Set to true will import the bookmarks.html file from the profile folder.
* - browser.places.smartBookmarksVersion
* Set during HTML import to indicate that Smart Bookmarks were created.
* Set to -1 to disable Smart Bookmarks creation.
* Set to 0 to restore current Smart Bookmarks.
* - browser.bookmarks.restore_default_bookmarks
* Set to true by safe-mode dialog to indicate we must restore default