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