eecf5e45845d6ded5737523bb8c7eb64b4f1ce6b
[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) {
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                 WebInspector.panels.resources.addMessageToResource(msg.resource, msg);
184             }
185
186             this.commandSincePreviousMessage = false;
187             this.previousMessage = msg;
188
189             if (messageRepeated)
190                 return;
191         } else if (msg instanceof WebInspector.ConsoleCommand) {
192             if (this.previousMessage) {
193                 this.commandSincePreviousMessage = true;
194                 this.repeatCountBeforeCommand = this.previousMessage.totalRepeatCount;
195             }
196         }
197
198         this.messages.push(msg);
199
200         if (msg.level === WebInspector.ConsoleMessage.MessageLevel.EndGroup) {
201             if (this.groupLevel < 1)
202                 return;
203
204             this.groupLevel--;
205
206             this.currentGroup = this.currentGroup.parentGroup;
207         } else {
208             if (msg.level === WebInspector.ConsoleMessage.MessageLevel.StartGroup) {
209                 this.groupLevel++;
210
211                 var group = new WebInspector.ConsoleGroup(this.currentGroup, this.groupLevel);
212                 this.currentGroup.messagesElement.appendChild(group.element);
213                 this.currentGroup = group;
214             }
215
216             this.currentGroup.addMessage(msg);
217         }
218
219         this.promptElement.scrollIntoView(false);
220     },
221
222     clearMessages: function(clearInspectorController)
223     {
224         if (clearInspectorController)
225             InspectorController.clearMessages();
226         WebInspector.panels.resources.clearMessages();
227
228         this.messages = [];
229
230         this.groupLevel = 0;
231         this.currentGroup = this.topGroup;
232         this.topGroup.messagesElement.removeChildren();
233
234         WebInspector.errors = 0;
235         WebInspector.warnings = 0;
236
237         delete this.commandSincePreviousMessage;
238         delete this.repeatCountBeforeCommand;
239         delete this.previousMessage;
240     },
241
242     completions: function(wordRange, bestMatchOnly)
243     {
244         // Pass less stop characters to rangeOfWord so the range will be a more complete expression.
245         const expressionStopCharacters = " =:{;";
246         var expressionRange = wordRange.startContainer.rangeOfWord(wordRange.startOffset, expressionStopCharacters, this.promptElement, "backward");
247         var expressionString = expressionRange.toString();
248         var lastIndex = expressionString.length - 1;
249
250         var dotNotation = (expressionString[lastIndex] === ".");
251         var bracketNotation = (expressionString[lastIndex] === "[");
252
253         if (dotNotation || bracketNotation)
254             expressionString = expressionString.substr(0, lastIndex);
255
256         var prefix = wordRange.toString();
257         if (!expressionString && !prefix)
258             return;
259
260         var result;
261         if (expressionString) {
262             try {
263                 result = this._evalInInspectedWindow(expressionString);
264             } catch(e) {
265                 // Do nothing, the prefix will be considered a window property.
266             }
267         } else {
268             // There is no expressionString, so the completion should happen against global properties.
269             // Or if the debugger is paused, against properties in scope of the selected call frame.
270             if (WebInspector.panels.scripts.paused)
271                 result = WebInspector.panels.scripts.variablesInScopeForSelectedCallFrame();
272             else
273                 result = InspectorController.inspectedWindow();
274         }
275
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             if (bracketNotation)
288                 property = quoteUsed + property.escapeCharacters(quoteUsed + "\\") + quoteUsed + "]";
289             if (property.length < prefix.length)
290                 continue;
291             if (property.indexOf(prefix) !== 0)
292                 continue;
293             results.push(property);
294             if (bestMatchOnly)
295                 break;
296         }
297
298         return results;
299     },
300
301     _toggleButtonClicked: function()
302     {
303         this.visible = !this.visible;
304     },
305
306     _clearButtonClicked: function()
307     {
308         this.clearMessages(true);
309     },
310
311     _messagesSelectStart: function(event)
312     {
313         if (this._selectionTimeout)
314             clearTimeout(this._selectionTimeout);
315
316         this.prompt.clearAutoComplete();
317
318         function moveBackIfOutside()
319         {
320             delete this._selectionTimeout;
321             if (!this.prompt.isCaretInsidePrompt() && window.getSelection().isCollapsed)
322                 this.prompt.moveCaretToEndOfPrompt();
323             this.prompt.autoCompleteSoon();
324         }
325
326         this._selectionTimeout = setTimeout(moveBackIfOutside.bind(this), 100);
327     },
328
329     _messagesClicked: function(event)
330     {
331         var link = event.target.enclosingNodeOrSelfWithNodeName("a");
332         if (!link || !link.representedNode)
333             return;
334
335         WebInspector.updateFocusedNode(link.representedNode);
336         event.stopPropagation();
337         event.preventDefault();
338     },
339
340     _promptKeyDown: function(event)
341     {
342         switch (event.keyIdentifier) {
343             case "Enter":
344                 this._enterKeyPressed(event);
345                 return;
346         }
347
348         this.prompt.handleKeyEvent(event);
349     },
350
351     _startStatusBarDragging: function(event)
352     {
353         if (!this.visible || event.target !== document.getElementById("main-status-bar"))
354             return;
355
356         WebInspector.elementDragStart(document.getElementById("main-status-bar"), this._statusBarDragging.bind(this), this._endStatusBarDragging.bind(this), event, "row-resize");
357
358         this._statusBarDragOffset = event.pageY - this.element.totalOffsetTop;
359
360         event.stopPropagation();
361     },
362
363     _statusBarDragging: function(event)
364     {
365         var mainElement = document.getElementById("main");
366
367         var height = window.innerHeight - event.pageY + this._statusBarDragOffset;
368         height = Number.constrain(height, Preferences.minConsoleHeight, window.innerHeight - mainElement.totalOffsetTop - Preferences.minConsoleHeight);
369
370         mainElement.style.bottom = height + "px";
371         this.element.style.height = height + "px";
372
373         event.preventDefault();
374         event.stopPropagation();
375     },
376
377     _endStatusBarDragging: function(event)
378     {
379         WebInspector.elementDragEnd(event);
380
381         delete this._statusBarDragOffset;
382
383         event.stopPropagation();
384     },
385
386     _evalInInspectedWindow: function(expression)
387     {
388         if (WebInspector.panels.scripts.paused)
389             return WebInspector.panels.scripts.evaluateInSelectedCallFrame(expression);
390
391         var inspectedWindow = InspectorController.inspectedWindow();
392         if (!inspectedWindow._inspectorCommandLineAPI) {
393             inspectedWindow.eval("window._inspectorCommandLineAPI = { \
394                 $: function() { return document.getElementById.apply(document, arguments) }, \
395                 $$: function() { return document.querySelectorAll.apply(document, arguments) }, \
396                 $x: function(xpath, context) { \
397                     var nodes = []; \
398                     try { \
399                         var doc = context || document; \
400                         var results = doc.evaluate(xpath, doc, null, XPathResult.ANY_TYPE, null); \
401                         var node; \
402                         while (node = results.iterateNext()) nodes.push(node); \
403                     } catch (e) {} \
404                     return nodes; \
405                 }, \
406                 dir: function() { return console.dir.apply(console, arguments) }, \
407                 dirxml: function() { return console.dirxml.apply(console, arguments) }, \
408                 keys: function(o) { var a = []; for (k in o) a.push(k); return a; }, \
409                 values: function(o) { var a = []; for (k in o) a.push(o[k]); return a; }, \
410                 profile: function() { return console.profile.apply(console, arguments) }, \
411                 profileEnd: function() { return console.profileEnd.apply(console, arguments) } \
412             };");
413
414             inspectedWindow._inspectorCommandLineAPI.clear = InspectorController.wrapCallback(this.clearMessages.bind(this));
415         }
416
417         // Surround the expression in with statements to inject our command line API so that
418         // the window object properties still take more precedent than our API functions.
419         expression = "with (window._inspectorCommandLineAPI) { with (window) { " + expression + " } }";
420
421         return inspectedWindow.eval(expression);
422     },
423
424     _enterKeyPressed: function(event)
425     {
426         if (event.altKey)
427             return;
428
429         event.preventDefault();
430         event.stopPropagation();
431
432         this.prompt.clearAutoComplete(true);
433
434         var str = this.prompt.text;
435         if (!str.length)
436             return;
437
438         var result;
439         var exception = false;
440         try {
441             result = this._evalInInspectedWindow(str);
442         } catch(e) {
443             result = e;
444             exception = true;
445         }
446
447         this.prompt.history.push(str);
448         this.prompt.historyOffset = 0;
449         this.prompt.text = "";
450
451         var level = exception ? WebInspector.ConsoleMessage.MessageLevel.Error : WebInspector.ConsoleMessage.MessageLevel.Log;
452         this.addMessage(new WebInspector.ConsoleCommand(str, result, this._format(result), level));
453     },
454
455     _mouseOverNode: function(event)
456     {
457         var anchorElement = event.target.enclosingNodeOrSelfWithNodeName("a");
458         WebInspector.hoveredDOMNode = (anchorElement ? anchorElement.representedNode : null);
459     },
460
461     _mouseOutOfNode: function(event)
462     {
463         var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY);
464         var anchorElement = nodeUnderMouse.enclosingNodeOrSelfWithNodeName("a");
465         if (!anchorElement || !anchorElement.representedNode)
466             WebInspector.hoveredDOMNode = null;
467     },
468
469     _format: function(output)
470     {
471         var type = Object.type(output, InspectorController.inspectedWindow());
472         if (type === "object") {
473             if (output instanceof InspectorController.inspectedWindow().Node)
474                 type = "node";
475         }
476
477         // We don't perform any special formatting on these types, so we just
478         // pass them through the simple _formatvalue function.
479         var undecoratedTypes = {
480             "undefined": 1,
481             "null": 1,
482             "boolean": 1,
483             "number": 1,
484             "date": 1,
485             "function": 1,
486         };
487
488         var formatter;
489         if (type in undecoratedTypes)
490             formatter = "_formatvalue";
491         else {
492             formatter = "_format" + type;
493             if (!(formatter in this)) {
494                 formatter = "_formatobject";
495                 type = "object";
496             }
497         }
498
499         var span = document.createElement("span");
500         span.addStyleClass("console-formatted-" + type);
501         this[formatter](output, span);
502         return span;
503     },
504
505     _formatvalue: function(val, elem)
506     {
507         elem.appendChild(document.createTextNode(val));
508     },
509
510     _formatstring: function(str, elem)
511     {
512         elem.appendChild(document.createTextNode("\"" + str + "\""));
513     },
514
515     _formatregexp: function(re, elem)
516     {
517         var formatted = String(re).replace(/([\\\/])/g, "\\$1").replace(/\\(\/[gim]*)$/, "$1").substring(1);
518         elem.appendChild(document.createTextNode(formatted));
519     },
520
521     _formatarray: function(arr, elem)
522     {
523         elem.appendChild(document.createTextNode("["));
524         for (var i = 0; i < arr.length; ++i) {
525             elem.appendChild(this._format(arr[i]));
526             if (i < arr.length - 1)
527                 elem.appendChild(document.createTextNode(", "));
528         }
529         elem.appendChild(document.createTextNode("]"));
530     },
531
532     _formatnode: function(node, elem)
533     {
534         var anchor = document.createElement("a");
535         anchor.className = "inspectible-node";
536         anchor.innerHTML = nodeTitleInfo.call(node).title;
537         anchor.representedNode = node;
538         anchor.addEventListener("mouseover", this._mouseOverNode.bind(this), false);
539         anchor.addEventListener("mouseout", this._mouseOutOfNode.bind(this), false);
540         elem.appendChild(anchor);
541     },
542
543     _formatobject: function(obj, elem)
544     {
545         elem.appendChild(document.createTextNode(Object.describe(obj)));
546     },
547
548     _formaterror: function(obj, elem)
549     {
550         elem.appendChild(document.createTextNode(obj.name + ": " + obj.message + " "));
551
552         if (obj.sourceURL) {
553             var urlElement = document.createElement("a");
554             urlElement.className = "console-message-url webkit-html-resource-link";
555             urlElement.href = obj.sourceURL;
556             urlElement.lineNumber = obj.line;
557             urlElement.preferredPanel = "scripts";
558
559             if (obj.line > 0)
560                 urlElement.textContent = WebInspector.UIString("%s (line %d)", obj.sourceURL, obj.line);
561             else
562                 urlElement.textContent = obj.sourceURL;
563
564             elem.appendChild(urlElement);
565         }
566     },
567 }
568
569 WebInspector.Console.prototype.__proto__ = WebInspector.View.prototype;
570
571 WebInspector.ConsoleMessage = function(source, level, line, url, groupLevel, repeatCount)
572 {
573     this.source = source;
574     this.level = level;
575     this.line = line;
576     this.url = url;
577     this.groupLevel = groupLevel;
578     this.repeatCount = repeatCount;
579
580     switch (this.level) {
581         case WebInspector.ConsoleMessage.MessageLevel.Object:
582             var propertiesSection = new WebInspector.ObjectPropertiesSection(arguments[6], null, null, null, true);
583             propertiesSection.element.addStyleClass("console-message");
584             this.propertiesSection = propertiesSection;
585             break;
586         case WebInspector.ConsoleMessage.MessageLevel.Node:
587             var node = arguments[6];
588             if (!(node instanceof InspectorController.inspectedWindow().Node))
589                 return;
590             this.elementsTreeOutline = new WebInspector.ElementsTreeOutline();
591             this.elementsTreeOutline.rootDOMNode = node;
592             break;
593         case WebInspector.ConsoleMessage.MessageLevel.Trace:
594             var span = document.createElement("span");
595             span.addStyleClass("console-formatted-trace");
596             var stack = Array.prototype.slice.call(arguments, 6);
597             var funcNames = stack.map(function(f) {
598                 return f.name || WebInspector.UIString("(anonymous function)");
599             });
600             span.appendChild(document.createTextNode(funcNames.join("\n")));
601             this.formattedMessage = span;
602             break;
603         default:
604             // The formatedMessage property is used for the rich and interactive console.
605             this.formattedMessage = this._format(Array.prototype.slice.call(arguments, 6));
606
607             // This is used for inline message bubbles in SourceFrames, or other plain-text representations.
608             this.message = this.formattedMessage.textContent;
609             break;
610     }
611 }
612
613 WebInspector.ConsoleMessage.prototype = {
614     isErrorOrWarning: function()
615     {
616         return (this.level === WebInspector.ConsoleMessage.MessageLevel.Warning || this.level === WebInspector.ConsoleMessage.MessageLevel.Error);
617     },
618
619     _format: function(parameters)
620     {
621         var formattedResult = document.createElement("span");
622
623         if (!parameters.length)
624             return formattedResult;
625
626         function formatForConsole(obj)
627         {
628             return WebInspector.console._format(obj);
629         }
630
631         if (Object.type(parameters[0], InspectorController.inspectedWindow()) === "string") {
632             var formatters = {}
633             for (var i in String.standardFormatters)
634                 formatters[i] = String.standardFormatters[i];
635
636             // Firebug uses %o for formatting objects.
637             formatters.o = formatForConsole;
638             // Firebug allows both %i and %d for formatting integers.
639             formatters.i = formatters.d;
640
641             function append(a, b)
642             {
643                 if (!(b instanceof Node))
644                     a.appendChild(WebInspector.linkifyStringAsFragment(b.toString()));
645                 else
646                     a.appendChild(b);
647                 return a;
648             }
649
650             var result = String.format(parameters[0], parameters.slice(1), formatters, formattedResult, append);
651             formattedResult = result.formattedResult;
652             parameters = result.unusedSubstitutions;
653             if (parameters.length)
654                 formattedResult.appendChild(document.createTextNode(" "));
655         }
656
657         for (var i = 0; i < parameters.length; ++i) {
658             if (typeof parameters[i] === "string")
659                 formattedResult.appendChild(WebInspector.linkifyStringAsFragment(parameters[i]));
660             else
661                 formattedResult.appendChild(formatForConsole(parameters[i]));
662             if (i < parameters.length - 1)
663                 formattedResult.appendChild(document.createTextNode(" "));
664         }
665
666         return formattedResult;
667     },
668
669     toMessageElement: function()
670     {
671         if (this.propertiesSection)
672             return this.propertiesSection.element;
673
674         var element = document.createElement("div");
675         element.message = this;
676         element.className = "console-message";
677
678         switch (this.source) {
679             case WebInspector.ConsoleMessage.MessageSource.HTML:
680                 element.addStyleClass("console-html-source");
681                 break;
682             case WebInspector.ConsoleMessage.MessageSource.XML:
683                 element.addStyleClass("console-xml-source");
684                 break;
685             case WebInspector.ConsoleMessage.MessageSource.JS:
686                 element.addStyleClass("console-js-source");
687                 break;
688             case WebInspector.ConsoleMessage.MessageSource.CSS:
689                 element.addStyleClass("console-css-source");
690                 break;
691             case WebInspector.ConsoleMessage.MessageSource.Other:
692                 element.addStyleClass("console-other-source");
693                 break;
694         }
695
696         switch (this.level) {
697             case WebInspector.ConsoleMessage.MessageLevel.Tip:
698                 element.addStyleClass("console-tip-level");
699                 break;
700             case WebInspector.ConsoleMessage.MessageLevel.Log:
701                 element.addStyleClass("console-log-level");
702                 break;
703             case WebInspector.ConsoleMessage.MessageLevel.Warning:
704                 element.addStyleClass("console-warning-level");
705                 break;
706             case WebInspector.ConsoleMessage.MessageLevel.Error:
707                 element.addStyleClass("console-error-level");
708                 break;
709             case WebInspector.ConsoleMessage.MessageLevel.StartGroup:
710                 element.addStyleClass("console-group-title-level");
711         }
712
713         if (this.elementsTreeOutline) {
714             element.addStyleClass("outline-disclosure");
715             element.appendChild(this.elementsTreeOutline.element);
716             return element;
717         }
718
719         if (this.repeatCount > 1) {
720             var messageRepeatCountElement = document.createElement("span");
721             messageRepeatCountElement.className = "bubble";
722             messageRepeatCountElement.textContent = this.repeatCount;
723
724             element.appendChild(messageRepeatCountElement);
725             element.addStyleClass("repeated-message");
726         }
727
728         if (this.url && this.url !== "undefined") {
729             var urlElement = document.createElement("a");
730             urlElement.className = "console-message-url webkit-html-resource-link";
731             urlElement.href = this.url;
732             urlElement.lineNumber = this.line;
733
734             if (this.source === WebInspector.ConsoleMessage.MessageSource.JS)
735                 urlElement.preferredPanel = "scripts";
736
737             if (this.line > 0)
738                 urlElement.textContent = WebInspector.UIString("%s (line %d)", WebInspector.displayNameForURL(this.url), this.line);
739             else
740                 urlElement.textContent = WebInspector.displayNameForURL(this.url);
741
742             element.appendChild(urlElement);
743         }
744
745         var messageTextElement = document.createElement("span");
746         messageTextElement.className = "console-message-text";
747         messageTextElement.appendChild(this.formattedMessage);
748         element.appendChild(messageTextElement);
749
750         return element;
751     },
752
753     toString: function()
754     {
755         var sourceString;
756         switch (this.source) {
757             case WebInspector.ConsoleMessage.MessageSource.HTML:
758                 sourceString = "HTML";
759                 break;
760             case WebInspector.ConsoleMessage.MessageSource.XML:
761                 sourceString = "XML";
762                 break;
763             case WebInspector.ConsoleMessage.MessageSource.JS:
764                 sourceString = "JS";
765                 break;
766             case WebInspector.ConsoleMessage.MessageSource.CSS:
767                 sourceString = "CSS";
768                 break;
769             case WebInspector.ConsoleMessage.MessageSource.Other:
770                 sourceString = "Other";
771                 break;
772         }
773
774         var levelString;
775         switch (this.level) {
776             case WebInspector.ConsoleMessage.MessageLevel.Tip:
777                 levelString = "Tip";
778                 break;
779             case WebInspector.ConsoleMessage.MessageLevel.Log:
780                 levelString = "Log";
781                 break;
782             case WebInspector.ConsoleMessage.MessageLevel.Warning:
783                 levelString = "Warning";
784                 break;
785             case WebInspector.ConsoleMessage.MessageLevel.Error:
786                 levelString = "Error";
787                 break;
788             case WebInspector.ConsoleMessage.MessageLevel.Object:
789                 levelString = "Object";
790                 break;
791             case WebInspector.ConsoleMessage.MessageLevel.GroupTitle:
792                 levelString = "GroupTitle";
793                 break;
794         }
795
796         return sourceString + " " + levelString + ": " + this.formattedMessage.textContent + "\n" + this.url + " line " + this.line;
797     },
798     
799     isEqual: function(msg, disreguardGroup)
800     {
801         if (!msg)
802             return false;
803
804         var ret = (this.source == msg.source)
805             && (this.level == msg.level)
806             && (this.line == msg.line)
807             && (this.url == msg.url)
808             && (this.message == msg.message);
809
810         return (disreguardGroup ? ret : (ret && (this.groupLevel == msg.groupLevel)));
811     }
812 }
813
814 // Note: Keep these constants in sync with the ones in Chrome.h
815 WebInspector.ConsoleMessage.MessageSource = {
816     HTML: 0,
817     XML: 1,
818     JS: 2,
819     CSS: 3,
820     Other: 4,
821 }
822
823 WebInspector.ConsoleMessage.MessageLevel = {
824     Tip: 0,
825     Log: 1,
826     Warning: 2,
827     Error: 3,
828     Object: 4,
829     Node: 5,
830     Trace: 6,
831     StartGroup: 7,
832     EndGroup: 8
833 }
834
835 WebInspector.ConsoleCommand = function(command, result, formattedResultElement, level)
836 {
837     this.command = command;
838     this.formattedResultElement = formattedResultElement;
839     this.level = level;
840 }
841
842 WebInspector.ConsoleCommand.prototype = {
843     toMessageElement: function()
844     {
845         var element = document.createElement("div");
846         element.command = this;
847         element.className = "console-user-command";
848
849         var commandTextElement = document.createElement("span");
850         commandTextElement.className = "console-message-text";
851         commandTextElement.textContent = this.command;
852         element.appendChild(commandTextElement);
853
854         var resultElement = document.createElement("div");
855         resultElement.className = "console-message";
856         element.appendChild(resultElement);
857
858         switch (this.level) {
859             case WebInspector.ConsoleMessage.MessageLevel.Log:
860                 resultElement.addStyleClass("console-log-level");
861                 break;
862             case WebInspector.ConsoleMessage.MessageLevel.Warning:
863                 resultElement.addStyleClass("console-warning-level");
864                 break;
865             case WebInspector.ConsoleMessage.MessageLevel.Error:
866                 resultElement.addStyleClass("console-error-level");
867         }
868
869         var resultTextElement = document.createElement("span");
870         resultTextElement.className = "console-message-text";
871         resultTextElement.appendChild(this.formattedResultElement);
872         resultElement.appendChild(resultTextElement);
873
874         return element;
875     }
876 }
877
878 WebInspector.ConsoleGroup = function(parentGroup, level)
879 {
880     this.parentGroup = parentGroup;
881     this.level = level;
882
883     var element = document.createElement("div");
884     element.className = "console-group";
885     element.group = this;
886     this.element = element;
887
888     var messagesElement = document.createElement("div");
889     messagesElement.className = "console-group-messages";
890     element.appendChild(messagesElement);
891     this.messagesElement = messagesElement;
892 }
893
894 WebInspector.ConsoleGroup.prototype = {
895     addMessage: function(msg)
896     {
897         var element = msg.toMessageElement();
898         
899         if (msg.level === WebInspector.ConsoleMessage.MessageLevel.StartGroup) {
900             this.messagesElement.parentNode.insertBefore(element, this.messagesElement);
901             element.addEventListener("click", this._titleClicked.bind(this), true);
902         } else
903             this.messagesElement.appendChild(element);
904     },
905     
906     _titleClicked: function(event)
907     {
908         var groupTitleElement = event.target.enclosingNodeOrSelfWithClass("console-group-title-level");
909         if (groupTitleElement) {
910             var groupElement = groupTitleElement.enclosingNodeOrSelfWithClass("console-group");
911             if (groupElement)
912                 if (groupElement.hasStyleClass("collapsed"))
913                     groupElement.removeStyleClass("collapsed");
914                 else
915                     groupElement.addStyleClass("collapsed");
916             groupTitleElement.scrollIntoViewIfNeeded(true);
917         }
918
919         event.stopPropagation();
920         event.preventDefault();
921     }
922 }