2 * Copyright (C) 2011 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 * @extends {WebInspector.View}
34 * @implements {WebInspector.Replaceable}
35 * @param {!WebInspector.ContentProvider} contentProvider
37 WebInspector.SourceFrame = function(contentProvider)
39 WebInspector.View.call(this);
40 this.element.classList.add("script-view");
42 this._url = contentProvider.contentURL();
43 this._contentProvider = contentProvider;
45 var textEditorDelegate = new WebInspector.TextEditorDelegateForSourceFrame(this);
47 WebInspector.moduleManager.loadModule("codemirror");
48 this._textEditor = new WebInspector.CodeMirrorTextEditor(this._url, textEditorDelegate);
50 this._currentSearchResultIndex = -1;
51 this._searchResults = [];
54 this._rowMessages = {};
55 this._messageBubbles = {};
57 this._textEditor.setReadOnly(!this.canEditSource());
60 this.element.addEventListener("keydown", this._handleKeyDown.bind(this), false);
62 this._sourcePosition = new WebInspector.StatusBarText("", "source-frame-cursor-position");
66 * @param {string} query
67 * @param {string=} modifiers
70 WebInspector.SourceFrame.createSearchRegex = function(query, modifiers)
73 modifiers = modifiers || "";
75 // First try creating regex if user knows the / / hint.
77 if (/^\/.+\/$/.test(query)) {
78 regex = new RegExp(query.substring(1, query.length - 1), modifiers);
79 regex.__fromRegExpQuery = true;
85 // Otherwise just do case-insensitive search.
87 regex = createPlainTextSearchRegex(query, "i" + modifiers);
92 WebInspector.SourceFrame.Events = {
93 ScrollChanged: "ScrollChanged",
94 SelectionChanged: "SelectionChanged",
95 JumpHappened: "JumpHappened"
98 WebInspector.SourceFrame.prototype = {
100 * @param {number} key
101 * @param {function()} handler
103 addShortcut: function(key, handler)
105 this._shortcuts[key] = handler;
110 this._ensureContentLoaded();
111 this._textEditor.show(this.element);
112 this._editorAttached = true;
113 this._wasShownOrLoaded();
119 _isEditorShowing: function()
121 return this.isShowing() && this._editorAttached;
126 WebInspector.View.prototype.willHide.call(this);
128 this._clearPositionHighlight();
129 this._clearLineToReveal();
135 statusBarText: function()
137 return this._sourcePosition.element;
141 * @return {!Array.<!Element>}
143 statusBarItems: function()
151 defaultFocusedElement: function()
153 return this._textEditor.defaultFocusedElement();
164 hasContent: function()
171 return this._textEditor;
174 _ensureContentLoaded: function()
176 if (!this._contentRequested) {
177 this._contentRequested = true;
178 this._contentProvider.requestContent(this.setContent.bind(this));
182 addMessage: function(msg)
184 this._messages.push(msg);
186 this.addMessageToSource(msg.line - 1, msg);
189 clearMessages: function()
191 for (var line in this._messageBubbles) {
192 var bubble = this._messageBubbles[line];
193 var lineNumber = parseInt(line, 10);
194 this._textEditor.removeDecoration(lineNumber, bubble);
198 this._rowMessages = {};
199 this._messageBubbles = {};
206 canHighlightPosition: function()
214 highlightPosition: function(line, column)
216 this._clearLineToReveal();
217 this._clearLineToScrollTo();
218 this._clearSelectionToSet();
219 this._positionToHighlight = { line: line, column: column };
220 this._innerHighlightPositionIfNeeded();
223 _innerHighlightPositionIfNeeded: function()
225 if (!this._positionToHighlight)
228 if (!this.loaded || !this._isEditorShowing())
231 this._textEditor.highlightPosition(this._positionToHighlight.line, this._positionToHighlight.column);
232 delete this._positionToHighlight;
235 _clearPositionHighlight: function()
237 this._textEditor.clearPositionHighlight();
238 delete this._positionToHighlight;
242 * @param {number} line
244 revealLine: function(line)
246 this._clearPositionHighlight();
247 this._clearLineToScrollTo();
248 this._clearSelectionToSet();
249 this._lineToReveal = line;
250 this._innerRevealLineIfNeeded();
253 _innerRevealLineIfNeeded: function()
255 if (typeof this._lineToReveal === "number") {
256 if (this.loaded && this._isEditorShowing()) {
257 this._textEditor.revealLine(this._lineToReveal);
258 delete this._lineToReveal;
263 _clearLineToReveal: function()
265 delete this._lineToReveal;
269 * @param {number} line
271 scrollToLine: function(line)
273 this._clearPositionHighlight();
274 this._clearLineToReveal();
275 this._lineToScrollTo = line;
276 this._innerScrollToLineIfNeeded();
279 _innerScrollToLineIfNeeded: function()
281 if (typeof this._lineToScrollTo === "number") {
282 if (this.loaded && this._isEditorShowing()) {
283 this._textEditor.scrollToLine(this._lineToScrollTo);
284 delete this._lineToScrollTo;
289 _clearLineToScrollTo: function()
291 delete this._lineToScrollTo;
295 * @param {!WebInspector.TextRange} textRange
297 setSelection: function(textRange)
299 this._selectionToSet = textRange;
300 this._innerSetSelectionIfNeeded();
303 _innerSetSelectionIfNeeded: function()
305 if (this._selectionToSet && this.loaded && this._isEditorShowing()) {
306 this._textEditor.setSelection(this._selectionToSet);
307 delete this._selectionToSet;
311 _clearSelectionToSet: function()
313 delete this._selectionToSet;
316 _wasShownOrLoaded: function()
318 this._innerHighlightPositionIfNeeded();
319 this._innerRevealLineIfNeeded();
320 this._innerSetSelectionIfNeeded();
321 this._innerScrollToLineIfNeeded();
324 onTextChanged: function(oldRange, newRange)
326 if (this._searchResultsChangedCallback && !this._isReplacing)
327 this._searchResultsChangedCallback();
328 this.clearMessages();
331 _simplifyMimeType: function(content, mimeType)
335 if (mimeType.indexOf("javascript") >= 0 ||
336 mimeType.indexOf("jscript") >= 0 ||
337 mimeType.indexOf("ecmascript") >= 0)
338 return "text/javascript";
339 // A hack around the fact that files with "php" extension might be either standalone or html embedded php scripts.
340 if (mimeType === "text/x-php" && content.match(/\<\?.*\?\>/g))
341 return "application/x-httpd-php";
346 * @param {string} highlighterType
348 setHighlighterType: function(highlighterType)
350 this._highlighterType = highlighterType;
351 this._updateHighlighterType("");
355 * @param {string} content
357 _updateHighlighterType: function(content)
359 this._textEditor.setMimeType(this._simplifyMimeType(content, this._highlighterType));
363 * @param {?string} content
365 setContent: function(content)
369 this._textEditor.setText(content || "");
370 this._textEditor.markClean();
372 var firstLine = this._textEditor.firstVisibleLine();
373 var selection = this._textEditor.selection();
374 this._textEditor.setText(content || "");
375 this._textEditor.scrollToLine(firstLine);
376 this._textEditor.setSelection(selection);
379 this._updateHighlighterType(content || "");
381 this._textEditor.beginUpdates();
383 this._setTextEditorDecorations();
385 this._wasShownOrLoaded();
387 if (this._delayedFindSearchMatches) {
388 this._delayedFindSearchMatches();
389 delete this._delayedFindSearchMatches;
392 this.onTextEditorContentLoaded();
394 this._textEditor.endUpdates();
397 onTextEditorContentLoaded: function() {},
399 _setTextEditorDecorations: function()
401 this._rowMessages = {};
402 this._messageBubbles = {};
404 this._textEditor.beginUpdates();
406 this._addExistingMessagesToSource();
408 this._textEditor.endUpdates();
412 * @param {string} query
413 * @param {boolean} shouldJump
414 * @param {function(!WebInspector.View, number)} callback
415 * @param {function(number)} currentMatchChangedCallback
416 * @param {function()} searchResultsChangedCallback
418 performSearch: function(query, shouldJump, callback, currentMatchChangedCallback, searchResultsChangedCallback)
421 * @param {string} query
422 * @this {WebInspector.SourceFrame}
424 function doFindSearchMatches(query)
426 this._currentSearchResultIndex = -1;
427 this._searchResults = [];
429 var regex = WebInspector.SourceFrame.createSearchRegex(query);
430 this._searchRegex = regex;
431 this._searchResults = this._collectRegexMatches(regex);
432 if (!this._searchResults.length)
433 this._textEditor.cancelSearchResultsHighlight();
435 this.jumpToNextSearchResult();
437 this._textEditor.highlightSearchResults(regex, null);
438 callback(this, this._searchResults.length);
442 this._currentSearchMatchChangedCallback = currentMatchChangedCallback;
443 this._searchResultsChangedCallback = searchResultsChangedCallback;
445 doFindSearchMatches.call(this, query);
447 this._delayedFindSearchMatches = doFindSearchMatches.bind(this, query);
449 this._ensureContentLoaded();
452 _editorFocused: function()
454 if (!this._searchResults.length)
456 this._currentSearchResultIndex = -1;
457 if (this._currentSearchMatchChangedCallback)
458 this._currentSearchMatchChangedCallback(this._currentSearchResultIndex);
459 this._textEditor.highlightSearchResults(this._searchRegex, null);
462 _searchResultAfterSelectionIndex: function(selection)
466 for (var i = 0; i < this._searchResults.length; ++i) {
467 if (this._searchResults[i].compareTo(selection) >= 0)
473 _resetSearch: function()
475 delete this._delayedFindSearchMatches;
476 delete this._currentSearchMatchChangedCallback;
477 delete this._searchResultsChangedCallback;
478 this._currentSearchResultIndex = -1;
479 this._searchResults = [];
480 delete this._searchRegex;
483 searchCanceled: function()
485 var range = this._currentSearchResultIndex !== -1 ? this._searchResults[this._currentSearchResultIndex] : null;
489 this._textEditor.cancelSearchResultsHighlight();
491 this._textEditor.setSelection(range);
497 hasSearchResults: function()
499 return this._searchResults.length > 0;
502 jumpToFirstSearchResult: function()
504 this.jumpToSearchResult(0);
507 jumpToLastSearchResult: function()
509 this.jumpToSearchResult(this._searchResults.length - 1);
512 jumpToNextSearchResult: function()
514 var currentIndex = this._searchResultAfterSelectionIndex(this._textEditor.selection());
515 var nextIndex = this._currentSearchResultIndex === -1 ? currentIndex : currentIndex + 1;
516 this.jumpToSearchResult(nextIndex);
519 jumpToPreviousSearchResult: function()
521 var currentIndex = this._searchResultAfterSelectionIndex(this._textEditor.selection());
522 this.jumpToSearchResult(currentIndex - 1);
528 showingFirstSearchResult: function()
530 return this._searchResults.length && this._currentSearchResultIndex === 0;
536 showingLastSearchResult: function()
538 return this._searchResults.length && this._currentSearchResultIndex === (this._searchResults.length - 1);
541 get currentSearchResultIndex()
543 return this._currentSearchResultIndex;
546 jumpToSearchResult: function(index)
548 if (!this.loaded || !this._searchResults.length)
550 this._currentSearchResultIndex = (index + this._searchResults.length) % this._searchResults.length;
551 if (this._currentSearchMatchChangedCallback)
552 this._currentSearchMatchChangedCallback(this._currentSearchResultIndex);
553 this._textEditor.highlightSearchResults(this._searchRegex, this._searchResults[this._currentSearchResultIndex]);
557 * @param {string} text
559 replaceSelectionWith: function(text)
561 var range = this._searchResults[this._currentSearchResultIndex];
564 this._textEditor.highlightSearchResults(this._searchRegex, null);
566 this._isReplacing = true;
567 var newRange = this._textEditor.editRange(range, text);
568 delete this._isReplacing;
570 this._textEditor.setSelection(newRange.collapseToEnd());
574 * @param {string} query
575 * @param {string} replacement
577 replaceAllWith: function(query, replacement)
579 this._textEditor.highlightSearchResults(this._searchRegex, null);
581 var text = this._textEditor.text();
582 var range = this._textEditor.range();
583 var regex = WebInspector.SourceFrame.createSearchRegex(query, "g");
584 if (regex.__fromRegExpQuery)
585 text = text.replace(regex, replacement);
587 text = text.replace(regex, function() { return replacement; });
589 this._isReplacing = true;
590 this._textEditor.editRange(range, text);
591 delete this._isReplacing;
594 _collectRegexMatches: function(regexObject)
597 for (var i = 0; i < this._textEditor.linesCount; ++i) {
598 var line = this._textEditor.line(i);
601 var match = regexObject.exec(line);
604 ranges.push(new WebInspector.TextRange(i, offset + match.index, i, offset + match.index + match[0].length));
605 offset += match.index + 1;
606 line = line.substring(match.index + 1);
608 } while (match && line);
613 _addExistingMessagesToSource: function()
615 var length = this._messages.length;
616 for (var i = 0; i < length; ++i)
617 this.addMessageToSource(this._messages[i].line - 1, this._messages[i]);
621 * @param {number} lineNumber
622 * @param {!WebInspector.ConsoleMessage} msg
624 addMessageToSource: function(lineNumber, msg)
626 if (lineNumber >= this._textEditor.linesCount)
627 lineNumber = this._textEditor.linesCount - 1;
631 var rowMessages = this._rowMessages[lineNumber];
634 this._rowMessages[lineNumber] = rowMessages;
637 for (var i = 0; i < rowMessages.length; ++i) {
638 if (rowMessages[i].consoleMessage.isEqual(msg)) {
639 rowMessages[i].repeatCount = msg.totalRepeatCount;
640 this._updateMessageRepeatCount(rowMessages[i]);
645 var rowMessage = { consoleMessage: msg };
646 rowMessages.push(rowMessage);
648 this._textEditor.beginUpdates();
649 var messageBubbleElement = this._messageBubbles[lineNumber];
650 if (!messageBubbleElement) {
651 messageBubbleElement = document.createElement("div");
652 messageBubbleElement.className = "webkit-html-message-bubble";
653 this._messageBubbles[lineNumber] = messageBubbleElement;
654 this._textEditor.addDecoration(lineNumber, messageBubbleElement);
657 var imageElement = document.createElement("div");
659 case WebInspector.ConsoleMessage.MessageLevel.Error:
660 messageBubbleElement.classList.add("webkit-html-error-message");
661 imageElement.className = "error-icon-small";
663 case WebInspector.ConsoleMessage.MessageLevel.Warning:
664 messageBubbleElement.classList.add("webkit-html-warning-message");
665 imageElement.className = "warning-icon-small";
669 var messageLineElement = document.createElement("div");
670 messageLineElement.className = "webkit-html-message-line";
671 messageBubbleElement.appendChild(messageLineElement);
673 // Create the image element in the Inspector's document so we can use relative image URLs.
674 messageLineElement.appendChild(imageElement);
675 messageLineElement.appendChild(document.createTextNode(msg.message));
677 rowMessage.element = messageLineElement;
678 rowMessage.repeatCount = msg.totalRepeatCount;
679 this._updateMessageRepeatCount(rowMessage);
680 this._textEditor.endUpdates();
683 _updateMessageRepeatCount: function(rowMessage)
685 if (rowMessage.repeatCount < 2)
688 if (!rowMessage.repeatCountElement) {
689 var repeatCountElement = document.createElement("span");
690 rowMessage.element.appendChild(repeatCountElement);
691 rowMessage.repeatCountElement = repeatCountElement;
694 rowMessage.repeatCountElement.textContent = WebInspector.UIString(" (repeated %d times)", rowMessage.repeatCount);
698 * @param {number} lineNumber
699 * @param {!WebInspector.ConsoleMessage} msg
701 removeMessageFromSource: function(lineNumber, msg)
703 if (lineNumber >= this._textEditor.linesCount)
704 lineNumber = this._textEditor.linesCount - 1;
708 var rowMessages = this._rowMessages[lineNumber];
709 for (var i = 0; rowMessages && i < rowMessages.length; ++i) {
710 var rowMessage = rowMessages[i];
711 if (rowMessage.consoleMessage !== msg)
714 var messageLineElement = rowMessage.element;
715 var messageBubbleElement = messageLineElement.parentElement;
716 messageBubbleElement.removeChild(messageLineElement);
717 rowMessages.remove(rowMessage);
718 if (!rowMessages.length)
719 delete this._rowMessages[lineNumber];
720 if (!messageBubbleElement.childElementCount) {
721 this._textEditor.removeDecoration(lineNumber, messageBubbleElement);
722 delete this._messageBubbles[lineNumber];
728 populateLineGutterContextMenu: function(contextMenu, lineNumber)
732 populateTextAreaContextMenu: function(contextMenu, lineNumber)
737 * @param {?WebInspector.TextRange} from
738 * @param {?WebInspector.TextRange} to
740 onJumpToPosition: function(from, to)
742 this.dispatchEventToListeners(WebInspector.SourceFrame.Events.JumpHappened, {
748 inheritScrollPositions: function(sourceFrame)
750 this._textEditor.inheritScrollPositions(sourceFrame._textEditor);
756 canEditSource: function()
762 * @param {!WebInspector.TextRange} textRange
764 selectionChanged: function(textRange)
766 this._updateSourcePosition(textRange);
767 this.dispatchEventToListeners(WebInspector.SourceFrame.Events.SelectionChanged, textRange);
768 WebInspector.notifications.dispatchEventToListeners(WebInspector.SourceFrame.Events.SelectionChanged, textRange);
772 * @param {!WebInspector.TextRange} textRange
774 _updateSourcePosition: function(textRange)
779 if (textRange.isEmpty()) {
780 this._sourcePosition.setText(WebInspector.UIString("Line %d, Column %d", textRange.endLine + 1, textRange.endColumn + 1));
783 textRange = textRange.normalize();
785 var selectedText = this._textEditor.copyRange(textRange);
786 if (textRange.startLine === textRange.endLine)
787 this._sourcePosition.setText(WebInspector.UIString("%d characters selected", selectedText.length));
789 this._sourcePosition.setText(WebInspector.UIString("%d lines, %d characters selected", textRange.endLine - textRange.startLine + 1, selectedText.length));
793 * @param {number} lineNumber
795 scrollChanged: function(lineNumber)
797 this.dispatchEventToListeners(WebInspector.SourceFrame.Events.ScrollChanged, lineNumber);
800 _handleKeyDown: function(e)
802 var shortcutKey = WebInspector.KeyboardShortcut.makeKeyFromEvent(e);
803 var handler = this._shortcuts[shortcutKey];
804 if (handler && handler())
808 __proto__: WebInspector.View.prototype
813 * @implements {WebInspector.TextEditorDelegate}
816 WebInspector.TextEditorDelegateForSourceFrame = function(sourceFrame)
818 this._sourceFrame = sourceFrame;
821 WebInspector.TextEditorDelegateForSourceFrame.prototype = {
822 onTextChanged: function(oldRange, newRange)
824 this._sourceFrame.onTextChanged(oldRange, newRange);
828 * @param {!WebInspector.TextRange} textRange
830 selectionChanged: function(textRange)
832 this._sourceFrame.selectionChanged(textRange);
836 * @param {number} lineNumber
838 scrollChanged: function(lineNumber)
840 this._sourceFrame.scrollChanged(lineNumber);
843 editorFocused: function()
845 this._sourceFrame._editorFocused();
848 populateLineGutterContextMenu: function(contextMenu, lineNumber)
850 this._sourceFrame.populateLineGutterContextMenu(contextMenu, lineNumber);
853 populateTextAreaContextMenu: function(contextMenu, lineNumber)
855 this._sourceFrame.populateTextAreaContextMenu(contextMenu, lineNumber);
859 * @param {string} hrefValue
860 * @param {boolean} isExternal
863 createLink: function(hrefValue, isExternal)
865 var targetLocation = WebInspector.ParsedURL.completeURL(this._sourceFrame._url, hrefValue);
866 return WebInspector.linkifyURLAsNode(targetLocation || hrefValue, hrefValue, undefined, isExternal);
870 * @param {?WebInspector.TextRange} from
871 * @param {?WebInspector.TextRange} to
873 onJumpToPosition: function(from, to)
875 this._sourceFrame.onJumpToPosition(from, to);