forked from phcode-dev/staging.phcode.dev
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDocument.js
More file actions
1 lines (1 loc) · 9.26 KB
/
Document.js
File metadata and controls
1 lines (1 loc) · 9.26 KB
1
define(function(require,exports,module){var EditorManager=require("editor/EditorManager"),EventDispatcher=require("utils/EventDispatcher"),FileUtils=require("file/FileUtils"),InMemoryFile=require("document/InMemoryFile"),PerfUtils=require("utils/PerfUtils"),LanguageManager=require("language/LanguageManager"),CodeMirror=require("thirdparty/CodeMirror/lib/codemirror"),_=require("thirdparty/lodash");function Document(file,initialTimestamp,rawText){this.file=file,this.editable=!file.readOnly,this._updateLanguage(),this.refreshText(rawText,initialTimestamp,!0),this._associatedFullEditors=[]}function oneOrEach(itemOrArr,cb){Array.isArray(itemOrArr)?_.each(itemOrArr,cb):cb(itemOrArr,0)}EventDispatcher.makeEventDispatcher(Document.prototype),Document.prototype._refCount=0,Document.prototype.file=null,Document.prototype.language=null,Document.prototype.isDirty=!1,Document.prototype.isSaving=!1,Document.prototype.diskTimestamp=null,Document.prototype.lastChangeTimestamp=null,Document.prototype.keepChangesTime=null,Document.prototype._refreshInProgress=!1,Document.prototype._text=null,Document.prototype._masterEditor=null,Document.prototype._lineEndings=null,Document.prototype.addRef=function(){0===this._refCount&&exports.trigger("_afterDocumentCreate",this)||this._refCount++},Document.prototype.releaseRef=function(){this._refCount--,this._refCount<0?console.error("Document ref count has fallen below zero!"):0!==this._refCount||exports.trigger("_beforeDocumentDelete",this)},Document.prototype._makeEditable=function(masterEditor){this._text=null,this._masterEditor=masterEditor,masterEditor.on("change",this._handleEditorChange.bind(this))},Document.prototype._makeNonEditable=function(){this._masterEditor?(this._text=this.getText(!0),this._associatedFullEditors.splice(this._associatedFullEditors.indexOf(this._masterEditor),1),this._associatedFullEditors.length>0?this._masterEditor=this._associatedFullEditors[this._associatedFullEditors.length-1]:this._masterEditor=null):console.error("Document is already non-editable")},Document.prototype._toggleMasterEditor=function(masterEditor){this.file===masterEditor.document.file&&this._associatedFullEditors.indexOf(masterEditor)>=0&&(this._masterEditor=masterEditor)},Document.prototype._checkAssociatedEditorForPane=function(paneId){var editorCount,editorForPane;for(editorCount=0;editorCount<this._associatedFullEditors.length;++editorCount)if(this._associatedFullEditors[editorCount]._paneId===paneId){editorForPane=this._associatedFullEditors[editorCount];break}return editorForPane},Document.prototype._disassociateEditor=function(editor){this._associatedFullEditors.indexOf(editor)>=0&&this._associatedFullEditors.splice(this._associatedFullEditors.indexOf(editor),1)},Document.prototype._associateEditor=function(editor){-1===this._associatedFullEditors.indexOf(editor)&&this._associatedFullEditors.push(editor)},Document.prototype._ensureMasterEditor=function(){this._masterEditor||EditorManager._createUnattachedMasterEditor(this)},Document.prototype.getText=function(useOriginalLineEndings){if(this._masterEditor){var codeMirrorText=this._masterEditor._codeMirror.getValue();return useOriginalLineEndings&&this._lineEndings===FileUtils.LINE_ENDINGS_CRLF?codeMirrorText.replace(/\n/g,"\r\n"):codeMirrorText}return useOriginalLineEndings?this._text:Document.normalizeText(this._text)},Document.prototype.getSelectedText=function(useOriginalLineEndings,allSelections){if(this._masterEditor){let codeMirrorText=this._masterEditor.getSelectedText(allSelections);return useOriginalLineEndings&&this._lineEndings===FileUtils.LINE_ENDINGS_CRLF?codeMirrorText.replace(/\n/g,"\r\n"):codeMirrorText}return null},Document.normalizeText=function(text){return text.replace(/\r\n/g,"\n")},Document.prototype.setText=function(text){this._ensureMasterEditor(),this._masterEditor._codeMirror.setValue(text)},Document.prototype._notifyDocumentChange=function(changeList){this.lastChangeTimestamp=Date.now(),this.trigger("change",this,changeList),exports.trigger("documentChange",this,changeList)},Document.prototype.refreshText=function(text,newTimestamp,initial){var perfTimerName=PerfUtils.markStart("refreshText:\t"+(!this.file||this.file.fullPath));this._refreshInProgress=!0,this._masterEditor?this._masterEditor._resetText(text):(this._text=text,initial||this._notifyDocumentChange([{text:text.split(/\r?\n/)}])),this._updateTimestamp(newTimestamp),this.isDirty&&this._markClean(),this._refreshInProgress=!1,this._lineEndings=FileUtils.sniffLineEndings(text),this._lineEndings||(this._lineEndings=FileUtils.getPlatformLineEndings()),exports.trigger("_documentRefreshed",this),PerfUtils.addMeasurement(perfTimerName)},Document.prototype.replaceRange=function(text,start,end,origin){this._ensureMasterEditor(),this._masterEditor._codeMirror.replaceRange(text,start,end,origin)},Document.prototype.getRange=function(start,end){return this._ensureMasterEditor(),this._masterEditor._codeMirror.getRange(start,end)},Document.prototype.getLine=function(lineNum){return this._ensureMasterEditor(),this._masterEditor._codeMirror.getLine(lineNum)},Document.prototype.posFromIndex=function(index){if(this._masterEditor)return this._masterEditor._codeMirror.posFromIndex(index);for(var text=this._text||"",line=0,ch=0,i=0;i<index&&i<text.length;i++)"\n"===text[i]?(line++,ch=0):ch++;return{line:line,ch:ch}},Document.prototype.batchOperation=function(doOperation){this._ensureMasterEditor();var self=this;this._masterEditor._codeMirror.operation(doOperation)},Document.prototype._handleEditorChange=function(event,editor,changeList){if(this._masterEditor===editor){if(!this._refreshInProgress){var wasDirty=this.isDirty;this.isDirty=!editor._codeMirror.isClean(),wasDirty!==this.isDirty&&exports.trigger("_dirtyFlagChange",this)}this._notifyDocumentChange(changeList)}},Document.prototype._markClean=function(){this.isDirty=!1,this._masterEditor&&this._masterEditor._codeMirror.markClean(),exports.trigger("_dirtyFlagChange",this)},Document.prototype._updateTimestamp=function(timestamp){this.diskTimestamp=timestamp,this.lastChangeTimestamp=Date.now(),this.keepChangesTime=null},Document.prototype.notifySaved=function(){this._masterEditor||console.log("### Warning: saving a Document that is not modifiable!"),this._markClean();var thisDoc=this;this.file.stat(function(err,stat){err?console.log("Error updating timestamp after saving file: "+thisDoc.file.fullPath):thisDoc._updateTimestamp(stat.mtime),exports.trigger("_documentSaved",thisDoc)})},Document.prototype.adjustPosForChange=function(pos,textLines,start,end){var change={text:textLines,from:start,to:end};if(CodeMirror.cmpPos(pos,start)<0)return pos;if(CodeMirror.cmpPos(pos,end)<=0)return CodeMirror.changeEnd(change);var line=pos.line+change.text.length-(change.to.line-change.from.line)-1,ch=pos.ch;return pos.line===change.to.line&&(ch+=CodeMirror.changeEnd(change).ch-change.to.ch),{line:line,ch:ch}},Document.prototype.doMultipleEdits=function(edits,origin){var self=this;edits.sort(function(editDesc1,editDesc2){var edit1=Array.isArray(editDesc1.edit)?editDesc1.edit[0]:editDesc1.edit,edit2=Array.isArray(editDesc2.edit)?editDesc2.edit[0]:editDesc2.edit;return edit1?edit2?CodeMirror.cmpPos(edit2.start,edit1.start):1:-1});var result=_.cloneDeep(_.pluck(edits,"selection"));return _.each(edits,function(editDesc,index){oneOrEach(editDesc.edit,function(edit){var prevEditGroup;edit&&(edit.end||(edit.end=edit.start),index>0&&oneOrEach(edits[index-1].edit,function(prevEdit){if(CodeMirror.cmpPos(edit.end,prevEdit.start)>0)throw new Error("Document.doMultipleEdits(): Overlapping edits specified")}))})}),this.batchOperation(function(){_.each(edits,function(editDesc,index){oneOrEach(editDesc.edit,function(edit){if(edit){self.replaceRange(edit.text,edit.start,edit.end,origin);var textLines=edit.text.split("\n");_.each(result,function(selections,selIndex){selections&&oneOrEach(selections,function(sel){(sel.isBeforeEdit||selIndex!==index)&&(sel.start=self.adjustPosForChange(sel.start,textLines,edit.start,edit.end),sel.end=self.adjustPosForChange(sel.end,textLines,edit.start,edit.end))})})}})})}),result=_.chain(result).filter(function(item){return void 0!==item}).flatten().sort(function(sel1,sel2){return CodeMirror.cmpPos(sel1.start,sel2.start)}).value(),_.each(result,function(item){delete item.isBeforeEdit}),result},Document.prototype.toString=function(){var dirtyInfo=this.isDirty?" (dirty!)":" (clean)",editorInfo=this._masterEditor?" (Editable)":" (Non-editable)",refInfo=" refs:"+this._refCount;return"[Document "+this.file.fullPath+dirtyInfo+editorInfo+refInfo+"]"},Document.prototype.getLanguage=function(){return this.language},Document.prototype._updateLanguage=function(){var oldLanguage=this.language;this.language=LanguageManager.getLanguageForPath(this.file.fullPath),oldLanguage&&oldLanguage!==this.language&&this.trigger("languageChanged",oldLanguage,this.language)},Document.prototype._notifyFilePathChanged=function(){this._updateLanguage()},Document.prototype.isUntitled=function(){return this.file instanceof InMemoryFile},Document.prototype.reload=function(){var $deferred=$.Deferred(),self=this;return FileUtils.readAsText(this.file,!0).done(function(text,readTimestamp){self.refreshText(text,readTimestamp),$deferred.resolve()}).fail(function(error){console.log("Error reloading contents of "+self.file.fullPath,error),$deferred.reject()}),$deferred.promise()},EventDispatcher.makeEventDispatcher(exports),exports.Document=Document});