WebCore:
[WebKit-https.git] / WebCore / inspector / front-end / Console.js
1 /*
2  * Copyright (C) 2007, 2008 Apple Inc.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer. 
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution. 
13  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission. 
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 WebInspector.Console = function()
30 {
31     this.messages = [];
32
33     WebInspector.View.call(this, document.getElementById("console"));
34
35     this.messagesElement = document.getElementById("console-messages");
36     this.messagesElement.addEventListener("selectstart", this._messagesSelectStart.bind(this), false);
37     this.messagesElement.addEventListener("click", this._messagesClicked.bind(this), true);
38
39     this.promptElement = document.getElementById("console-prompt");
40     this.promptElement.handleKeyEvent = this._promptKeyDown.bind(this);
41     this.prompt = new WebInspector.TextPrompt(this.promptElement, this.completions.bind(this), " .=:[({;");
42
43     this.toggleButton = document.getElementById("console-status-bar-item");
44     this.toggleButton.title = WebInspector.UIString("Show console.");
45     this.toggleButton.addEventListener("click", this._toggleButtonClicked.bind(this), false);
46
47     this.clearButton = document.getElementById("clear-console-status-bar-item");
48     this.clearButton.title = WebInspector.UIString("Clear console log.");
49     this.clearButton.addEventListener("click", this._clearButtonClicked.bind(this), false);
50
51     this.topGroup = new WebInspector.ConsoleGroup(null, 0);
52     this.messagesElement.insertBefore(this.topGroup.element, this.promptElement);
53     this.groupLevel = 0;
54     this.currentGroup = this.topGroup;
55
56     document.getElementById("main-status-bar").addEventListener("mousedown", this._startStatusBarDragging.bind(this), true);
57 }
58
59 WebInspector.Console.prototype = {
60     show: function()
61     {
62         if (this._animating || this.visible)
63             return;
64
65         WebInspector.View.prototype.show.call(this);
66
67         this._animating = true;
68
69         this.toggleButton.addStyleClass("toggled-on");
70         this.toggleButton.title = WebInspector.UIString("Hide console.");
71
72         document.body.addStyleClass("console-visible");
73
74         var anchoredItems = document.getElementById("anchored-status-bar-items");
75
76         var animations = [
77             {element: document.getElementById("main"), end: {bottom: this.element.offsetHeight}},
78             {element: document.getElementById("main-status-bar"), start: {"padding-left": anchoredItems.offsetWidth - 1}, end: {"padding-left": 0}},
79             {element: document.getElementById("other-console-status-bar-items"), start: {opacity: 0}, end: {opacity: 1}}
80         ];
81
82         var consoleStatusBar = document.getElementById("console-status-bar");
83         consoleStatusBar.insertBefore(anchoredItems, consoleStatusBar.firstChild);
84
85         function animationFinished()
86         {
87             if ("updateStatusBarItems" in WebInspector.currentPanel)
88                 WebInspector.currentPanel.updateStatusBarItems();
89             WebInspector.currentFocusElement = this.promptElement;
90             delete this._animating;
91         }
92
93         WebInspector.animateStyle(animations, window.event && window.event.shiftKey ? 2000 : 250, animationFinished.bind(this));
94
95         if (!this.prompt.isCaretInsidePrompt())
96             this.prompt.moveCaretToEndOfPrompt();
97     },
98
99     hide: function()
100     {
101         if (this._animating || !this.visible)
102             return;
103
104         WebInspector.View.prototype.hide.call(this);
105
106         this._animating = true;
107
108         this.toggleButton.removeStyleClass("toggled-on");
109         this.toggleButton.title = WebInspector.UIString("Show console.");
110
111         if (this.element === WebInspector.currentFocusElement || this.element.isAncestor(WebInspector.currentFocusElement))
112             WebInspector.currentFocusElement = WebInspector.previousFocusElement;
113
114         var anchoredItems = document.getElementById("anchored-status-bar-items");
115
116         // Temporally set properties and classes to mimic the post-animation values so panels
117         // like Elements in their updateStatusBarItems call will size things to fit the final location.
118         document.getElementById("main-status-bar").style.setProperty("padding-left", (anchoredItems.offsetWidth - 1) + "px");
119         document.body.removeStyleClass("console-visible");
120         if ("updateStatusBarItems" in WebInspector.currentPanel)
121             WebInspector.currentPanel.updateStatusBarItems();
122         document.body.addStyleClass("console-visible");
123
124         var animations = [
125             {element: document.getElementById("main"), end: {bottom: 0}},
126             {element: document.getElementById("main-status-bar"), start: {"padding-left": 0}, end: {"padding-left": anchoredItems.offsetWidth - 1}},
127             {element: document.getElementById("other-console-status-bar-items"), start: {opacity: 1}, end: {opacity: 0}}
128         ];
129
130         function animationFinished()
131         {
132             var mainStatusBar = document.getElementById("main-status-bar");
133             mainStatusBar.insertBefore(anchoredItems, mainStatusBar.firstChild);
134             mainStatusBar.style.removeProperty("padding-left");
135             document.body.removeStyleClass("console-visible");
136             delete this._animating;
137         }
138
139         WebInspector.animateStyle(animations, window.event && window.event.shiftKey ? 2000 : 250, animationFinished.bind(this));
140     },
141
142     addMessage: function(msg)
143     {
144         if (msg instanceof WebInspector.ConsoleMessage && !(msg instanceof WebInspector.ConsoleCommandResult)) {
145             msg.totalRepeatCount = msg.repeatCount;
146             msg.repeatDelta = msg.repeatCount;
147
148             var messageRepeated = false;
149
150             if (msg.isEqual && msg.isEqual(this.previousMessage)) {
151                 // Because sometimes we get a large number of repeated messages and sometimes
152                 // we get them one at a time, we need to know the difference between how many
153                 // repeats we used to have and how many we have now.
154                 msg.repeatDelta -= this.previousMessage.totalRepeatCount;
155
156                 if (!isNaN(this.repeatCountBeforeCommand))
157                     msg.repeatCount -= this.repeatCountBeforeCommand;
158
159                 if (!this.commandSincePreviousMessage) {
160                     // Recreate the previous message element to reset the repeat count.
161                     var messagesElement = this.currentGroup.messagesElement;
162                     messagesElement.removeChild(messagesElement.lastChild);
163                     messagesElement.appendChild(msg.toMessageElement());
164
165                     messageRepeated = true;
166                 }
167             } else
168                 delete this.repeatCountBeforeCommand;
169
170             // Increment the error or warning count
171             switch (msg.level) {
172             case WebInspector.ConsoleMessage.MessageLevel.Warning:
173                 WebInspector.warnings += msg.repeatDelta;
174                 break;
175             case WebInspector.ConsoleMessage.MessageLevel.Error:
176                 WebInspector.errors += msg.repeatDelta;
177                 break;
178             }
179
180             // Add message to the resource panel
181             if (msg.url in WebInspector.resourceURLMap) {
182                 msg.resource = WebInspector.resourceURLMap[msg.url];
183                 if (WebInspector.panels.resources)
184                     WebInspector.panels.resources.addMessageToResource(msg.resource, msg);
185             }
186
187             this.commandSincePreviousMessage = false;
188             this.previousMessage = msg;
189
190             if (messageRepeated)
191                 return;
192         } else if (msg instanceof WebInspector.ConsoleCommand) {
193             if (this.previousMessage) {
194                 this.commandSincePreviousMessage = true;
195                 this.repeatCountBeforeCommand = this.previousMessage.totalRepeatCount;
196             }
197         }
198
199         this.messages.push(msg);
200
201         if (msg.level === WebInspector.ConsoleMessage.MessageLevel.EndGroup) {
202             if (this.groupLevel < 1)
203                 return;
204
205             this.groupLevel--;
206
207             this.currentGroup = this.currentGroup.parentGroup;
208         } else {
209             if (msg.level === WebInspector.ConsoleMessage.MessageLevel.StartGroup) {
210                 this.groupLevel++;
211
212                 var group = new WebInspector.ConsoleGroup(this.currentGroup, this.groupLevel);
213                 this.currentGroup.messagesElement.appendChild(group.element);
214                 this.currentGroup = group;
215             }
216
217             this.currentGroup.addMessage(msg);
218         }
219
220         this.promptElement.scrollIntoView(false);
221     },
222
223     clearMessages: function(clearInspectorController)
224     {
225         if (clearInspectorController)
226             InspectorController.clearMessages();
227         if (WebInspector.panels.resources)
228             WebInspector.panels.resources.clearMessages();
229
230         this.messages = [];
231
232         this.groupLevel = 0;
233         this.currentGroup = this.topGroup;
234         this.topGroup.messagesElement.removeChildren();
235
236         WebInspector.errors = 0;
237         WebInspector.warnings = 0;
238
239         delete this.commandSincePreviousMessage;
240         delete this.repeatCountBeforeCommand;
241         delete this.previousMessage;
242     },
243
244     completions: function(wordRange, bestMatchOnly, completionsReadyCallback)
245     {
246         // Pass less stop characters to rangeOfWord so the range will be a more complete expression.
247         const expressionStopCharacters = " =:{;";
248         var expressionRange = wordRange.startContainer.rangeOfWord(wordRange.startOffset, expressionStopCharacters, this.promptElement, "backward");
249         var expressionString = expressionRange.toString();
250         var lastIndex = expressionString.length - 1;
251
252         var dotNotation = (expressionString[lastIndex] === ".");
253         var bracketNotation = (expressionString[lastIndex] === "[");
254
255         if (dotNotation || bracketNotation)
256             expressionString = expressionString.substr(0, lastIndex);
257
258         var prefix = wordRange.toString();
259         if (!expressionString && !prefix)
260             return;
261
262         var reportCompletions = this._reportCompletions.bind(this, bestMatchOnly, completionsReadyCallback, dotNotation, bracketNotation, prefix);
263         if (expressionString) {
264             this._evalInInspectedWindow(expressionString, reportCompletions);
265         } else {
266             // There is no expressionString, so the completion should happen against global properties.
267             // Or if the debugger is paused, against properties in scope of the selected call frame.
268             if (WebInspector.panels.scripts && WebInspector.panels.scripts.paused)
269                 reportCompletions(WebInspector.panels.scripts.variablesInScopeForSelectedCallFrame());
270             else
271                 reportCompletions(InspectorController.inspectedWindow());
272         }
273     },
274     
275     _reportCompletions: function(bestMatchOnly, completionsReadyCallback, dotNotation, bracketNotation, prefix, result) {
276         if (bracketNotation) {
277             if (prefix.length && prefix[0] === "'")
278                 var quoteUsed = "'";
279             else
280                 var quoteUsed = "\"";
281         }
282
283         var results = [];
284         var properties = Object.sortedProperties(result);
285         for (var i = 0; i < properties.length; ++i) {
286             var property = properties[i];
287
288             if (dotNotation && !/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(property))
289                 continue;
290
291             if (bracketNotation) {
292                 if (!/^[0-9]+$/.test(property))
293                     property = quoteUsed + property.escapeCharacters(quoteUsed + "\\") + quoteUsed;
294                 property += "]";
295             }
296
297             if (property.length < prefix.length)
298                 continue;
299             if (property.indexOf(prefix) !== 0)
300                 continue;
301
302             results.push(property);
303             if (bestMatchOnly)
304                 break;
305         }
306         setTimeout(completionsReadyCallback, 0, results);
307     },
308
309     _toggleButtonClicked: function()
310     {
311         this.visible = !this.visible;
312     },
313
314     _clearButtonClicked: function()
315     {
316         this.clearMessages(true);
317     },
318
319     _messagesSelectStart: function(event)
320     {
321         if (this._selectionTimeout)
322             clearTimeout(this._selectionTimeout);
323
324         this.prompt.clearAutoComplete();
325
326         function moveBackIfOutside()
327         {
328             delete this._selectionTimeout;
329             if (!this.prompt.isCaretInsidePrompt() && window.getSelection().isCollapsed)
330                 this.prompt.moveCaretToEndOfPrompt();
331             this.prompt.autoCompleteSoon();
332         }
333
334         this._selectionTimeout = setTimeout(moveBackIfOutside.bind(this), 100);
335     },
336
337     _messagesClicked: function(event)
338     {
339         var link = event.target.enclosingNodeOrSelfWithNodeName("a");
340         if (!link || !link.representedNode)
341             return;
342
343         WebInspector.updateFocusedNode(link.representedNode);
344         event.stopPropagation();
345         event.preventDefault();
346     },
347
348     _promptKeyDown: function(event)
349     {
350         switch (event.keyIdentifier) {
351             case "Enter":
352                 this._enterKeyPressed(event);
353                 return;
354         }
355
356         this.prompt.handleKeyEvent(event);
357     },
358
359     _startStatusBarDragging: function(event)
360     {
361         if (!this.visible || event.target !== document.getElementById("main-status-bar"))
362             return;
363
364         WebInspector.elementDragStart(document.getElementById("main-status-bar"), this._statusBarDragging.bind(this), this._endStatusBarDragging.bind(this), event, "row-resize");
365
366         this._statusBarDragOffset = event.pageY - this.element.totalOffsetTop;
367
368         event.stopPropagation();
369     },
370
371     _statusBarDragging: function(event)
372     {
373         var mainElement = document.getElementById("main");
374
375         var height = window.innerHeight - event.pageY + this._statusBarDragOffset;
376         height = Number.constrain(height, Preferences.minConsoleHeight, window.innerHeight - mainElement.totalOffsetTop - Preferences.minConsoleHeight);
377
378         mainElement.style.bottom = height + "px";
379         this.element.style.height = height + "px";
380
381         event.preventDefault();
382         event.stopPropagation();
383     },
384
385     _endStatusBarDragging: function(event)
386     {
387         WebInspector.elementDragEnd(event);
388
389         delete this._statusBarDragOffset;
390
391         event.stopPropagation();
392     },
393
394     _evalInInspectedWindow: function(expression, callback)
395     {
396         if (WebInspector.panels.scripts && WebInspector.panels.scripts.paused) {
397             WebInspector.panels.scripts.evaluateInSelectedCallFrame(expression, false, callback);
398             return;
399         }
400
401         this.doEvalInWindow(expression, callback);
402     },
403     
404     _ensureCommandLineAPIInstalled: function(inspectedWindow)
405     {
406         if (!inspectedWindow._inspectorCommandLineAPI) {
407             inspectedWindow.eval("window._inspectorCommandLineAPI = { \
408                 $: function() { return document.getElementById.apply(document, arguments) }, \
409                 $$: function() { return document.querySelectorAll.apply(document, arguments) }, \
410                 $x: function(xpath, context) { \
411                     var nodes = []; \
412                     try { \
413                         var doc = context || document; \
414                         var results = doc.evaluate(xpath, doc, null, XPathResult.ANY_TYPE, null); \
415                         var node; \
416                         while (node = results.iterateNext()) nodes.push(node); \
417                     } catch (e) {} \
418                     return nodes; \
419                 }, \
420                 dir: function() { return console.dir.apply(console, arguments) }, \
421                 dirxml: function() { return console.dirxml.apply(console, arguments) }, \
422                 keys: function(o) { var a = []; for (k in o) a.push(k); return a; }, \
423                 values: function(o) { var a = []; for (k in o) a.push(o[k]); return a; }, \
424                 profile: function() { return console.profile.apply(console, arguments) }, \
425                 profileEnd: function() { return console.profileEnd.apply(console, arguments) } \
426             };");
427
428             inspectedWindow._inspectorCommandLineAPI.clear = InspectorController.wrapCallback(this.clearMessages.bind(this));
429         }
430     },
431     
432     doEvalInWindow: function(expression, callback)
433     {
434         // Surround the expression in with statements to inject our command line API so that
435         // the window object properties still take more precedent than our API functions.
436         expression = "with (window._inspectorCommandLineAPI) { with (window) { " + expression + " } }";
437
438         var self = this;
439         function delayedEvaluation()
440         {
441             var inspectedWindow = InspectorController.inspectedWindow();
442             self._ensureCommandLineAPIInstalled(inspectedWindow);
443             try {
444                 callback(inspectedWindow.eval(expression));
445             } catch (e) {
446                 callback(e, true);
447             }
448         }
449         setTimeout(delayedEvaluation, 0);
450     },
451
452     _enterKeyPressed: function(event)
453     {
454         if (event.altKey)
455             return;
456
457         event.preventDefault();
458         event.stopPropagation();
459
460         this.prompt.clearAutoComplete(true);
461
462         var str = this.prompt.text;
463         if (!str.length)
464             return;
465
466         var commandMessage = new WebInspector.ConsoleCommand(str);
467         this.addMessage(commandMessage);
468
469         var self = this;
470         function printResult(result, exception)
471         {
472             self.prompt.history.push(str);
473             self.prompt.historyOffset = 0;
474             self.prompt.text = "";
475             self.addMessage(new WebInspector.ConsoleCommandResult(result, exception, commandMessage));
476         }
477         this._evalInInspectedWindow(str, printResult);
478     },
479
480     _format: function(output, forceObjectFormat)
481     {
482         var type = (forceObjectFormat ? "object" : Object.type(output, InspectorController.inspectedWindow()));
483
484         // We don't perform any special formatting on these types, so we just
485         // pass them through the simple _formatvalue function.
486         var undecoratedTypes = {
487             "undefined": 1,
488             "null": 1,
489             "boolean": 1,
490             "number": 1,
491             "date": 1,
492             "function": 1,
493         };
494
495         var formatter;
496         if (forceObjectFormat)
497             formatter = "_formatobject";
498         else if (type in undecoratedTypes)
499             formatter = "_formatvalue";
500         else {
501             formatter = "_format" + type;
502             if (!(formatter in this)) {
503                 formatter = "_formatobject";
504                 type = "object";
505             }
506         }
507
508         var span = document.createElement("span");
509         span.addStyleClass("console-formatted-" + type);
510         this[formatter](output, span);
511         return span;
512     },
513
514     _formatvalue: function(val, elem)
515     {
516         elem.appendChild(document.createTextNode(val));
517     },
518
519     _formatstring: function(str, elem)
520     {
521         elem.appendChild(document.createTextNode("\"" + str + "\""));
522     },
523
524     _formatregexp: function(re, elem)
525     {
526         var formatted = String(re).replace(/([\\\/])/g, "\\$1").replace(/\\(\/[gim]*)$/, "$1").substring(1);
527         elem.appendChild(document.createTextNode(formatted));
528     },
529
530     _formatarray: function(arr, elem)
531     {
532         elem.appendChild(document.createTextNode("["));
533         for (var i = 0; i < arr.length; ++i) {
534             elem.appendChild(this._format(arr[i]));
535             if (i < arr.length - 1)
536                 elem.appendChild(document.createTextNode(", "));
537         }
538         elem.appendChild(document.createTextNode("]"));
539     },
540
541     _formatnode: function(node, elem)
542     {
543         var treeOutline = new WebInspector.ElementsTreeOutline();
544         treeOutline.rootDOMNode = node;
545         treeOutline.element.addStyleClass("outline-disclosure");
546         if (!treeOutline.children[0].hasChildren)
547             treeOutline.element.addStyleClass("single-node");
548         elem.appendChild(treeOutline.element);
549     },
550
551     _formatobject: function(obj, elem)
552     {
553         elem.appendChild(new WebInspector.ObjectPropertiesSection(obj, null, null, null, true).element);
554     },
555
556     _formaterror: function(obj, elem)
557     {
558         var messageElement = document.createElement("span");
559         messageElement.className = "error-message";
560         messageElement.textContent = obj.name + ": " + obj.message;
561         elem.appendChild(messageElement);
562
563         if (obj.sourceURL) {
564             var urlElement = document.createElement("a");
565             urlElement.className = "webkit-html-resource-link";
566             urlElement.href = obj.sourceURL;
567             urlElement.lineNumber = obj.line;
568             urlElement.preferredPanel = "scripts";
569
570             if (obj.line > 0)
571                 urlElement.textContent = WebInspector.displayNameForURL(obj.sourceURL) + ":" + obj.line;
572             else
573                 urlElement.textContent = WebInspector.displayNameForURL(obj.sourceURL);
574
575             elem.appendChild(document.createTextNode(" ("));
576             elem.appendChild(urlElement);
577             elem.appendChild(document.createTextNode(")"));
578         }
579     },
580 }
581
582 WebInspector.Console.prototype.__proto__ = WebInspector.View.prototype;
583
584 WebInspector.ConsoleMessage = function(source, level, line, url, groupLevel, repeatCount)
585 {
586     this.source = source;
587     this.level = level;
588     this.line = line;
589     this.url = url;
590     this.groupLevel = groupLevel;
591     this.repeatCount = repeatCount;
592     if (arguments.length > 6)
593         this.setMessageBody(Array.prototype.slice.call(arguments, 6));
594 }
595
596 WebInspector.ConsoleMessage.prototype = {
597     setMessageBody: function(args)
598     {
599         switch (this.level) {
600             case WebInspector.ConsoleMessage.MessageLevel.Trace:
601                 var span = document.createElement("span");
602                 span.addStyleClass("console-formatted-trace");
603                 var stack = Array.prototype.slice.call(args);
604                 var funcNames = stack.map(function(f) {
605                     return f || WebInspector.UIString("(anonymous function)");
606                 });
607                 span.appendChild(document.createTextNode(funcNames.join("\n")));
608                 this.formattedMessage = span;
609                 break;
610             case WebInspector.ConsoleMessage.MessageLevel.Object:
611                 this.formattedMessage = this._format(["%O", args[0]]);
612                 break;
613             default:
614                 this.formattedMessage = this._format(args);
615                 break;
616         }
617
618         // This is used for inline message bubbles in SourceFrames, or other plain-text representations.
619         this.message = this.formattedMessage.textContent;
620     },
621
622     isErrorOrWarning: function()
623     {
624         return (this.level === WebInspector.ConsoleMessage.MessageLevel.Warning || this.level === WebInspector.ConsoleMessage.MessageLevel.Error);
625     },
626
627     _format: function(parameters)
628     {
629         var formattedResult = document.createElement("span");
630
631         if (!parameters.length)
632             return formattedResult;
633
634         function formatForConsole(obj)
635         {
636             return WebInspector.console._format(obj);
637         }
638
639         function formatAsObjectForConsole(obj)
640         {
641             return WebInspector.console._format(obj, true);
642         }
643
644         if (Object.type(parameters[0], InspectorController.inspectedWindow()) === "string") {
645             var formatters = {}
646             for (var i in String.standardFormatters)
647                 formatters[i] = String.standardFormatters[i];
648
649             // Firebug uses %o for formatting objects.
650             formatters.o = formatForConsole;
651             // Firebug allows both %i and %d for formatting integers.
652             formatters.i = formatters.d;
653             // Support %O to force object formating, instead of the type-based %o formatting.
654             formatters.O = formatAsObjectForConsole;
655
656             function append(a, b)
657             {
658                 if (!(b instanceof Node))
659                     a.appendChild(WebInspector.linkifyStringAsFragment(b.toString()));
660                 else
661                     a.appendChild(b);
662                 return a;
663             }
664
665             var result = String.format(parameters[0], parameters.slice(1), formatters, formattedResult, append);
666             formattedResult = result.formattedResult;
667             parameters = result.unusedSubstitutions;
668             if (parameters.length)
669                 formattedResult.appendChild(document.createTextNode(" "));
670         }
671
672         for (var i = 0; i < parameters.length; ++i) {
673             if (typeof parameters[i] === "string")
674                 formattedResult.appendChild(WebInspector.linkifyStringAsFragment(parameters[i]));
675             else
676                 formattedResult.appendChild(formatForConsole(parameters[i]));
677
678             if (i < parameters.length - 1)
679                 formattedResult.appendChild(document.createTextNode(" "));
680         }
681
682         return formattedResult;
683     },
684
685     toMessageElement: function()
686     {
687         if (this.propertiesSection)
688             return this.propertiesSection.element;
689
690         var element = document.createElement("div");
691         element.message = this;
692         element.className = "console-message";
693
694         switch (this.source) {
695             case WebInspector.ConsoleMessage.MessageSource.HTML:
696                 element.addStyleClass("console-html-source");
697                 break;
698             case WebInspector.ConsoleMessage.MessageSource.WML:
699                 element.addStyleClass("console-wml-source");
700                 break;
701             case WebInspector.ConsoleMessage.MessageSource.XML:
702                 element.addStyleClass("console-xml-source");
703                 break;
704             case WebInspector.ConsoleMessage.MessageSource.JS:
705                 element.addStyleClass("console-js-source");
706                 break;
707             case WebInspector.ConsoleMessage.MessageSource.CSS:
708                 element.addStyleClass("console-css-source");
709                 break;
710             case WebInspector.ConsoleMessage.MessageSource.Other:
711                 element.addStyleClass("console-other-source");
712                 break;
713         }
714
715         switch (this.level) {
716             case WebInspector.ConsoleMessage.MessageLevel.Tip:
717                 element.addStyleClass("console-tip-level");
718                 break;
719             case WebInspector.ConsoleMessage.MessageLevel.Log:
720                 element.addStyleClass("console-log-level");
721                 break;
722             case WebInspector.ConsoleMessage.MessageLevel.Warning:
723                 element.addStyleClass("console-warning-level");
724                 break;
725             case WebInspector.ConsoleMessage.MessageLevel.Error:
726                 element.addStyleClass("console-error-level");
727                 break;
728             case WebInspector.ConsoleMessage.MessageLevel.StartGroup:
729                 element.addStyleClass("console-group-title-level");
730         }
731
732         if (this.elementsTreeOutline) {
733             element.addStyleClass("outline-disclosure");
734             element.appendChild(this.elementsTreeOutline.element);
735             return element;
736         }
737
738         if (this.repeatCount > 1) {
739             var messageRepeatCountElement = document.createElement("span");
740             messageRepeatCountElement.className = "bubble";
741             messageRepeatCountElement.textContent = this.repeatCount;
742
743             element.appendChild(messageRepeatCountElement);
744             element.addStyleClass("repeated-message");
745         }
746
747         if (this.url && this.url !== "undefined") {
748             var urlElement = document.createElement("a");
749             urlElement.className = "console-message-url webkit-html-resource-link";
750             urlElement.href = this.url;
751             urlElement.lineNumber = this.line;
752
753             if (this.source === WebInspector.ConsoleMessage.MessageSource.JS)
754                 urlElement.preferredPanel = "scripts";
755
756             if (this.line > 0)
757                 urlElement.textContent = WebInspector.displayNameForURL(this.url) + ":" + this.line;
758             else
759                 urlElement.textContent = WebInspector.displayNameForURL(this.url);
760
761             element.appendChild(urlElement);
762         }
763
764         var messageTextElement = document.createElement("span");
765         messageTextElement.className = "console-message-text";
766         messageTextElement.appendChild(this.formattedMessage);
767         element.appendChild(messageTextElement);
768
769         return element;
770     },
771
772     toString: function()
773     {
774         var sourceString;
775         switch (this.source) {
776             case WebInspector.ConsoleMessage.MessageSource.HTML:
777                 sourceString = "HTML";
778                 break;
779             case WebInspector.ConsoleMessage.MessageSource.WML:
780                 sourceString = "WML";
781                 break;
782             case WebInspector.ConsoleMessage.MessageSource.XML:
783                 sourceString = "XML";
784                 break;
785             case WebInspector.ConsoleMessage.MessageSource.JS:
786                 sourceString = "JS";
787                 break;
788             case WebInspector.ConsoleMessage.MessageSource.CSS:
789                 sourceString = "CSS";
790                 break;
791             case WebInspector.ConsoleMessage.MessageSource.Other:
792                 sourceString = "Other";
793                 break;
794         }
795
796         var levelString;
797         switch (this.level) {
798             case WebInspector.ConsoleMessage.MessageLevel.Tip:
799                 levelString = "Tip";
800                 break;
801             case WebInspector.ConsoleMessage.MessageLevel.Log:
802                 levelString = "Log";
803                 break;
804             case WebInspector.ConsoleMessage.MessageLevel.Warning:
805                 levelString = "Warning";
806                 break;
807             case WebInspector.ConsoleMessage.MessageLevel.Error:
808                 levelString = "Error";
809                 break;
810             case WebInspector.ConsoleMessage.MessageLevel.Object:
811                 levelString = "Object";
812                 break;
813             case WebInspector.ConsoleMessage.MessageLevel.Trace:
814                 levelString = "Trace";
815                 break;
816             case WebInspector.ConsoleMessage.MessageLevel.StartGroup:
817                 levelString = "Start Group";
818                 break;
819             case WebInspector.ConsoleMessage.MessageLevel.EndGroup:
820                 levelString = "End Group";
821                 break;
822         }
823
824         return sourceString + " " + levelString + ": " + this.formattedMessage.textContent + "\n" + this.url + " line " + this.line;
825     },
826
827     isEqual: function(msg, disreguardGroup)
828     {
829         if (!msg)
830             return false;
831
832         var ret = (this.source == msg.source)
833             && (this.level == msg.level)
834             && (this.line == msg.line)
835             && (this.url == msg.url)
836             && (this.message == msg.message);
837
838         return (disreguardGroup ? ret : (ret && (this.groupLevel == msg.groupLevel)));
839     }
840 }
841
842 // Note: Keep these constants in sync with the ones in Console.h
843 WebInspector.ConsoleMessage.MessageSource = {
844     HTML: 0,
845     WML: 1,
846     XML: 2,
847     JS: 3,
848     CSS: 4,
849     Other: 5
850 }
851
852 WebInspector.ConsoleMessage.MessageLevel = {
853     Tip: 0,
854     Log: 1,
855     Warning: 2,
856     Error: 3,
857     Object: 4,
858     Trace: 5,
859     StartGroup: 6,
860     EndGroup: 7
861 }
862
863 WebInspector.ConsoleCommand = function(command)
864 {
865     this.command = command;
866 }
867
868 WebInspector.ConsoleCommand.prototype = {
869     toMessageElement: function()
870     {
871         var element = document.createElement("div");
872         element.command = this;
873         element.className = "console-user-command";
874
875         var commandTextElement = document.createElement("span");
876         commandTextElement.className = "console-message-text";
877         commandTextElement.textContent = this.command;
878         element.appendChild(commandTextElement);
879
880         return element;
881     }
882 }
883
884 WebInspector.ConsoleCommandResult = function(result, exception, originatingCommand)
885 {
886     var level = (exception ? WebInspector.ConsoleMessage.MessageLevel.Error : WebInspector.ConsoleMessage.MessageLevel.Log);
887     var message = (exception ? String(result) : result);
888     var line = (exception ? result.line : -1);
889     var url = (exception ? result.sourceURL : null);
890
891     WebInspector.ConsoleMessage.call(this, WebInspector.ConsoleMessage.MessageSource.JS, level, line, url, null, 1, message);
892
893     this.originatingCommand = originatingCommand;
894 }
895
896 WebInspector.ConsoleCommandResult.prototype = {
897     toMessageElement: function()
898     {
899         var element = WebInspector.ConsoleMessage.prototype.toMessageElement.call(this);
900         element.addStyleClass("console-user-command-result");
901         return element;
902     }
903 }
904
905 WebInspector.ConsoleCommandResult.prototype.__proto__ = WebInspector.ConsoleMessage.prototype;
906
907 WebInspector.ConsoleGroup = function(parentGroup, level)
908 {
909     this.parentGroup = parentGroup;
910     this.level = level;
911
912     var element = document.createElement("div");
913     element.className = "console-group";
914     element.group = this;
915     this.element = element;
916
917     var messagesElement = document.createElement("div");
918     messagesElement.className = "console-group-messages";
919     element.appendChild(messagesElement);
920     this.messagesElement = messagesElement;
921 }
922
923 WebInspector.ConsoleGroup.prototype = {
924     addMessage: function(msg)
925     {
926         var element = msg.toMessageElement();
927         
928         if (msg.level === WebInspector.ConsoleMessage.MessageLevel.StartGroup) {
929             this.messagesElement.parentNode.insertBefore(element, this.messagesElement);
930             element.addEventListener("click", this._titleClicked.bind(this), true);
931         } else
932             this.messagesElement.appendChild(element);
933
934         if (element.previousSibling && msg.originatingCommand && element.previousSibling.command === msg.originatingCommand)
935             element.previousSibling.addStyleClass("console-adjacent-user-command-result");
936     },
937
938     _titleClicked: function(event)
939     {
940         var groupTitleElement = event.target.enclosingNodeOrSelfWithClass("console-group-title-level");
941         if (groupTitleElement) {
942             var groupElement = groupTitleElement.enclosingNodeOrSelfWithClass("console-group");
943             if (groupElement)
944                 if (groupElement.hasStyleClass("collapsed"))
945                     groupElement.removeStyleClass("collapsed");
946                 else
947                     groupElement.addStyleClass("collapsed");
948             groupTitleElement.scrollIntoViewIfNeeded(true);
949         }
950
951         event.stopPropagation();
952         event.preventDefault();
953     }
954 }