0cde3cd4ad0a2a37dd4c54b9a716626ded7cf455
[WebKit-https.git] / WebCore / page / inspector / inspector.js
1 /*
2  * Copyright (C) 2006, 2007 Apple Inc.  All rights reserved.
3  * Copyright (C) 2007 Matt Lilek (pewtermoose@gmail.com).
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer. 
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution. 
14  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission. 
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 var Preferences = {
31     ignoreWhitespace: true,
32     showUserAgentStyles: true,
33     maxInlineTextChildLength: 80,
34     maxTextSearchResultLength: 80,
35     showInheritedComputedStyleProperties: false,
36     toolbarHeight: 28
37 }
38
39 var WebInspector = {
40     resources: [],
41     resourceURLMap: {},
42     backForwardList: [],
43     searchResultsHeight: 100,
44
45     get consolePanel()
46     {
47         if (!this._consolePanel)
48             this._consolePanel = new WebInspector.ConsolePanel();
49
50         return this._consolePanel;
51     },
52
53     get networkPanel()
54     {
55         if (!this._networkPanel)
56             this._networkPanel = new WebInspector.NetworkPanel();
57
58         return this._networkPanel;
59     },
60
61     get currentBackForwardIndex()
62     {
63         if (this._currentBackForwardIndex === undefined)
64             this._currentBackForwardIndex = -1;
65
66         return this._currentBackForwardIndex;
67     },
68
69     set currentBackForwardIndex(x)
70     {
71         if (this._currentBackForwardIndex === x)
72             return;
73
74         this._currentBackForwardIndex = x;
75         this.updateBackForwardButtons();
76     },
77
78     get currentFocusElement()
79     {
80         return this._currentFocusElement;
81     },
82
83     set currentFocusElement(x)
84     {
85         if (!x || this._currentFocusElement === x)
86             return;
87
88         if (this._currentFocusElement) {
89             this._currentFocusElement.removeStyleClass("focused");
90             this._currentFocusElement.addStyleClass("blurred");
91         }
92
93         this._currentFocusElement = x;
94
95         if (x) {
96             x.addStyleClass("focused");
97             x.removeStyleClass("blurred");
98         }
99     },
100
101     get currentPanel()
102     {
103         return this._currentPanel;
104     },
105
106     set currentPanel(x)
107     {
108         if (this._currentPanel === x)
109             return;
110
111         if (this._currentPanel)
112             this._currentPanel.hide();
113
114         this._currentPanel = x;
115
116         if (x)
117             x.show();
118     },
119
120     get attached()
121     {
122         return this._attached;
123     },
124
125     set attached(x)
126     {
127         if (this._attached === x)
128             return;
129
130         this._attached = x;
131
132         var body = document.body;
133         if (x) {
134             InspectorController.attach();
135             body.removeStyleClass("detached");
136             body.addStyleClass("attached");
137         } else {
138             InspectorController.detach();
139             body.removeStyleClass("attached");
140             body.addStyleClass("detached");
141         }
142     },
143
144     get showingStatusArea()
145     {
146         return this._showingStatusArea;
147     },
148
149     set showingStatusArea(x)
150     {
151         if (this._showingStatusArea === x)
152             return;
153
154         this._showingStatusArea = x;
155
156         var list = document.getElementById("list");
157         var status = document.getElementById("status");
158         var statusButton = document.getElementById("statusToggle");
159
160         if (x) {
161             statusButton.addStyleClass("hide");
162             WebInspector.animateStyle([{element: list, end: {bottom: 99}}, {element: status, end: {bottom: 21}}], 250);
163         } else {
164             statusButton.removeStyleClass("hide");
165             WebInspector.animateStyle([{element: list, end: {bottom: 21}}, {element: status, end: {bottom: -57}}], 250);
166         }
167     },
168
169     get showingSearchResults()
170     {
171         return this._showingSearchResults;
172     },
173
174     set showingSearchResults(x)
175     {
176         if (this._showingSearchResults === x)
177             return;
178
179         this._showingSearchResults = x;
180
181         var resultsContainer = document.getElementById("searchResults");
182         var searchResultsResizer = document.getElementById("searchResultsResizer");
183
184         if (x) {
185             searchResultsResizer.style.display = null;
186             var animations = [
187                 {element: resultsContainer, end: {top: Preferences.toolbarHeight}},
188                 {element: searchResultsResizer, end: {top: WebInspector.searchResultsHeight + Preferences.toolbarHeight - 2}},
189                 {element: document.getElementById("main"), end: {top: WebInspector.searchResultsHeight + Preferences.toolbarHeight + 1}}
190             ];
191             WebInspector.animateStyle(animations, 250);
192         } else {
193             searchResultsResizer.style.display = "none";
194             var animations = [
195                 {element: resultsContainer, end: {top: Preferences.toolbarHeight - WebInspector.searchResultsHeight - 1}},
196                 {element: searchResultsResizer, end: {top: 0}},
197                 {element: document.getElementById("main"), end: {top: Preferences.toolbarHeight}}
198             ];
199             WebInspector.animateStyle(animations, 250, function() { resultsContainer.removeChildren(); delete this.searchResultsTree; });
200         }
201     }
202 }
203
204 WebInspector.loaded = function(event)
205 {
206     this.fileOutline = new TreeOutline(document.getElementById("list"));
207     this.fileOutline.expandTreeElementsWhenArrowing = true;
208
209     this.statusOutline = new TreeOutline(document.getElementById("status"));
210     this.statusOutline.expandTreeElementsWhenArrowing = true;
211
212     this.resourceCategories = {
213         documents: new WebInspector.ResourceCategory("documents"),
214         stylesheets: new WebInspector.ResourceCategory("stylesheets"),
215         images: new WebInspector.ResourceCategory("images"),
216         scripts: new WebInspector.ResourceCategory("scripts"),
217         fonts: new WebInspector.ResourceCategory("fonts"),
218         databases: new WebInspector.ResourceCategory("databases"),
219         other: new WebInspector.ResourceCategory("other")
220     };
221
222     this.consoleListItem = new WebInspector.ConsoleStatusTreeElement();
223     this.consoleListItem.item.onselect = function(element) { WebInspector.StatusTreeElement.selected(element); WebInspector.navigateToPanel(WebInspector.consolePanel) };
224     this.consoleListItem.item.ondeselect = function(element) { WebInspector.consolePanel.hide() };
225     this.statusOutline.appendChild(this.consoleListItem.item);
226
227     this.networkListItem = new WebInspector.StatusTreeElement("Network");
228     this.networkListItem.onselect = function(element) { WebInspector.StatusTreeElement.selected(element); WebInspector.navigateToPanel(WebInspector.networkPanel); };
229     this.networkListItem.ondeselect = function(element) { WebInspector.networkPanel.hide() };
230     this.statusOutline.appendChild(this.networkListItem);
231
232     this.resourceCategories.documents.listItem.expand();
233
234     this.currentFocusElement = document.getElementById("sidebar");
235
236     this.addMainEventListeners(document);
237
238     window.addEventListener("unload", function(event) { WebInspector.windowUnload(event) }, true);
239     document.addEventListener("mousedown", function(event) { WebInspector.changeFocus(event) }, true);
240     document.addEventListener("focus", function(event) { WebInspector.changeFocus(event) }, true);
241     document.addEventListener("keypress", function(event) { WebInspector.documentKeypress(event) }, true);
242
243     document.getElementById("back").title = "Show previous panel.";
244     document.getElementById("forward").title = "Show next panel.";
245
246     document.getElementById("back").addEventListener("click", function(event) { WebInspector.back() }, true);
247     document.getElementById("forward").addEventListener("click", function(event) { WebInspector.forward() }, true);
248     this.updateBackForwardButtons();
249
250     document.getElementById("attachToggle").addEventListener("click", function(event) { WebInspector.toggleAttach() }, true);
251     document.getElementById("statusToggle").addEventListener("click", function(event) { WebInspector.toggleStatusArea() }, true);
252     document.getElementById("sidebarResizeWidget").addEventListener("mousedown", WebInspector.sidebarResizerDragStart, true);
253     document.getElementById("searchResultsResizer").addEventListener("mousedown", WebInspector.searchResultsResizerDragStart, false);
254
255     document.body.addStyleClass("detached");
256
257     window.removeEventListener("load", this.loaded, false);
258     delete this.loaded;
259
260     InspectorController.loaded();
261 }
262
263 window.addEventListener("load", function(event) { WebInspector.loaded(event) }, false);
264
265 WebInspector.windowUnload = function(event)
266 {
267     InspectorController.windowUnloading();
268 }
269
270 WebInspector.windowFocused = function(event)
271 {
272     if (event.target.nodeType === Node.DOCUMENT_NODE)
273         document.body.removeStyleClass("inactive");
274 }
275
276 WebInspector.windowBlured = function(event)
277 {
278     if (event.target.nodeType === Node.DOCUMENT_NODE)
279         document.body.addStyleClass("inactive");
280 }
281
282 WebInspector.changeFocus = function(event)
283 {
284     var nextFocusElement;
285
286     var current = event.target;
287     while (current) {
288         if (current.nodeName.toLowerCase() === "input")
289             nextFocusElement = current;
290         current = current.parentNode;
291     }
292
293     if (!nextFocusElement)
294         nextFocusElement = event.target.firstParentWithClass("focusable");
295
296     this.currentFocusElement = nextFocusElement;
297 }
298
299 WebInspector.documentClick = function(event)
300 {
301     var anchor = event.target.firstParentOrSelfWithNodeName("a");
302     if (!anchor || !anchor.hasStyleClass("webkit-html-resource-link"))
303         return;
304
305     if (WebInspector.showResourceForURL(anchor.getAttribute("href"))) {
306         event.preventDefault();
307         event.stopPropagation();
308     }
309 }
310
311 WebInspector.documentKeypress = function(event)
312 {
313     if (!this.currentFocusElement || !this.currentFocusElement.id || !this.currentFocusElement.id.length)
314         return;
315     if (this.currentFocusElement.id + "Keypress" in WebInspector)
316         WebInspector[this.currentFocusElement.id + "Keypress"](event);
317 }
318
319 WebInspector.sidebarKeypress = function(event)
320 {
321     var nextSelectedElement;
322
323     if (this.fileOutline.selectedTreeElement) {
324         if (!this.fileOutline.handleKeyEvent(event) && event.keyIdentifier === "Down" && !event.altKey && this.showingStatusArea) {
325             var nextSelectedElement = this.statusOutline.children[0];
326             while (nextSelectedElement && !nextSelectedElement.selectable)
327                 nextSelectedElement = nextSelectedElement.traverseNextTreeElement(false);
328         }
329     } else if (this.statusOutline.selectedTreeElement) {
330         if (!this.showingStatusArea || (!this.statusOutline.handleKeyEvent(event) && event.keyIdentifier === "Up" && !event.altKey)) {
331             var nextSelectedElement = this.fileOutline.children[0];
332             var lastSelectable = null;
333
334             while (nextSelectedElement) {
335                 if (nextSelectedElement.selectable)
336                     lastSelectable = nextSelectedElement;
337                 nextSelectedElement = nextSelectedElement.traverseNextTreeElement(false);
338             }
339
340             nextSelectedElement = lastSelectable;
341         }
342     }
343
344     if (nextSelectedElement) {
345         nextSelectedElement.reveal();
346         nextSelectedElement.select();
347
348         event.preventDefault();
349         event.stopPropagation();
350     }
351 }
352
353 WebInspector.mainKeypress = function(event)
354 {
355     if (this.currentPanel && this.currentPanel.handleKeyEvent)
356         this.currentPanel.handleKeyEvent(event);
357 }
358
359 WebInspector.searchResultsKeypress = function(event)
360 {
361     if (this.searchResultsTree)
362         this.searchResultsTree.handleKeyEvent(event);
363 }
364
365 WebInspector.animateStyle = function(animations, duration, callback, complete)
366 {
367     if (complete === undefined)
368         complete = 0;
369     var slice = (1000 / 30); // 30 frames per second
370
371     var defaultUnit = "px";
372     var propertyUnit = {opacity: ""};
373
374     for (var i = 0; i < animations.length; ++i) {
375         var animation = animations[i];
376         var element = null;
377         var start = null;
378         var current = null;
379         var end = null;
380         for (key in animation) {
381             if (key === "element")
382                 element = animation[key];
383             else if (key === "start")
384                 start = animation[key];
385             else if (key == "current")
386                 current = animation[key];
387             else if (key === "end")
388                 end = animation[key];
389         }
390
391         if (!element || !end)
392             continue;
393
394         var computedStyle = element.ownerDocument.defaultView.getComputedStyle(element);
395         if (!start) {
396             start = {};
397             for (key in end)
398                 start[key] = parseInt(computedStyle.getPropertyValue(key));
399             animation.start = start;
400         } else if (complete == 0)
401             for (key in start)
402                 element.style.setProperty(key, start[key] + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
403
404         if (!current) {
405             current = {};
406             for (key in start)
407                 current[key] = start[key];
408             animation.current = current;
409         }
410
411         function cubicInOut(t, b, c, d)
412         {
413             if ((t/=d/2) < 1) return c/2*t*t*t + b;
414             return c/2*((t-=2)*t*t + 2) + b;
415         }
416
417         var style = element.style;
418         for (key in end) {
419             var startValue = start[key];
420             var currentValue = current[key];
421             var endValue = end[key];
422             if ((complete + slice) < duration) {
423                 var delta = (endValue - startValue) / (duration / slice);
424                 var newValue = cubicInOut(complete, startValue, endValue - startValue, duration);
425                 style.setProperty(key, newValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
426                 current[key] = newValue;
427             } else {
428                 style.setProperty(key, endValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
429             }
430         }
431     }
432
433     if (complete < duration)
434         setTimeout(WebInspector.animateStyle, slice, animations, duration, callback, complete + slice);
435     else if (callback)
436         callback();
437 }
438
439 WebInspector.toggleAttach = function()
440 {
441     this.attached = !this.attached;
442 }
443
444 WebInspector.toggleStatusArea = function()
445 {
446     this.showingStatusArea = !this.showingStatusArea;
447 }
448
449 WebInspector.sidebarResizerDragStart = function(event)
450 {
451     WebInspector.dividerDragStart(document.getElementById("sidebar"), WebInspector.sidebarResizerDrag, WebInspector.sidebarResizerDragEnd, event, "col-resize");
452 }
453
454 WebInspector.sidebarResizerDragEnd = function(event)
455 {
456     WebInspector.dividerDragEnd(document.getElementById("sidebar"), WebInspector.sidebarResizerDrag, WebInspector.sidebarResizerDragEnd, event);
457 }
458
459 WebInspector.sidebarResizerDrag = function(event)
460 {
461     var sidebar = document.getElementById("sidebar");
462     if (sidebar.dragging == true) {
463
464         var x = event.clientX + window.scrollX;
465
466         // FIXME: We can should come up with a better hueristic for constraining the size
467         // of the sidebar.
468         var newWidth = Number.constrain(x, 100, window.innerWidth - 100);
469
470         if (x == newWidth)
471             sidebar.dragLastX = x;
472
473         sidebar.style.width = newWidth + "px";
474         document.getElementById("main").style.left = newWidth + "px";
475         document.getElementById("toolbarButtons").style.left = newWidth + "px";
476         document.getElementById("searchResults").style.left = newWidth + "px";
477         document.getElementById("searchResultsResizer").style.left = newWidth + "px";
478         event.preventDefault();
479     }
480 }
481
482 WebInspector.searchResultsResizerDragStart = function(event)
483 {
484     WebInspector.dividerDragStart(document.getElementById("searchResults"), WebInspector.searchResultsResizerDrag, WebInspector.searchResultsResizerDragEnd, event, "row-resize");
485 }
486
487 WebInspector.searchResultsResizerDragEnd = function(event)
488 {
489     WebInspector.dividerDragEnd(document.getElementById("searchResults"), WebInspector.searchResultsResizerDrag, WebInspector.searchResultsResizerDragEnd, event);
490 }
491
492 WebInspector.searchResultsResizerDrag = function(event)
493 {
494     var searchResults = document.getElementById("searchResults");
495     if (searchResults.dragging == true) {
496         var y = event.clientY;
497         var newHeight = Number.constrain(y, 100, window.innerHeight - 100);
498
499         if (y == newHeight)
500             searchResults.dragLastY = y;
501
502         WebInspector.searchResultsHeight = newHeight - Preferences.toolbarHeight;
503         searchResults.style.height = WebInspector.searchResultsHeight + "px";
504         document.getElementById("main").style.top = (newHeight + 1) + "px";
505         document.getElementById("searchResultsResizer").style.top = (newHeight - 2) + "px";
506         event.preventDefault();
507     }
508 }
509
510 WebInspector.dividerDragStart = function(element, dividerDrag, dividerDragEnd, event, cursor) 
511 {
512     element.dragging = true;
513     element.dragLastY = event.clientY + window.scrollY;
514     element.dragLastX = event.clientX + window.scrollX;
515     document.addEventListener("mousemove", dividerDrag, true);
516     document.addEventListener("mouseup", dividerDragEnd, true);
517     document.body.style.cursor = cursor;
518     event.preventDefault();
519 }
520
521 WebInspector.dividerDragEnd = function(element, dividerDrag, dividerDragEnd, event) 
522 {
523     element.dragging = false;
524     document.removeEventListener("mousemove", dividerDrag, true);
525     document.removeEventListener("mouseup", dividerDragEnd, true);
526     document.body.style.removeProperty("cursor");
527 }
528
529 WebInspector.back = function()
530 {
531     if (this.currentBackForwardIndex <= 0) {
532         alert("Can't go back from index " + this.currentBackForwardIndex);
533         return;
534     }
535
536     this.navigateToPanel(this.backForwardList[--this.currentBackForwardIndex], null, true);
537 }
538
539 WebInspector.forward = function()
540 {
541     if (this.currentBackForwardIndex >= this.backForwardList.length - 1) {
542         alert("Can't go forward from index " + this.currentBackForwardIndex);
543         return;
544     }
545
546     this.navigateToPanel(this.backForwardList[++this.currentBackForwardIndex], null, true);
547 }
548
549 WebInspector.updateBackForwardButtons = function()
550 {
551     var index = this.currentBackForwardIndex;
552
553     document.getElementById("back").disabled = index <= 0;
554     document.getElementById("forward").disabled = index >= this.backForwardList.length - 1;
555 }
556
557 WebInspector.addResource = function(resource)
558 {
559     this.resources.push(resource);
560
561     if (resource.mainResource)
562         this.mainResource = resource;
563
564     if (resource.url) {
565         this.resourceURLMap[resource.url] = resource;
566         this.networkPanel.addResourceToTimeline(resource);
567     }
568 }
569
570 WebInspector.removeResource = function(resource)
571 {
572     resource.detach();
573
574     resource.category.removeResource(resource);
575
576     if (resource.url)
577         delete this.resourceURLMap[resource.url];
578
579     var resourcesLength = this.resources.length;
580     for (var i = 0; i < resourcesLength; ++i) {
581         if (this.resources[i] === resource) {
582             this.resources.splice(i, 1);
583             break;
584         }
585     }
586 }
587
588 WebInspector.clearResources = function()
589 {
590     for (var category in this.resourceCategories)
591         this.resourceCategories[category].removeAllResources();
592     this.resources = [];
593     this.backForwardList = [];
594     this.currentBackForwardIndex = -1;
595     delete this.mainResource;
596 }
597
598 WebInspector.clearDatabaseResources = function()
599 {
600     this.resourceCategories.databases.removeAllResources();
601 }
602
603 WebInspector.resourceURLChanged = function(resource, oldURL)
604 {
605     delete this.resourceURLMap[oldURL];
606     this.resourceURLMap[resource.url] = resource;
607 }
608
609 WebInspector.addMessageToConsole = function(msg)
610 {
611     this.consolePanel.addMessage(msg);
612     switch (msg.level) {
613         case WebInspector.ConsoleMessage.MessageLevel.Warning:
614             ++this.consoleListItem.warnings;
615             this.showingStatusArea = true;
616             break;
617         case WebInspector.ConsoleMessage.MessageLevel.Error:
618             ++this.consoleListItem.errors;
619             this.showingStatusArea = true;
620             break;
621     }
622 }
623
624 WebInspector.clearConsoleMessages = function()
625 {
626     this.consolePanel.clearMessages();
627     this.consoleListItem.warnings = this.consoleListItem.errors = 0;
628 }
629
630 WebInspector.clearNetworkTimeline = function()
631 {
632     if (this._networkPanel)
633         this._networkPanel.clearTimeline();
634 }
635
636 WebInspector.drawLoadingPieChart = function(canvas, percent) {
637     var g = canvas.getContext("2d");
638     var darkColor = "rgb(122, 168, 218)";
639     var lightColor = "rgb(228, 241, 251)";
640     var cx = 8;
641     var cy = 8;
642     var r = 7;
643
644     g.beginPath();
645     g.arc(cx, cy, r, 0, Math.PI * 2, false); 
646     g.closePath();
647
648     g.lineWidth = 1;
649     g.strokeStyle = darkColor;
650     g.fillStyle = lightColor;
651     g.fill();
652     g.stroke();
653
654     var startangle = -Math.PI / 2;
655     var endangle = startangle + (percent * Math.PI * 2);
656
657     g.beginPath();
658     g.moveTo(cx, cy);
659     g.arc(cx, cy, r, startangle, endangle, false); 
660     g.closePath();
661
662     g.fillStyle = darkColor;
663     g.fill();
664 }
665
666 WebInspector.updateFocusedNode = function(node)
667 {
668     if (!node)
669         // FIXME: Should we deselect if null is passed in?
670         return;
671
672     for (var i = 0; i < this.resourceCategories.documents.resources.length; ++i) {
673         var resource = this.resourceCategories.documents.resources[i];
674         if (resource.documentNode !== node.ownerDocument)
675             continue;
676
677         this.navigateToPanel(resource.panel, "dom");
678         resource.panel.focusedDOMNode = node;
679
680         this.currentFocusElement = document.getElementById("main");
681
682         break;
683     }
684 }
685
686 WebInspector.resourceForURL = function(url)
687 {
688     for (var resourceURL in this.resourceURLMap) {
689         if (resourceURL.hasSubstring(url))
690             return this.resourceURLMap[resourceURL];
691     }
692
693     return null;
694 }
695
696 WebInspector.showResourceForURL = function(url)
697 {
698     var resource = this.resourceForURL(url);
699     if (!resource)
700         return false;
701
702     this.navigateToResource(resource);
703     return true;
704 }
705
706 WebInspector.linkifyURL = function(url, linkText, classes, isExternal)
707 {
708     if (linkText === undefined)
709         linkText = url.escapeHTML();
710     classes = (classes === undefined) ? "" : classes + " ";
711     classes += isExternal ? "webkit-html-external-link" : "webkit-html-resource-link";
712     var link = "<a href=\"" + url + "\" class=\"" + classes + "\" target=\"_blank\">" + linkText + "</a>";
713     return link;
714 }
715
716 WebInspector.addMainEventListeners = function(doc)
717 {
718     doc.defaultView.addEventListener("focus", function(event) { WebInspector.windowFocused(event) }, true);
719     doc.defaultView.addEventListener("blur", function(event) { WebInspector.windowBlured(event) }, true);
720     doc.addEventListener("click", function(event) { WebInspector.documentClick(event) }, true);
721 }
722
723 WebInspector.performSearch = function(query)
724 {
725     if (!query || !query.length) {
726         this.showingSearchResults = false;
727         return;
728     }
729
730     var resultsContainer = document.getElementById("searchResults");
731     resultsContainer.removeChildren();
732
733     var isXPath = query.indexOf("/") !== -1;
734
735     var xpathQuery;
736     if (isXPath)
737         xpathQuery = query;
738     else {
739         var escapedQuery = query.escapeCharacters("'");
740         xpathQuery = "//*[contains(name(),'" + escapedQuery + "') or contains(@*,'" + escapedQuery + "')] | //text()[contains(.,'" + escapedQuery + "')] | //comment()[contains(.,'" + escapedQuery + "')]";
741     }
742
743     var resourcesToSearch = [].concat(this.resourceCategories.documents.resources, this.resourceCategories.stylesheets.resources, this.resourceCategories.scripts.resources, this.resourceCategories.other.resources);
744
745     var files = [];
746     for (var i = 0; i < resourcesToSearch.length; ++i) {
747         var resource = resourcesToSearch[i];
748
749         var sourceResults = [];
750         if (!isXPath && "source" in resource.panel.views) {
751             resource.panel.setupSourceFrameIfNeeded();
752             sourceResults = InspectorController.search(resource.panel.views.source.frameElement.contentDocument, query);
753         }
754
755         var domResults = [];
756         if (resource.category === this.resourceCategories.documents) {
757             try {
758                 var doc = resource.documentNode;
759                 var nodeList = doc.evaluate(xpathQuery, doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE);
760                 for (var j = 0; j < nodeList.snapshotLength; ++j)
761                     domResults.push(nodeList.snapshotItem(i));
762             } catch(err) {
763                 // ignore any exceptions. the query might be malformed, but we allow that.
764             }
765         }
766
767         if ((!sourceResults || !sourceResults.length) && !domResults.length)
768             continue;
769
770         files.push({resource: resource, sourceResults: sourceResults, domResults: domResults});
771     }
772
773     if (!files.length)
774         return;
775
776     this.showingSearchResults = true;
777
778     var fileList = document.createElement("ol");
779     fileList.className = "outline-disclosure";
780     resultsContainer.appendChild(fileList);
781
782     this.searchResultsTree = new TreeOutline(fileList);
783     this.searchResultsTree.expandTreeElementsWhenArrowing = true;
784
785     var sourceResultSelected = function(element)
786     {
787         var selection = window.getSelection();
788         selection.removeAllRanges();
789         selection.addRange(element.representedObject.range);
790
791         WebInspector.navigateToPanel(element.representedObject.panel, "source");
792         element.representedObject.line.scrollIntoView(true);
793         resultsContainer.scrollToElement(element._listItemNode);
794     }
795
796     var domResultSelected = function(element)
797     {
798         WebInspector.navigateToPanel(element.representedObject.panel, "dom");
799         element.representedObject.panel.focusedDOMNode = element.representedObject.node;
800         resultsContainer.scrollToElement(element._listItemNode);
801     }
802
803     for (var i = 0; i < files.length; ++i) {
804         var file = files[i];
805
806         var fileItem = new TreeElement(file.resource.displayName, {}, true);
807         fileItem.expanded = true;
808         fileItem.selectable = false;
809         this.searchResultsTree.appendChild(fileItem);
810
811         if (file.sourceResults && file.sourceResults.length) {
812             for (var j = 0; j < file.sourceResults.length; ++j) {
813                 var range = file.sourceResults[j];
814
815                 var line = range.startContainer;
816                 while (line.parentNode && line.nodeName.toLowerCase() != "tr")
817                     line = line.parentNode;
818                 var lineRange = file.resource.panel.views.source.frameElement.contentDocument.createRange();
819                 lineRange.selectNodeContents(line);
820
821                 // Don't include any error bubbles in the search result
822                 var end = line.lastChild.lastChild;
823                 if (end.nodeName.toLowerCase() == "div" && end.hasStyleClass("webkit-html-message-bubble")) {
824                     while (end && end.nodeName.toLowerCase() == "div" && end.hasStyleClass("webkit-html-message-bubble"))
825                         end = end.previousSibling;
826                     lineRange.setEndAfter(end);
827                 }
828
829                 var beforeRange = file.resource.panel.views.source.frameElement.contentDocument.createRange();
830                 beforeRange.setStart(lineRange.startContainer, lineRange.startOffset);
831                 beforeRange.setEnd(range.startContainer, range.startOffset);
832
833                 var afterRange = file.resource.panel.views.source.frameElement.contentDocument.createRange();
834                 afterRange.setStart(range.endContainer, range.endOffset);
835                 afterRange.setEnd(lineRange.endContainer, lineRange.endOffset);
836
837                 var beforeText = beforeRange.toString().trimLeadingWhitespace();
838                 var text = range.toString();
839                 var afterText = afterRange.toString().trimTrailingWhitespace();
840
841                 var length = beforeText.length + text.length + afterText.length;
842                 if (length > Preferences.maxTextSearchResultLength) {
843                     var beforeAfterLength = (Preferences.maxTextSearchResultLength - text.length) / 2;
844                     if (beforeText.length > beforeAfterLength)
845                         beforeText = "\u2026" + beforeText.substr(-beforeAfterLength);
846                     if (afterText.length > beforeAfterLength)
847                         afterText = afterText.substr(0, beforeAfterLength) + "\u2026";
848                 }
849
850                 var title = "<div class=\"selection selected\"></div>";
851                 if (j == 0)
852                     title += "<div class=\"search-results-section\">Source</div>";
853                 title += beforeText.escapeHTML() + "<span class=\"search-matched-string\">" + text.escapeHTML() + "</span>" + afterText.escapeHTML();
854                 var item = new TreeElement(title, {panel: file.resource.panel, line: line, range: range}, false);
855                 item.onselect = sourceResultSelected;
856                 fileItem.appendChild(item);
857             }
858         }
859
860         if (file.domResults.length) {
861             for (var j = 0; j < file.domResults.length; ++j) {
862                 var node = file.domResults[j];
863                 var title = "<div class=\"selection selected\"></div>";
864                 if (j == 0)
865                     title += "<div class=\"search-results-section\">DOM</div>";
866                 title += nodeTitleInfo.call(node).title;
867                 var item = new TreeElement(title, {panel: file.resource.panel, node: node}, false);
868                 item.onselect = domResultSelected;
869                 fileItem.appendChild(item);
870             }
871         }
872     }
873 }
874
875 WebInspector.navigateToResource = function(resource)
876 {
877     this.navigateToPanel(resource.panel);
878 }
879
880 WebInspector.navigateToPanel = function(panel, view, fromBackForwardAction)
881 {
882     if (this.currentPanel === panel) {
883         if (panel && view)
884             panel.currentView = view;
885         return;
886     }
887
888     if (!fromBackForwardAction) {
889         var oldIndex = this.currentBackForwardIndex;
890         if (oldIndex >= 0)
891             this.backForwardList.splice(oldIndex + 1, this.backForwardList.length - oldIndex);
892         this.currentBackForwardIndex++;
893         this.backForwardList.push(panel);
894     }
895
896     this.currentPanel = panel;
897     if (panel && view)
898         panel.currentView = view;
899 }
900
901 WebInspector.StatusTreeElement = function(title)
902 {
903     var item = new TreeElement("<span class=\"title only\">" + title + "</span><span class=\"icon " + title.toLowerCase() + "\"></span>", {}, false);
904     item.onselect = WebInspector.StatusTreeElement.selected;
905     return item;
906 }
907
908 WebInspector.StatusTreeElement.selected = function(element)
909 {
910     var selectedElement = WebInspector.fileOutline.selectedTreeElement;
911     if (selectedElement)
912         selectedElement.deselect();
913 }
914
915 WebInspector.ConsoleStatusTreeElement = function()
916 {
917     this.item = WebInspector.StatusTreeElement.call(this, "Console");
918 }
919
920 WebInspector.ConsoleStatusTreeElement.prototype = {
921     get warnings()
922     {
923         if (!("_warnings" in this))
924             this._warnings = 0;
925
926         return this._warnings;
927     },
928
929     set warnings(x)
930     {
931         if (this._warnings === x)
932             return;
933
934         this._warnings = x;
935
936         this._updateTitle();
937     },
938
939     get errors()
940     {
941         if (!("_errors" in this))
942             this._errors = 0;
943
944         return this._errors;
945     },
946
947     set errors(x)
948     {
949         if (this._errors === x)
950             return;
951
952         this._errors = x;
953
954         this._updateTitle();
955     },
956
957     _updateTitle: function()
958     {
959         var title = "<span class=\"title";
960         if (!this.warnings && !this.errors)
961             title += " only";
962         title += "\">Console</span><span class=\"icon console\"></span>";
963
964         if (this.warnings || this.errors) {
965             title += "<span class=\"info\">";
966             if (this.errors) {
967                 title += this.errors + " error";
968                 if (this.errors > 1)
969                     title += "s";
970             }
971             if (this.warnings) {
972                 if (this.errors)
973                     title += ", ";
974                 title += this.warnings + " warning";
975                 if (this.warnings > 1)
976                     title += "s";
977             }
978             title += "</span>";
979         }
980
981         this.item.title = title;
982     }
983 }
984
985 WebInspector.ConsoleStatusTreeElement.prototype.__proto__ = WebInspector.StatusTreeElement.prototype;
986
987 WebInspector.Tips = {
988     ResourceNotCompressed: {id: 0, message: "You could save bandwidth by having your web server compress this transfer with gzip or zlib."}
989 }
990
991 WebInspector.Warnings = {
992     IncorrectMIMEType: {id: 0, message: "Resource interpreted as %s but transferred with MIME type %s."}
993 }
994
995 // This table maps MIME types to the Resource.Types which are valid for them.
996 // The following line:
997 //    "text/html":                {0: 1},
998 // means that text/html is a valid MIME type for resources that have type
999 // WebInspector.Resource.Type.Document (which has a value of 0).
1000 WebInspector.MIMETypes = {
1001     "text/html":                   {0: true},
1002     "text/xml":                    {0: true},
1003     "text/plain":                  {0: true},
1004     "application/xhtml+xml":       {0: true},
1005     "text/css":                    {1: true},
1006     "text/xsl":                    {1: true},
1007     "image/jpeg":                  {2: true},
1008     "image/png":                   {2: true},
1009     "image/gif":                   {2: true},
1010     "image/bmp":                   {2: true},
1011     "image/x-icon":                {2: true},
1012     "image/x-xbitmap":             {2: true},
1013     "font/ttf":                    {3: true},
1014     "font/opentype":               {3: true},
1015     "application/x-font-type1":    {3: true},
1016     "application/x-font-ttf":      {3: true},
1017     "application/x-truetype-font": {3: true},
1018     "text/javascript":             {4: true},
1019     "text/ecmascript":             {4: true},
1020     "application/javascript":      {4: true},
1021     "application/ecmascript":      {4: true},
1022     "application/x-javascript":    {4: true},
1023     "text/javascript1.1":          {4: true},
1024     "text/javascript1.2":          {4: true},
1025     "text/javascript1.3":          {4: true},
1026     "text/jscript":                {4: true},
1027     "text/livescript":             {4: true},
1028 }