forked from rnewman/services-central-old
/
nsBrowserGlue.js
1279 lines (1122 loc) · 50.3 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
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.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 Browser Search Service.
#
# The Initial Developer of the Original Code is
# Giorgio Maone
# Portions created by the Initial Developer are Copyright (C) 2005
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Giorgio Maone <g.maone@informaction.com>
# Seth Spitzer <sspitzer@mozilla.com>
# Asaf Romano <mano@mozilla.com>
# Marco Bonardo <mak77@bonardo.net>
# Dietrich Ayala <dietrich@mozilla.com>
# Ehsan Akhgari <ehsan.akhgari@gmail.com>
# Nils Maier <maierman@web.de>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# ***** END LICENSE BLOCK *****
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:///modules/distribution.js");
const PREF_EM_NEW_ADDONS_LIST = "extensions.newAddons";
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 (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, "_prefs",
"@mozilla.org/preferences-service;1",
"nsIPrefBranch");
XPCOMUtils.defineLazyServiceGetter(this, "_bundleService",
"@mozilla.org/intl/stringbundle;1",
"nsIStringBundleService");
XPCOMUtils.defineLazyServiceGetter(this, "_idleService",
"@mozilla.org/widget/idleservice;1",
"nsIIdleService");
XPCOMUtils.defineLazyGetter(this, "_distributionCustomizer", function() {
return new DistributionCustomizer();
});
XPCOMUtils.defineLazyGetter(this, "_sanitizer",
function() {
let sanitizerScope = {};
Cc["@mozilla.org/moz/jssubscript-loader;1"].
getService(Ci.mozIJSSubScriptLoader).
loadSubScript("chrome://browser/content/sanitize.js", sanitizerScope);
return sanitizerScope.Sanitizer;
});
// The observer service is immediately used in _init(), so there's no reason
// to have a getter.
this._observerService = Cc["@mozilla.org/observer-service;1"].
getService(Ci.nsIObserverService);
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,
_isPlacesDatabaseLocked: false,
_setPrefToSaveSession: function(aForce)
{
if (!this._saveSession && !aForce)
return;
this._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.
this._prefs.QueryInterface(Ci.nsIPrefService).savePrefFile(null);
},
// nsIObserver implementation
observe: function(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 "sessionstore-windows-restored":
this._onBrowserStartup();
break;
case "browser:purge-session-history":
// reset the console service's error buffer
const cs = Cc["@mozilla.org/consoleservice;1"].
getService(Ci.nsIConsoleService);
cs.logStringMessage(null); // clear the console (in case it's open)
cs.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();
this._onProfileShutdown();
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
case "session-save":
this._setPrefToSaveSession(true);
subject.QueryInterface(Ci.nsISupportsPRBool);
subject.data = true;
break;
case "places-init-complete":
this._initPlaces();
this._observerService.removeObserver(this, "places-init-complete");
this._isPlacesInitObserver = false;
// no longer needed, since history was initialized completely.
this._observerService.removeObserver(this, "places-database-locked");
this._isPlacesLockedObserver = false;
// Now apply distribution customized bookmarks.
// This should always run after Places initialization.
this._distributionCustomizer.applyBookmarks();
break;
case "places-database-locked":
this._isPlacesDatabaseLocked = true;
// Stop observing, so further attempts to load history service
// will not show the prompt.
this._observerService.removeObserver(this, "places-database-locked");
this._isPlacesLockedObserver = false;
break;
case "idle":
if (this._idleService.idleTime > BOOKMARKS_BACKUP_IDLE_TIME * 1000)
this._backupBookmarks();
break;
case "distribution-customization-complete":
this._observerService
.removeObserver(this, "distribution-customization-complete");
// Customization has finished, we don't need the customizer anymore.
delete this._distributionCustomizer;
break;
}
},
// initialization (called on application startup)
_init: function()
{
// observer registration
const osvr = this._observerService;
osvr.addObserver(this, "xpcom-shutdown", false);
osvr.addObserver(this, "prefservice:after-app-defaults", false);
osvr.addObserver(this, "final-ui-startup", false);
osvr.addObserver(this, "sessionstore-windows-restored", false);
osvr.addObserver(this, "browser:purge-session-history", false);
osvr.addObserver(this, "quit-application-requested", false);
osvr.addObserver(this, "quit-application-granted", false);
#ifdef OBSERVE_LASTWINDOW_CLOSE_TOPICS
osvr.addObserver(this, "browser-lastwindow-close-requested", false);
osvr.addObserver(this, "browser-lastwindow-close-granted", false);
#endif
osvr.addObserver(this, "session-save", false);
osvr.addObserver(this, "places-init-complete", false);
this._isPlacesInitObserver = true;
osvr.addObserver(this, "places-database-locked", false);
this._isPlacesLockedObserver = true;
osvr.addObserver(this, "distribution-customization-complete", false);
},
// cleanup (called on application shutdown)
_dispose: function()
{
// observer removal
const osvr = this._observerService;
osvr.removeObserver(this, "xpcom-shutdown");
osvr.removeObserver(this, "prefservice:after-app-defaults");
osvr.removeObserver(this, "final-ui-startup");
osvr.removeObserver(this, "sessionstore-windows-restored");
osvr.removeObserver(this, "browser:purge-session-history");
osvr.removeObserver(this, "quit-application-requested");
osvr.removeObserver(this, "quit-application-granted");
#ifdef OBSERVE_LASTWINDOW_CLOSE_TOPICS
osvr.removeObserver(this, "browser-lastwindow-close-requested");
osvr.removeObserver(this, "browser-lastwindow-close-granted");
#endif
osvr.removeObserver(this, "session-save");
if (this._isIdleObserver)
this._idleService.removeIdleObserver(this, BOOKMARKS_BACKUP_IDLE_TIME);
if (this._isPlacesInitObserver)
osvr.removeObserver(this, "places-init-complete");
if (this._isPlacesLockedObserver)
osvr.removeObserver(this, "places-database-locked");
},
_onAppDefaults: function()
{
// apply distribution customizations (prefs)
// other customizations are applied in _onProfileStartup()
this._distributionCustomizer.applyPrefDefaults();
},
// profile startup handler (contains profile initialization routines)
_onProfileStartup: function()
{
this._sanitizer.onStartup();
// check if we're in safe mode
var app = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo).
QueryInterface(Ci.nsIXULRuntime);
if (app.inSafeMode) {
var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
getService(Ci.nsIWindowWatcher);
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();
var ioService = Cc["@mozilla.org/network/io-service;1"].
getService(Ci.nsIIOService2);
// if ioService is managing the offline status, then ioservice.offline
// is already set correctly. We will continue to allow the ioService
// to manage its offline state until the user uses the "Work Offline" UI.
if (!ioService.manageOfflineStatus) {
// set the initial state
try {
ioService.offline = this._prefs.getBoolPref("browser.offline");
}
catch (e) {
ioService.offline = false;
}
}
this._observerService
.notifyObservers(null, "browser-ui-startup-complete", "");
},
// profile shutdown handler (contains profile cleanup routines)
_onProfileShutdown: function()
{
#ifdef WINCE
// If there's a pending update, clear cache to free up disk space.
try {
let um = Cc["@mozilla.org/updates/update-manager;1"].
getService(Ci.nsIUpdateManager);
if (um.activeUpdate && um.activeUpdate.state == "pending") {
let cacheService = Cc["@mozilla.org/network/cache-service;1"].
getService(Ci.nsICacheService);
cacheService.evictEntries(Ci.nsICache.STORE_ANYWHERE);
}
} catch (e) { }
#endif
this._shutdownPlaces();
this._idleService.removeIdleObserver(this, BOOKMARKS_BACKUP_IDLE_TIME);
this._isIdleObserver = false;
this._sanitizer.onShutdown();
},
// Browser startup complete. All initial windows have opened.
_onBrowserStartup: function()
{
// Show about:rights notification, if needed.
if (this._shouldShowRights())
this._showRightsNotification();
// If new add-ons were installed during startup open the add-ons manager.
if (this._prefs.prefHasUserValue(PREF_EM_NEW_ADDONS_LIST)) {
var args = Cc["@mozilla.org/supports-array;1"].
createInstance(Ci.nsISupportsArray);
var str = Cc["@mozilla.org/supports-string;1"].
createInstance(Ci.nsISupportsString);
str.data = "";
args.AppendElement(str);
var str = Cc["@mozilla.org/supports-string;1"].
createInstance(Ci.nsISupportsString);
str.data = this._prefs.getCharPref(PREF_EM_NEW_ADDONS_LIST);
args.AppendElement(str);
const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
const EMFEATURES = "chrome,menubar,extra-chrome,toolbar,dialog=no,resizable";
var ww = Cc["@mozilla.org/embedcomp/window-watcher;1"].
getService(Ci.nsIWindowWatcher);
ww.openWindow(null, EMURL, "_blank", EMFEATURES, args);
this._prefs.clearUserPref(PREF_EM_NEW_ADDONS_LIST);
}
// Load the "more info" page for a locked places.sqlite
// This property is set earlier in the startup process:
// nsPlacesDBFlush loads after profile-after-change and initializes
// the history service, which sends out places-database-locked
// which sets this property.
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 (this._prefs.getBoolPref(PREF_PLUGINS_NOTIFYUSER))
this._showPluginUpdatePage();
#ifdef XP_WIN
#ifndef WINCE
// 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
#endif
},
_onQuitRequest: function(aCancelQuit, aQuitType)
{
// If user has already dismissed quit request, then do nothing
if ((aCancelQuit instanceof Ci.nsISupportsPRBool) && aCancelQuit.data)
return;
var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
getService(Ci.nsIWindowMediator);
var windowcount = 0;
var pagecount = 0;
var browserEnum = wm.getEnumerator("navigator:browser");
while (browserEnum.hasMoreElements()) {
windowcount++;
var browser = browserEnum.getNext();
var tabbrowser = browser.document.getElementById("content");
if (tabbrowser)
pagecount += tabbrowser.browsers.length;
}
this._saveSession = false;
if (pagecount < 2)
return;
if (aQuitType != "restart")
aQuitType = "quit";
var showPrompt = true;
try {
// browser.warnOnQuit is a hidden global boolean to override all quit prompts
// 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 sessionWillBeSaved = this._prefs.getIntPref("browser.startup.page") == 3 ||
this._prefs.getBoolPref("browser.sessionstore.resume_session_once");
if (sessionWillBeSaved || !this._prefs.getBoolPref("browser.warnOnQuit"))
showPrompt = false;
else if (aQuitType == "restart")
showPrompt = this._prefs.getBoolPref("browser.warnOnRestart");
else
showPrompt = this._prefs.getBoolPref("browser.tabs.warnOnClose");
} catch (ex) {}
// Never show a prompt inside the private browsing mode
var inPrivateBrowsing = Cc["@mozilla.org/privatebrowsing;1"].
getService(Ci.nsIPrivateBrowsingService).
privateBrowsingEnabled;
if (!showPrompt || inPrivateBrowsing)
return false;
var quitBundle = this._bundleService.createBundle("chrome://browser/locale/quitDialog.properties");
var brandBundle = this._bundleService.createBundle("chrome://branding/locale/brand.properties");
var appName = brandBundle.GetStringFromName("brandShortName");
var quitDialogTitle = quitBundle.formatStringFromName(aQuitType + "DialogTitle",
[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 = Cc["@mozilla.org/embedcomp/prompt-service;1"].
getService(Ci.nsIPromptService);
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");
}
var mostRecentBrowserWindow = 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)
this._prefs.setBoolPref("browser.tabs.warnOnClose", 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")
this._prefs.setBoolPref("browser.warnOnRestart", false);
else {
// always save state when shutting down
this._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 () {
// Look for an unconditional override pref. If set, do what it says.
// (true --> never show, false --> always show)
try {
return !this._prefs.getBoolPref("browser.rights.override");
} catch (e) { }
// Ditto, for the legacy EULA pref.
try {
return !this._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 = this._prefs.getIntPref("browser.rights.version");
try {
return !this._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 !this._prefs.getBoolPref("browser.EULA." + currentVersion + ".accepted");
} catch (e) { }
// We haven't shown the notification before, so do so now.
return true;
},
_showRightsNotification : function () {
// 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 = this._bundleService.createBundle("chrome://branding/locale/brand.properties");
var rightsBundle = this._bundleService.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 = this._prefs.getIntPref("browser.rights.version");
this._prefs.setBoolPref("browser.rights." + currentVersion + ".shown", true);
var box = notifyBox.appendNotification(notifyRightsText, "about-rights", null, notifyBox.PRIORITY_INFO_LOW, buttons);
box.persistence = 3; // arbitrary number, just so bar sticks around for a bit
},
_showPluginUpdatePage : function () {
this._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
* bookmarks.
*/
_initPlaces: function bg__initPlaces() {
// We must instantiate the history service since it will tell us if we
// need to import or restore bookmarks due to first-run, corruption or
// forced migration (due to a major schema change).
var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
getService(Ci.nsINavHistoryService);
// If the database is corrupt or has been newly created we should
// import bookmarks.
var databaseStatus = histsvc.databaseStatus;
var importBookmarks = databaseStatus == histsvc.DATABASE_STATUS_CREATE ||
databaseStatus == histsvc.DATABASE_STATUS_CORRUPT;
if (databaseStatus == histsvc.DATABASE_STATUS_CREATE) {
// If the database has just been created, but we already have any
// bookmark, this is not the initial import. This can happen after a
// migration from a different browser since migrators run before us.
// In such a case we should not import, unless some pref has been set.
var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
getService(Ci.nsINavBookmarksService);
if (bmsvc.getIdForItemAt(bmsvc.bookmarksMenuFolder, 0) != -1 ||
bmsvc.getIdForItemAt(bmsvc.toolbarFolder, 0) != -1)
importBookmarks = false;
}
// Check if user or an extension has required to import bookmarks.html
var importBookmarksHTML = false;
try {
importBookmarksHTML =
this._prefs.getBoolPref("browser.places.importBookmarksHTML");
if (importBookmarksHTML)
importBookmarks = true;
} catch(ex) {}
// Check if Safe Mode or the user has required to restore bookmarks from
// default profile's bookmarks.html
var restoreDefaultBookmarks = false;
try {
restoreDefaultBookmarks =
this._prefs.getBoolPref("browser.bookmarks.restore_default_bookmarks");
if (restoreDefaultBookmarks) {
// Ensure that we already have a bookmarks backup for today.
this._backupBookmarks();
importBookmarks = true;
}
} catch(ex) {}
// If the user did not require to restore default bookmarks, or import
// from bookmarks.html, we will try to restore from JSON
if (importBookmarks && !restoreDefaultBookmarks && !importBookmarksHTML) {
// get latest JSON backup
Cu.import("resource://gre/modules/utils.js");
var bookmarksBackupFile = PlacesUtils.backups.getMostRecent("json");
if (bookmarksBackupFile) {
// restore from JSON backup
PlacesUtils.restoreBookmarksFromJSONFile(bookmarksBackupFile);
importBookmarks = false;
}
else {
// We have created a new database but we don't have any backup available
importBookmarks = true;
var dirService = Cc["@mozilla.org/file/directory_service;1"].
getService(Ci.nsIProperties);
var bookmarksHTMLFile = dirService.get("BMarks", Ci.nsILocalFile);
if (bookmarksHTMLFile.exists()) {
// If bookmarks.html is available in current profile import it...
importBookmarksHTML = true;
}
else {
// ...otherwise we will restore defaults
restoreDefaultBookmarks = true;
}
}
}
if (!importBookmarks) {
// Call it here for Fx3 profiles created before the Places folder
// has been added, otherwise it's called during import.
this.ensurePlacesDefaultQueriesInitialized();
}
else {
// ensurePlacesDefaultQueriesInitialized() is called by import.
// Don't try to recreate smart bookmarks if autoExportHTML is true or
// smart bookmarks are disabled.
var autoExportHTML = false;
try {
autoExportHTML = this._prefs.getBoolPref("browser.bookmarks.autoExportHTML");
} catch(ex) {}
var smartBookmarksVersion = 0;
try {
smartBookmarksVersion = this._prefs.getIntPref("browser.places.smartBookmarksVersion");
} catch(ex) {}
if (!autoExportHTML && smartBookmarksVersion != -1)
this._prefs.setIntPref("browser.places.smartBookmarksVersion", 0);
// Get bookmarks.html file location
var dirService = Cc["@mozilla.org/file/directory_service;1"].
getService(Ci.nsIProperties);
var bookmarksFile = null;
if (restoreDefaultBookmarks) {
// User wants to restore bookmarks.html file from default profile folder
bookmarksFile = dirService.get("profDef", Ci.nsILocalFile);
bookmarksFile.append("bookmarks.html");
}
else
bookmarksFile = dirService.get("BMarks", Ci.nsILocalFile);
if (bookmarksFile.exists()) {
// import the file
try {
var importer = Cc["@mozilla.org/browser/places/import-export-service;1"].
getService(Ci.nsIPlacesImportExportService);
importer.importHTMLFromFile(bookmarksFile, true /* overwrite existing */);
} catch (err) {
// Report the error, but ignore it.
Cu.reportError("Bookmarks.html file could be corrupt. " + err);
}
}
else
Cu.reportError("Unable to find bookmarks.html file.");
// Reset preferences, so we won't try to import again at next run
if (importBookmarksHTML)
this._prefs.setBoolPref("browser.places.importBookmarksHTML", false);
if (restoreDefaultBookmarks)
this._prefs.setBoolPref("browser.bookmarks.restore_default_bookmarks",
false);
}
// Initialize bookmark archiving on idle.
// Once a day, either on idle or shutdown, bookmarks are backed up.
if (!this._isIdleObserver) {
this._idleService.addIdleObserver(this, BOOKMARKS_BACKUP_IDLE_TIME);
this._isIdleObserver = true;
}
},
/**
* Places shut-down tasks
* - back up bookmarks if needed.
* - export bookmarks as HTML, if so configured.
*
* Note: quit-application-granted notification is received twice
* so replace this method with a no-op when first called.
*/
_shutdownPlaces: function bg__shutdownPlaces() {
this._backupBookmarks();
// Backup bookmarks to bookmarks.html to support apps that depend
// on the legacy format.
var autoExportHTML = false;
try {
autoExportHTML = this._prefs.getBoolPref("browser.bookmarks.autoExportHTML");
} catch(ex) { /* Don't export */ }
if (autoExportHTML) {
Cc["@mozilla.org/browser/places/import-export-service;1"].
getService(Ci.nsIPlacesImportExportService).
backupBookmarksFile();
}
},
/**
* Backup bookmarks if needed.
*/
_backupBookmarks: function nsBrowserGlue__backupBookmarks() {
Cu.import("resource://gre/modules/utils.js");
let lastBackupFile = PlacesUtils.backups.getMostRecent();
// Backup bookmarks if there are no backups or the maximum interval between
// backups elapsed.
if (!lastBackupFile ||
new Date() - PlacesUtils.backups.getDateForFile(lastBackupFile) > BOOKMARKS_BACKUP_INTERVAL) {
let maxBackups = BOOKMARKS_BACKUP_MAX_BACKUPS;
try {
maxBackups = this._prefs.getIntPref("browser.bookmarks.max_backups");
}
catch(ex) { /* Use default. */ }
PlacesUtils.backups.create(maxBackups); // Don't force creation.
}
},
/**
* Show the notificationBox for a locked places database.
*/
_showPlacesLockedNotificationBox: function nsBrowserGlue__showPlacesLockedNotificationBox() {
var brandBundle = this._bundleService.createBundle("chrome://branding/locale/brand.properties");
var applicationName = brandBundle.GetStringFromName("brandShortName");
var placesBundle = this._bundleService.createBundle("chrome://browser/locale/places/places.properties");
var title = placesBundle.GetStringFromName("lockPrompt.title");
var text = placesBundle.formatStringFromName("lockPrompt.text", [applicationName], 1);
var buttonText = placesBundle.GetStringFromName("lockPromptInfoButton.label");
var accessKey = placesBundle.GetStringFromName("lockPromptInfoButton.accessKey");
var helpTopic = "places-locked";
var url = Cc["@mozilla.org/toolkit/URLFormatterService;1"].
getService(Components.interfaces.nsIURLFormatter).
formatURLPref("app.support.baseURL");
url += helpTopic;
var browser = this.getMostRecentBrowserWindow().gBrowser;
var buttons = [
{
label: buttonText,
accessKey: accessKey,
popup: null,
callback: function(aNotificationBar, aButton) {
browser.selectedTab = browser.addTab(url);
}
}
];
var notifyBox = browser.getNotificationBox();
var box = notifyBox.appendNotification(text, title, null,
notifyBox.PRIORITY_CRITICAL_MEDIUM,
buttons);
box.persistence = -1; // Until user closes it
},
_migrateUI: function bg__migrateUI() {
var migration = 0;
try {
migration = this._prefs.getIntPref("browser.migration.version");
} catch(ex) {}
if (migration == 0) {
// this code should always migrate pre-FF3 profiles to the current UI state
// grab the localstore.rdf and make changes needed for new UI
this._rdf = Cc["@mozilla.org/rdf/rdf-service;1"].getService(Ci.nsIRDFService);
this._dataSource = this._rdf.GetDataSource("rdf:local-store");
this._dirty = false;
let currentsetResource = this._rdf.GetResource("currentset");
let toolbars = ["nav-bar", "toolbar-menubar", "PersonalToolbar"];
for (let i = 0; i < toolbars.length; i++) {
let toolbar = this._rdf.GetResource("chrome://browser/content/browser.xul#" + toolbars[i]);
let currentset = this._getPersist(toolbar, currentsetResource);
if (!currentset) {
// toolbar isn't customized
if (i == 0)
// new button is in the defaultset, nothing to migrate
break;
continue;
}
if (/(?:^|,)unified-back-forward-button(?:$|,)/.test(currentset))
// new button is already there, nothing to migrate
break;
if (/(?:^|,)back-button(?:$|,)/.test(currentset)) {
let newset = currentset.replace(/(^|,)back-button($|,)/,
"$1unified-back-forward-button,back-button$2")
this._setPersist(toolbar, currentsetResource, newset);
// done migrating
break;
}
}
// force the RDF to be saved
if (this._dirty)
this._dataSource.QueryInterface(Ci.nsIRDFRemoteDataSource).Flush();
// free up the RDF service
this._rdf = null;
this._dataSource = null;
// update the migration version
this._prefs.setIntPref("browser.migration.version", 1);
}
},
_getPersist: function bg__getPersist(aSource, aProperty) {
var target = this._dataSource.GetTarget(aSource, aProperty, true);
if (target instanceof Ci.nsIRDFLiteral)
return target.Value;
return null;
},
_setPersist: function bg__setPersist(aSource, aProperty, aTarget) {
this._dirty = true;
try {
var oldTarget = this._dataSource.GetTarget(aSource, aProperty, true);
if (oldTarget) {
if (aTarget)
this._dataSource.Change(aSource, aProperty, oldTarget, this._rdf.GetLiteral(aTarget));
else
this._dataSource.Unassert(aSource, aProperty, oldTarget);
}
else {
this._dataSource.Assert(aSource, aProperty, this._rdf.GetLiteral(aTarget), true);
}
}
catch(ex) {}
},
// ------------------------------
// public nsIBrowserGlue members
// ------------------------------
sanitize: function(aParentWindow)
{
this._sanitizer.sanitize(aParentWindow);
},
ensurePlacesDefaultQueriesInitialized: function() {
// This is actual version of the smart bookmarks, must be increased every
// time smart bookmarks change.
// When adding a new smart bookmark below, its newInVersion property must
// be set to the version it has been added in, we will compare its value
// to users' smartBookmarksVersion and add new smart bookmarks without
// recreating old deleted ones.
const SMART_BOOKMARKS_VERSION = 2;
const SMART_BOOKMARKS_ANNO = "Places/SmartBookmark";
const SMART_BOOKMARKS_PREF = "browser.places.smartBookmarksVersion";
// TODO bug 399268: should this be a pref?
const MAX_RESULTS = 10;
// get current smart bookmarks version
// By default, if the pref is not set up, we must create Smart Bookmarks
var smartBookmarksCurrentVersion = 0;
try {
smartBookmarksCurrentVersion = this._prefs.getIntPref(SMART_BOOKMARKS_PREF);
} catch(ex) { /* no version set, new profile */ }
// bail out if we don't have to create or update Smart Bookmarks
if (smartBookmarksCurrentVersion == -1 ||
smartBookmarksCurrentVersion >= SMART_BOOKMARKS_VERSION)
return;
var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
getService(Ci.nsINavBookmarksService);
var annosvc = Cc["@mozilla.org/browser/annotation-service;1"].
getService(Ci.nsIAnnotationService);
var callback = {
_uri: function(aSpec) {
return Cc["@mozilla.org/network/io-service;1"].
getService(Ci.nsIIOService).
newURI(aSpec, null, null);
},
runBatched: function() {
var smartBookmarks = [];
var bookmarksMenuIndex = 0;
var bookmarksToolbarIndex = 0;
var placesBundle = Cc["@mozilla.org/intl/stringbundle;1"].
getService(Ci.nsIStringBundleService).
createBundle("chrome://browser/locale/places/places.properties");
// MOST VISITED
var smart = {queryId: "MostVisited", // don't change this
itemId: null,
title: placesBundle.GetStringFromName("mostVisitedTitle"),
uri: this._uri("place:redirectsMode=" +
Ci.nsINavHistoryQueryOptions.REDIRECTS_MODE_TARGET +
"&sort=" +
Ci.nsINavHistoryQueryOptions.SORT_BY_VISITCOUNT_DESCENDING +
"&maxResults=" + MAX_RESULTS),
parent: bmsvc.toolbarFolder,
position: bookmarksToolbarIndex++,
newInVersion: 1 };
smartBookmarks.push(smart);
// RECENTLY BOOKMARKED
smart = {queryId: "RecentlyBookmarked", // don't change this
itemId: null,
title: placesBundle.GetStringFromName("recentlyBookmarkedTitle"),
uri: this._uri("place:folder=BOOKMARKS_MENU" +
"&folder=UNFILED_BOOKMARKS" +
"&folder=TOOLBAR" +
"&queryType=" +
Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS +
"&sort=" +
Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING +
"&excludeItemIfParentHasAnnotation=livemark%2FfeedURI" +
"&maxResults=" + MAX_RESULTS +
"&excludeQueries=1"),
parent: bmsvc.bookmarksMenuFolder,
position: bookmarksMenuIndex++,
newInVersion: 1 };
smartBookmarks.push(smart);