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