-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathwebconsole.js
5503 lines (4852 loc) · 168 KB
/
webconsole.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
/* -*- js-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* 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/. */
"use strict";
const {Cc, Ci, Cu} = require("chrome");
const {Utils: WebConsoleUtils, CONSOLE_WORKER_IDS} = require("devtools/shared/webconsole/utils");
const promise = require("promise");
loader.lazyServiceGetter(this, "clipboardHelper",
"@mozilla.org/widget/clipboardhelper;1",
"nsIClipboardHelper");
loader.lazyImporter(this, "Services", "resource://gre/modules/Services.jsm");
loader.lazyRequireGetter(this, "EventEmitter", "devtools/shared/event-emitter");
loader.lazyRequireGetter(this, "AutocompletePopup", "devtools/client/shared/autocomplete-popup", true);
loader.lazyRequireGetter(this, "ToolSidebar", "devtools/client/framework/sidebar", true);
loader.lazyRequireGetter(this, "ConsoleOutput", "devtools/client/webconsole/console-output", true);
loader.lazyRequireGetter(this, "Messages", "devtools/client/webconsole/console-output", true);
loader.lazyRequireGetter(this, "asyncStorage", "devtools/shared/async-storage");
loader.lazyRequireGetter(this, "EnvironmentClient", "devtools/shared/client/main", true);
loader.lazyRequireGetter(this, "ObjectClient", "devtools/shared/client/main", true);
loader.lazyRequireGetter(this, "system", "devtools/shared/system");
loader.lazyRequireGetter(this, "Timers", "sdk/timers");
loader.lazyImporter(this, "VariablesView", "resource://devtools/client/shared/widgets/VariablesView.jsm");
loader.lazyImporter(this, "VariablesViewController", "resource://devtools/client/shared/widgets/VariablesViewController.jsm");
loader.lazyImporter(this, "PluralForm", "resource://gre/modules/PluralForm.jsm");
loader.lazyImporter(this, "gDevTools", "resource://devtools/client/framework/gDevTools.jsm");
const STRINGS_URI = "chrome://devtools/locale/webconsole.properties";
var l10n = new WebConsoleUtils.l10n(STRINGS_URI);
const XHTML_NS = "http://www.w3.org/1999/xhtml";
const MIXED_CONTENT_LEARN_MORE = "https://developer.mozilla.org/docs/Security/MixedContent";
const TRACKING_PROTECTION_LEARN_MORE = "https://developer.mozilla.org/Firefox/Privacy/Tracking_Protection";
const INSECURE_PASSWORDS_LEARN_MORE = "https://developer.mozilla.org/docs/Security/InsecurePasswords";
const PUBLIC_KEY_PINS_LEARN_MORE = "https://developer.mozilla.org/docs/Web/Security/Public_Key_Pinning";
const STRICT_TRANSPORT_SECURITY_LEARN_MORE = "https://developer.mozilla.org/docs/Security/HTTP_Strict_Transport_Security";
const WEAK_SIGNATURE_ALGORITHM_LEARN_MORE = "https://developer.mozilla.org/docs/Security/Weak_Signature_Algorithm";
const HELP_URL = "https://developer.mozilla.org/docs/Tools/Web_Console/Helpers";
const VARIABLES_VIEW_URL = "chrome://devtools/content/shared/widgets/VariablesView.xul";
const IGNORED_SOURCE_URLS = ["debugger eval code"];
// The amount of time in milliseconds that we wait before performing a live
// search.
const SEARCH_DELAY = 200;
// The number of lines that are displayed in the console output by default, for
// each category. The user can change this number by adjusting the hidden
// "devtools.hud.loglimit.{network,cssparser,exception,console}" preferences.
const DEFAULT_LOG_LIMIT = 1000;
// The various categories of messages. We start numbering at zero so we can
// use these as indexes into the MESSAGE_PREFERENCE_KEYS matrix below.
const CATEGORY_NETWORK = 0;
const CATEGORY_CSS = 1;
const CATEGORY_JS = 2;
const CATEGORY_WEBDEV = 3;
const CATEGORY_INPUT = 4; // always on
const CATEGORY_OUTPUT = 5; // always on
const CATEGORY_SECURITY = 6;
const CATEGORY_SERVER = 7;
// The possible message severities. As before, we start at zero so we can use
// these as indexes into MESSAGE_PREFERENCE_KEYS.
const SEVERITY_ERROR = 0;
const SEVERITY_WARNING = 1;
const SEVERITY_INFO = 2;
const SEVERITY_LOG = 3;
// The fragment of a CSS class name that identifies each category.
const CATEGORY_CLASS_FRAGMENTS = [
"network",
"cssparser",
"exception",
"console",
"input",
"output",
"security",
"server",
];
// The fragment of a CSS class name that identifies each severity.
const SEVERITY_CLASS_FRAGMENTS = [
"error",
"warn",
"info",
"log",
];
// The preference keys to use for each category/severity combination, indexed
// first by category (rows) and then by severity (columns).
//
// Most of these rather idiosyncratic names are historical and predate the
// division of message type into "category" and "severity".
const MESSAGE_PREFERENCE_KEYS = [
// Error Warning Info Log
[ "network", "netwarn", "netxhr", "networkinfo", ], // Network
[ "csserror", "cssparser", null, "csslog", ], // CSS
[ "exception", "jswarn", null, "jslog", ], // JS
[ "error", "warn", "info", "log", ], // Web Developer
[ null, null, null, null, ], // Input
[ null, null, null, null, ], // Output
[ "secerror", "secwarn", null, null, ], // Security
[ "servererror", "serverwarn", "serverinfo", "serverlog", ], // Server Logging
];
// A mapping from the console API log event levels to the Web Console
// severities.
const LEVELS = {
error: SEVERITY_ERROR,
exception: SEVERITY_ERROR,
assert: SEVERITY_ERROR,
warn: SEVERITY_WARNING,
info: SEVERITY_INFO,
log: SEVERITY_LOG,
trace: SEVERITY_LOG,
table: SEVERITY_LOG,
debug: SEVERITY_LOG,
dir: SEVERITY_LOG,
dirxml: SEVERITY_LOG,
group: SEVERITY_LOG,
groupCollapsed: SEVERITY_LOG,
groupEnd: SEVERITY_LOG,
time: SEVERITY_LOG,
timeEnd: SEVERITY_LOG,
count: SEVERITY_LOG
};
// This array contains the prefKey for the workers and it must keep them in the
// same order as CONSOLE_WORKER_IDS
const WORKERTYPES_PREFKEYS = [ 'sharedworkers', 'serviceworkers', 'windowlessworkers' ];
// The lowest HTTP response code (inclusive) that is considered an error.
const MIN_HTTP_ERROR_CODE = 400;
// The highest HTTP response code (inclusive) that is considered an error.
const MAX_HTTP_ERROR_CODE = 599;
// Constants used for defining the direction of JSTerm input history navigation.
const HISTORY_BACK = -1;
const HISTORY_FORWARD = 1;
// The indent of a console group in pixels.
const GROUP_INDENT = 12;
// The number of messages to display in a single display update. If we display
// too many messages at once we slow down the Firefox UI too much.
const MESSAGES_IN_INTERVAL = DEFAULT_LOG_LIMIT;
// The delay between display updates - tells how often we should *try* to push
// new messages to screen. This value is optimistic, updates won't always
// happen. Keep this low so the Web Console output feels live.
const OUTPUT_INTERVAL = 20; // milliseconds
// The maximum amount of time that can be spent doing cleanup inside of the
// flush output callback. If things don't get cleaned up in this time,
// then it will start again the next time it is called.
const MAX_CLEANUP_TIME = 10; // milliseconds
// When the output queue has more than MESSAGES_IN_INTERVAL items we throttle
// output updates to this number of milliseconds. So during a lot of output we
// update every N milliseconds given here.
const THROTTLE_UPDATES = 1000; // milliseconds
// The preference prefix for all of the Web Console filters.
const FILTER_PREFS_PREFIX = "devtools.webconsole.filter.";
// The minimum font size.
const MIN_FONT_SIZE = 10;
const PREF_CONNECTION_TIMEOUT = "devtools.debugger.remote-timeout";
const PREF_PERSISTLOG = "devtools.webconsole.persistlog";
const PREF_MESSAGE_TIMESTAMP = "devtools.webconsole.timestampMessages";
const PREF_INPUT_HISTORY_COUNT = "devtools.webconsole.inputHistoryCount";
/**
* A WebConsoleFrame instance is an interactive console initialized *per target*
* that displays console log data as well as provides an interactive terminal to
* manipulate the target's document content.
*
* The WebConsoleFrame is responsible for the actual Web Console UI
* implementation.
*
* @constructor
* @param object aWebConsoleOwner
* The WebConsole owner object.
*/
function WebConsoleFrame(aWebConsoleOwner)
{
this.owner = aWebConsoleOwner;
this.hudId = this.owner.hudId;
this.window = this.owner.iframeWindow;
this._repeatNodes = {};
this._outputQueue = [];
this._itemDestroyQueue = [];
this._pruneCategoriesQueue = {};
this.filterPrefs = {};
this.output = new ConsoleOutput(this);
this._toggleFilter = this._toggleFilter.bind(this);
this._onPanelSelected = this._onPanelSelected.bind(this);
this._flushMessageQueue = this._flushMessageQueue.bind(this);
this._onToolboxPrefChanged = this._onToolboxPrefChanged.bind(this);
this._onUpdateListeners = this._onUpdateListeners.bind(this);
this._outputTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
this._outputTimerInitialized = false;
EventEmitter.decorate(this);
}
exports.WebConsoleFrame = WebConsoleFrame;
WebConsoleFrame.prototype = {
/**
* The WebConsole instance that owns this frame.
* @see hudservice.js::WebConsole
* @type object
*/
owner: null,
/**
* Proxy between the Web Console and the remote Web Console instance. This
* object holds methods used for connecting, listening and disconnecting from
* the remote server, using the remote debugging protocol.
*
* @see WebConsoleConnectionProxy
* @type object
*/
proxy: null,
/**
* Getter for the xul:popupset that holds any popups we open.
* @type nsIDOMElement
*/
get popupset() {
return this.owner.mainPopupSet;
},
/**
* Holds the initialization promise object.
* @private
* @type object
*/
_initDefer: null,
/**
* Last time when we displayed any message in the output.
*
* @private
* @type number
* Timestamp in milliseconds since the Unix epoch.
*/
_lastOutputFlush: 0,
/**
* Message nodes are stored here in a queue for later display.
*
* @private
* @type array
*/
_outputQueue: null,
/**
* Keep track of the categories we need to prune from time to time.
*
* @private
* @type array
*/
_pruneCategoriesQueue: null,
/**
* Function invoked whenever the output queue is emptied. This is used by some
* tests.
*
* @private
* @type function
*/
_flushCallback: null,
/**
* Timer used for flushing the messages output queue.
*
* @private
* @type nsITimer
*/
_outputTimer: null,
_outputTimerInitialized: null,
/**
* Store for tracking repeated nodes.
* @private
* @type object
*/
_repeatNodes: null,
/**
* Preferences for filtering messages by type.
* @see this._initDefaultFilterPrefs()
* @type object
*/
filterPrefs: null,
/**
* Prefix used for filter preferences.
* @private
* @type string
*/
_filterPrefsPrefix: FILTER_PREFS_PREFIX,
/**
* The nesting depth of the currently active console group.
*/
groupDepth: 0,
/**
* The current target location.
* @type string
*/
contentLocation: "",
/**
* The JSTerm object that manage the console's input.
* @see JSTerm
* @type object
*/
jsterm: null,
/**
* The element that holds all of the messages we display.
* @type nsIDOMElement
*/
outputNode: null,
/**
* The ConsoleOutput instance that manages all output.
* @type object
*/
output: null,
/**
* The input element that allows the user to filter messages by string.
* @type nsIDOMElement
*/
filterBox: null,
/**
* Getter for the debugger WebConsoleClient.
* @type object
*/
get webConsoleClient() {
return this.proxy ? this.proxy.webConsoleClient : null;
},
_destroyer: null,
// Used in tests.
_saveRequestAndResponseBodies: false,
// Chevron width at the starting of Web Console's input box.
_chevronWidth: 0,
// Width of the monospace characters in Web Console's input box.
_inputCharWidth: 0,
/**
* Tells whether to save the bodies of network requests and responses.
* Disabled by default to save memory.
*
* @return boolean
* The saveRequestAndResponseBodies pref value.
*/
getSaveRequestAndResponseBodies:
function WCF_getSaveRequestAndResponseBodies() {
let deferred = promise.defer();
let toGet = [
"NetworkMonitor.saveRequestAndResponseBodies"
];
// Make sure the web console client connection is established first.
this.webConsoleClient.getPreferences(toGet, aResponse => {
if (!aResponse.error) {
this._saveRequestAndResponseBodies = aResponse.preferences[toGet[0]];
deferred.resolve(this._saveRequestAndResponseBodies);
}
else {
deferred.reject(aResponse.error);
}
});
return deferred.promise;
},
/**
* Setter for saving of network request and response bodies.
*
* @param boolean aValue
* The new value you want to set.
*/
setSaveRequestAndResponseBodies:
function WCF_setSaveRequestAndResponseBodies(aValue) {
if (!this.webConsoleClient) {
// Don't continue if the webconsole disconnected.
return promise.resolve(null);
}
let deferred = promise.defer();
let newValue = !!aValue;
let toSet = {
"NetworkMonitor.saveRequestAndResponseBodies": newValue,
};
// Make sure the web console client connection is established first.
this.webConsoleClient.setPreferences(toSet, aResponse => {
if (!aResponse.error) {
this._saveRequestAndResponseBodies = newValue;
deferred.resolve(aResponse);
}
else {
deferred.reject(aResponse.error);
}
});
return deferred.promise;
},
/**
* Getter for the persistent logging preference.
* @type boolean
*/
get persistLog() {
// For the browser console, we receive tab navigation
// when the original top level window we attached to is closed,
// but we don't want to reset console history and just switch to
// the next available window.
return this.owner._browserConsole || Services.prefs.getBoolPref(PREF_PERSISTLOG);
},
/**
* Initialize the WebConsoleFrame instance.
* @return object
* A promise object that resolves once the frame is ready to use.
*/
init: function()
{
this._initUI();
let connectionInited = this._initConnection();
// Don't reject if the history fails to load for some reason.
// This would be fine, the panel will just start with empty history.
let allReady = this.jsterm.historyLoaded.catch(() => {}).then(() => {
return connectionInited;
});
// This notification is only used in tests. Don't chain it onto
// the returned promise because the console panel needs to be attached
// to the toolbox before the web-console-created event is receieved.
let notifyObservers = () => {
let id = WebConsoleUtils.supportsString(this.hudId);
Services.obs.notifyObservers(id, "web-console-created", null);
};
allReady.then(notifyObservers, notifyObservers);
return allReady;
},
/**
* Connect to the server using the remote debugging protocol.
*
* @private
* @return object
* A promise object that is resolved/reject based on the connection
* result.
*/
_initConnection: function WCF__initConnection()
{
if (this._initDefer) {
return this._initDefer.promise;
}
this._initDefer = promise.defer();
this.proxy = new WebConsoleConnectionProxy(this, this.owner.target);
this.proxy.connect().then(() => { // on success
this._initDefer.resolve(this);
}, (aReason) => { // on failure
let node = this.createMessageNode(CATEGORY_JS, SEVERITY_ERROR,
aReason.error + ": " + aReason.message);
this.outputMessage(CATEGORY_JS, node, [aReason]);
this._initDefer.reject(aReason);
});
return this._initDefer.promise;
},
/**
* Find the Web Console UI elements and setup event listeners as needed.
* @private
*/
_initUI: function WCF__initUI()
{
this.document = this.window.document;
this.rootElement = this.document.documentElement;
this._initDefaultFilterPrefs();
// Register the controller to handle "select all" properly.
this._commandController = new CommandController(this);
this.window.controllers.insertControllerAt(0, this._commandController);
this._contextMenuHandler = new ConsoleContextMenu(this);
let doc = this.document;
if (system.constants.platform === "macosx") {
doc.querySelector("#key_clearOSX").removeAttribute("disabled");
} else {
doc.querySelector("#key_clear").removeAttribute("disabled");
}
this.filterBox = doc.querySelector(".hud-filter-box");
this.outputNode = doc.getElementById("output-container");
this.completeNode = doc.querySelector(".jsterm-complete-node");
this.inputNode = doc.querySelector(".jsterm-input-node");
this._setFilterTextBoxEvents();
this._initFilterButtons();
let fontSize = this.owner._browserConsole ?
Services.prefs.getIntPref("devtools.webconsole.fontSize") : 0;
if (fontSize != 0) {
fontSize = Math.max(MIN_FONT_SIZE, fontSize);
this.outputNode.style.fontSize = fontSize + "px";
this.completeNode.style.fontSize = fontSize + "px";
this.inputNode.style.fontSize = fontSize + "px";
}
if (this.owner._browserConsole) {
for (let id of ["Enlarge", "Reduce", "Reset"]) {
this.document.getElementById("cmd_fullZoom" + id)
.removeAttribute("disabled");
}
}
// Update the character width and height needed for the popup offset
// calculations.
this._updateCharSize();
let updateSaveBodiesPrefUI = (aElement) => {
this.getSaveRequestAndResponseBodies().then(aValue => {
aElement.setAttribute("checked", aValue);
this.emit("save-bodies-ui-toggled");
});
}
let reverseSaveBodiesPref = ({ target: aElement }) => {
this.getSaveRequestAndResponseBodies().then(aValue => {
this.setSaveRequestAndResponseBodies(!aValue);
aElement.setAttribute("checked", aValue);
this.emit("save-bodies-pref-reversed");
});
}
let saveBodiesDisabled = !this.getFilterState("networkinfo") &&
!this.getFilterState("netxhr") &&
!this.getFilterState("network");
let saveBodies = doc.getElementById("saveBodies");
saveBodies.addEventListener("command", reverseSaveBodiesPref);
saveBodies.disabled = saveBodiesDisabled;
let saveBodiesContextMenu = doc.getElementById("saveBodiesContextMenu");
saveBodiesContextMenu.addEventListener("command", reverseSaveBodiesPref);
saveBodiesContextMenu.disabled = saveBodiesDisabled;
saveBodies.parentNode.addEventListener("popupshowing", () => {
updateSaveBodiesPrefUI(saveBodies);
saveBodies.disabled = !this.getFilterState("networkinfo") &&
!this.getFilterState("netxhr") &&
!this.getFilterState("network");
});
saveBodiesContextMenu.parentNode.addEventListener("popupshowing", () => {
updateSaveBodiesPrefUI(saveBodiesContextMenu);
saveBodiesContextMenu.disabled = !this.getFilterState("networkinfo") &&
!this.getFilterState("netxhr") &&
!this.getFilterState("network");
});
let clearButton = doc.getElementsByClassName("webconsole-clear-console-button")[0];
clearButton.addEventListener("command", () => {
this.owner._onClearButton();
this.jsterm.clearOutput(true);
});
this.jsterm = new JSTerm(this);
this.jsterm.init();
let toolbox = gDevTools.getToolbox(this.owner.target);
if (toolbox) {
toolbox.on("webconsole-selected", this._onPanelSelected);
}
/*
* Focus input line whenever the output area is clicked.
* Reusing _addMEssageLinkCallback since it correctly filters
* drag and select events.
*/
this._addFocusCallback(this.outputNode, (evt) => {
if ((evt.target.nodeName.toLowerCase() != "a") &&
(evt.target.parentNode.nodeName.toLowerCase() != "a")) {
this.jsterm.inputNode.focus();
}
});
// Toggle the timestamp on preference change
gDevTools.on("pref-changed", this._onToolboxPrefChanged);
this._onToolboxPrefChanged("pref-changed", {
pref: PREF_MESSAGE_TIMESTAMP,
newValue: Services.prefs.getBoolPref(PREF_MESSAGE_TIMESTAMP),
});
// focus input node
this.jsterm.inputNode.focus();
},
/**
* Sets the focus to JavaScript input field when the web console tab is
* selected or when there is a split console present.
* @private
*/
_onPanelSelected: function WCF__onPanelSelected(evt, id)
{
this.jsterm.inputNode.focus();
},
/**
* Initialize the default filter preferences.
* @private
*/
_initDefaultFilterPrefs: function WCF__initDefaultFilterPrefs()
{
let prefs = ["network", "networkinfo", "csserror", "cssparser", "csslog",
"exception", "jswarn", "jslog", "error", "info", "warn", "log",
"secerror", "secwarn", "netwarn", "netxhr", "sharedworkers",
"serviceworkers", "windowlessworkers", "servererror",
"serverwarn", "serverinfo", "serverlog"];
for (let pref of prefs) {
this.filterPrefs[pref] = Services.prefs.getBoolPref(
this._filterPrefsPrefix + pref);
}
},
/**
* Attach / detach reflow listeners depending on the checked status
* of the `CSS > Log` menuitem.
*
* @param function [aCallback=null]
* Optional function to invoke when the listener has been
* added/removed.
*/
_updateReflowActivityListener:
function WCF__updateReflowActivityListener(aCallback)
{
if (this.webConsoleClient) {
let pref = this._filterPrefsPrefix + "csslog";
if (Services.prefs.getBoolPref(pref)) {
this.webConsoleClient.startListeners(["ReflowActivity"], aCallback);
} else {
this.webConsoleClient.stopListeners(["ReflowActivity"], aCallback);
}
}
},
/**
* Attach / detach server logging listener depending on the filter
* preferences. If the user isn't interested in the server logs at
* all the listener is not registered.
*
* @param function [aCallback=null]
* Optional function to invoke when the listener has been
* added/removed.
*/
_updateServerLoggingListener:
function WCF__updateServerLoggingListener(aCallback)
{
if (!this.webConsoleClient) {
return;
}
let startListener = false;
let prefs = ["servererror", "serverwarn", "serverinfo", "serverlog"];
for (let i = 0; i < prefs.length; i++) {
if (this.filterPrefs[prefs[i]]) {
startListener = true;
break;
}
}
if (startListener) {
this.webConsoleClient.startListeners(["ServerLogging"], aCallback);
} else {
this.webConsoleClient.stopListeners(["ServerLogging"], aCallback);
}
},
/**
* Sets the events for the filter input field.
* @private
*/
_setFilterTextBoxEvents: function WCF__setFilterTextBoxEvents()
{
let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
let timerEvent = this.adjustVisibilityOnSearchStringChange.bind(this);
let onChange = function _onChange() {
// To improve responsiveness, we let the user finish typing before we
// perform the search.
timer.cancel();
timer.initWithCallback(timerEvent, SEARCH_DELAY,
Ci.nsITimer.TYPE_ONE_SHOT);
};
this.filterBox.addEventListener("command", onChange, false);
this.filterBox.addEventListener("input", onChange, false);
},
/**
* Creates one of the filter buttons on the toolbar.
*
* @private
* @param nsIDOMNode aParent
* The node to which the filter button should be appended.
* @param object aDescriptor
* A descriptor that contains info about the button. Contains "name",
* "category", and "prefKey" properties, and optionally a "severities"
* property.
*/
_initFilterButtons: function WCF__initFilterButtons()
{
let categories = this.document
.querySelectorAll(".webconsole-filter-button[category]");
Array.forEach(categories, function(aButton) {
aButton.addEventListener("contextmenu", (aEvent) => {
aButton.open = true;
}, false);
aButton.addEventListener("click", this._toggleFilter, false);
let someChecked = false;
let severities = aButton.querySelectorAll("menuitem[prefKey]");
Array.forEach(severities, function(aMenuItem) {
aMenuItem.addEventListener("command", this._toggleFilter, false);
let prefKey = aMenuItem.getAttribute("prefKey");
let checked = this.filterPrefs[prefKey];
aMenuItem.setAttribute("checked", checked);
someChecked = someChecked || checked;
}, this);
aButton.setAttribute("checked", someChecked);
aButton.setAttribute("aria-pressed", someChecked);
}, this);
if (!this.owner._browserConsole) {
// The Browser Console displays nsIConsoleMessages which are messages that
// end up in the JS category, but they are not errors or warnings, they
// are just log messages. The Web Console does not show such messages.
let jslog = this.document.querySelector("menuitem[prefKey=jslog]");
jslog.hidden = true;
}
if (Services.appinfo.OS == "Darwin") {
let net = this.document.querySelector("toolbarbutton[category=net]");
let accesskey = net.getAttribute("accesskeyMacOSX");
net.setAttribute("accesskey", accesskey);
let logging = this.document.querySelector("toolbarbutton[category=logging]");
logging.removeAttribute("accesskey");
let serverLogging = this.document.querySelector("toolbarbutton[category=server]");
serverLogging.removeAttribute("accesskey");
}
},
/**
* Increase, decrease or reset the font size.
*
* @param string size
* The size of the font change. Accepted values are "+" and "-".
* An unmatched size assumes a font reset.
*/
changeFontSize: function WCF_changeFontSize(aSize)
{
let fontSize = this.window
.getComputedStyle(this.outputNode, null)
.getPropertyValue("font-size").replace("px", "");
if (this.outputNode.style.fontSize) {
fontSize = this.outputNode.style.fontSize.replace("px", "");
}
if (aSize == "+" || aSize == "-") {
fontSize = parseInt(fontSize, 10);
if (aSize == "+") {
fontSize += 1;
}
else {
fontSize -= 1;
}
if (fontSize < MIN_FONT_SIZE) {
fontSize = MIN_FONT_SIZE;
}
Services.prefs.setIntPref("devtools.webconsole.fontSize", fontSize);
fontSize = fontSize + "px";
this.completeNode.style.fontSize = fontSize;
this.inputNode.style.fontSize = fontSize;
this.outputNode.style.fontSize = fontSize;
}
else {
this.completeNode.style.fontSize = "";
this.inputNode.style.fontSize = "";
this.outputNode.style.fontSize = "";
Services.prefs.clearUserPref("devtools.webconsole.fontSize");
}
this._updateCharSize();
},
/**
* Calculates the width and height of a single character of the input box.
* This will be used in opening the popup at the correct offset.
*
* @private
*/
_updateCharSize: function WCF__updateCharSize()
{
let doc = this.document;
let tempLabel = doc.createElementNS(XHTML_NS, "span");
let style = tempLabel.style;
style.position = "fixed";
style.padding = "0";
style.margin = "0";
style.width = "auto";
style.color = "transparent";
WebConsoleUtils.copyTextStyles(this.inputNode, tempLabel);
tempLabel.textContent = "x";
doc.documentElement.appendChild(tempLabel);
this._inputCharWidth = tempLabel.offsetWidth;
tempLabel.parentNode.removeChild(tempLabel);
// Calculate the width of the chevron placed at the beginning of the input
// box. Remove 4 more pixels to accomodate the padding of the popup.
this._chevronWidth = +doc.defaultView.getComputedStyle(this.inputNode)
.paddingLeft.replace(/[^0-9.]/g, "") - 4;
},
/**
* The event handler that is called whenever a user switches a filter on or
* off.
*
* @private
* @param nsIDOMEvent aEvent
* The event that triggered the filter change.
*/
_toggleFilter: function WCF__toggleFilter(aEvent)
{
let target = aEvent.target;
let tagName = target.tagName;
// Prevent toggle if generated from a contextmenu event (right click)
let isRightClick = (aEvent.button === 2); // right click is button 2;
if (tagName != aEvent.currentTarget.tagName || isRightClick) {
return;
}
switch (tagName) {
case "toolbarbutton": {
let originalTarget = aEvent.originalTarget;
let classes = originalTarget.classList;
if (originalTarget.localName !== "toolbarbutton") {
// Oddly enough, the click event is sent to the menu button when
// selecting a menu item with the mouse. Detect this case and bail
// out.
break;
}
if (!classes.contains("toolbarbutton-menubutton-button") &&
originalTarget.getAttribute("type") === "menu-button") {
// This is a filter button with a drop-down. The user clicked the
// drop-down, so do nothing. (The menu will automatically appear
// without our intervention.)
break;
}
// Toggle on the targeted filter button, and if the user alt clicked,
// toggle off all other filter buttons and their associated filters.
let state = target.getAttribute("checked") !== "true";
if (aEvent.getModifierState("Alt")) {
let buttons = this.document
.querySelectorAll(".webconsole-filter-button");
Array.forEach(buttons, (button) => {
if (button !== target) {
button.setAttribute("checked", false);
button.setAttribute("aria-pressed", false);
this._setMenuState(button, false);
}
});
state = true;
}
target.setAttribute("checked", state);
target.setAttribute("aria-pressed", state);
// This is a filter button with a drop-down, and the user clicked the
// main part of the button. Go through all the severities and toggle
// their associated filters.
this._setMenuState(target, state);
// CSS reflow logging can decrease web page performance.
// Make sure the option is always unchecked when the CSS filter button is selected.
// See bug 971798.
if (target.getAttribute("category") == "css" && state) {
let csslogMenuItem = target.querySelector("menuitem[prefKey=csslog]");
csslogMenuItem.setAttribute("checked", false);
this.setFilterState("csslog", false);
}
break;
}
case "menuitem": {
let state = target.getAttribute("checked") !== "true";
target.setAttribute("checked", state);
let prefKey = target.getAttribute("prefKey");
this.setFilterState(prefKey, state);
// Disable the log response and request body if network logging is off.
if (prefKey == "networkinfo" || prefKey == "netxhr" || prefKey == "network") {
let checkState = !this.getFilterState("networkinfo") &&
!this.getFilterState("netxhr") &&
!this.getFilterState("network");
this.document.getElementById("saveBodies").disabled = checkState;
this.document.getElementById("saveBodiesContextMenu").disabled = checkState;
}
// Adjust the state of the button appropriately.
let menuPopup = target.parentNode;
let someChecked = false;
let menuItem = menuPopup.firstChild;
while (menuItem) {
if (menuItem.hasAttribute("prefKey") &&
menuItem.getAttribute("checked") === "true") {
someChecked = true;
break;
}
menuItem = menuItem.nextSibling;
}
let toolbarButton = menuPopup.parentNode;
toolbarButton.setAttribute("checked", someChecked);
toolbarButton.setAttribute("aria-pressed", someChecked);
break;
}
}
},
/**
* Set the menu attributes for a specific toggle button.
*
* @private
* @param XULElement aTarget
* Button with drop down items to be toggled.
* @param boolean aState
* True if the menu item is being toggled on, and false otherwise.
*/
_setMenuState: function WCF__setMenuState(aTarget, aState)
{
let menuItems = aTarget.querySelectorAll("menuitem");
Array.forEach(menuItems, (item) => {
item.setAttribute("checked", aState);
let prefKey = item.getAttribute("prefKey");
this.setFilterState(prefKey, aState);
});