This repository has been archived by the owner on Apr 10, 2024. It is now read-only.
/
browser.js
5017 lines (4289 loc) · 178 KB
/
browser.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
// -*- Mode: js2; tab-width: 2; indent-tabs-mode: nil; js2-basic-offset: 2; js2-skip-preprocessor-directives: t; -*-
/*
* ***** 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 Mozilla Mobile Browser.
*
* The Initial Developer of the Original Code is
* Mozilla Corporation.
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* 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 ***** */
"use strict";
let Cc = Components.classes;
let Ci = Components.interfaces;
let Cu = Components.utils;
let Cr = Components.results;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm")
Cu.import("resource://gre/modules/AddonManager.jsm");
Cu.import("resource://gre/modules/FileUtils.jsm");
XPCOMUtils.defineLazyGetter(this, "PluralForm", function() {
Cu.import("resource://gre/modules/PluralForm.jsm");
return PluralForm;
});
XPCOMUtils.defineLazyGetter(this, "DebuggerServer", function() {
Cu.import("resource://gre/modules/devtools/dbg-server.jsm");
return DebuggerServer;
});
// Lazily-loaded browser scripts:
[
["SelectHelper", "chrome://browser/content/SelectHelper.js"],
].forEach(function (aScript) {
let [name, script] = aScript;
XPCOMUtils.defineLazyGetter(window, name, function() {
let sandbox = {};
Services.scriptloader.loadSubScript(script, sandbox);
return sandbox[name];
});
});
XPCOMUtils.defineLazyServiceGetter(this, "Haptic",
"@mozilla.org/widget/hapticfeedback;1", "nsIHapticFeedback");
XPCOMUtils.defineLazyServiceGetter(this, "DOMUtils",
"@mozilla.org/inspector/dom-utils;1", "inIDOMUtils");
XPCOMUtils.defineLazyServiceGetter(window, "URIFixup",
"@mozilla.org/docshell/urifixup;1", "nsIURIFixup");
const kStateActive = 0x00000001; // :active pseudoclass for elements
const kXLinkNamespace = "http://www.w3.org/1999/xlink";
// The element tag names that are considered to receive input. Mouse-down
// events directed to one of these are allowed to go through.
const kElementsReceivingInput = {
applet: true,
audio: true,
button: true,
embed: true,
input: true,
map: true,
select: true,
textarea: true,
video: true
};
const kDefaultCSSViewportWidth = 980;
const kDefaultCSSViewportHeight = 480;
function dump(a) {
Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService).logStringMessage(a);
}
function getBridge() {
return Cc["@mozilla.org/android/bridge;1"].getService(Ci.nsIAndroidBridge);
}
function sendMessageToJava(aMessage) {
return getBridge().handleGeckoMessage(JSON.stringify(aMessage));
}
#ifdef MOZ_CRASHREPORTER
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "CrashReporter",
"@mozilla.org/xre/app-info;1", "nsICrashReporter");
#endif
XPCOMUtils.defineLazyGetter(this, "ContentAreaUtils", function() {
let ContentAreaUtils = {};
Services.scriptloader.loadSubScript("chrome://global/content/contentAreaUtils.js", ContentAreaUtils);
return ContentAreaUtils;
});
XPCOMUtils.defineLazyGetter(this, "Rect", function() {
Cu.import("resource://gre/modules/Geometry.jsm");
return Rect;
});
function resolveGeckoURI(aURI) {
if (aURI.indexOf("chrome://") == 0) {
let registry = Cc['@mozilla.org/chrome/chrome-registry;1'].getService(Ci["nsIChromeRegistry"]);
return registry.convertChromeURL(Services.io.newURI(aURI, null, null)).spec;
} else if (aURI.indexOf("resource://") == 0) {
let handler = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
return handler.resolveURI(Services.io.newURI(aURI, null, null));
}
return aURI;
}
/**
* Cache of commonly used string bundles.
*/
var Strings = {};
[
["brand", "chrome://branding/locale/brand.properties"],
["browser", "chrome://browser/locale/browser.properties"],
["charset", "chrome://global/locale/charsetTitles.properties"]
].forEach(function (aStringBundle) {
let [name, bundle] = aStringBundle;
XPCOMUtils.defineLazyGetter(Strings, name, function() {
return Services.strings.createBundle(bundle);
});
});
var BrowserApp = {
_tabs: [],
_selectedTab: null,
deck: null,
startup: function startup() {
window.QueryInterface(Ci.nsIDOMChromeWindow).browserDOMWindow = new nsBrowserAccess();
dump("zerdatime " + Date.now() + " - browser chrome startup finished.");
this.deck = document.getElementById("browsers");
BrowserEventHandler.init();
ViewportHandler.init();
getBridge().browserApp = this;
Services.obs.addObserver(this, "Tab:Add", false);
Services.obs.addObserver(this, "Tab:Load", false);
Services.obs.addObserver(this, "Tab:Selected", false);
Services.obs.addObserver(this, "Tab:Closed", false);
Services.obs.addObserver(this, "Session:Back", false);
Services.obs.addObserver(this, "Session:Forward", false);
Services.obs.addObserver(this, "Session:Reload", false);
Services.obs.addObserver(this, "Session:Stop", false);
Services.obs.addObserver(this, "SaveAs:PDF", false);
Services.obs.addObserver(this, "Browser:Quit", false);
Services.obs.addObserver(this, "Preferences:Get", false);
Services.obs.addObserver(this, "Preferences:Set", false);
Services.obs.addObserver(this, "ScrollTo:FocusedInput", false);
Services.obs.addObserver(this, "Sanitize:ClearAll", false);
Services.obs.addObserver(this, "Telemetry:Add", false);
Services.obs.addObserver(this, "PanZoom:PanZoom", false);
Services.obs.addObserver(this, "FullScreen:Exit", false);
Services.obs.addObserver(this, "Viewport:Change", false);
Services.obs.addObserver(this, "Passwords:Init", false);
Services.obs.addObserver(this, "FormHistory:Init", false);
Services.obs.addObserver(this, "ToggleProfiling", false);
Services.obs.addObserver(this, "sessionstore-state-purge-complete", false);
function showFullScreenWarning() {
NativeWindow.toast.show(Strings.browser.GetStringFromName("alertFullScreenToast"), "short");
}
window.addEventListener("fullscreen", function() {
sendMessageToJava({
gecko: {
type: window.fullScreen ? "ToggleChrome:Show" : "ToggleChrome:Hide"
}
});
}, false);
window.addEventListener("mozfullscreenchange", function() {
sendMessageToJava({
gecko: {
type: document.mozFullScreen ? "DOMFullScreen:Start" : "DOMFullScreen:Stop"
}
});
if (document.mozFullScreen)
showFullScreenWarning();
}, false);
// When a restricted key is pressed in DOM full-screen mode, we should display
// the "Press ESC to exit" warning message.
window.addEventListener("MozShowFullScreenWarning", showFullScreenWarning, true);
NativeWindow.init();
Downloads.init();
FormAssistant.init();
OfflineApps.init();
IndexedDB.init();
XPInstallObserver.init();
ConsoleAPI.init();
ClipboardHelper.init();
PermissionsHelper.init();
CharacterEncoding.init();
SearchEngines.init();
ActivityObserver.init();
WebappsUI.init();
RemoteDebugger.init();
UserAgent.init();
// Init LoginManager
Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
// Init FormHistory
Cc["@mozilla.org/satchel/form-history;1"].getService(Ci.nsIFormHistory2);
let loadParams = {};
let url = "about:home";
let restoreMode = 0;
let pinned = false;
if ("arguments" in window) {
if (window.arguments[0])
url = window.arguments[0];
if (window.arguments[1])
restoreMode = window.arguments[1];
if (window.arguments[2])
gScreenWidth = window.arguments[2];
if (window.arguments[3])
gScreenHeight = window.arguments[3];
if (window.arguments[4])
pinned = window.arguments[4];
}
if (url == "about:empty")
loadParams.flags = Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_HISTORY;
// XXX maybe we don't do this if the launch was kicked off from external
Services.io.offline = false;
// Broadcast a UIReady message so add-ons know we are finished with startup
let event = document.createEvent("Events");
event.initEvent("UIReady", true, false);
window.dispatchEvent(event);
// Restore the previous session
// restoreMode = 0 means no restore
// restoreMode = 1 means force restore (after an OOM kill)
// restoreMode = 2 means restore only if we haven't crashed multiple times
let ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
if (restoreMode || ss.shouldRestore()) {
// A restored tab should not be active if we are loading a URL
let restoreToFront = false;
sendMessageToJava({
gecko: {
type: "Session:RestoreBegin"
}
});
// Open any commandline URLs, except the homepage
if (url && url != "about:home") {
loadParams.pinned = pinned;
this.addTab(url, loadParams);
} else {
// Let the session make a restored tab active
restoreToFront = true;
}
// Be ready to handle any restore failures by making sure we have a valid tab opened
let restoreCleanup = {
observe: function(aSubject, aTopic, aData) {
Services.obs.removeObserver(restoreCleanup, "sessionstore-windows-restored");
if (aData == "fail") {
BrowserApp.addTab("about:home", {
showProgress: false,
selected: restoreToFront
});
}
sendMessageToJava({
gecko: {
type: "Session:RestoreEnd"
}
});
}
};
Services.obs.addObserver(restoreCleanup, "sessionstore-windows-restored", false);
// Start the restore
ss.restoreLastSession(restoreToFront, restoreMode == 1);
} else {
loadParams.showProgress = (url != "about:home");
loadParams.pinned = pinned;
this.addTab(url, loadParams);
}
if (this.isAppUpdated())
this.onAppUpdated();
// notify java that gecko has loaded
sendMessageToJava({
gecko: {
type: "Gecko:Ready"
}
});
// after gecko has loaded, set the checkerboarding pref once at startup (for testing only)
sendMessageToJava({
gecko: {
"type": "Checkerboard:Toggle",
"value": Services.prefs.getBoolPref("gfx.show_checkerboard_pattern")
}
});
// disable telemetry for beta
Services.prefs.clearUserPref("toolkit.telemetry.enabled");
Services.prefs.clearUserPref("toolkit.telemetry.prompted");
Services.prefs.clearUserPref("toolkit.telemetry.rejected");
},
isAppUpdated: function() {
let savedmstone = null;
try {
savedmstone = Services.prefs.getCharPref("browser.startup.homepage_override.mstone");
} catch (e) {
}
#expand let ourmstone = "__MOZ_APP_VERSION__";
if (ourmstone != savedmstone) {
Services.prefs.setCharPref("browser.startup.homepage_override.mstone", ourmstone);
return savedmstone ? "upgrade" : "new";
}
return "";
},
onAppUpdated: function() {
// initialize the form history and passwords databases on upgrades
Services.obs.notifyObservers(null, "FormHistory:Init", "");
Services.obs.notifyObservers(null, "Passwords:Init", "");
},
_showTelemetryPrompt: function _showTelemetryPrompt() {
const PREF_TELEMETRY_PROMPTED = "toolkit.telemetry.prompted";
const PREF_TELEMETRY_ENABLED = "toolkit.telemetry.enabled";
const PREF_TELEMETRY_REJECTED = "toolkit.telemetry.rejected";
const PREF_TELEMETRY_SERVER_OWNER = "toolkit.telemetry.server_owner";
// This is used to reprompt users when privacy message changes
const TELEMETRY_PROMPT_REV = 2;
let serverOwner = Services.prefs.getCharPref(PREF_TELEMETRY_SERVER_OWNER);
let telemetryPrompted = null;
try {
telemetryPrompted = Services.prefs.getIntPref(PREF_TELEMETRY_PROMPTED);
} catch (e) { /* Optional */ }
// 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);
let buttons = [
{
label: Strings.browser.GetStringFromName("telemetry.optin.yes"),
callback: function () {
Services.prefs.setIntPref(PREF_TELEMETRY_PROMPTED, TELEMETRY_PROMPT_REV);
Services.prefs.setBoolPref(PREF_TELEMETRY_ENABLED, true);
}
},
{
label: Strings.browser.GetStringFromName("telemetry.optin.no"),
callback: function () {
Services.prefs.setIntPref(PREF_TELEMETRY_PROMPTED, TELEMETRY_PROMPT_REV);
Services.prefs.setBoolPref(PREF_TELEMETRY_REJECTED, true);
}
}
];
let brandShortName = Strings.brand.GetStringFromName("brandShortName");
let message = Strings.browser.formatStringFromName("telemetry.optin.message2", [serverOwner, brandShortName], 2);
let learnMoreLabel = Strings.browser.GetStringFromName("telemetry.optin.learnMore");
let learnMoreUrl = Services.urlFormatter.formatURLPref("app.support.baseURL");
learnMoreUrl += "how-can-i-help-submitting-performance-data";
let options = {
link: {
label: learnMoreLabel,
url: learnMoreUrl
},
// We're adding this doorhanger during startup, before the initial onLocationChange
// event fires, so we need to set persistence to make sure it doesn't disappear.
persistence: 1
};
NativeWindow.doorhanger.show(message, "telemetry-optin", buttons, this.selectedTab.id, options);
},
shutdown: function shutdown() {
NativeWindow.uninit();
FormAssistant.uninit();
OfflineApps.uninit();
IndexedDB.uninit();
ViewportHandler.uninit();
XPInstallObserver.uninit();
ConsoleAPI.uninit();
CharacterEncoding.uninit();
SearchEngines.uninit();
WebappsUI.uninit();
RemoteDebugger.uninit();
UserAgent.uninit();
},
// This function returns false during periods where the browser displayed document is
// different from the browser content document, so user actions and some kinds of viewport
// updates should be ignored. This period starts when we start loading a new page or
// switch tabs, and ends when the new browser content document has been drawn and handed
// off to the compositor.
isBrowserContentDocumentDisplayed: function() {
if (window.top.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils).isFirstPaint)
return false;
let tab = this.selectedTab;
if (!tab)
return true;
return tab.contentDocumentIsDisplayed;
},
displayedDocumentChanged: function() {
window.top.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils).isFirstPaint = true;
},
get tabs() {
return this._tabs;
},
get selectedTab() {
return this._selectedTab;
},
set selectedTab(aTab) {
if (this._selectedTab == aTab)
return;
if (this._selectedTab)
this._selectedTab.setActive(false);
this._selectedTab = aTab;
if (!aTab)
return;
aTab.setActive(true);
aTab.setResolution(aTab._zoom, true);
this.displayedDocumentChanged();
this.deck.selectedPanel = aTab.browser;
},
get selectedBrowser() {
if (this._selectedTab)
return this._selectedTab.browser;
return null;
},
getTabForId: function getTabForId(aId) {
let tabs = this._tabs;
for (let i=0; i < tabs.length; i++) {
if (tabs[i].id == aId)
return tabs[i];
}
return null;
},
getTabForBrowser: function getTabForBrowser(aBrowser) {
let tabs = this._tabs;
for (let i = 0; i < tabs.length; i++) {
if (tabs[i].browser == aBrowser)
return tabs[i];
}
return null;
},
getTabForWindow: function getTabForWindow(aWindow) {
let tabs = this._tabs;
for (let i = 0; i < tabs.length; i++) {
if (tabs[i].browser.contentWindow == aWindow)
return tabs[i];
}
return null;
},
getBrowserForWindow: function getBrowserForWindow(aWindow) {
let tabs = this._tabs;
for (let i = 0; i < tabs.length; i++) {
if (tabs[i].browser.contentWindow == aWindow)
return tabs[i].browser;
}
return null;
},
getBrowserForDocument: function getBrowserForDocument(aDocument) {
let tabs = this._tabs;
for (let i = 0; i < tabs.length; i++) {
if (tabs[i].browser.contentDocument == aDocument)
return tabs[i].browser;
}
return null;
},
loadURI: function loadURI(aURI, aBrowser, aParams) {
aBrowser = aBrowser || this.selectedBrowser;
if (!aBrowser)
return;
aParams = aParams || {};
let flags = "flags" in aParams ? aParams.flags : Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
let postData = ("postData" in aParams && aParams.postData) ? aParams.postData : null;
let referrerURI = "referrerURI" in aParams ? aParams.referrerURI : null;
let charset = "charset" in aParams ? aParams.charset : null;
if ("showProgress" in aParams) {
let tab = this.getTabForBrowser(aBrowser);
if (tab)
tab.showProgress = aParams.showProgress;
}
try {
aBrowser.loadURIWithFlags(aURI, flags, referrerURI, charset, postData);
} catch(e) {
let tab = this.getTabForBrowser(aBrowser);
if (tab) {
let message = {
gecko: {
type: "Content:LoadError",
tabID: tab.id,
uri: aBrowser.currentURI.spec,
title: aBrowser.contentTitle
}
};
sendMessageToJava(message);
dump("Handled load error: " + e)
}
}
},
addTab: function addTab(aURI, aParams) {
aParams = aParams || {};
let newTab = new Tab(aURI, aParams);
this._tabs.push(newTab);
let selected = "selected" in aParams ? aParams.selected : true;
if (selected)
this.selectedTab = newTab;
let pinned = "pinned" in aParams ? aParams.pinned : false;
if (pinned) {
let ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
ss.setTabValue(newTab, "appOrigin", aURI);
}
let evt = document.createEvent("UIEvents");
evt.initUIEvent("TabOpen", true, false, window, null);
newTab.browser.dispatchEvent(evt);
return newTab;
},
// Use this method to close a tab from JS. This method sends a message
// to Java to close the tab in the Java UI (we'll get a Tab:Closed message
// back from Java when that happens).
closeTab: function closeTab(aTab) {
if (!aTab) {
Cu.reportError("Error trying to close tab (tab doesn't exist)");
return;
}
let message = {
gecko: {
type: "Tab:Close",
tabID: aTab.id
}
};
sendMessageToJava(message);
},
// Calling this will update the state in BrowserApp after a tab has been
// closed in the Java UI.
_handleTabClosed: function _handleTabClosed(aTab) {
if (aTab == this.selectedTab)
this.selectedTab = null;
let evt = document.createEvent("UIEvents");
evt.initUIEvent("TabClose", true, false, window, null);
aTab.browser.dispatchEvent(evt);
aTab.destroy();
this._tabs.splice(this._tabs.indexOf(aTab), 1);
},
// Use this method to select a tab from JS. This method sends a message
// to Java to select the tab in the Java UI (we'll get a Tab:Selected message
// back from Java when that happens).
selectTab: function selectTab(aTab) {
if (!aTab) {
Cu.reportError("Error trying to select tab (tab doesn't exist)");
return;
}
// There's nothing to do if the tab is already selected
if (aTab == this.selectedTab)
return;
let message = {
gecko: {
type: "Tab:Select",
tabID: aTab.id
}
};
sendMessageToJava(message);
},
// This method updates the state in BrowserApp after a tab has been selected
// in the Java UI.
_handleTabSelected: function _handleTabSelected(aTab) {
this.selectedTab = aTab;
let evt = document.createEvent("UIEvents");
evt.initUIEvent("TabSelect", true, false, window, null);
aTab.browser.dispatchEvent(evt);
},
quit: function quit() {
// Figure out if there's at least one other browser window around.
let lastBrowser = true;
let e = Services.wm.getEnumerator("navigator:browser");
while (e.hasMoreElements() && lastBrowser) {
let win = e.getNext();
if (win != window)
lastBrowser = false;
}
if (lastBrowser) {
// Let everyone know we are closing the last browser window
let closingCanceled = Cc["@mozilla.org/supports-PRBool;1"].createInstance(Ci.nsISupportsPRBool);
Services.obs.notifyObservers(closingCanceled, "browser-lastwindow-close-requested", null);
if (closingCanceled.data)
return;
Services.obs.notifyObservers(null, "browser-lastwindow-close-granted", null);
}
window.QueryInterface(Ci.nsIDOMChromeWindow).minimize();
window.close();
},
saveAsPDF: function saveAsPDF(aBrowser) {
// Create the final destination file location
let fileName = ContentAreaUtils.getDefaultFileName(aBrowser.contentTitle, aBrowser.currentURI, null, null);
fileName = fileName.trim() + ".pdf";
let dm = Cc["@mozilla.org/download-manager;1"].getService(Ci.nsIDownloadManager);
let downloadsDir = dm.defaultDownloadsDirectory;
let file = downloadsDir.clone();
file.append(fileName);
file.createUnique(file.NORMAL_FILE_TYPE, parseInt("666", 8));
let printSettings = Cc["@mozilla.org/gfx/printsettings-service;1"].getService(Ci.nsIPrintSettingsService).newPrintSettings;
printSettings.printSilent = true;
printSettings.showPrintProgress = false;
printSettings.printBGImages = true;
printSettings.printBGColors = true;
printSettings.printToFile = true;
printSettings.toFileName = file.path;
printSettings.printFrameType = Ci.nsIPrintSettings.kFramesAsIs;
printSettings.outputFormat = Ci.nsIPrintSettings.kOutputFormatPDF;
//XXX we probably need a preference here, the header can be useful
printSettings.footerStrCenter = "";
printSettings.footerStrLeft = "";
printSettings.footerStrRight = "";
printSettings.headerStrCenter = "";
printSettings.headerStrLeft = "";
printSettings.headerStrRight = "";
// Create a valid mimeInfo for the PDF
let ms = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
let mimeInfo = ms.getFromTypeAndExtension("application/pdf", "pdf");
let webBrowserPrint = aBrowser.contentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebBrowserPrint);
let cancelable = {
cancel: function (aReason) {
webBrowserPrint.cancel();
}
}
let download = dm.addDownload(Ci.nsIDownloadManager.DOWNLOAD_TYPE_DOWNLOAD,
aBrowser.currentURI,
Services.io.newFileURI(file), "", mimeInfo,
Date.now() * 1000, null, cancelable);
webBrowserPrint.print(printSettings, download);
},
getPreferences: function getPreferences(aPrefNames) {
try {
let json = JSON.parse(aPrefNames);
let prefs = [];
for each (let prefName in json) {
let pref = {
name: prefName
};
// The plugin pref is actually two separate prefs, so
// we need to handle it differently
if (prefName == "plugin.enable") {
// Use a string type for java's ListPreference
pref.type = "string";
pref.value = PluginHelper.getPluginPreference();
prefs.push(pref);
continue;
} else if (prefName == MasterPassword.pref) {
// Master password is not a "real" pref
pref.type = "bool";
pref.value = MasterPassword.enabled;
prefs.push(pref);
continue;
}
try {
switch (Services.prefs.getPrefType(prefName)) {
case Ci.nsIPrefBranch.PREF_BOOL:
pref.type = "bool";
pref.value = Services.prefs.getBoolPref(prefName);
break;
case Ci.nsIPrefBranch.PREF_INT:
pref.type = "int";
pref.value = Services.prefs.getIntPref(prefName);
break;
case Ci.nsIPrefBranch.PREF_STRING:
default:
pref.type = "string";
try {
// Try in case it's a localized string (will throw an exception if not)
pref.value = Services.prefs.getComplexValue(prefName, Ci.nsIPrefLocalizedString).data;
} catch (e) {
pref.value = Services.prefs.getCharPref(prefName);
}
break;
}
} catch (e) {
dump("Error reading pref [" + prefName + "]: " + e);
// preference does not exist; do not send it
continue;
}
// some preferences use integers or strings instead of booleans for
// indicating enabled/disabled. since the java ui uses the type to
// determine which ui elements to show, we need to normalize these
// preferences to be actual booleans.
switch (prefName) {
case "network.cookie.cookieBehavior":
pref.type = "bool";
pref.value = pref.value == 0;
break;
case "font.size.inflation.minTwips":
pref.type = "string";
pref.value = pref.value.toString();
break;
}
prefs.push(pref);
}
sendMessageToJava({
gecko: {
type: "Preferences:Data",
preferences: prefs
}
});
} catch (e) {}
},
addTelemetry: function addTelemetry(aData) {
let json = JSON.parse(aData);
var telemetry = Cc["@mozilla.org/base/telemetry;1"]
.getService(Ci.nsITelemetry);
let histogram = telemetry.getHistogramById(json.name);
histogram.add(json.value);
},
setPreferences: function setPreferences(aPref) {
let json = JSON.parse(aPref);
if (json.name == "plugin.enable") {
// The plugin pref is actually two separate prefs, so
// we need to handle it differently
PluginHelper.setPluginPreference(json.value);
return;
} else if (json.name == MasterPassword.pref) {
// MasterPassword pref is not real, we just need take action and leave
if (MasterPassword.enabled)
MasterPassword.removePassword(json.value);
else
MasterPassword.setPassword(json.value);
return;
}
// when sending to java, we normalized special preferences that use
// integers and strings to represent booleans. here, we convert them back
// to their actual types so we can store them.
switch (json.name) {
case "network.cookie.cookieBehavior":
json.type = "int";
json.value = (json.value ? 0 : 2);
break;
case "font.size.inflation.minTwips":
json.type = "int";
json.value = parseInt(json.value);
break;
}
if (json.type == "bool") {
Services.prefs.setBoolPref(json.name, json.value);
} else if (json.type == "int") {
Services.prefs.setIntPref(json.name, json.value);
} else {
let pref = Cc["@mozilla.org/pref-localizedstring;1"].createInstance(Ci.nsIPrefLocalizedString);
pref.data = json.value;
Services.prefs.setComplexValue(json.name, Ci.nsISupportsString, pref);
}
},
scrollToFocusedInput: function(aBrowser) {
let doc = aBrowser.contentDocument;
if (!doc)
return;
let focused = doc.activeElement;
if ((focused instanceof HTMLInputElement && focused.mozIsTextField(false)) || (focused instanceof HTMLTextAreaElement)) {
let tab = BrowserApp.getTabForBrowser(aBrowser);
let win = aBrowser.contentWindow;
// tell gecko to scroll the field into view. this will scroll any nested scrollable elements
// as well as the browser's content window, and modify the scrollX and scrollY on the content window.
focused.scrollIntoView(false);
// As Gecko isn't aware of the zoom level we're drawing with, the element may not entirely be in view
// yet. Check for that, and scroll some extra to compensate, if necessary.
let focusedRect = focused.getBoundingClientRect();
let visibleContentWidth = gScreenWidth / tab._zoom;
let visibleContentHeight = gScreenHeight / tab._zoom;
let positionChanged = false;
let scrollX = win.scrollX;
let scrollY = win.scrollY;
if (focusedRect.right >= visibleContentWidth && focusedRect.left > 0) {
// the element is too far off the right side, so we need to scroll to the right more
scrollX += Math.min(focusedRect.left, focusedRect.right - visibleContentWidth);
positionChanged = true;
} else if (focusedRect.left < 0) {
// the element is too far off the left side, so we need to scroll to the left more
scrollX += focusedRect.left;
positionChanged = true;
}
if (focusedRect.bottom >= visibleContentHeight && focusedRect.top > 0) {
// the element is too far down, so we need to scroll down more
scrollY += Math.min(focusedRect.top, focusedRect.bottom - visibleContentHeight);
positionChanged = true;
} else if (focusedRect.top < 0) {
// the element is too far up, so we need to scroll up more
scrollY += focusedRect.top;
positionChanged = true;
}
if (positionChanged)
win.scrollTo(scrollX, scrollY);
// update userScrollPos so that we don't send a duplicate viewport update by triggering
// our scroll listener
tab.userScrollPos.x = win.scrollX;
tab.userScrollPos.y = win.scrollY;
// finally, let java know where we ended up
tab.sendViewportUpdate();
}
},
observe: function(aSubject, aTopic, aData) {
let browser = this.selectedBrowser;
if (!browser)
return;
if (aTopic == "Session:Back") {
browser.goBack();
} else if (aTopic == "Session:Forward") {
browser.goForward();
} else if (aTopic == "Session:Reload") {
browser.reload();
} else if (aTopic == "Session:Stop") {
browser.stop();
} else if (aTopic == "Tab:Add" || aTopic == "Tab:Load") {
let data = JSON.parse(aData);
// Pass LOAD_FLAGS_DISALLOW_INHERIT_OWNER to prevent any loads from
// inheriting the currently loaded document's principal.
let flags = Ci.nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP;
if (data.userEntered)
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_DISALLOW_INHERIT_OWNER;
let params = {
selected: true,
parentId: ("parentId" in data) ? data.parentId : -1,
flags: flags
};
let url = data.url;
if (data.engine) {
let engine = Services.search.getEngineByName(data.engine);
if (engine) {
let submission = engine.getSubmission(url);
url = submission.uri.spec;
params.postData = submission.postData;
}
}
// Don't show progress throbber for about:home
if (url == "about:home")
params.showProgress = false;
if (aTopic == "Tab:Add")
this.addTab(url, params);
else
this.loadURI(url, browser, params);
} else if (aTopic == "Tab:Selected") {
this._handleTabSelected(this.getTabForId(parseInt(aData)));
} else if (aTopic == "Tab:Closed") {
this._handleTabClosed(this.getTabForId(parseInt(aData)));
} else if (aTopic == "Browser:Quit") {
this.quit();
} else if (aTopic == "SaveAs:PDF") {
this.saveAsPDF(browser);
} else if (aTopic == "Preferences:Get") {
this.getPreferences(aData);
} else if (aTopic == "Preferences:Set") {
this.setPreferences(aData);
} else if (aTopic == "ScrollTo:FocusedInput") {
this.scrollToFocusedInput(browser);
} else if (aTopic == "Sanitize:ClearAll") {
Sanitizer.sanitize();
} else if (aTopic == "FullScreen:Exit") {
browser.contentDocument.mozCancelFullScreen();
} else if (aTopic == "Viewport:Change") {
if (this.isBrowserContentDocumentDisplayed())
this.selectedTab.setViewport(JSON.parse(aData));
} else if (aTopic == "Passwords:Init") {
let storage = Components.classes["@mozilla.org/login-manager/storage/mozStorage;1"].
getService(Components.interfaces.nsILoginManagerStorage);
storage.init();
sendMessageToJava({gecko: { type: "Passwords:Init:Return" }});
Services.obs.removeObserver(this, "Passwords:Init", false);
} else if (aTopic == "FormHistory:Init") {
let fh = Cc["@mozilla.org/satchel/form-history;1"].getService(Ci.nsIFormHistory2);
// Force creation/upgrade of formhistory.sqlite
let db = fh.DBConnection;
sendMessageToJava({gecko: { type: "FormHistory:Init:Return" }});
Services.obs.removeObserver(this, "FormHistory:Init", false);
} else if (aTopic == "sessionstore-state-purge-complete") {
sendMessageToJava({ gecko: { type: "Session:StatePurged" }});