Focus the DOM tree in the Web Inspector when a node is inspected.
[WebKit-https.git] / WebCore / page / inspector / inspector.js
1 /*
2  * Copyright (C) 2006, 2007, 2008 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     minConsoleHeight: 75,
35     minSidebarWidth: 100,
36     minElementsSidebarWidth: 200,
37     minScriptsSidebarWidth: 200,
38     showInheritedComputedStyleProperties: false,
39     showMissingLocalizedStrings: false
40 }
41
42 var WebInspector = {
43     resources: [],
44     resourceURLMap: {},
45     missingLocalizedStrings: {},
46
47     get previousFocusElement()
48     {
49         return this._previousFocusElement;
50     },
51
52     get currentFocusElement()
53     {
54         return this._currentFocusElement;
55     },
56
57     set currentFocusElement(x)
58     {
59         if (this._currentFocusElement !== x)
60             this._previousFocusElement = this._currentFocusElement;
61         this._currentFocusElement = x;
62
63         if (this._currentFocusElement) {
64             this._currentFocusElement.focus();
65
66             // Make a caret selection inside the new element if there isn't a range selection and
67             // there isn't already a caret selection inside.
68             var selection = window.getSelection();
69             if (selection.isCollapsed && !this._currentFocusElement.isInsertionCaretInside()) {
70                 var selectionRange = document.createRange();
71                 selectionRange.setStart(this._currentFocusElement, 0);
72                 selectionRange.setEnd(this._currentFocusElement, 0);
73
74                 selection.removeAllRanges();
75                 selection.addRange(selectionRange);
76             }
77         } else if (this._previousFocusElement)
78             this._previousFocusElement.blur();
79     },
80
81     get currentPanel()
82     {
83         return this._currentPanel;
84     },
85
86     set currentPanel(x)
87     {
88         if (this._currentPanel === x)
89             return;
90
91         if (this._currentPanel)
92             this._currentPanel.hide();
93
94         this._currentPanel = x;
95
96         this.updateSearchLabel();
97
98         if (x) {
99             x.show();
100
101             if (this.currentQuery) {
102                 if (x.performSearch) {
103                     function performPanelSearch()
104                     {
105                         this.updateSearchMatchesCount();
106
107                         x.currentQuery = this.currentQuery;
108                         x.performSearch(this.currentQuery);
109                     }
110
111                     // Perform the search on a timeout so the panel switches fast.
112                     setTimeout(performPanelSearch.bind(this), 0);
113                 } else {
114                     // Update to show Not found for panels that can't be searched.
115                     this.updateSearchMatchesCount();
116                 }
117             }
118         }
119     },
120
121     get attached()
122     {
123         return this._attached;
124     },
125
126     set attached(x)
127     {
128         if (this._attached === x)
129             return;
130
131         this._attached = x;
132
133         this.updateSearchLabel();
134
135         var dockToggleButton = document.getElementById("dock-status-bar-item");
136         var body = document.body;
137
138         if (x) {
139             InspectorController.attach();
140             body.removeStyleClass("detached");
141             body.addStyleClass("attached");
142             dockToggleButton.title = WebInspector.UIString("Undock into separate window.");
143         } else {
144             InspectorController.detach();
145             body.removeStyleClass("attached");
146             body.addStyleClass("detached");
147             dockToggleButton.title = WebInspector.UIString("Dock to main window.");
148         }
149     },
150
151     get errors()
152     {
153         return this._errors || 0;
154     },
155
156     set errors(x)
157     {
158         x = Math.max(x, 0);
159
160         if (this._errors === x)
161             return;
162         this._errors = x;
163         this._updateErrorAndWarningCounts();
164     },
165
166     get warnings()
167     {
168         return this._warnings || 0;
169     },
170
171     set warnings(x)
172     {
173         x = Math.max(x, 0);
174
175         if (this._warnings === x)
176             return;
177         this._warnings = x;
178         this._updateErrorAndWarningCounts();
179     },
180
181     _updateErrorAndWarningCounts: function()
182     {
183         var errorWarningElement = document.getElementById("error-warning-count");
184         if (!errorWarningElement)
185             return;
186
187         if (!this.errors && !this.warnings) {
188             errorWarningElement.addStyleClass("hidden");
189             return;
190         }
191
192         errorWarningElement.removeStyleClass("hidden");
193
194         errorWarningElement.removeChildren();
195
196         if (this.errors) {
197             var errorElement = document.createElement("span");
198             errorElement.id = "error-count";
199             errorElement.textContent = this.errors;
200             errorWarningElement.appendChild(errorElement);
201         }
202
203         if (this.warnings) {
204             var warningsElement = document.createElement("span");
205             warningsElement.id = "warning-count";
206             warningsElement.textContent = this.warnings;
207             errorWarningElement.appendChild(warningsElement);
208         }
209
210         if (this.errors) {
211             if (this.warnings) {
212                 if (this.errors == 1) {
213                     if (this.warnings == 1)
214                         errorWarningElement.title = WebInspector.UIString("%d error, %d warning", this.errors, this.warnings);
215                     else
216                         errorWarningElement.title = WebInspector.UIString("%d error, %d warnings", this.errors, this.warnings);
217                 } else if (this.warnings == 1)
218                     errorWarningElement.title = WebInspector.UIString("%d errors, %d warning", this.errors, this.warnings);
219                 else
220                     errorWarningElement.title = WebInspector.UIString("%d errors, %d warnings", this.errors, this.warnings);
221             } else if (this.errors == 1)
222                 errorWarningElement.title = WebInspector.UIString("%d error", this.errors);
223             else
224                 errorWarningElement.title = WebInspector.UIString("%d errors", this.errors);
225         } else if (this.warnings == 1)
226             errorWarningElement.title = WebInspector.UIString("%d warning", this.warnings);
227         else if (this.warnings)
228             errorWarningElement.title = WebInspector.UIString("%d warnings", this.warnings);
229         else
230             errorWarningElement.title = null;
231     },
232
233     get hoveredDOMNode()
234     {
235         return this._hoveredDOMNode;
236     },
237
238     set hoveredDOMNode(x)
239     {
240         if (objectsAreSame(this._hoveredDOMNode, x))
241             return;
242
243         this._hoveredDOMNode = x;
244
245         if (this._hoveredDOMNode)
246             this._updateHoverHighlightSoon(this.showingDOMNodeHighlight ? 50 : 500);
247         else
248             this._updateHoverHighlight();
249     },
250
251     _updateHoverHighlightSoon: function(delay)
252     {
253         if ("_updateHoverHighlightTimeout" in this)
254             clearTimeout(this._updateHoverHighlightTimeout);
255         this._updateHoverHighlightTimeout = setTimeout(this._updateHoverHighlight.bind(this), delay);
256     },
257
258     _updateHoverHighlight: function()
259     {
260         if ("_updateHoverHighlightTimeout" in this) {
261             clearTimeout(this._updateHoverHighlightTimeout);
262             delete this._updateHoverHighlightTimeout;
263         }
264
265         if (this._hoveredDOMNode) {
266             InspectorController.highlightDOMNode(this._hoveredDOMNode);
267             this.showingDOMNodeHighlight = true;
268         } else {
269             InspectorController.hideDOMNodeHighlight();
270             this.showingDOMNodeHighlight = false;
271         }
272     }
273 }
274
275 WebInspector.loaded = function()
276 {
277     var platform = InspectorController.platform();
278     document.body.addStyleClass("platform-" + platform);
279
280     this.console = new WebInspector.Console();
281     this.panels = {
282         elements: new WebInspector.ElementsPanel(),
283         resources: new WebInspector.ResourcesPanel(),
284         scripts: new WebInspector.ScriptsPanel(),
285         profiles: new WebInspector.ProfilesPanel(),
286         databases: new WebInspector.DatabasesPanel()
287     };
288
289     var toolbarElement = document.getElementById("toolbar");
290     var previousToolbarItem = toolbarElement.children[0];
291
292     for (var panelName in this.panels) {
293         var panel = this.panels[panelName];
294         var panelToolbarItem = panel.toolbarItem;
295         panelToolbarItem.addEventListener("click", this._toolbarItemClicked.bind(this));
296         if (previousToolbarItem)
297             toolbarElement.insertBefore(panelToolbarItem, previousToolbarItem.nextSibling);
298         else
299             toolbarElement.insertBefore(panelToolbarItem, toolbarElement.firstChild);
300         previousToolbarItem = panelToolbarItem;
301     }
302
303     this.currentPanel = this.panels.elements;
304
305     this.resourceCategories = {
306         documents: new WebInspector.ResourceCategory(WebInspector.UIString("Documents"), "documents"),
307         stylesheets: new WebInspector.ResourceCategory(WebInspector.UIString("Stylesheets"), "stylesheets"),
308         images: new WebInspector.ResourceCategory(WebInspector.UIString("Images"), "images"),
309         scripts: new WebInspector.ResourceCategory(WebInspector.UIString("Scripts"), "scripts"),
310         xhr: new WebInspector.ResourceCategory(WebInspector.UIString("XHR"), "xhr"),
311         fonts: new WebInspector.ResourceCategory(WebInspector.UIString("Fonts"), "fonts"),
312         other: new WebInspector.ResourceCategory(WebInspector.UIString("Other"), "other")
313     };
314
315     this.Tips = {
316         ResourceNotCompressed: {id: 0, message: WebInspector.UIString("You could save bandwidth by having your web server compress this transfer with gzip or zlib.")}
317     };
318
319     this.Warnings = {
320         IncorrectMIMEType: {id: 0, message: WebInspector.UIString("Resource interpreted as %s but transferred with MIME type %s.")}
321     };
322
323     this.addMainEventListeners(document);
324
325     window.addEventListener("unload", this.windowUnload.bind(this), true);
326     window.addEventListener("resize", this.windowResize.bind(this), true);
327
328     document.addEventListener("focus", this.focusChanged.bind(this), true);
329     document.addEventListener("keydown", this.documentKeyDown.bind(this), true);
330     document.addEventListener("keyup", this.documentKeyUp.bind(this), true);
331     document.addEventListener("beforecopy", this.documentCanCopy.bind(this), true);
332     document.addEventListener("copy", this.documentCopy.bind(this), true);
333
334     var mainPanelsElement = document.getElementById("main-panels");
335     mainPanelsElement.handleKeyEvent = this.mainKeyDown.bind(this);
336     mainPanelsElement.handleKeyUpEvent = this.mainKeyUp.bind(this);
337     mainPanelsElement.handleCopyEvent = this.mainCopy.bind(this);
338
339     // Focus the mainPanelsElement in a timeout so it happens after the initial focus,
340     // so it doesn't get reset to the first toolbar button. This initial focus happens
341     // on Mac when the window is made key and the WebHTMLView becomes the first responder.
342     setTimeout(function() { WebInspector.currentFocusElement = mainPanelsElement }, 0);
343
344     var dockToggleButton = document.getElementById("dock-status-bar-item");
345     dockToggleButton.addEventListener("click", this.toggleAttach.bind(this), false);
346
347     if (this.attached)
348         dockToggleButton.title = WebInspector.UIString("Undock into separate window.");
349     else
350         dockToggleButton.title = WebInspector.UIString("Dock to main window.");
351
352     var errorWarningCount = document.getElementById("error-warning-count");
353     errorWarningCount.addEventListener("click", this.console.show.bind(this.console), false);
354     this._updateErrorAndWarningCounts();
355
356     var searchField = document.getElementById("search");
357     searchField.addEventListener("keydown", this.searchKeyDown.bind(this), false);
358     searchField.addEventListener("keyup", this.searchKeyUp.bind(this), false);
359     searchField.addEventListener("search", this.performSearch.bind(this), false); // when the search is emptied
360
361     document.getElementById("toolbar").addEventListener("mousedown", this.toolbarDragStart, true);
362     document.getElementById("close-button").addEventListener("click", this.close, true);
363
364     InspectorController.loaded();
365 }
366
367 var windowLoaded = function()
368 {
369     var localizedStringsURL = InspectorController.localizedStringsURL();
370     if (localizedStringsURL) {
371         var localizedStringsScriptElement = document.createElement("script");
372         localizedStringsScriptElement.addEventListener("load", WebInspector.loaded.bind(WebInspector), false);
373         localizedStringsScriptElement.type = "text/javascript";
374         localizedStringsScriptElement.src = localizedStringsURL;
375         document.getElementsByTagName("head").item(0).appendChild(localizedStringsScriptElement);
376     } else
377         WebInspector.loaded();
378
379     window.removeEventListener("load", windowLoaded, false);
380     delete windowLoaded;
381 };
382
383 window.addEventListener("load", windowLoaded, false);
384
385 WebInspector.windowUnload = function(event)
386 {
387     InspectorController.windowUnloading();
388 }
389
390 WebInspector.windowResize = function(event)
391 {
392     if (this.currentPanel && this.currentPanel.resize)
393         this.currentPanel.resize();
394 }
395
396 WebInspector.windowFocused = function(event)
397 {
398     if (event.target.nodeType === Node.DOCUMENT_NODE)
399         document.body.removeStyleClass("inactive");
400 }
401
402 WebInspector.windowBlured = function(event)
403 {
404     if (event.target.nodeType === Node.DOCUMENT_NODE)
405         document.body.addStyleClass("inactive");
406 }
407
408 WebInspector.focusChanged = function(event)
409 {
410     this.currentFocusElement = event.target;
411 }
412
413 WebInspector.setAttachedWindow = function(attached)
414 {
415     this.attached = attached;
416 }
417
418 WebInspector.close = function(event)
419 {
420     InspectorController.closeWindow();
421 }
422
423 WebInspector.documentClick = function(event)
424 {
425     var anchor = event.target.enclosingNodeOrSelfWithNodeName("a");
426     if (!anchor)
427         return;
428
429     // Prevent the link from navigating, since we don't do any navigation by following links normally.
430     event.preventDefault();
431
432     function followLink()
433     {
434         // FIXME: support webkit-html-external-link links here.
435         if (anchor.href in WebInspector.resourceURLMap) {
436             if (anchor.hasStyleClass("webkit-html-external-link")) {
437                 anchor.removeStyleClass("webkit-html-external-link");
438                 anchor.addStyleClass("webkit-html-resource-link");
439             }
440
441             WebInspector.showResourceForURL(anchor.href, anchor.lineNumber, anchor.preferredPanel);
442         } else {
443 console.log("followLink");
444             var profileStringRegEx = new RegExp("webkit-profile://.+/([0-9]+)");
445             var profileString = profileStringRegEx.exec(anchor.href);
446             if (profileString)
447                 WebInspector.showProfileById(profileString[1])
448         }
449     }
450
451     if (WebInspector.followLinkTimeout)
452         clearTimeout(WebInspector.followLinkTimeout);
453
454     if (anchor.preventFollowOnDoubleClick) {
455         // Start a timeout if this is the first click, if the timeout is canceled
456         // before it fires, then a double clicked happened or another link was clicked.
457         if (event.detail === 1)
458             WebInspector.followLinkTimeout = setTimeout(followLink, 333);
459         return;
460     }
461
462     followLink();
463 }
464
465 WebInspector.documentKeyDown = function(event)
466 {
467     if (!this.currentFocusElement)
468         return;
469     if (this.currentFocusElement.handleKeyEvent)
470         this.currentFocusElement.handleKeyEvent(event);
471     else if (this.currentFocusElement.id && this.currentFocusElement.id.length && WebInspector[this.currentFocusElement.id + "KeyDown"])
472         WebInspector[this.currentFocusElement.id + "KeyDown"](event);
473
474     if (!event.handled) {
475         var isMac = InspectorController.platform().indexOf("mac-") === 0;
476
477         switch (event.keyIdentifier) {
478             case "U+001B": // Escape key
479                 this.console.visible = !this.console.visible;
480                 event.preventDefault();
481                 break;
482
483             case "U+0046": // F key
484                 if (isMac)
485                     var isFindKey = event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey;
486                 else
487                     var isFindKey = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey;
488
489                 if (isFindKey) {
490                     var searchField = document.getElementById("search");
491                     searchField.focus();
492                     searchField.select();
493                     event.preventDefault();
494                 }
495
496                 break;
497
498             case "U+0047": // G key
499                 if (isMac)
500                     var isFindAgainKey = event.metaKey && !event.ctrlKey && !event.altKey;
501                 else
502                     var isFindAgainKey = event.ctrlKey && !event.metaKey && !event.altKey;
503
504                 if (isFindAgainKey) {
505                     if (event.shiftKey) {
506                         if (this.currentPanel.jumpToPreviousSearchResult)
507                             this.currentPanel.jumpToPreviousSearchResult();
508                     } else if (this.currentPanel.jumpToNextSearchResult)
509                         this.currentPanel.jumpToNextSearchResult();
510                     event.preventDefault();
511                 }
512
513                 break;
514         }
515     }
516 }
517
518 WebInspector.documentKeyUp = function(event)
519 {
520     if (!this.currentFocusElement || !this.currentFocusElement.handleKeyUpEvent)
521         return;
522     this.currentFocusElement.handleKeyUpEvent(event);
523 }
524
525 WebInspector.documentCanCopy = function(event)
526 {
527     if (!this.currentFocusElement)
528         return;
529     // Calling preventDefault() will say "we support copying, so enable the Copy menu".
530     if (this.currentFocusElement.handleCopyEvent)
531         event.preventDefault();
532     else if (this.currentFocusElement.id && this.currentFocusElement.id.length && WebInspector[this.currentFocusElement.id + "Copy"])
533         event.preventDefault();
534 }
535
536 WebInspector.documentCopy = function(event)
537 {
538     if (!this.currentFocusElement)
539         return;
540     if (this.currentFocusElement.handleCopyEvent)
541         this.currentFocusElement.handleCopyEvent(event);
542     else if (this.currentFocusElement.id && this.currentFocusElement.id.length && WebInspector[this.currentFocusElement.id + "Copy"])
543         WebInspector[this.currentFocusElement.id + "Copy"](event);
544 }
545
546 WebInspector.mainKeyDown = function(event)
547 {
548     if (this.currentPanel && this.currentPanel.handleKeyEvent)
549         this.currentPanel.handleKeyEvent(event);
550 }
551
552 WebInspector.mainKeyUp = function(event)
553 {
554     if (this.currentPanel && this.currentPanel.handleKeyUpEvent)
555         this.currentPanel.handleKeyUpEvent(event);
556 }
557
558 WebInspector.mainCopy = function(event)
559 {
560     if (this.currentPanel && this.currentPanel.handleCopyEvent)
561         this.currentPanel.handleCopyEvent(event);
562 }
563
564 WebInspector.animateStyle = function(animations, duration, callback, complete)
565 {
566     if (complete === undefined)
567         complete = 0;
568     var slice = (1000 / 30); // 30 frames per second
569
570     var defaultUnit = "px";
571     var propertyUnit = {opacity: ""};
572
573     for (var i = 0; i < animations.length; ++i) {
574         var animation = animations[i];
575         var element = null;
576         var start = null;
577         var current = null;
578         var end = null;
579         for (key in animation) {
580             if (key === "element")
581                 element = animation[key];
582             else if (key === "start")
583                 start = animation[key];
584             else if (key === "current")
585                 current = animation[key];
586             else if (key === "end")
587                 end = animation[key];
588         }
589
590         if (!element || !end)
591             continue;
592
593         var computedStyle = element.ownerDocument.defaultView.getComputedStyle(element);
594         if (!start) {
595             start = {};
596             for (key in end)
597                 start[key] = parseInt(computedStyle.getPropertyValue(key));
598             animation.start = start;
599         } else if (complete == 0)
600             for (key in start)
601                 element.style.setProperty(key, start[key] + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
602
603         if (!current) {
604             current = {};
605             for (key in start)
606                 current[key] = start[key];
607             animation.current = current;
608         }
609
610         function cubicInOut(t, b, c, d)
611         {
612             if ((t/=d/2) < 1) return c/2*t*t*t + b;
613             return c/2*((t-=2)*t*t + 2) + b;
614         }
615
616         var style = element.style;
617         for (key in end) {
618             var startValue = start[key];
619             var currentValue = current[key];
620             var endValue = end[key];
621             if ((complete + slice) < duration) {
622                 var delta = (endValue - startValue) / (duration / slice);
623                 var newValue = cubicInOut(complete, startValue, endValue - startValue, duration);
624                 style.setProperty(key, newValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
625                 current[key] = newValue;
626             } else {
627                 style.setProperty(key, endValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
628             }
629         }
630     }
631
632     if (complete < duration)
633         setTimeout(WebInspector.animateStyle, slice, animations, duration, callback, complete + slice);
634     else if (callback)
635         callback();
636 }
637
638 WebInspector.updateSearchLabel = function()
639 {
640     if (!this.currentPanel)
641         return;
642
643     var newLabel = WebInspector.UIString("Search %s", this.currentPanel.toolbarItemLabel);
644     if (this.attached)
645         document.getElementById("search").setAttribute("placeholder", newLabel);
646     else {
647         document.getElementById("search").removeAttribute("placeholder");
648         document.getElementById("search-toolbar-label").textContent = newLabel;
649     }
650 }
651
652 WebInspector.toggleAttach = function()
653 {
654     this.attached = !this.attached;
655 }
656
657 WebInspector.toolbarDragStart = function(event)
658 {
659     if (!WebInspector.attached && InspectorController.platform() !== "mac-leopard")
660         return;
661
662     var target = event.target;
663     if (target.hasStyleClass("toolbar-item") && target.hasStyleClass("toggleable"))
664         return;
665
666     var toolbar = document.getElementById("toolbar");
667     if (target !== toolbar && !target.hasStyleClass("toolbar-item"))
668         return;
669
670     toolbar.lastScreenX = event.screenX;
671     toolbar.lastScreenY = event.screenY;
672
673     WebInspector.elementDragStart(toolbar, WebInspector.toolbarDrag, WebInspector.toolbarDragEnd, event, (WebInspector.attached ? "row-resize" : "default"));
674 }
675
676 WebInspector.toolbarDragEnd = function(event)
677 {
678     var toolbar = document.getElementById("toolbar");
679
680     WebInspector.elementDragEnd(event);
681
682     delete toolbar.lastScreenX;
683     delete toolbar.lastScreenY;
684 }
685
686 WebInspector.toolbarDrag = function(event)
687 {
688     var toolbar = document.getElementById("toolbar");
689
690     if (WebInspector.attached) {
691         var height = window.innerHeight - (event.screenY - toolbar.lastScreenY);
692
693         InspectorController.setAttachedWindowHeight(height);
694     } else {
695         var x = event.screenX - toolbar.lastScreenX;
696         var y = event.screenY - toolbar.lastScreenY;
697
698         // We cannot call window.moveBy here because it restricts the movement
699         // of the window at the edges.
700         InspectorController.moveByUnrestricted(x, y);
701     }
702
703     toolbar.lastScreenX = event.screenX;
704     toolbar.lastScreenY = event.screenY;
705
706     event.preventDefault();
707 }
708
709 WebInspector.elementDragStart = function(element, dividerDrag, elementDragEnd, event, cursor) 
710 {
711     if (this._elementDraggingEventListener || this._elementEndDraggingEventListener)
712         this.elementDragEnd(event);
713
714     this._elementDraggingEventListener = dividerDrag;
715     this._elementEndDraggingEventListener = elementDragEnd;
716
717     document.addEventListener("mousemove", dividerDrag, true);
718     document.addEventListener("mouseup", elementDragEnd, true);
719
720     document.body.style.cursor = cursor;
721
722     event.preventDefault();
723 }
724
725 WebInspector.elementDragEnd = function(event)
726 {
727     document.removeEventListener("mousemove", this._elementDraggingEventListener, true);
728     document.removeEventListener("mouseup", this._elementEndDraggingEventListener, true);
729
730     document.body.style.removeProperty("cursor");
731
732     delete this._elementDraggingEventListener;
733     delete this._elementEndDraggingEventListener;
734
735     event.preventDefault();
736 }
737
738 WebInspector.showConsole = function()
739 {
740     this.console.show();
741 }
742
743 WebInspector.showElementsPanel = function()
744 {
745     this.currentPanel = this.panels.elements;
746 }
747
748 WebInspector.showResourcesPanel = function()
749 {
750     this.currentPanel = this.panels.resources;
751 }
752
753 WebInspector.showScriptsPanel = function()
754 {
755     this.currentPanel = this.panels.scripts;
756 }
757
758 WebInspector.showProfilesPanel = function()
759 {
760     this.currentPanel = this.panels.profiles;
761 }
762
763 WebInspector.showDatabasesPanel = function()
764 {
765     this.currentPanel = this.panels.databases;
766 }
767
768 WebInspector.addResource = function(resource)
769 {
770     this.resources.push(resource);
771     this.resourceURLMap[resource.url] = resource;
772
773     if (resource.mainResource) {
774         this.mainResource = resource;
775         this.panels.elements.reset();
776     }
777
778     this.panels.resources.addResource(resource);
779 }
780
781 WebInspector.removeResource = function(resource)
782 {
783     resource.category.removeResource(resource);
784     delete this.resourceURLMap[resource.url];
785
786     this.resources.remove(resource, true);
787
788     this.panels.resources.removeResource(resource);
789 }
790
791 WebInspector.addDatabase = function(database)
792 {
793     this.panels.databases.addDatabase(database);
794 }
795
796 WebInspector.debuggerAttached = function()
797 {
798     this.panels.scripts.debuggerAttached();
799 }
800
801 WebInspector.debuggerDetached = function()
802 {
803     this.panels.scripts.debuggerDetached();
804 }
805
806 WebInspector.parsedScriptSource = function(sourceID, sourceURL, source, startingLine)
807 {
808     this.panels.scripts.addScript(sourceID, sourceURL, source, startingLine);
809 }
810
811 WebInspector.failedToParseScriptSource = function(sourceURL, source, startingLine, errorLine, errorMessage)
812 {
813     this.panels.scripts.addScript(null, sourceURL, source, startingLine, errorLine, errorMessage);
814 }
815
816 WebInspector.pausedScript = function()
817 {
818     this.panels.scripts.debuggerPaused();
819 }
820
821 WebInspector.populateInterface = function()
822 {
823     for (var panelName in this.panels) {
824         var panel = this.panels[panelName];
825         if ("populateInterface" in panel)
826             panel.populateInterface();
827     }
828 }
829
830 WebInspector.reset = function()
831 {
832     for (var panelName in this.panels) {
833         var panel = this.panels[panelName];
834         if ("reset" in panel)
835             panel.reset();
836     }
837
838     for (var category in this.resourceCategories)
839         this.resourceCategories[category].removeAllResources();
840
841     this.resources = [];
842     this.resourceURLMap = {};
843     this.hoveredDOMNode = null;
844
845     delete this.mainResource;
846
847     this.console.clearMessages();
848 }
849
850 WebInspector.inspectedWindowCleared = function(inspectedWindow)
851 {
852     this.panels.elements.inspectedWindowCleared(inspectedWindow);
853 }
854
855 WebInspector.resourceURLChanged = function(resource, oldURL)
856 {
857     delete this.resourceURLMap[oldURL];
858     this.resourceURLMap[resource.url] = resource;
859 }
860
861 WebInspector.addMessageToConsole = function(msg)
862 {
863     this.console.addMessage(msg);
864 }
865
866 WebInspector.addProfile = function(profile)
867 {
868     this.panels.profiles.addProfile(profile);
869 }
870
871 WebInspector.setRecordingProfile = function(isProfiling)
872 {
873     this.panels.profiles.setRecordingProfile(isProfiling);
874 }
875
876 WebInspector.drawLoadingPieChart = function(canvas, percent) {
877     var g = canvas.getContext("2d");
878     var darkColor = "rgb(122, 168, 218)";
879     var lightColor = "rgb(228, 241, 251)";
880     var cx = 8;
881     var cy = 8;
882     var r = 7;
883
884     g.beginPath();
885     g.arc(cx, cy, r, 0, Math.PI * 2, false); 
886     g.closePath();
887
888     g.lineWidth = 1;
889     g.strokeStyle = darkColor;
890     g.fillStyle = lightColor;
891     g.fill();
892     g.stroke();
893
894     var startangle = -Math.PI / 2;
895     var endangle = startangle + (percent * Math.PI * 2);
896
897     g.beginPath();
898     g.moveTo(cx, cy);
899     g.arc(cx, cy, r, startangle, endangle, false); 
900     g.closePath();
901
902     g.fillStyle = darkColor;
903     g.fill();
904 }
905
906 WebInspector.updateFocusedNode = function(node)
907 {
908     if (!node)
909         // FIXME: Should we deselect if null is passed in?
910         return;
911
912     this.currentPanel = this.panels.elements;
913     this.panels.elements.focusedDOMNode = node;
914 }
915
916 WebInspector.displayNameForURL = function(url)
917 {
918     if (!url)
919         return "";
920     var resource = this.resourceURLMap[url];
921     if (resource)
922         return resource.displayName;
923     return url.trimURL(WebInspector.mainResource ? WebInspector.mainResource.domain : "");
924 }
925
926 WebInspector.resourceForURL = function(url)
927 {
928     if (url in this.resourceURLMap)
929         return this.resourceURLMap[url];
930
931     // No direct match found. Search for resources that contain
932     // a substring of the URL.
933     for (var resourceURL in this.resourceURLMap) {
934         if (resourceURL.hasSubstring(url))
935             return this.resourceURLMap[resourceURL];
936     }
937
938     return null;
939 }
940
941 WebInspector.showResourceForURL = function(url, line, preferredPanel)
942 {
943     var resource = this.resourceForURL(url);
944     if (!resource)
945         return false;
946
947     if (preferredPanel && preferredPanel in WebInspector.panels) {
948         var panel = this.panels[preferredPanel];
949         if (!("showResource" in panel))
950             panel = null;
951         else if ("canShowResource" in panel && !panel.canShowResource(resource))
952             panel = null;
953     }
954
955     this.currentPanel = panel || this.panels.resources;
956     this.currentPanel.showResource(resource, line);
957     return true;
958 }
959
960 WebInspector.linkifyStringAsFragment = function(string)
961 {
962     var container = document.createDocumentFragment();
963     var linkStringRegEx = new RegExp("(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}://|www\\.)[\\w$\\-_+*'=\\|/\\\\(){}[\\]%@&#~,:;.!?]{4,}[\\w$\\-_+*=\\|/\\\\({%@&#~]");
964
965     while (string) {
966         var linkString = linkStringRegEx.exec(string);
967         if (!linkString)
968             break;
969
970         linkString = linkString[0];
971         var title = linkString;
972         var linkIndex = string.indexOf(linkString);
973         var nonLink = string.substring(0, linkIndex);
974         container.appendChild(document.createTextNode(nonLink));
975
976         var profileStringRegEx = new RegExp("webkit-profile://(.+)/[0-9]+");
977         var profileStringMatches = profileStringRegEx.exec(title);
978         var profileTitle;
979         if (profileStringMatches)
980             profileTitle = profileStringMatches[1];
981         if (profileTitle)
982             title = WebInspector.panels.profiles.displayTitleForProfileLink(profileTitle);
983
984         var realURL = (linkString.indexOf("www.") === 0 ? "http://" + linkString : linkString);
985         container.appendChild(WebInspector.linkifyURLAsNode(realURL, title, null, (realURL in WebInspector.resourceURLMap)));
986         string = string.substring(linkIndex + linkString.length, string.length);
987     }
988
989     if (string)
990         container.appendChild(document.createTextNode(string));
991
992     return container;
993 }
994
995 WebInspector.showProfileById = function(uid) {
996     WebInspector.showProfilesPanel();
997     WebInspector.panels.profiles.showProfileById(uid);
998 }
999
1000 WebInspector.linkifyURLAsNode = function(url, linkText, classes, isExternal)
1001 {
1002     if (!linkText)
1003         linkText = url;
1004     classes = (classes ? classes + " " : "");
1005     classes += isExternal ? "webkit-html-external-link" : "webkit-html-resource-link";
1006
1007     var a = document.createElement("a");
1008     a.href = url;
1009     a.className = classes;
1010     a.title = url;
1011     a.target = "_blank";
1012     a.textContent = linkText;
1013     
1014     return a;
1015 }
1016
1017 WebInspector.linkifyURL = function(url, linkText, classes, isExternal)
1018 {
1019     // Use the DOM version of this function so as to avoid needing to escape attributes.
1020     // FIXME:  Get rid of linkifyURL entirely.
1021     return WebInspector.linkifyURLAsNode(url, linkText, classes, isExternal).outerHTML;
1022 }
1023
1024 WebInspector.addMainEventListeners = function(doc)
1025 {
1026     doc.defaultView.addEventListener("focus", this.windowFocused.bind(this), true);
1027     doc.defaultView.addEventListener("blur", this.windowBlured.bind(this), true);
1028     doc.addEventListener("click", this.documentClick.bind(this), true);
1029 }
1030
1031 WebInspector.searchKeyDown = function(event)
1032 {
1033     if (event.keyIdentifier !== "Enter")
1034         return;
1035
1036     // Call preventDefault since this was the Enter key. This prevents a "search" event
1037     // from firing for key down. We handle the Enter key on key up in searchKeyUp. This
1038     // stops performSearch from being called twice in a row.
1039     event.preventDefault();
1040 }
1041
1042 WebInspector.searchKeyUp = function(event)
1043 {
1044     if (event.keyIdentifier !== "Enter")
1045         return;
1046
1047     // Select all of the text so the user can easily type an entirely new query.
1048     event.target.select();
1049
1050     // Only call performSearch if the Enter key was pressed. Otherwise the search
1051     // performance is poor because of searching on every key. The search field has
1052     // the incremental attribute set, so we still get incremental searches.
1053     this.performSearch(event);
1054 }
1055
1056 WebInspector.performSearch = function(event)
1057 {
1058     var query = event.target.value;
1059     var forceSearch = event.keyIdentifier === "Enter";
1060
1061     if (!query || !query.length || (!forceSearch && query.length < 3)) {
1062         delete this.currentQuery;
1063
1064         for (var panelName in this.panels) {
1065             var panel = this.panels[panelName];
1066             if (panel.currentQuery && panel.searchCanceled)
1067                 panel.searchCanceled();
1068             delete panel.currentQuery;
1069         }
1070
1071         this.updateSearchMatchesCount();
1072
1073         return;
1074     }
1075
1076     if (query === this.currentPanel.currentQuery && this.currentPanel.currentQuery === this.currentQuery) {
1077         // When this is the same query and a forced search, jump to the next
1078         // search result for a good user experience.
1079         if (forceSearch && this.currentPanel.jumpToNextSearchResult)
1080             this.currentPanel.jumpToNextSearchResult();
1081         return;
1082     }
1083
1084     this.currentQuery = query;
1085
1086     this.updateSearchMatchesCount();
1087
1088     if (!this.currentPanel.performSearch)
1089         return;
1090
1091     this.currentPanel.currentQuery = query;
1092     this.currentPanel.performSearch(query);
1093 }
1094
1095 WebInspector.updateSearchMatchesCount = function(matches, panel)
1096 {
1097     if (!panel)
1098         panel = this.currentPanel;
1099
1100     panel.currentSearchMatches = matches;
1101
1102     if (panel !== this.currentPanel)
1103         return;
1104
1105     if (!this.currentPanel.currentQuery) {
1106         document.getElementById("search-results-matches").addStyleClass("hidden");
1107         return;
1108     }
1109
1110     if (matches) {
1111         if (matches === 1)
1112             var matchesString = WebInspector.UIString("1 match");
1113         else
1114             var matchesString = WebInspector.UIString("%d matches", matches);
1115     } else
1116         var matchesString = WebInspector.UIString("Not Found");
1117
1118     var matchesToolbarElement = document.getElementById("search-results-matches");
1119     matchesToolbarElement.removeStyleClass("hidden");
1120     matchesToolbarElement.textContent = matchesString;
1121 }
1122
1123 WebInspector.UIString = function(string)
1124 {
1125     if (window.localizedStrings && string in window.localizedStrings)
1126         string = window.localizedStrings[string];
1127     else {
1128         if (!(string in this.missingLocalizedStrings)) {
1129             console.error("Localized string \"" + string + "\" not found.");
1130             this.missingLocalizedStrings[string] = true;
1131         }
1132
1133         if (Preferences.showMissingLocalizedStrings)
1134             string += " (not localized)";
1135     }
1136
1137     return String.vsprintf(string, Array.prototype.slice.call(arguments, 1));
1138 }
1139
1140 WebInspector.isBeingEdited = function(element)
1141 {
1142     return element.__editing;
1143 }
1144
1145 WebInspector.startEditing = function(element, committedCallback, cancelledCallback, context)
1146 {
1147     if (element.__editing)
1148         return;
1149     element.__editing = true;
1150
1151     var oldText = element.textContent;
1152     var oldHandleKeyEvent = element.handleKeyEvent;
1153
1154     element.addStyleClass("editing");
1155
1156     var oldTabIndex = element.tabIndex;
1157     if (element.tabIndex < 0)
1158         element.tabIndex = 0;
1159
1160     function blurEventListener() {
1161         editingCommitted.call(element);
1162     }
1163
1164     function cleanUpAfterEditing() {
1165         delete this.__editing;
1166
1167         this.removeStyleClass("editing");
1168         this.tabIndex = oldTabIndex;
1169         this.scrollTop = 0;
1170         this.scrollLeft = 0;
1171
1172         this.handleKeyEvent = oldHandleKeyEvent;
1173         element.removeEventListener("blur", blurEventListener, false);
1174
1175         if (element === WebInspector.currentFocusElement || element.isAncestor(WebInspector.currentFocusElement))
1176             WebInspector.currentFocusElement = WebInspector.previousFocusElement;
1177     }
1178
1179     function editingCancelled() {
1180         this.innerText = oldText;
1181
1182         cleanUpAfterEditing.call(this);
1183
1184         cancelledCallback(this, context);
1185     }
1186
1187     function editingCommitted() {
1188         cleanUpAfterEditing.call(this);
1189
1190         committedCallback(this, this.textContent, oldText, context);
1191     }
1192
1193     element.handleKeyEvent = function(event) {
1194         if (oldHandleKeyEvent)
1195             oldHandleKeyEvent(event);
1196         if (event.handled)
1197             return;
1198
1199         if (event.keyIdentifier === "Enter") {
1200             editingCommitted.call(element);
1201             event.preventDefault();
1202         } else if (event.keyCode === 27) { // Escape key
1203             editingCancelled.call(element);
1204             event.preventDefault();
1205             event.handled = true;
1206         }
1207     }
1208
1209     element.addEventListener("blur", blurEventListener, false);
1210
1211     WebInspector.currentFocusElement = element;
1212 }
1213
1214 WebInspector._toolbarItemClicked = function(event)
1215 {
1216     var toolbarItem = event.currentTarget;
1217     this.currentPanel = toolbarItem.panel;
1218 }
1219
1220 // This table maps MIME types to the Resource.Types which are valid for them.
1221 // The following line:
1222 //    "text/html":                {0: 1},
1223 // means that text/html is a valid MIME type for resources that have type
1224 // WebInspector.Resource.Type.Document (which has a value of 0).
1225 WebInspector.MIMETypes = {
1226     "text/html":                   {0: true},
1227     "text/xml":                    {0: true},
1228     "text/plain":                  {0: true},
1229     "application/xhtml+xml":       {0: true},
1230     "text/css":                    {1: true},
1231     "text/xsl":                    {1: true},
1232     "image/jpeg":                  {2: true},
1233     "image/png":                   {2: true},
1234     "image/gif":                   {2: true},
1235     "image/bmp":                   {2: true},
1236     "image/x-icon":                {2: true},
1237     "image/x-xbitmap":             {2: true},
1238     "font/ttf":                    {3: true},
1239     "font/opentype":               {3: true},
1240     "application/x-font-type1":    {3: true},
1241     "application/x-font-ttf":      {3: true},
1242     "application/x-truetype-font": {3: true},
1243     "text/javascript":             {4: true},
1244     "text/ecmascript":             {4: true},
1245     "application/javascript":      {4: true},
1246     "application/ecmascript":      {4: true},
1247     "application/x-javascript":    {4: true},
1248     "text/javascript1.1":          {4: true},
1249     "text/javascript1.2":          {4: true},
1250     "text/javascript1.3":          {4: true},
1251     "text/jscript":                {4: true},
1252     "text/livescript":             {4: true},
1253 }