Search in sources :

Example 76 with CodeStyleManager

use of com.intellij.psi.codeStyle.CodeStyleManager in project intellij-community by JetBrains.

the class FieldConflictsResolver method qualifyReference.

public static GrReferenceExpression qualifyReference(GrReferenceExpression referenceExpression, final PsiMember member, @Nullable final PsiClass qualifyingClass) throws IncorrectOperationException {
    PsiManager manager = referenceExpression.getManager();
    GrReferenceExpression expressionFromText;
    final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(referenceExpression.getProject());
    if (qualifyingClass == null) {
        PsiClass parentClass = PsiTreeUtil.getParentOfType(referenceExpression, PsiClass.class);
        final PsiClass containingClass = member.getContainingClass();
        if (parentClass != null && !InheritanceUtil.isInheritorOrSelf(parentClass, containingClass, true)) {
            while (parentClass != null && !InheritanceUtil.isInheritorOrSelf(parentClass, containingClass, true)) {
                parentClass = PsiTreeUtil.getParentOfType(parentClass, PsiClass.class, true);
            }
            LOG.assertTrue(parentClass != null);
            expressionFromText = factory.createReferenceExpressionFromText("A.this." + member.getName());
            //noinspection ConstantConditions
            ((GrReferenceExpression) expressionFromText.getQualifier()).getQualifier().replace(factory.createReferenceElementForClass(parentClass));
        } else {
            expressionFromText = (GrReferenceExpression) factory.createExpressionFromText("this." + member.getName());
        }
    } else {
        expressionFromText = (GrReferenceExpression) factory.createExpressionFromText("A." + member.getName());
        expressionFromText.setQualifier(factory.createReferenceElementForClass(qualifyingClass));
    }
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
    expressionFromText = (GrReferenceExpression) codeStyleManager.reformat(expressionFromText);
    return (GrReferenceExpression) referenceExpression.replace(expressionFromText);
}
Also used : GroovyPsiElementFactory(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression)

Example 77 with CodeStyleManager

use of com.intellij.psi.codeStyle.CodeStyleManager in project intellij-community by JetBrains.

the class Generator method generateDataBindingMethods.

/**
   * Should be invoked in command and write action
   */
@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<>();
    final HashMap<String, String> binding2beanSetter = new HashMap<>();
    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...
                // just generated bean class should contain all necessary properties
                LOG.assertTrue(!data.myBindToNewBean);
                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();
    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());
    }
}
Also used : JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) HashMap(java.util.HashMap) LwRootContainer(com.intellij.uiDesigner.lw.LwRootContainer) Project(com.intellij.openapi.project.Project) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) IncorrectOperationException(com.intellij.util.IncorrectOperationException) OpenFileDescriptor(com.intellij.openapi.fileEditor.OpenFileDescriptor) Module(com.intellij.openapi.module.Module)

Example 78 with CodeStyleManager

use of com.intellij.psi.codeStyle.CodeStyleManager in project intellij-community by JetBrains.

the class FormSourceCodeGenerator method _generate.

private void _generate(final LwRootContainer rootContainer, final Module module) throws CodeGenerationException, IncorrectOperationException {
    myBuffer = new StringBuffer();
    myIsFirstParameterStack = new Stack<>();
    final HashMap<LwComponent, String> component2variable = new HashMap<>();
    final TObjectIntHashMap<String> class2variableIndex = new TObjectIntHashMap<>();
    final HashMap<String, LwComponent> id2component = new HashMap<>();
    if (rootContainer.getComponentCount() != 1) {
        throw new CodeGenerationException(null, UIDesignerBundle.message("error.one.toplevel.component.required"));
    }
    final LwComponent topComponent = (LwComponent) rootContainer.getComponent(0);
    String id = Utils.findNotEmptyPanelWithXYLayout(topComponent);
    if (id != null) {
        throw new CodeGenerationException(id, UIDesignerBundle.message("error.nonempty.xy.panels.found"));
    }
    final PsiClass classToBind = FormEditingUtil.findClassToBind(module, rootContainer.getClassToBind());
    if (classToBind == null) {
        throw new ClassToBindNotFoundException(UIDesignerBundle.message("error.class.to.bind.not.found", rootContainer.getClassToBind()));
    }
    final boolean haveCustomCreateComponents = Utils.getCustomCreateComponentCount(rootContainer) > 0;
    if (haveCustomCreateComponents) {
        if (FormEditingUtil.findCreateComponentsMethod(classToBind) == null) {
            throw new CodeGenerationException(null, UIDesignerBundle.message("error.no.custom.create.method"));
        }
        myBuffer.append(AsmCodeGenerator.CREATE_COMPONENTS_METHOD_NAME).append("();");
    }
    generateSetupCodeForComponent(topComponent, component2variable, class2variableIndex, id2component, module, classToBind);
    generateComponentReferenceProperties(topComponent, component2variable, class2variableIndex, id2component, classToBind);
    generateButtonGroups(rootContainer, component2variable, class2variableIndex, id2component, classToBind);
    final String methodText = myBuffer.toString();
    final PsiManager psiManager = PsiManager.getInstance(module.getProject());
    final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
    PsiClass newClass = (PsiClass) classToBind.copy();
    cleanup(newClass);
    // [anton] the comments are written according to the SCR 26896  
    final PsiClass fakeClass = elementFactory.createClassFromText("{\n" + "// GUI initializer generated by " + ApplicationNamesInfo.getInstance().getFullProductName() + " GUI Designer\n" + "// >>> IMPORTANT!! <<<\n" + "// DO NOT EDIT OR ADD ANY CODE HERE!\n" + "" + AsmCodeGenerator.SETUP_METHOD_NAME + "();\n" + "}\n" + "\n" + "/** Method generated by " + ApplicationNamesInfo.getInstance().getFullProductName() + " GUI Designer\n" + " * >>> IMPORTANT!! <<<\n" + " * DO NOT edit this method OR call it in your code!\n" + " * @noinspection ALL\n" + " */\n" + "private void " + AsmCodeGenerator.SETUP_METHOD_NAME + "()\n" + "{\n" + methodText + "}\n", null);
    final CodeStyleManager formatter = CodeStyleManager.getInstance(module.getProject());
    final JavaCodeStyleManager styler = JavaCodeStyleManager.getInstance(module.getProject());
    PsiMethod method = (PsiMethod) newClass.add(fakeClass.getMethods()[0]);
    // don't generate initializer block if $$$setupUI$$$() is called explicitly from one of the constructors
    boolean needInitializer = true;
    boolean needSetupUI = false;
    for (PsiMethod constructor : newClass.getConstructors()) {
        if (containsMethodIdentifier(constructor, method)) {
            needInitializer = false;
        } else if (haveCustomCreateComponents && hasCustomComponentAffectingReferences(constructor, newClass, rootContainer, null)) {
            needInitializer = false;
            needSetupUI = true;
        }
    }
    if (needSetupUI) {
        for (PsiMethod constructor : newClass.getConstructors()) {
            addSetupUICall(constructor, rootContainer, method);
        }
    }
    if (needInitializer) {
        newClass.addBefore(fakeClass.getInitializers()[0], method);
    }
    @NonNls final String grcMethodText = "/** @noinspection ALL */ public javax.swing.JComponent " + AsmCodeGenerator.GET_ROOT_COMPONENT_METHOD_NAME + "() { return " + topComponent.getBinding() + "; }";
    generateMethodIfRequired(newClass, method, AsmCodeGenerator.GET_ROOT_COMPONENT_METHOD_NAME, grcMethodText, topComponent.getBinding() != null);
    final String loadButtonTextMethodText = getLoadMethodText(AsmCodeGenerator.LOAD_BUTTON_TEXT_METHOD, AbstractButton.class, module);
    generateMethodIfRequired(newClass, method, AsmCodeGenerator.LOAD_BUTTON_TEXT_METHOD, loadButtonTextMethodText, myNeedLoadButtonText);
    final String loadLabelTextMethodText = getLoadMethodText(AsmCodeGenerator.LOAD_LABEL_TEXT_METHOD, JLabel.class, module);
    generateMethodIfRequired(newClass, method, AsmCodeGenerator.LOAD_LABEL_TEXT_METHOD, loadLabelTextMethodText, myNeedLoadLabelText);
    newClass = (PsiClass) styler.shortenClassReferences(newClass);
    newClass = (PsiClass) formatter.reformat(newClass);
    if (!lexemsEqual(classToBind, newClass)) {
        classToBind.replace(newClass);
    }
}
Also used : NonNls(org.jetbrains.annotations.NonNls) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) TObjectIntHashMap(gnu.trove.TObjectIntHashMap) TIntObjectHashMap(gnu.trove.TIntObjectHashMap) TObjectIntHashMap(gnu.trove.TObjectIntHashMap) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager)

Example 79 with CodeStyleManager

use of com.intellij.psi.codeStyle.CodeStyleManager in project intellij-community by JetBrains.

the class PsiReplacementUtil method replaceExpression.

public static void replaceExpression(@NotNull PsiExpression expression, @NotNull @NonNls String newExpressionText) {
    final Project project = expression.getProject();
    final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
    final PsiElementFactory factory = psiFacade.getElementFactory();
    final PsiExpression newExpression = factory.createExpressionFromText(newExpressionText, expression);
    final PsiElement replacementExpression = expression.replace(newExpression);
    final CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
    styleManager.reformat(replacementExpression);
}
Also used : Project(com.intellij.openapi.project.Project) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager)

Example 80 with CodeStyleManager

use of com.intellij.psi.codeStyle.CodeStyleManager in project intellij-community by JetBrains.

the class PsiReplacementUtil method replaceExpressionAndShorten.

public static PsiElement replaceExpressionAndShorten(@NotNull PsiExpression expression, @NotNull @NonNls String newExpressionText) {
    final Project project = expression.getProject();
    final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
    final PsiElementFactory factory = psiFacade.getElementFactory();
    final PsiExpression newExpression = factory.createExpressionFromText(newExpressionText, expression);
    final PsiElement replacementExp = expression.replace(newExpression);
    final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
    javaCodeStyleManager.shortenClassReferences(replacementExp);
    final CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
    return styleManager.reformat(replacementExp);
}
Also used : Project(com.intellij.openapi.project.Project) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) JavaCodeStyleManager(com.intellij.psi.codeStyle.JavaCodeStyleManager)

Aggregations

CodeStyleManager (com.intellij.psi.codeStyle.CodeStyleManager)97 JavaCodeStyleManager (com.intellij.psi.codeStyle.JavaCodeStyleManager)29 Project (com.intellij.openapi.project.Project)26 TextRange (com.intellij.openapi.util.TextRange)19 NonNls (org.jetbrains.annotations.NonNls)18 IncorrectOperationException (com.intellij.util.IncorrectOperationException)16 NotNull (org.jetbrains.annotations.NotNull)8 Document (com.intellij.openapi.editor.Document)6 PsiFile (com.intellij.psi.PsiFile)6 Module (com.intellij.openapi.module.Module)5 PsiElement (com.intellij.psi.PsiElement)4 PsiDocComment (com.intellij.psi.javadoc.PsiDocComment)4 Nullable (org.jetbrains.annotations.Nullable)4 CaretModel (com.intellij.openapi.editor.CaretModel)3 CodeStyleSettings (com.intellij.psi.codeStyle.CodeStyleSettings)3 JavaLanguage (com.intellij.lang.java.JavaLanguage)2 FileType (com.intellij.openapi.fileTypes.FileType)2 Comparing (com.intellij.openapi.util.Comparing)2 StringUtil (com.intellij.openapi.util.text.StringUtil)2 com.intellij.psi (com.intellij.psi)2