pyedit.java

来自「Python Development Environment (Python I」· Java 代码 · 共 1,112 行 · 第 1/3 页

JAVA
1,112
字号
	                    } catch (RuntimeException e1) {
	                    }
	                } catch (Exception e) {
	                }
	
	            }
	        };
	        thread2.setName("Shell starter");
	        thread2.start();
	
	        
	        // listen to changes in TAB_WIDTH preference
	        prefListener = new Preferences.IPropertyChangeListener() {
	            public void propertyChange(Preferences.PropertyChangeEvent event) {
	                String property = event.getProperty();
	                //tab width
	                if (property.equals(PydevPrefs.TAB_WIDTH)) {
	                    ISourceViewer sourceViewer = getSourceViewer();
	                    if (sourceViewer == null){
	                        return;
	                    }
	                    getIndentPrefs().regenerateIndentString();
	                    sourceViewer.getTextWidget().setTabs(DefaultIndentPrefs.getStaticTabWidth());
	                    
	                }else if (property.equals(PydevPrefs.SUBSTITUTE_TABS)) {
	                	getIndentPrefs().regenerateIndentString();
	                   
	                //auto adjust for file tabs
	                } else if (property.equals(PydevPrefs.GUESS_TAB_SUBSTITUTION)) {
	                    resetForceTabs();
	                    
	                //hyperlink
	                }else if (property.equals(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_HYPERLINK_COLOR)) {
	                    colorCache.reloadNamedColor(property);
	                    if (fMouseListener != null){
	                        fMouseListener.updateColor(getSourceViewer());
	                    }
	                
	                //colors and styles
	                } else if (property.equals(PydevPrefs.CODE_COLOR) || property.equals(PydevPrefs.DECORATOR_COLOR) || property.equals(PydevPrefs.NUMBER_COLOR)
	                        || property.equals(PydevPrefs.KEYWORD_COLOR) || property.equals(PydevPrefs.SELF_COLOR) || property.equals(PydevPrefs.COMMENT_COLOR) 
	                        || property.equals(PydevPrefs.STRING_COLOR) || property.equals(PydevPrefs.CLASS_NAME_COLOR) || property.equals(PydevPrefs.FUNC_NAME_COLOR)
	                        || property.equals(PydevPrefs.DEFAULT_BACKQUOTES_COLOR)
	                        || property.endsWith("_STYLE")
	                        ) {
	                    colorCache.reloadNamedColor(property); //all reference this cache
	                    editConfiguration.updateSyntaxColorAndStyle(); //the style needs no reloading
	                    getSourceViewer().invalidateTextPresentation();
	                } 
	            }
	        };
	        resetForceTabs();
	        PydevPrefs.getPreferences().addPropertyChangeListener(prefListener);
	        
	    
	        Runnable runnable = new Runnable(){
	
				public void run() {
					//let's do that in a thread, so that we don't have any delays in setting up the editor
					pyEditScripting = new PyEditScripting();
					addPyeditListener(pyEditScripting);
					
					initFinished = true;
					synchronized(getLock()){
						getLock().notifyAll();
					}
				}
	        };
	        Thread thread = new Thread(runnable);
	        thread.setPriority(Thread.MIN_PRIORITY);
	        thread.setName("PyEdit initializer");
	        thread.start();
    	}catch (Throwable e) {
    		//never fail in the init
			PydevPlugin.log(e);
		}
    }
    
    

    /**
     * When we have the editor input re-set, we have to change the parser and the partition scanner to
     * the new document. This happens in 3 cases:
     * - when the editor has been created 
     * - when the editor is reused in the search window
     * - when we create a file, and make a save as, to change its name
     * 
     * there were related bugs in each of these cases:
     * https://sourceforge.net/tracker/?func=detail&atid=577329&aid=1250307&group_id=85796
     * https://sourceforge.net/tracker/?func=detail&atid=577329&aid=1251271&group_id=85796
     *  
     * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetInput(org.eclipse.ui.IEditorInput)
     */
    @Override
    protected void doSetInput(IEditorInput input) throws CoreException {
        super.doSetInput(input);
        try{
	        IDocument document = getDocument(input);
	        //see if we have to change the encoding of the file on load
	        fixEncoding(input, document);
	
            PyParserManager.getPyParserManager(PydevPrefs.getPreferences()).attachParserTo(this);
	        if(document != null){
	            PyPartitionScanner.checkPartitionScanner(document);
	        }
	        notifier.notifyOnSetDocument(document);
        }catch (Throwable e) {
			PydevPlugin.log(e);
		}
    }
    
    public boolean hasSameInput(IPyEdit edit) {
        IEditorInput thisInput = this.getEditorInput();
        IEditorInput otherInput = edit.getEditorInput();
        if(thisInput == null || otherInput == null){
            return false;
        }
        
        if(thisInput == otherInput || thisInput.equals(otherInput)){
            return true;
        }
        
        IResource r1 = (IResource) thisInput.getAdapter(IResource.class);
        IResource r2 = (IResource) otherInput.getAdapter(IResource.class);
        if(r1 == null || r2 == null){
            return false;
        }
        if(r1.equals(r2)){
            return true;
        }
        return false;
    }
    
    /**
     * @param input
     * @return
     */
    private IDocument getDocument(final IEditorInput input) {
        return getDocumentProvider().getDocument(input);
    }

    /**
     * @return the document that is binded to this editor (may be null)
     */
    public IDocument getDocument() {
        IDocumentProvider documentProvider = getDocumentProvider();
        if(documentProvider != null){
            return documentProvider.getDocument(getEditorInput());
        }
        return null;
    }
    
    /** 
     * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean, org.eclipse.core.runtime.IProgressMonitor)
     */
    protected void performSave(boolean overwrite, IProgressMonitor progressMonitor) {
        fixEncoding(getEditorInput(), getDocument());
        super.performSave(overwrite, progressMonitor);
        PyParserManager.getPyParserManager(null).notifySaved(this);
        notifier.notifyOnSave();
    }

    /**
     * Forces the encoding to the one specified in the file
     * 
     * @param input
     * @param document
     */
    private void fixEncoding(final IEditorInput input, IDocument document) {
        if (input instanceof FileEditorInput) {
            final IFile file = (IFile) ((FileEditorInput) input).getAdapter(IFile.class);
            try{
                final String encoding = REF.getPythonFileEncoding(document, file.getFullPath().toOSString());
                if (encoding != null) {
                    try {
                        if (encoding.equals(file.getCharset()) == false) {
    
                            new Job("Change encoding") {
    
                                protected IStatus run(IProgressMonitor monitor) {
                                    try {
                                        file.setCharset(encoding, monitor);
                                        ((TextFileDocumentProvider) getDocumentProvider()).setEncoding(input, encoding);
                                        //refresh it...
                                        file.refreshLocal(IResource.DEPTH_INFINITE, null);
                                    } catch (CoreException e) {
                                        PydevPlugin.log(e);
                                    }
                                    return Status.OK_STATUS;
                                }
    
                            }.schedule();
                        }
                    } catch (CoreException e) {
                        PydevPlugin.log(e);
                    }
                }
            }catch (Exception e) {
                PydevPlugin.log(e);
            }
        }
    }

    public IProject getProject() {
        IEditorInput editorInput = this.getEditorInput();
        if (editorInput instanceof FileEditorInput) {
            IFile file = (IFile) ((FileEditorInput) editorInput).getAdapter(IFile.class);
            return file.getProject();
        }
        return null;
    }
    

    public IFile getIFile() {
        IEditorInput editorInput = this.getEditorInput();
        if (editorInput instanceof FileEditorInput) {
            IFile file = (IFile) ((FileEditorInput) editorInput).getAdapter(IFile.class);
            return file;
        }
        return null;
        
    }
    
    /**
     * @return
     *  
     */
    public File getEditorFile() {
        File f = null;
        IEditorInput editorInput = this.getEditorInput();
        if (editorInput instanceof FileEditorInput) {
            IFile file = (IFile) ((FileEditorInput) editorInput).getAdapter(IFile.class);

            IPath path = file.getLocation().makeAbsolute();
            f = path.toFile();
        
        }else if (editorInput instanceof PydevFileEditorInput) {
        	PydevFileEditorInput pyEditorInput = (PydevFileEditorInput) editorInput;
        	f = pyEditorInput.getPath().toFile();
        	
        }else{
        	try {
				IPath path = (IPath) REF.invoke(editorInput, "getPath", new Object[0]);
				f = path.toFile();
			} catch (Exception e) {
				//ok, it has no getPath
			}
        }
        return f;
    }

    // cleanup
    public void dispose() {
    	this.disposed = true;
    	try{
	    	notifier.notifyOnDispose();
	
	        PydevPrefs.getPreferences().removePropertyChangeListener(prefListener);
            PyParserManager.getPyParserManager(null).notifyEditorDisposed(this);
            
	        colorCache.dispose();
	        pyEditScripting = null;
	        cache.clear();
	        cache = null;
    	}catch (Throwable e) {
			PydevPlugin.log(e);
		}
        super.dispose();
        
    }


    public static class MyResources extends ListResourceBundle {
        public Object[][] getContents() {
            return contents;
        }

        static final Object[][] contents = { { "CorrectionAssist", "CorrectionAssist" }, { "ContentAssistProposal", "ContentAssistProposal" }, { "TemplateProposals", "TemplateProposals" }, };
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.ui.texteditor.AbstractTextEditor#createActions()
     * 
     * TODO: Fix content assist to work in emacs mode:  
     * http://wiki.eclipse.org/index.php/FAQ_How_do_I_add_Content_Assist_to_my_editor%3F
     * http://www.eclipse.org/newsportal/article.php?id=61744&group=eclipse.platform#61744
     */
    protected void createActions() {
        super.createActions();
        try{
	        MyResources resources = new MyResources();
	        IAction action;
	
	        //Quick-Assist: it's added to the platform as of Eclipse 3.2, so, we do not have to put the binding here
	        
	        
	        // -------------------------------------------------------------------------------------
	        // This action will fire a CONTENTASSIST_PROPOSALS operation
	        // when executed
	        action = new ContentAssistAction(resources, "ContentAssistProposal.", this);
	        action.setActionDefinitionId(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
	        setAction("ContentAssistProposal", action); 
	        markAsStateDependentAction("ContentAssistProposal", true); 
	
	        
	        // ----------------------------------------------------------------------------------------
	        //open action
	        IAction openAction = new PyOpenAction();
	        setAction(ACTION_OPEN, openAction);
	        enableBrowserLikeLinks();
	        
	        
	        // ----------------------------------------------------------------------------------------
	        // Offline action
	        action = new OfflineAction(resources, "Pyedit.ScriptEngine.", this); 
	        action.setActionDefinitionId("org.python.pydev.editor.actions.scriptEngine");
	        action.setId("org.python.pydev.editor.actions.scriptEngine");
	        setAction("PydevScriptEngine", action);
	        
	        
	        notifier.notifyOnCreateActions(resources);
        }catch (Throwable e) {
			PydevPlugin.log(e);
		}
    }


    protected void initializeKeyBindingScopes() {
        setKeyBindingScopes(new String[] { "org.python.pydev.ui.editor.scope" }); //$NON-NLS-1$
    }

    /**
     * Used to: request a reparse / add listener / remove listener
     * @return the parser that is being used in this editor.
     */
    public PyParser getParser() {
        return (PyParser) PyParserManager.getPyParserManager(null).getParser(this);
    }


    /**
     * Returns the status line manager of this editor.
     * @return the status line manager of this editor
     * @since 2.0
     * 
     * copied from superclass, as it is private there...
     */
    public IStatusLineManager getStatusLineManager() {

        IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
        if (!(contributor instanceof EditorActionBarContributor))
            return null;

        IActionBars actionBars= ((EditorActionBarContributor) contributor).getActionBars();
        if (actionBars == null)
            return null;

        return actionBars.getStatusLineManager();
    }

    /**
     * This is the 'offline' action
     */
    protected OfflineActionTarget fOfflineActionTarget;
    
    /**
     * @return an outline view
     */
    public Object getAdapter(Class adapter) {

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?