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