Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / devtools / front_end / UIUtils.js
1 /*
2  * Copyright (C) 2011 Google Inc.  All rights reserved.
3  * Copyright (C) 2006, 2007, 2008 Apple Inc.  All rights reserved.
4  * Copyright (C) 2007 Matt Lilek (pewtermoose@gmail.com).
5  * Copyright (C) 2009 Joseph Pecoraro
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1.  Redistributions of source code must retain the above copyright
12  *     notice, this list of conditions and the following disclaimer.
13  * 2.  Redistributions in binary form must reproduce the above copyright
14  *     notice, this list of conditions and the following disclaimer in the
15  *     documentation and/or other materials provided with the distribution.
16  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
17  *     its contributors may be used to endorse or promote products derived
18  *     from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
21  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
24  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
25  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
27  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 /**
33  * @param {!Element} element
34  * @param {?function(!MouseEvent): boolean} elementDragStart
35  * @param {function(!MouseEvent)} elementDrag
36  * @param {?function(!MouseEvent)} elementDragEnd
37  * @param {!string} cursor
38  * @param {?string=} hoverCursor
39  */
40 WebInspector.installDragHandle = function(element, elementDragStart, elementDrag, elementDragEnd, cursor, hoverCursor)
41 {
42     element.addEventListener("mousedown", WebInspector.elementDragStart.bind(WebInspector, elementDragStart, elementDrag, elementDragEnd, cursor), false);
43     if (hoverCursor !== null)
44         element.style.cursor = hoverCursor || cursor;
45 }
46
47 /**
48  * @param {?function(!MouseEvent):boolean} elementDragStart
49  * @param {function(!MouseEvent)} elementDrag
50  * @param {?function(!MouseEvent)} elementDragEnd
51  * @param {string} cursor
52  * @param {?Event} event
53  */
54 WebInspector.elementDragStart = function(elementDragStart, elementDrag, elementDragEnd, cursor, event)
55 {
56     // Only drag upon left button. Right will likely cause a context menu. So will ctrl-click on mac.
57     if (event.button || (WebInspector.isMac() && event.ctrlKey))
58         return;
59
60     if (WebInspector._elementDraggingEventListener)
61         return;
62
63     if (elementDragStart && !elementDragStart(/** @type {!MouseEvent} */ (event)))
64         return;
65
66     if (WebInspector._elementDraggingGlassPane) {
67         WebInspector._elementDraggingGlassPane.dispose();
68         delete WebInspector._elementDraggingGlassPane;
69     }
70
71     var targetDocument = event.target.ownerDocument;
72
73     WebInspector._elementDraggingEventListener = elementDrag;
74     WebInspector._elementEndDraggingEventListener = elementDragEnd;
75     WebInspector._mouseOutWhileDraggingTargetDocument = targetDocument;
76
77     targetDocument.addEventListener("mousemove", WebInspector._elementDragMove, true);
78     targetDocument.addEventListener("mouseup", WebInspector._elementDragEnd, true);
79     targetDocument.addEventListener("mouseout", WebInspector._mouseOutWhileDragging, true);
80
81     targetDocument.body.style.cursor = cursor;
82
83     event.preventDefault();
84 }
85
86 WebInspector._mouseOutWhileDragging = function()
87 {
88     WebInspector._unregisterMouseOutWhileDragging();
89     WebInspector._elementDraggingGlassPane = new WebInspector.GlassPane();
90 }
91
92 WebInspector._unregisterMouseOutWhileDragging = function()
93 {
94     if (!WebInspector._mouseOutWhileDraggingTargetDocument)
95         return;
96     WebInspector._mouseOutWhileDraggingTargetDocument.removeEventListener("mouseout", WebInspector._mouseOutWhileDragging, true);
97     delete WebInspector._mouseOutWhileDraggingTargetDocument;
98 }
99
100 /**
101  * @param {!Event} event
102  */
103 WebInspector._elementDragMove = function(event)
104 {
105     if (WebInspector._elementDraggingEventListener(/** @type {!MouseEvent} */ (event)))
106         WebInspector._cancelDragEvents(event);
107 }
108
109 /**
110  * @param {!Event} event
111  */
112 WebInspector._cancelDragEvents = function(event)
113 {
114     var targetDocument = event.target.ownerDocument;
115     targetDocument.removeEventListener("mousemove", WebInspector._elementDragMove, true);
116     targetDocument.removeEventListener("mouseup", WebInspector._elementDragEnd, true);
117     WebInspector._unregisterMouseOutWhileDragging();
118
119     targetDocument.body.style.removeProperty("cursor");
120
121     if (WebInspector._elementDraggingGlassPane)
122         WebInspector._elementDraggingGlassPane.dispose();
123
124     delete WebInspector._elementDraggingGlassPane;
125     delete WebInspector._elementDraggingEventListener;
126     delete WebInspector._elementEndDraggingEventListener;
127 }
128
129 /**
130  * @param {!Event} event
131  */
132 WebInspector._elementDragEnd = function(event)
133 {
134     var elementDragEnd = WebInspector._elementEndDraggingEventListener;
135
136     WebInspector._cancelDragEvents(/** @type {!MouseEvent} */ (event));
137
138     event.preventDefault();
139     if (elementDragEnd)
140         elementDragEnd(/** @type {!MouseEvent} */ (event));
141 }
142
143 /**
144  * @constructor
145  */
146 WebInspector.GlassPane = function()
147 {
148     this.element = document.createElement("div");
149     this.element.style.cssText = "position:absolute;top:0;bottom:0;left:0;right:0;background-color:transparent;z-index:1000;";
150     this.element.id = "glass-pane";
151     document.body.appendChild(this.element);
152     WebInspector._glassPane = this;
153 }
154
155 WebInspector.GlassPane.prototype = {
156     dispose: function()
157     {
158         delete WebInspector._glassPane;
159         if (WebInspector.HelpScreen.isVisible())
160             WebInspector.HelpScreen.focus();
161         else
162             WebInspector.inspectorView.focus();
163         this.element.remove();
164     }
165 }
166
167 WebInspector.isBeingEdited = function(element)
168 {
169     if (element.classList.contains("text-prompt") || element.nodeName === "INPUT" || element.nodeName === "TEXTAREA")
170         return true;
171
172     if (!WebInspector.__editingCount)
173         return false;
174
175     while (element) {
176         if (element.__editing)
177             return true;
178         element = element.parentElement;
179     }
180     return false;
181 }
182
183 WebInspector.markBeingEdited = function(element, value)
184 {
185     if (value) {
186         if (element.__editing)
187             return false;
188         element.classList.add("being-edited");
189         element.__editing = true;
190         WebInspector.__editingCount = (WebInspector.__editingCount || 0) + 1;
191     } else {
192         if (!element.__editing)
193             return false;
194         element.classList.remove("being-edited");
195         delete element.__editing;
196         --WebInspector.__editingCount;
197     }
198     return true;
199 }
200
201 WebInspector.CSSNumberRegex = /^(-?(?:\d+(?:\.\d+)?|\.\d+))$/;
202
203 WebInspector.StyleValueDelimiters = " \xA0\t\n\"':;,/()";
204
205
206 /**
207   * @param {!Event} event
208   * @return {?string}
209   */
210 WebInspector._valueModificationDirection = function(event)
211 {
212     var direction = null;
213     if (event.type === "mousewheel") {
214         if (event.wheelDeltaY > 0)
215             direction = "Up";
216         else if (event.wheelDeltaY < 0)
217             direction = "Down";
218     } else {
219         if (event.keyIdentifier === "Up" || event.keyIdentifier === "PageUp")
220             direction = "Up";
221         else if (event.keyIdentifier === "Down" || event.keyIdentifier === "PageDown")
222             direction = "Down";        
223     }
224     return direction;
225 }
226
227 /**
228  * @param {string} hexString
229  * @param {!Event} event
230  */
231 WebInspector._modifiedHexValue = function(hexString, event)
232 {
233     var direction = WebInspector._valueModificationDirection(event);
234     if (!direction)
235         return hexString;
236
237     var number = parseInt(hexString, 16);
238     if (isNaN(number) || !isFinite(number))
239         return hexString;
240
241     var maxValue = Math.pow(16, hexString.length) - 1;
242     var arrowKeyOrMouseWheelEvent = (event.keyIdentifier === "Up" || event.keyIdentifier === "Down" || event.type === "mousewheel");
243     var delta;
244
245     if (arrowKeyOrMouseWheelEvent)
246         delta = (direction === "Up") ? 1 : -1;
247     else
248         delta = (event.keyIdentifier === "PageUp") ? 16 : -16;
249
250     if (event.shiftKey)
251         delta *= 16;
252
253     var result = number + delta;
254     if (result < 0)
255         result = 0; // Color hex values are never negative, so clamp to 0.
256     else if (result > maxValue)
257         return hexString;
258
259     // Ensure the result length is the same as the original hex value.
260     var resultString = result.toString(16).toUpperCase();
261     for (var i = 0, lengthDelta = hexString.length - resultString.length; i < lengthDelta; ++i)
262         resultString = "0" + resultString;
263     return resultString;
264 }
265
266 /**
267  * @param {number} number
268  * @param {!Event} event
269  */
270 WebInspector._modifiedFloatNumber = function(number, event)
271 {
272     var direction = WebInspector._valueModificationDirection(event);
273     if (!direction)
274         return number;
275     
276     var arrowKeyOrMouseWheelEvent = (event.keyIdentifier === "Up" || event.keyIdentifier === "Down" || event.type === "mousewheel");
277
278     // Jump by 10 when shift is down or jump by 0.1 when Alt/Option is down.
279     // Also jump by 10 for page up and down, or by 100 if shift is held with a page key.
280     var changeAmount = 1;
281     if (event.shiftKey && !arrowKeyOrMouseWheelEvent)
282         changeAmount = 100;
283     else if (event.shiftKey || !arrowKeyOrMouseWheelEvent)
284         changeAmount = 10;
285     else if (event.altKey)
286         changeAmount = 0.1;
287
288     if (direction === "Down")
289         changeAmount *= -1;
290
291     // Make the new number and constrain it to a precision of 6, this matches numbers the engine returns.
292     // Use the Number constructor to forget the fixed precision, so 1.100000 will print as 1.1.
293     var result = Number((number + changeAmount).toFixed(6));
294     if (!String(result).match(WebInspector.CSSNumberRegex))
295         return null;
296
297     return result;
298 }
299
300 /**
301   * @param {?Event} event
302   * @param {!Element} element
303   * @param {function(string,string)=} finishHandler
304   * @param {function(string)=} suggestionHandler
305   * @param {function(number):number=} customNumberHandler
306   * @return {boolean}
307  */
308 WebInspector.handleElementValueModifications = function(event, element, finishHandler, suggestionHandler, customNumberHandler)
309 {
310     var arrowKeyOrMouseWheelEvent = (event.keyIdentifier === "Up" || event.keyIdentifier === "Down" || event.type === "mousewheel");
311     var pageKeyPressed = (event.keyIdentifier === "PageUp" || event.keyIdentifier === "PageDown");
312     if (!arrowKeyOrMouseWheelEvent && !pageKeyPressed)
313         return false;
314
315     var selection = window.getSelection();
316     if (!selection.rangeCount)
317         return false;
318
319     var selectionRange = selection.getRangeAt(0);
320     if (!selectionRange.commonAncestorContainer.isSelfOrDescendant(element))
321         return false;
322
323     var originalValue = element.textContent;
324     var wordRange = selectionRange.startContainer.rangeOfWord(selectionRange.startOffset, WebInspector.StyleValueDelimiters, element);
325     var wordString = wordRange.toString();
326     
327     if (suggestionHandler && suggestionHandler(wordString))
328         return false;
329
330     var replacementString;
331     var prefix, suffix, number;
332
333     var matches;
334     matches = /(.*#)([\da-fA-F]+)(.*)/.exec(wordString);
335     if (matches && matches.length) {
336         prefix = matches[1];
337         suffix = matches[3];
338         number = WebInspector._modifiedHexValue(matches[2], event);
339         
340         if (customNumberHandler)
341             number = customNumberHandler(number);
342
343         replacementString = prefix + number + suffix;
344     } else {
345         matches = /(.*?)(-?(?:\d+(?:\.\d+)?|\.\d+))(.*)/.exec(wordString);
346         if (matches && matches.length) {
347             prefix = matches[1];
348             suffix = matches[3];
349             number = WebInspector._modifiedFloatNumber(parseFloat(matches[2]), event);
350             
351             // Need to check for null explicitly.
352             if (number === null)                
353                 return false;
354             
355             if (customNumberHandler)
356                 number = customNumberHandler(number);
357
358             replacementString = prefix + number + suffix;
359         }
360     }
361
362     if (replacementString) {
363         var replacementTextNode = document.createTextNode(replacementString);
364
365         wordRange.deleteContents();
366         wordRange.insertNode(replacementTextNode);
367
368         var finalSelectionRange = document.createRange();
369         finalSelectionRange.setStart(replacementTextNode, 0);
370         finalSelectionRange.setEnd(replacementTextNode, replacementString.length);
371
372         selection.removeAllRanges();
373         selection.addRange(finalSelectionRange);
374
375         event.handled = true;
376         event.preventDefault();
377                 
378         if (finishHandler)
379             finishHandler(originalValue, replacementString);
380
381         return true;
382     }
383     return false;
384 }
385
386 /**
387  * @param {number} seconds
388  * @param {boolean=} higherResolution
389  * @return {string}
390  */
391 Number.secondsToString = function(seconds, higherResolution)
392 {
393     if (!isFinite(seconds))
394         return "-";
395
396     if (seconds === 0)
397         return "0";
398
399     var ms = seconds * 1000;
400     if (higherResolution && ms < 1000)
401         return WebInspector.UIString("%.3f\u2009ms", ms);
402     else if (ms < 1000)
403         return WebInspector.UIString("%.0f\u2009ms", ms);
404
405     if (seconds < 60)
406         return WebInspector.UIString("%.2f\u2009s", seconds);
407
408     var minutes = seconds / 60;
409     if (minutes < 60)
410         return WebInspector.UIString("%.1f\u2009min", minutes);
411
412     var hours = minutes / 60;
413     if (hours < 24)
414         return WebInspector.UIString("%.1f\u2009hrs", hours);
415
416     var days = hours / 24;
417     return WebInspector.UIString("%.1f\u2009days", days);
418 }
419
420 /**
421  * @param {number} bytes
422  * @return {string}
423  */
424 Number.bytesToString = function(bytes)
425 {
426     if (bytes < 1024)
427         return WebInspector.UIString("%.0f\u2009B", bytes);
428
429     var kilobytes = bytes / 1024;
430     if (kilobytes < 100)
431         return WebInspector.UIString("%.1f\u2009KB", kilobytes);
432     if (kilobytes < 1024)
433         return WebInspector.UIString("%.0f\u2009KB", kilobytes);
434
435     var megabytes = kilobytes / 1024;
436     if (megabytes < 100)
437         return WebInspector.UIString("%.1f\u2009MB", megabytes);
438     else
439         return WebInspector.UIString("%.0f\u2009MB", megabytes);
440 }
441
442 Number.withThousandsSeparator = function(num)
443 {
444     var str = num + "";
445     var re = /(\d+)(\d{3})/;
446     while (str.match(re))
447         str = str.replace(re, "$1\u2009$2"); // \u2009 is a thin space.
448     return str;
449 }
450
451 WebInspector.useLowerCaseMenuTitles = function()
452 {
453     return WebInspector.platform() === "windows";
454 }
455
456 WebInspector.formatLocalized = function(format, substitutions, formatters, initialValue, append)
457 {
458     return String.format(WebInspector.UIString(format), substitutions, formatters, initialValue, append);
459 }
460
461 WebInspector.openLinkExternallyLabel = function()
462 {
463     return WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Open link in new tab" : "Open Link in New Tab");
464 }
465
466 WebInspector.copyLinkAddressLabel = function()
467 {
468     return WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Copy link address" : "Copy Link Address");
469 }
470
471 WebInspector.installPortStyles = function()
472 {
473     var platform = WebInspector.platform();
474     document.body.classList.add("platform-" + platform);
475     var flavor = WebInspector.platformFlavor();
476     if (flavor)
477         document.body.classList.add("platform-" + flavor);
478     var port = WebInspector.port();
479     document.body.classList.add("port-" + port);
480 }
481
482 WebInspector._windowFocused = function(event)
483 {
484     if (event.target.document.nodeType === Node.DOCUMENT_NODE)
485         document.body.classList.remove("inactive");
486 }
487
488 WebInspector._windowBlurred = function(event)
489 {
490     if (event.target.document.nodeType === Node.DOCUMENT_NODE)
491         document.body.classList.add("inactive");
492 }
493
494 WebInspector.previousFocusElement = function()
495 {
496     return WebInspector._previousFocusElement;
497 }
498
499 WebInspector.currentFocusElement = function()
500 {
501     return WebInspector._currentFocusElement;
502 }
503
504 WebInspector._focusChanged = function(event)
505 {
506     WebInspector.setCurrentFocusElement(event.target);
507 }
508
509 WebInspector._textInputTypes = ["text", "search", "tel", "url", "email", "password"].keySet(); 
510 WebInspector._isTextEditingElement = function(element)
511 {
512     if (element instanceof HTMLInputElement)
513         return element.type in WebInspector._textInputTypes;
514
515     if (element instanceof HTMLTextAreaElement)
516         return true;
517
518     return false;
519 }
520
521 WebInspector.setCurrentFocusElement = function(x)
522 {
523     if (WebInspector._glassPane && x && !WebInspector._glassPane.element.isAncestor(x))
524         return;
525     if (WebInspector._currentFocusElement !== x)
526         WebInspector._previousFocusElement = WebInspector._currentFocusElement;
527     WebInspector._currentFocusElement = x;
528
529     if (WebInspector._currentFocusElement) {
530         WebInspector._currentFocusElement.focus();
531
532         // Make a caret selection inside the new element if there isn't a range selection and there isn't already a caret selection inside.
533         // This is needed (at least) to remove caret from console when focus is moved to some element in the panel.
534         // The code below should not be applied to text fields and text areas, hence _isTextEditingElement check.
535         var selection = window.getSelection();
536         if (!WebInspector._isTextEditingElement(WebInspector._currentFocusElement) && selection.isCollapsed && !WebInspector._currentFocusElement.isInsertionCaretInside()) {
537             var selectionRange = WebInspector._currentFocusElement.ownerDocument.createRange();
538             selectionRange.setStart(WebInspector._currentFocusElement, 0);
539             selectionRange.setEnd(WebInspector._currentFocusElement, 0);
540
541             selection.removeAllRanges();
542             selection.addRange(selectionRange);
543         }
544     } else if (WebInspector._previousFocusElement)
545         WebInspector._previousFocusElement.blur();
546 }
547
548 WebInspector.restoreFocusFromElement = function(element)
549 {
550     if (element && element.isSelfOrAncestor(WebInspector.currentFocusElement()))
551         WebInspector.setCurrentFocusElement(WebInspector.previousFocusElement());
552 }
553
554 WebInspector.setToolbarColors = function(backgroundColor, color)
555 {
556     if (!WebInspector._themeStyleElement) {
557         WebInspector._themeStyleElement = document.createElement("style");
558         document.head.appendChild(WebInspector._themeStyleElement);
559     }
560     var parsedColor = WebInspector.Color.parse(color);
561     var shadowColor = parsedColor ? parsedColor.invert().setAlpha(0.33).toString(WebInspector.Color.Format.RGBA) : "white";
562     var prefix = WebInspector.isMac() ? "body:not(.undocked)" : "";
563     WebInspector._themeStyleElement.textContent =
564         String.sprintf(
565             "%s .toolbar-background {\
566                  background-image: none !important;\
567                  background-color: %s !important;\
568                  color: %s !important;\
569              }", prefix, backgroundColor, color) +
570         String.sprintf(
571              "%s .toolbar-background button.status-bar-item .glyph, %s .toolbar-background button.status-bar-item .long-click-glyph {\
572                  background-color: %s;\
573              }", prefix, prefix, color) +
574         String.sprintf(
575              "%s .toolbar-background button.status-bar-item .glyph.shadow, %s .toolbar-background button.status-bar-item .long-click-glyph.shadow {\
576                  background-color: %s;\
577              }", prefix, prefix, shadowColor);
578 }
579
580 WebInspector.resetToolbarColors = function()
581 {
582     if (WebInspector._themeStyleElement)
583         WebInspector._themeStyleElement.textContent = "";
584 }
585
586 /**
587  * @param {!Element} element
588  * @param {number} offset
589  * @param {number} length
590  * @param {!Array.<!Object>=} domChanges
591  */
592 WebInspector.highlightSearchResult = function(element, offset, length, domChanges)
593 {
594     var result = WebInspector.highlightSearchResults(element, [new WebInspector.SourceRange(offset, length)], domChanges);
595     return result.length ? result[0] : null;
596 }
597
598 /**
599  * @param {!Element} element
600  * @param {!Array.<!WebInspector.SourceRange>} resultRanges
601  * @param {!Array.<!Object>=} changes
602  */
603 WebInspector.highlightSearchResults = function(element, resultRanges, changes)
604 {
605     return WebInspector.highlightRangesWithStyleClass(element, resultRanges, "highlighted-search-result", changes);
606 }
607
608 /**
609  * @param {!Element} element
610  * @param {string} className
611  */
612 WebInspector.runCSSAnimationOnce = function(element, className)
613 {
614     function animationEndCallback()
615     {
616         element.classList.remove(className);
617         element.removeEventListener("animationend", animationEndCallback, false);
618     }
619
620     if (element.classList.contains(className))
621         element.classList.remove(className);
622
623     element.addEventListener("animationend", animationEndCallback, false);
624     element.classList.add(className);
625 }
626
627 /**
628  * @param {!Element} element
629  * @param {!Array.<!WebInspector.SourceRange>} resultRanges
630  * @param {string} styleClass
631  * @param {!Array.<!Object>=} changes
632  * @return {!Array.<!Element>}
633  */
634 WebInspector.highlightRangesWithStyleClass = function(element, resultRanges, styleClass, changes)
635 {
636     changes = changes || [];
637     var highlightNodes = [];
638     var lineText = element.textContent;
639     var ownerDocument = element.ownerDocument;
640     var textNodeSnapshot = ownerDocument.evaluate(".//text()", element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
641
642     var snapshotLength = textNodeSnapshot.snapshotLength;
643     if (snapshotLength === 0)
644         return highlightNodes;
645
646     var nodeRanges = [];
647     var rangeEndOffset = 0;
648     for (var i = 0; i < snapshotLength; ++i) {
649         var range = {};
650         range.offset = rangeEndOffset;
651         range.length = textNodeSnapshot.snapshotItem(i).textContent.length;
652         rangeEndOffset = range.offset + range.length;
653         nodeRanges.push(range);
654     }
655
656     var startIndex = 0;
657     for (var i = 0; i < resultRanges.length; ++i) {
658         var startOffset = resultRanges[i].offset;
659         var endOffset = startOffset + resultRanges[i].length;
660
661         while (startIndex < snapshotLength && nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset)
662             startIndex++;
663         var endIndex = startIndex;
664         while (endIndex < snapshotLength && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset)
665             endIndex++;
666         if (endIndex === snapshotLength)
667             break;
668
669         var highlightNode = ownerDocument.createElement("span");
670         highlightNode.className = styleClass;
671         highlightNode.textContent = lineText.substring(startOffset, endOffset);
672
673         var lastTextNode = textNodeSnapshot.snapshotItem(endIndex);
674         var lastText = lastTextNode.textContent;
675         lastTextNode.textContent = lastText.substring(endOffset - nodeRanges[endIndex].offset);
676         changes.push({ node: lastTextNode, type: "changed", oldText: lastText, newText: lastTextNode.textContent });
677
678         if (startIndex === endIndex) {
679             lastTextNode.parentElement.insertBefore(highlightNode, lastTextNode);
680             changes.push({ node: highlightNode, type: "added", nextSibling: lastTextNode, parent: lastTextNode.parentElement });
681             highlightNodes.push(highlightNode);
682
683             var prefixNode = ownerDocument.createTextNode(lastText.substring(0, startOffset - nodeRanges[startIndex].offset));
684             lastTextNode.parentElement.insertBefore(prefixNode, highlightNode);
685             changes.push({ node: prefixNode, type: "added", nextSibling: highlightNode, parent: lastTextNode.parentElement });
686         } else {
687             var firstTextNode = textNodeSnapshot.snapshotItem(startIndex);
688             var firstText = firstTextNode.textContent;
689             var anchorElement = firstTextNode.nextSibling;
690
691             firstTextNode.parentElement.insertBefore(highlightNode, anchorElement);
692             changes.push({ node: highlightNode, type: "added", nextSibling: anchorElement, parent: firstTextNode.parentElement });
693             highlightNodes.push(highlightNode);
694
695             firstTextNode.textContent = firstText.substring(0, startOffset - nodeRanges[startIndex].offset);
696             changes.push({ node: firstTextNode, type: "changed", oldText: firstText, newText: firstTextNode.textContent });
697
698             for (var j = startIndex + 1; j < endIndex; j++) {
699                 var textNode = textNodeSnapshot.snapshotItem(j);
700                 var text = textNode.textContent;
701                 textNode.textContent = "";
702                 changes.push({ node: textNode, type: "changed", oldText: text, newText: textNode.textContent });
703             }
704         }
705         startIndex = endIndex;
706         nodeRanges[startIndex].offset = endOffset;
707         nodeRanges[startIndex].length = lastTextNode.textContent.length;
708
709     }
710     return highlightNodes;
711 }
712
713 WebInspector.applyDomChanges = function(domChanges)
714 {
715     for (var i = 0, size = domChanges.length; i < size; ++i) {
716         var entry = domChanges[i];
717         switch (entry.type) {
718         case "added":
719             entry.parent.insertBefore(entry.node, entry.nextSibling);
720             break;
721         case "changed":
722             entry.node.textContent = entry.newText;
723             break;
724         }
725     }
726 }
727
728 WebInspector.revertDomChanges = function(domChanges)
729 {
730     for (var i = domChanges.length - 1; i >= 0; --i) {
731         var entry = domChanges[i];
732         switch (entry.type) {
733         case "added":
734             entry.node.remove();
735             break;
736         case "changed":
737             entry.node.textContent = entry.oldText;
738             break;
739         }
740     }
741 }
742
743 WebInspector._coalescingLevel = 0;
744
745 WebInspector.startBatchUpdate = function()
746 {
747     if (!WebInspector._coalescingLevel)
748         WebInspector._postUpdateHandlers = new Map();
749     WebInspector._coalescingLevel++;
750 }
751
752 WebInspector.endBatchUpdate = function()
753 {
754     if (--WebInspector._coalescingLevel)
755         return;
756
757     var handlers = WebInspector._postUpdateHandlers;
758     delete WebInspector._postUpdateHandlers;
759
760     var keys = handlers.keys();
761     for (var i = 0; i < keys.length; ++i) {
762         var object = keys[i];
763         var methods = handlers.get(object).keys();
764         for (var j = 0; j < methods.length; ++j)
765             methods[j].call(object);
766     }
767 }
768
769 /**
770  * @param {!Object} object
771  * @param {function()} method
772  */
773 WebInspector.invokeOnceAfterBatchUpdate = function(object, method)
774 {
775     if (!WebInspector._coalescingLevel) {
776         method.call(object);
777         return;
778     }
779     
780     var methods = WebInspector._postUpdateHandlers.get(object);
781     if (!methods) {
782         methods = new Map();
783         WebInspector._postUpdateHandlers.put(object, methods);
784     }
785     methods.put(method);
786 }
787
788 ;(function() {
789
790 /**
791  * @this {Window}
792  */
793 function windowLoaded()
794 {
795     window.addEventListener("focus", WebInspector._windowFocused, false);
796     window.addEventListener("blur", WebInspector._windowBlurred, false);
797     document.addEventListener("focus", WebInspector._focusChanged.bind(this), true);
798     window.removeEventListener("DOMContentLoaded", windowLoaded, false);
799 }
800
801 window.addEventListener("DOMContentLoaded", windowLoaded, false);
802
803 })();