Example usage for com.intellij.openapi.fileEditor OpenFileDescriptor OpenFileDescriptor

List of usage examples for com.intellij.openapi.fileEditor OpenFileDescriptor OpenFileDescriptor

Introduction

In this page you can find the example usage for com.intellij.openapi.fileEditor OpenFileDescriptor OpenFileDescriptor.

Prototype

public OpenFileDescriptor(@NotNull Project project, @NotNull VirtualFile file, int offset) 

Source Link

Usage

From source file:com.intellij.psi.impl.source.resolve.reference.impl.providers.CreateXmlElementIntentionAction.java

License:Apache License

@Override
public void invoke(@Nonnull final Project project, final Editor editor, final PsiFile file)
        throws IncorrectOperationException {
    if (!FileModificationService.getInstance().prepareFileForWrite(file))
        return;/* ww  w  .j  av a2s .  c  om*/

    final XmlTag rootTag = myTargetFile.getDocument().getRootTag();

    OpenFileDescriptor descriptor = new OpenFileDescriptor(project, myTargetFile.getVirtualFile(),
            rootTag.getValue().getTextRange().getEndOffset());
    Editor targetEditor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
    TemplateManager manager = TemplateManager.getInstance(project);
    final Template template = manager.createTemplate("", "");

    addTextTo(template, rootTag);

    manager.startTemplate(targetEditor, template);
}

From source file:com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil.java

License:Apache License

public static Editor openEditorFor(@NotNull PsiFile file, @NotNull Project project) {
    Document document = PsiDocumentManager.getInstance(project).getDocument(file);
    // may return editor injected in current selection in the host editor, not for the file passed as argument
    VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile == null) {
        return null;
    }//from  w ww  . j a  v  a2 s  .c o m
    if (virtualFile instanceof VirtualFileWindow) {
        virtualFile = ((VirtualFileWindow) virtualFile).getDelegate();
    }
    Editor editor = FileEditorManager.getInstance(project)
            .openTextEditor(new OpenFileDescriptor(project, virtualFile, -1), false);
    if (editor == null || editor instanceof EditorWindow || editor.isDisposed())
        return editor;
    if (document instanceof DocumentWindowImpl) {
        return EditorWindowImpl.create((DocumentWindowImpl) document, (EditorImpl) editor, file);
    }
    return editor;
}

From source file:com.intellij.psi.impl.source.xml.XmlAttributeDeclImpl.java

License:Apache License

public void navigate(final boolean requestFocus) {
    if (isPhysical()) {
        super.navigate(requestFocus);
        return;//from ww w . jav a 2s.  com
    }
    final PsiNamedElement psiNamedElement = XmlUtil.findRealNamedElement(this);
    Navigatable navigatable = EditSourceUtil.getDescriptor(psiNamedElement);

    if (psiNamedElement instanceof XmlEntityDecl) {
        final OpenFileDescriptor fileDescriptor = (OpenFileDescriptor) navigatable;
        navigatable = new OpenFileDescriptor(fileDescriptor.getProject(), fileDescriptor.getFile(),
                psiNamedElement.getTextRange().getStartOffset() + psiNamedElement.getText().indexOf(getName()));
    }
    navigatable.navigate(requestFocus);
}

From source file:com.intellij.refactoring.move.moveInner.MoveInnerProcessor.java

License:Apache License

protected void performRefactoring(final UsageInfo[] usages) {
    final PsiManager manager = PsiManager.getInstance(myProject);
    final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();

    final RefactoringElementListener elementListener = getTransaction().getElementListener(myInnerClass);
    try {//from   w w w .  ja  v a  2 s. com
        PsiField field = null;
        if (myParameterNameOuterClass != null) {
            // pass outer as a parameter
            field = factory.createField(myFieldNameOuterClass, factory.createType(myOuterClass));
            field = addOuterField(field);
            myInnerClass = field.getContainingClass();
            addFieldInitializationToConstructors(myInnerClass, field, myParameterNameOuterClass);
        }

        ChangeContextUtil.encodeContextInfo(myInnerClass, false);

        myInnerClass = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(myInnerClass);

        final MoveInnerOptions moveInnerOptions = new MoveInnerOptions(myInnerClass, myOuterClass,
                myTargetContainer, myNewClassName);
        final MoveInnerHandler handler = MoveInnerHandler.EP_NAME.forLanguage(myInnerClass.getLanguage());
        final PsiClass newClass;
        try {
            newClass = handler.copyClass(moveInnerOptions);
        } catch (IncorrectOperationException e) {
            RefactoringUIUtil.processIncorrectOperation(myProject, e);
            return;
        }

        // replace references in a new class to old inner class with references to itself
        for (PsiReference ref : ReferencesSearch.search(myInnerClass, new LocalSearchScope(newClass), true)) {
            PsiElement element = ref.getElement();
            if (element.getParent() instanceof PsiJavaCodeReferenceElement) {
                PsiJavaCodeReferenceElement parentRef = (PsiJavaCodeReferenceElement) element.getParent();
                PsiElement parentRefElement = parentRef.resolve();
                if (parentRefElement instanceof PsiClass) { // reference to inner class inside our inner
                    parentRef.getQualifier().delete();
                    continue;
                }
            }
            ref.bindToElement(newClass);
        }

        List<PsiReference> referencesToRebind = new ArrayList<PsiReference>();
        for (UsageInfo usage : usages) {
            if (usage.isNonCodeUsage)
                continue;
            PsiElement refElement = usage.getElement();
            PsiReference[] references = refElement.getReferences();
            for (PsiReference reference : references) {
                if (reference.isReferenceTo(myInnerClass)) {
                    referencesToRebind.add(reference);
                }
            }
        }

        myInnerClass.delete();

        // correct references in usages
        for (UsageInfo usage : usages) {
            if (usage.isNonCodeUsage)
                continue;
            PsiElement refElement = usage.getElement();
            if (myParameterNameOuterClass != null) { // should pass outer as parameter
                PsiElement refParent = refElement.getParent();
                if (refParent instanceof PsiNewExpression || refParent instanceof PsiAnonymousClass) {
                    PsiNewExpression newExpr = refParent instanceof PsiNewExpression
                            ? (PsiNewExpression) refParent
                            : (PsiNewExpression) refParent.getParent();

                    PsiExpressionList argList = newExpr.getArgumentList();

                    if (argList != null) { // can happen in incomplete code
                        if (newExpr.getQualifier() == null) {
                            PsiThisExpression thisExpr;
                            PsiClass parentClass = RefactoringChangeUtil.getThisClass(newExpr);
                            if (myOuterClass.equals(parentClass)) {
                                thisExpr = RefactoringChangeUtil.createThisExpression(manager, null);
                            } else {
                                thisExpr = RefactoringChangeUtil.createThisExpression(manager, myOuterClass);
                            }
                            argList.addAfter(thisExpr, null);
                        } else {
                            argList.addAfter(newExpr.getQualifier(), null);
                            newExpr.getQualifier().delete();
                        }
                    }
                }
            }
        }

        for (PsiReference reference : referencesToRebind) {
            reference.bindToElement(newClass);
        }

        if (field != null) {
            final PsiExpression paramAccessExpression = factory
                    .createExpressionFromText(myParameterNameOuterClass, null);
            for (final PsiMethod constructor : newClass.getConstructors()) {
                final PsiStatement[] statements = constructor.getBody().getStatements();
                if (statements.length > 0) {
                    if (statements[0] instanceof PsiExpressionStatement) {
                        PsiExpression expression = ((PsiExpressionStatement) statements[0]).getExpression();
                        if (expression instanceof PsiMethodCallExpression) {
                            @NonNls
                            String text = ((PsiMethodCallExpression) expression).getMethodExpression()
                                    .getText();
                            if ("this".equals(text) || "super".equals(text)) {
                                ChangeContextUtil.decodeContextInfo(expression, myOuterClass,
                                        paramAccessExpression);
                            }
                        }
                    }
                }
            }

            PsiExpression accessExpression = factory.createExpressionFromText(myFieldNameOuterClass, null);
            ChangeContextUtil.decodeContextInfo(newClass, myOuterClass, accessExpression);
        } else {
            ChangeContextUtil.decodeContextInfo(newClass, null, null);
        }

        PsiFile targetFile = newClass.getContainingFile();
        OpenFileDescriptor descriptor = new OpenFileDescriptor(myProject, targetFile.getVirtualFile(),
                newClass.getTextOffset());
        FileEditorManager.getInstance(myProject).openTextEditor(descriptor, true);

        if (myMoveCallback != null) {
            myMoveCallback.refactoringCompleted();
        }
        elementListener.elementMoved(newClass);

        List<NonCodeUsageInfo> nonCodeUsages = new ArrayList<NonCodeUsageInfo>();
        for (UsageInfo usage : usages) {
            if (usage instanceof NonCodeUsageInfo) {
                nonCodeUsages.add((NonCodeUsageInfo) usage);
            }
        }
        myNonCodeUsages = nonCodeUsages.toArray(new NonCodeUsageInfo[nonCodeUsages.size()]);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}

From source file:com.intellij.refactoring.rename.inplace.InplaceRefactoring.java

License:Apache License

private static void navigateToStarted(final Document oldDocument, final Project project, final int exitCode) {
    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(oldDocument);
    if (file != null) {
        final VirtualFile virtualFile = file.getVirtualFile();
        if (virtualFile != null) {
            final FileEditor[] editors = FileEditorManager.getInstance(project).getEditors(virtualFile);
            for (FileEditor editor : editors) {
                if (editor instanceof TextEditor) {
                    final Editor textEditor = ((TextEditor) editor).getEditor();
                    final TemplateState templateState = TemplateManagerImpl.getTemplateState(textEditor);
                    if (templateState != null) {
                        if (exitCode == DialogWrapper.OK_EXIT_CODE) {
                            final TextRange range = templateState.getVariableRange(PRIMARY_VARIABLE_NAME);
                            if (range != null) {
                                new OpenFileDescriptor(project, virtualFile, range.getStartOffset())
                                        .navigate(true);
                                return;
                            }/* www. java2  s  . c o  m*/
                        } else if (exitCode > 0) {
                            templateState.gotoEnd();
                            return;
                        }
                    }
                }
            }
        }
    }
}

From source file:com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl.java

License:Apache License

@Nullable
private Editor createEditor(VirtualFile file) {
    final Project project = getProject();
    final FileEditorManager instance = FileEditorManager.getInstance(project);
    if (file.getFileType().isBinary()) {
        return null;
    }/*from  w w w .j  av a 2 s .c  om*/
    return instance.openTextEditor(new OpenFileDescriptor(project, file, 0), false);
}

From source file:com.intellij.testFramework.LightPlatformCodeInsightTestCase.java

License:Apache License

protected static Editor createEditor(@NotNull VirtualFile file) {
    Editor editor = FileEditorManager.getInstance(getProject())
            .openTextEditor(new OpenFileDescriptor(getProject(), file, 0), false);
    ((EditorImpl) editor).setCaretActive();
    return editor;
}

From source file:com.intellij.uiDesigner.propertyInspector.properties.CustomCreateProperty.java

License:Apache License

public static void generateCreateComponentsMethod(final PsiClass aClass) {
    final PsiFile psiFile = aClass.getContainingFile();
    if (psiFile == null)
        return;//w  w w.jav a  2  s  .c  om
    final VirtualFile vFile = psiFile.getVirtualFile();
    if (vFile == null)
        return;
    if (!FileModificationService.getInstance().prepareFileForWrite(psiFile))
        return;

    final Ref<SmartPsiElementPointer> refMethod = new Ref<SmartPsiElementPointer>();
    CommandProcessor.getInstance().executeCommand(aClass.getProject(), new Runnable() {
        public void run() {
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                public void run() {
                    PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject())
                            .getElementFactory();
                    try {
                        PsiMethod method = factory.createMethodFromText(
                                "private void " + AsmCodeGenerator.CREATE_COMPONENTS_METHOD_NAME
                                        + "() { \n // TODO: place custom component creation code here \n }",
                                aClass);
                        final PsiMethod psiMethod = (PsiMethod) aClass.add(method);
                        refMethod.set(SmartPointerManager.getInstance(aClass.getProject())
                                .createSmartPsiElementPointer(psiMethod));
                        CodeStyleManager.getInstance(aClass.getProject()).reformat(psiMethod);
                    } catch (IncorrectOperationException e) {
                        LOG.error(e);
                    }
                }
            });
        }
    }, null, null);

    if (!refMethod.isNull()) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                final PsiMethod element = (PsiMethod) refMethod.get().getElement();
                if (element != null) {
                    final PsiCodeBlock body = element.getBody();
                    assert body != null;
                    final PsiComment comment = PsiTreeUtil.getChildOfType(body, PsiComment.class);
                    if (comment != null) {
                        new OpenFileDescriptor(comment.getProject(), vFile, comment.getTextOffset())
                                .navigate(true);
                    }
                }
            }
        });
    }
}

From source file:com.intellij.uiDesigner.wizard.Generator.java

License:Apache License

/**
 * Should be invoked in command and write action
 *///w w  w .  j a v  a2 s .  com
@SuppressWarnings({ "HardCodedStringLiteral" })
public static void generateDataBindingMethods(final WizardData data) throws MyException {
    if (data.myBindToNewBean) {
        data.myBeanClass = createBeanClass(data);
    } else {
        if (!CommonRefactoringUtil.checkReadOnlyStatus(data.myBeanClass.getProject(), data.myBeanClass)) {
            return;
        }
    }

    final HashMap<String, String> binding2beanGetter = new HashMap<String, String>();
    final HashMap<String, String> binding2beanSetter = new HashMap<String, String>();

    final FormProperty2BeanProperty[] bindings = data.myBindings;
    for (final FormProperty2BeanProperty form2bean : bindings) {
        if (form2bean == null || form2bean.myBeanProperty == null) {
            continue;
        }

        // check that bean contains the property, and if not, try to add the property to the bean
        {
            final String setterName = PropertyUtil.suggestSetterName(form2bean.myBeanProperty.myName);
            final PsiMethod[] methodsByName = data.myBeanClass.findMethodsByName(setterName, true);
            if (methodsByName.length < 1) {
                // bean does not contain this property
                // try to add...

                LOG.assertTrue(!data.myBindToNewBean); // just generated bean class should contain all necessary properties

                if (!data.myBeanClass.isWritable()) {
                    throw new MyException(
                            "Cannot add property to non writable class " + data.myBeanClass.getQualifiedName());
                }

                final StringBuffer membersBuffer = new StringBuffer();
                final StringBuffer methodsBuffer = new StringBuffer();

                final Project project = data.myBeanClass.getProject();
                final CodeStyleManager formatter = CodeStyleManager.getInstance(project);
                final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(project);

                generateProperty(styler, form2bean.myBeanProperty.myName, form2bean.myBeanProperty.myType,
                        membersBuffer, methodsBuffer);

                final PsiClass fakeClass;
                try {
                    fakeClass = JavaPsiFacade.getInstance(data.myBeanClass.getProject()).getElementFactory()
                            .createClassFromText(membersBuffer.toString() + methodsBuffer.toString(), null);

                    final PsiField[] fields = fakeClass.getFields();
                    {
                        final PsiElement result = data.myBeanClass.add(fields[0]);
                        styler.shortenClassReferences(result);
                        formatter.reformat(result);
                    }

                    final PsiMethod[] methods = fakeClass.getMethods();
                    {
                        final PsiElement result = data.myBeanClass.add(methods[0]);
                        styler.shortenClassReferences(result);
                        formatter.reformat(result);
                    }
                    {
                        final PsiElement result = data.myBeanClass.add(methods[1]);
                        styler.shortenClassReferences(result);
                        formatter.reformat(result);
                    }
                } catch (IncorrectOperationException e) {
                    throw new MyException(e.getMessage());
                }
            }
        }

        final PsiMethod propertySetter = PropertyUtil.findPropertySetter(data.myBeanClass,
                form2bean.myBeanProperty.myName, false, true);
        final PsiMethod propertyGetter = PropertyUtil.findPropertyGetter(data.myBeanClass,
                form2bean.myBeanProperty.myName, false, true);

        if (propertyGetter == null) {
            // todo
            continue;
        }
        if (propertySetter == null) {
            // todo
            continue;
        }

        final String binding = form2bean.myFormProperty.getLwComponent().getBinding();
        binding2beanGetter.put(binding, propertyGetter.getName());
        binding2beanSetter.put(binding, propertySetter.getName());
    }

    final String dataBeanClassName = data.myBeanClass.getQualifiedName();

    final LwRootContainer[] rootContainer = new LwRootContainer[1];
    final FormProperty[] formProperties = exposeForm(data.myProject, data.myFormFile, rootContainer);

    final StringBuffer getDataBody = new StringBuffer();
    final StringBuffer setDataBody = new StringBuffer();
    final StringBuffer isModifiedBody = new StringBuffer();

    // iterate exposed formproperties

    for (final FormProperty formProperty : formProperties) {
        final String binding = formProperty.getLwComponent().getBinding();
        if (!binding2beanGetter.containsKey(binding)) {
            continue;
        }

        getDataBody.append("data.");
        getDataBody.append(binding2beanSetter.get(binding));
        getDataBody.append("(");
        getDataBody.append(binding);
        getDataBody.append(".");
        getDataBody.append(formProperty.getComponentPropertyGetterName());
        getDataBody.append("());\n");

        setDataBody.append(binding);
        setDataBody.append(".");
        setDataBody.append(formProperty.getComponentPropertySetterName());
        setDataBody.append("(data.");
        setDataBody.append(binding2beanGetter.get(binding));
        setDataBody.append("());\n");

        final String propertyClassName = formProperty.getComponentPropertyClassName();
        if ("boolean".equals(propertyClassName)) {
            isModifiedBody.append("if (");
            //
            isModifiedBody.append(binding);
            isModifiedBody.append(".");
            isModifiedBody.append(formProperty.getComponentPropertyGetterName());
            isModifiedBody.append("()");
            //
            isModifiedBody.append("!= ");
            //
            isModifiedBody.append("data.");
            isModifiedBody.append(binding2beanGetter.get(binding));
            isModifiedBody.append("()");
            //
            isModifiedBody.append(") return true;\n");
        } else {
            isModifiedBody.append("if (");
            //
            isModifiedBody.append(binding);
            isModifiedBody.append(".");
            isModifiedBody.append(formProperty.getComponentPropertyGetterName());
            isModifiedBody.append("()");
            //
            isModifiedBody.append("!= null ? ");
            //
            isModifiedBody.append("!");
            //
            isModifiedBody.append(binding);
            isModifiedBody.append(".");
            isModifiedBody.append(formProperty.getComponentPropertyGetterName());
            isModifiedBody.append("()");
            //
            isModifiedBody.append(".equals(");
            //
            isModifiedBody.append("data.");
            isModifiedBody.append(binding2beanGetter.get(binding));
            isModifiedBody.append("()");
            isModifiedBody.append(") : ");
            //
            isModifiedBody.append("data.");
            isModifiedBody.append(binding2beanGetter.get(binding));
            isModifiedBody.append("()");
            isModifiedBody.append("!= null");
            //
            isModifiedBody.append(") return true;\n");
        }
    }
    isModifiedBody.append("return false;\n");

    final String textOfMethods = "public void setData(" + dataBeanClassName + " data){\n"
            + setDataBody.toString() + "}\n" + "\n" + "public void getData(" + dataBeanClassName + " data){\n"
            + getDataBody.toString() + "}\n" + "\n" + "public boolean isModified(" + dataBeanClassName
            + " data){\n" + isModifiedBody.toString() + "}\n";

    // put them to the bound class

    final Module module = ModuleUtil.findModuleForFile(data.myFormFile, data.myProject);
    LOG.assertTrue(module != null);
    final PsiClass boundClass = FormEditingUtil.findClassToBind(module, rootContainer[0].getClassToBind());
    LOG.assertTrue(boundClass != null);

    if (!CommonRefactoringUtil.checkReadOnlyStatus(module.getProject(), boundClass)) {
        return;
    }

    // todo: check that this method does not exist yet

    final PsiClass fakeClass;
    try {
        fakeClass = JavaPsiFacade.getInstance(data.myProject).getElementFactory()
                .createClassFromText(textOfMethods, null);

        final PsiMethod methodSetData = fakeClass.getMethods()[0];
        final PsiMethod methodGetData = fakeClass.getMethods()[1];
        final PsiMethod methodIsModified = fakeClass.getMethods()[2];

        final PsiMethod existing1 = boundClass.findMethodBySignature(methodSetData, false);
        final PsiMethod existing2 = boundClass.findMethodBySignature(methodGetData, false);
        final PsiMethod existing3 = boundClass.findMethodBySignature(methodIsModified, false);

        // warning already shown
        if (existing1 != null) {
            existing1.delete();
        }
        if (existing2 != null) {
            existing2.delete();
        }
        if (existing3 != null) {
            existing3.delete();
        }

        final CodeStyleManager formatter = CodeStyleManager.getInstance(module.getProject());
        final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(module.getProject());

        final PsiElement setData = boundClass.add(methodSetData);
        styler.shortenClassReferences(setData);
        formatter.reformat(setData);

        final PsiElement getData = boundClass.add(methodGetData);
        styler.shortenClassReferences(getData);
        formatter.reformat(getData);

        if (data.myGenerateIsModified) {
            final PsiElement isModified = boundClass.add(methodIsModified);
            styler.shortenClassReferences(isModified);
            formatter.reformat(isModified);
        }

        final OpenFileDescriptor descriptor = new OpenFileDescriptor(setData.getProject(),
                setData.getContainingFile().getVirtualFile(), setData.getTextOffset());
        FileEditorManager.getInstance(data.myProject).openTextEditor(descriptor, true);
    } catch (IncorrectOperationException e) {
        throw new MyException(e.getMessage());
    }
}

From source file:com.intellij.usages.UsageInfo2UsageAdapter.java

License:Apache License

@Nullable
private OpenFileDescriptor getDescriptor() {
    VirtualFile file = getFile();/*  w w w. ja  v a  2  s .c  om*/
    if (file == null)
        return null;
    int offset = getNavigationOffset();
    return new OpenFileDescriptor(getProject(), file, offset);
}