forked from phcode-dev/staging.phcode.dev
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
1 lines (1 loc) · 16.1 KB
/
Copy pathmain.js
File metadata and controls
1 lines (1 loc) · 16.1 KB
1
define(function(require,exports,module){var _=require("thirdparty/lodash"),AppInit=require("utils/AppInit"),Async=require("utils/Async"),Strings=require("strings"),MainViewManager=require("view/MainViewManager"),DocumentManager=require("document/DocumentManager"),EditorManager=require("editor/EditorManager"),ProjectManager=require("project/ProjectManager"),CommandManager=require("command/CommandManager"),Commands=require("command/Commands"),Menus=require("command/Menus"),FileSystem=require("filesystem/FileSystem"),FileUtils=require("file/FileUtils"),ViewUtils=require("utils/ViewUtils"),KeyEvent=require("utils/KeyEvent"),WorkingSetView=require("project/WorkingSetView"),PreferencesManager=require("preferences/PreferencesManager"),KeyBindingManager=require("command/KeyBindingManager"),Mustache=require("thirdparty/mustache/mustache"),NavigationProvider=require("./NavigationProvider"),FileRecovery=require("./FileRecovery"),KeyboardPrefs=JSON.parse(require("text!./keyboard.json")),PREFS_RECENT_FILES="recent-files.navigation",SHOW_RECENT_FILES="recent-files.show",NEXT_IN_RECENT_FILES="recent-files.next",PREV_IN_RECENT_FILES="recent-files.prev",OPEN_FILES_VIEW_STATE="openFiles",htmlTemplate=require("text!./html/recentfiles-template.html"),dirtyDotTemplate="<div class='file-status-icon dirty' style='position: absolute;margin-left: -2px;'></div>",MAX_ENTRY_COUNT=50,isRecentFilesNavEnabled=!0,_mrofList=[],$mrofContainer=null,$currentContext,activeEditor,_hideMROFList;function _openEditorForContext(contextData){var activePaneId=MainViewManager.getActivePaneId(),targetPaneId=contextData.paneId;return 1===MainViewManager.getPaneCount()&&(targetPaneId=activePaneId),contextData.hideOnOpenFile&&_hideMROFList(),CommandManager.execute(Commands.FILE_OPEN,{fullPath:contextData.path,paneId:targetPaneId}).done(function(){contextData.cursor&&((activeEditor=EditorManager.getActiveEditor()).setCursorPos(contextData.cursor),activeEditor.centerOnCursor())})}function _makeMROFListEntry(path,pane,cursorPos){return{file:path,paneId:pane,cursor:cursorPos}}function _isOpenAndDirty(file){var docIfOpen=DocumentManager.getOpenDocumentForPath(file.fullPath);return docIfOpen&&docIfOpen.isDirty}function _checkExt(entry,index){var deferred=new $.Deferred,fileEntry=FileSystem.getFileForPath(entry.file),indxInWS;entry.inMem?-1===MainViewManager.findInWorkingSet(entry.paneId,entry.file)?(_mrofList[index]=null,deferred.reject()):deferred.resolve():fileEntry.exists(function(err,exists){!err&&exists?deferred.resolve():(_mrofList[index]=null,deferred.reject())});return deferred.promise()}function _syncWithFileSystem(){return _mrofList=_mrofList.filter(function(e){return e}),Async.doSequentially(_mrofList,_checkExt,!1)}function _getFileListForEntries(entries){return $.map(entries,function(value,index){return FileSystem.getFileForPath(value.file)})}function _addDirectoriesForDuplicateBaseNames(){var checked={},baseName;$.map(_mrofList,function(value,index){baseName=FileUtils.getBaseName(value.file),checked[baseName]||(checked[baseName]=[]),checked[baseName].push(value)}),_.forEach(checked,function(value){if(value.length>1){var dirs=ViewUtils.getDirNamesForDuplicateFiles(_getFileListForEntries(value));$.map(value,function(value,index){$mrofContainer.find("#mrof-list > li").each(function(){var $li=$(this);if($li.data("path")===value.file){var dirSplit=dirs[index].split("/");dirSplit.length>3&&(dirs[index]=dirSplit[0]+"/…/"+dirSplit[dirSplit.length-1]);var $dir=$("<span class='directory'/>").html(" — "+dirs[index]);$li.children("a.mroitem").find("span.directory").remove(),$li.children("a.mroitem").append($dir)}})})}})}function _createFileEntries($mrofList){var data,fileEntry,$link,$newItem,$removeBtn,isPaneLabelReqd=MainViewManager.getPaneCount()>1;isPaneLabelReqd&&($mrofContainer.addClass("split-mode"),$(".first.pane-label",$mrofContainer).text(MainViewManager.getPaneTitle("first-pane")),$(".second.pane-label",$mrofContainer).text(MainViewManager.getPaneTitle("second-pane"))),$.each(_mrofList,function(index,value){if(!isPaneLabelReqd&&value.paneId!==MainViewManager.getActivePaneId()){var entryIndex;if(_.findIndex(_mrofList,function(record){return record&&record.file===value.file&&record.paneId===MainViewManager.getActivePaneId()})>=0)return!0;value.paneId=MainViewManager.getActivePaneId()}var indxInWS=MainViewManager.findInWorkingSet(value.paneId,value.file);data={fullPath:value.file,name:FileUtils.getBaseName(value.file),isFile:!0},fileEntry=FileSystem.getFileForPath(value.file),$link=$("<a href='#' class='mroitem'></a>").html(ViewUtils.getFileEntryDisplay({name:FileUtils.getBaseName(value.file)})),$removeBtn=null,-1===indxInWS&&($removeBtn=$("<span class='remove-file'>×</span>").on("click",function(e){e.preventDefault(),e.stopPropagation();var filePath=$(this).parent().data("path"),paneId=$(this).parent().data("paneId");_mrofList=_mrofList.filter(function(entry){return!(entry&&entry.file===filePath&&entry.paneId===paneId)}),$(this).parent().remove(),PreferencesManager.setViewState(OPEN_FILES_VIEW_STATE,_mrofList,PreferencesManager.STATE_PROJECT_CONTEXT)})),WorkingSetView.useIconProviders(data,$link),$newItem=$("<li></li>").append($link),$removeBtn&&$newItem.append($removeBtn),-1!==indxInWS&&$newItem.addClass("working-set"),$newItem.data("path",value.file);var displayPath=Phoenix.app.getDisplayPath(value.file);if($newItem.data("paneId",value.paneId),$newItem.data("cursor",value.cursor),$newItem.data("file",fileEntry),$newItem.attr("title",displayPath),isPaneLabelReqd&&value.paneId&&($newItem.addClass(value.paneId),$newItem.css("top",22*$("."+value.paneId,$mrofList).length+"px")),WorkingSetView.useClassProviders(data,$newItem),_isOpenAndDirty(fileEntry)&&$(dirtyDotTemplate).prependTo($newItem),$mrofList.append($newItem),index===MAX_ENTRY_COUNT-1)return!1}),_addDirectoriesForDuplicateBaseNames()}function _createMROFList(){var paneList=MainViewManager.getPaneIdList(),mrofList=[],fileList,index,pane,file,mrofEntry,paneCount,fileCount;for(paneCount=0;paneCount<paneList.length;paneCount++)for(pane=paneList[paneCount],fileList=MainViewManager.getWorkingSet(pane),fileCount=0;fileCount<fileList.length;fileCount++)mrofEntry=_makeMROFListEntry((file=fileList[fileCount]).fullPath,pane,null),mrofList[index=MainViewManager.findInGlobalMRUList(pane,file)]=mrofEntry;return mrofList}function _handleArrowKeys(event){var UP=38,DOWN=40,$context,$nextContext;!$mrofContainer||38!==event.which&&40!==event.which||(($context=$currentContext||$("#mrof-container #mrof-list > li.highlight")).length>0?($nextContext=38===event.which?$context.prev():$context.next()).length>0&&($currentContext=$nextContext,$nextContext.find("a.mroitem").trigger("focus")):$("#mrof-container #mrof-list > li > a.mroitem:visited").last().trigger("focus"),event.preventDefault(),event.stopImmediatePropagation())}function _hideMROFListOnEscape(event){$mrofContainer&&event.keyCode===KeyEvent.DOM_VK_ESCAPE&&_hideMROFList()}function _createMROFDisplayList(refresh){var $def=$.Deferred(),$mrofList,$link,$newItem,data,fileEntry;function _purgeAllExceptWorkingSet(){_mrofList=_createMROFList(),$mrofList.empty(),_createMROFDisplayList(!0),$currentContext=null,PreferencesManager.setViewState(OPEN_FILES_VIEW_STATE,_mrofList,PreferencesManager.STATE_PROJECT_CONTEXT)}function _onFocus(event){var $scope=$(event.target).parent();$("#mrof-container #mrof-list > li.highlight").removeClass("highlight"),$(event.target).parent().addClass("highlight");var displayPath=Phoenix.app.getDisplayPath($scope.data("path"));$mrofContainer.find("#recent-file-path").text(displayPath),$mrofContainer.find("#recent-file-path").attr("title",displayPath),$currentContext=$scope}function _onClick(event){var $scope=$(event.delegateTarget).parent();_openEditorForContext({path:$scope.data("path"),paneId:$scope.data("paneId"),cursor:$scope.data("cursor"),hideOnOpenFile:!0})}return refresh||(_hideMROFList(),$mrofContainer=$(Mustache.render(htmlTemplate,{Strings:Strings})).appendTo("body"),$("#mrof-list-close").one("click",_hideMROFList),$("#mrof-container .footer > div#clear-mrof-list").on("click",_purgeAllExceptWorkingSet),$(window).on("keydown",_handleArrowKeys),$(window).on("keyup",_hideMROFListOnEscape)),$mrofList=$mrofContainer.find("#mrof-list"),_syncWithFileSystem().always(function(){_mrofList=_mrofList.filter(function(e){return e}),_createFileEntries($mrofList);var $fileLinks=$("#mrof-container #mrof-list > li > a.mroitem");$fileLinks.on("focus",_onFocus),$fileLinks.on("click",_onClick),$fileLinks.on("select",_onClick),$fileLinks.first().trigger("focus"),$def.resolve()}),$def.promise()}function _openFile(){$currentContext&&_openEditorForContext({path:$currentContext.data("path"),paneId:$currentContext.data("paneId"),cursor:$currentContext.data("cursor")})}function _hideMROFListOnNavigationEnd(event){$mrofContainer&&event.keyCode===KeyEvent.DOM_VK_CONTROL&&(_openFile(),_hideMROFList())}function _moveNext(){var $context,$next;($context=$currentContext||$("#mrof-container #mrof-list > li.highlight")).length>0?(0===($next=$context.next()).length&&($next=$("#mrof-container #mrof-list > li").first()),$next.length>0&&($currentContext=$next,$next.find("a.mroitem").trigger("focus"))):$("#mrof-container #mrof-list > li > a.mroitem:visited").last().trigger("focus")}function _cmdMoveNext(){var $displayPromise;$mrofContainer||($displayPromise=_createMROFDisplayList(),$mrofContainer.addClass("confirmation-mode"),$(window).on("keyup",_hideMROFListOnNavigationEnd)),$displayPromise?$displayPromise.always(function(){_moveNext()}):_moveNext()}function _movePrev(){var $context,$prev;($context=$currentContext||$("#mrof-container #mrof-list > li.highlight")).length>0?(0===($prev=$context.prev()).length&&($prev=$("#mrof-container #mrof-list > li").last()),$prev.length>0&&($currentContext=$prev,$prev.find("a.mroitem").trigger("focus"))):$("#mrof-container #mrof-list > li > a.mroitem:visited").last().trigger("focus")}function _cmdMovePrev(){var $displayPromise;$mrofContainer||($displayPromise=_createMROFDisplayList(),$mrofContainer.addClass("confirmation-mode"),$(window).on("keyup",_hideMROFListOnNavigationEnd)),$displayPromise?$displayPromise.always(function(){_movePrev()}):_movePrev()}function _updateCursorPosition(filePath,paneId,cursorPos){if(paneId){var index=_.findIndex(_mrofList,function(record){return record&&record.file===filePath&&record.paneId===paneId}),entry;-1!==index&&(_mrofList[index].cursor=cursorPos),PreferencesManager.setViewState(OPEN_FILES_VIEW_STATE,_mrofList,PreferencesManager.STATE_PROJECT_CONTEXT)}}function _addToMROFList(file,paneId,cursorPos){var filePath=file.fullPath;if(paneId){var index=_.findIndex(_mrofList,function(record){return record&&record.file===filePath&&record.paneId===paneId}),entry;-1!==index&&(entry=_mrofList[index]).cursor&&!cursorPos&&(cursorPos=entry.cursor),entry=_makeMROFListEntry(filePath,paneId,cursorPos),"InMemoryFile"===file.constructor.name&&(entry.inMem=!0),-1!==index&&_mrofList.splice(index,1),_mrofList.unshift(entry),PreferencesManager.setViewState(OPEN_FILES_VIEW_STATE,_mrofList,PreferencesManager.STATE_PROJECT_CONTEXT)}}function _handleWorkingSetMove(event,file,sourcePaneId,destinationPaneId){var index=_.findIndex(_mrofList,function(record){return record&&record.file===file.fullPath&&record.paneId===sourcePaneId}),tIndex;index>=0&&(-1===(tIndex=_.findIndex(_mrofList,function(record){return record&&record.file===file.fullPath&&record.paneId===destinationPaneId}))?_mrofList[index].paneId=destinationPaneId:_mrofList.splice(index,1))}function _handleAppClose(){PreferencesManager.setViewState(OPEN_FILES_VIEW_STATE,_mrofList,PreferencesManager.STATE_PROJECT_CONTEXT),_mrofList=[]}function _initRecentFilesList(){(_mrofList=(_mrofList=PreferencesManager.getViewState(OPEN_FILES_VIEW_STATE,PreferencesManager.STATE_PROJECT_CONTEXT)||[]).filter(function(entry){return entry})).length<MainViewManager.getWorkingSetSize(MainViewManager.ALL_PANES)&&(_mrofList=_createMROFList())}function _handleProjectOpen(){_mrofList=[]}function _showRecentFileList(){isRecentFilesNavEnabled&&_createMROFDisplayList()}function _handlePaneMerge(e,paneId){var index,targetPaneId=MainViewManager.FIRST_PANE;$.each(_mrofList,function(itrIndex,value){value&&value.paneId===paneId&&(-1!==(index=_.findIndex(_mrofList,function(record){return record&&record.file===value.file&&record.paneId===targetPaneId}))?_mrofList[index]=null:_mrofList[itrIndex].paneId=targetPaneId)}),_mrofList=_mrofList.filter(function(e){return e}),PreferencesManager.setViewState(OPEN_FILES_VIEW_STATE,_mrofList,PreferencesManager.STATE_PROJECT_CONTEXT)}function _initRecentFileMenusAndCommands(){var menu;CommandManager.get(SHOW_RECENT_FILES)||(CommandManager.register(Strings.CMD_RECENT_FILES_OPEN,SHOW_RECENT_FILES,_showRecentFileList,{supportsDesignMode:!0}),KeyBindingManager.addBinding(SHOW_RECENT_FILES,Phoenix.isNativeApp?"Ctrl-R":"Ctrl-Alt-Shift-O")),CommandManager.get(NEXT_IN_RECENT_FILES)||CommandManager.register(Strings.CMD_NEXT_DOC,NEXT_IN_RECENT_FILES,_cmdMoveNext,{supportsDesignMode:!0}),KeyBindingManager.addBinding(NEXT_IN_RECENT_FILES,KeyboardPrefs[NEXT_IN_RECENT_FILES]),CommandManager.get(PREV_IN_RECENT_FILES)||CommandManager.register(Strings.CMD_PREV_DOC,PREV_IN_RECENT_FILES,_cmdMovePrev,{supportsDesignMode:!0}),KeyBindingManager.addBinding(PREV_IN_RECENT_FILES,KeyboardPrefs[PREV_IN_RECENT_FILES]),Menus.getMenu(Menus.AppMenuBar.FILE_MENU).addMenuItem(SHOW_RECENT_FILES,"",Menus.AFTER,Commands.FILE_REOPEN_CLOSED)}function _initDefaultNavigationCommands(){KeyBindingManager.addBinding(Commands.NAVIGATE_NEXT_DOC,KeyboardPrefs[NEXT_IN_RECENT_FILES]),KeyBindingManager.addBinding(Commands.NAVIGATE_PREV_DOC,KeyboardPrefs[PREV_IN_RECENT_FILES])}function _removeKeys(keys){_.forEach(keys,function(config){KeyBindingManager.removeBinding(config.key)})}function _removeNavigationKeys(){_removeKeys(KeyboardPrefs[NEXT_IN_RECENT_FILES]),_removeKeys(KeyboardPrefs[PREV_IN_RECENT_FILES])}function _deregisterSortcutsAndMenus(){_removeNavigationKeys(),Menus.getMenu(Menus.AppMenuBar.FILE_MENU).removeMenuItem(SHOW_RECENT_FILES)}function handleCurrentFileChange(e,newFile,newPaneId,oldFile){newFile&&(0===_mrofList.length&&_initRecentFilesList(),_addToMROFList(newFile,newPaneId))}function _handleActiveEditorChange(event,current,previous){var file,paneId;current&&(0===_mrofList.length&&_initRecentFilesList(),_addToMROFList(current.document.file,current._paneId,current.getCursorPos(!0,"first")));previous&&_updateCursorPosition(previous.document.file.fullPath,previous._paneId,previous.getCursorPos(!0,"first"))}function _attachListners(){MainViewManager.on("workingSetMove.pane-first-pane",_handleWorkingSetMove),MainViewManager.on("currentFileChange",handleCurrentFileChange),MainViewManager.on("paneDestroy",_handlePaneMerge),EditorManager.on("activeEditorChange",_handleActiveEditorChange),ProjectManager.on("beforeProjectClose beforeAppClose",_handleAppClose)}function _detachListners(){MainViewManager.off("workingSetMove.pane-first-pane",_handleWorkingSetMove),MainViewManager.off("currentFileChange",handleCurrentFileChange),MainViewManager.off("paneDestroy",_handlePaneMerge),EditorManager.off("activeEditorChange",_handleActiveEditorChange),ProjectManager.off("beforeProjectClose beforeAppClose",_handleAppClose)}PreferencesManager.definePreference(PREFS_RECENT_FILES,"boolean",!0,{description:Strings.DESCRIPTION_RECENT_FILES_NAV}),ProjectManager.on("projectOpen",_handleProjectOpen),_hideMROFList=function(){$mrofContainer&&($mrofContainer.remove(),$mrofContainer=null,$currentContext=null,(activeEditor=EditorManager.getActiveEditor())&&activeEditor.focus()),$(window).off("keydown",_handleArrowKeys),$(window).off("keyup",_hideMROFListOnNavigationEnd),$(window).off("keyup",_hideMROFListOnEscape)},$(window).on("blur focus",function(){_hideMROFList()}),PreferencesManager.on("change",PREFS_RECENT_FILES,function(){PreferencesManager.get(PREFS_RECENT_FILES)?(_removeNavigationKeys(),_initRecentFileMenusAndCommands(),_mrofList=[],_initRecentFilesList(),PreferencesManager.setViewState(OPEN_FILES_VIEW_STATE,_mrofList,PreferencesManager.STATE_PROJECT_CONTEXT),_detachListners(),_attachListners(),isRecentFilesNavEnabled=!0):(_mrofList=[],PreferencesManager.setViewState(OPEN_FILES_VIEW_STATE,_mrofList,PreferencesManager.STATE_PROJECT_CONTEXT),_deregisterSortcutsAndMenus(),_initDefaultNavigationCommands(),_detachListners(),isRecentFilesNavEnabled=!1)}),AppInit.appReady(function(){FileRecovery.init(),NavigationProvider.init()})});