Java Code Examples for com.intellij.psi.codeStyle.JavaCodeStyleManager#getInstance()

The following examples show how to use com.intellij.psi.codeStyle.JavaCodeStyleManager#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseLombokHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void addAnnotation(@NotNull PsiModifierListOwner targetElement, @NotNull PsiAnnotation newPsiAnnotation,
                           @NotNull Class<? extends Annotation> annotationClass) {
  final PsiAnnotation presentAnnotation = PsiAnnotationSearchUtil.findAnnotation(targetElement, annotationClass);

  final Project project = targetElement.getProject();
  final JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
  javaCodeStyleManager.shortenClassReferences(newPsiAnnotation);

  if (null == presentAnnotation) {
    PsiModifierList modifierList = targetElement.getModifierList();
    if (null != modifierList) {
      modifierList.addAfter(newPsiAnnotation, null);
    }
  } else {
    presentAnnotation.setDeclaredAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME,
      newPsiAnnotation.findDeclaredAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME));
  }
}
 
Example 2
Source File: InjectWriter.java    From android-butterknife-zelezny with Apache License 2.0 6 votes vote down vote up
@Override
public void run() throws Throwable {
    final IButterKnife butterKnife = ButterKnifeFactory.findButterKnifeForPsiElement(mProject, mFile);
    if (butterKnife == null) {
        return; // Butterknife library is not available for project
    }

    if (mCreateHolder) {
        generateAdapter(butterKnife);
    } else {
        if (Utils.getInjectCount(mElements) > 0) {
            generateFields(butterKnife);
        }
        generateInjects(butterKnife);
        if (Utils.getClickCount(mElements) > 0) {
            generateClick();
        }
        Utils.showInfoNotification(mProject, String.valueOf(Utils.getInjectCount(mElements)) + " injections and " + String.valueOf(Utils.getClickCount(mElements)) + " onClick added to " + mFile.getName());
    }

    // reformat class
    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(mProject);
    styleManager.optimizeImports(mFile);
    styleManager.shortenClassReferences(mClass);
    new ReformatCodeProcessor(mProject, mClass.getContainingFile(), null, false).runWithoutProgress();
}
 
Example 3
Source File: GodClassPreviewResultDialog.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
public GodClassPreviewResultDialog(@NotNull Project project, @NotNull MutableDiffRequestChain requestChain,
                                   @NotNull DiffDialogHints hints, ExtractClassPreviewProcessor previewProcessor) {
    super(project, requestChain, hints);
    this.myChain = requestChain;
    this.project = project;
    this.diffContentFactory = DiffContentFactory.getInstance();
    this.previewProcessor = previewProcessor;
    this.javaCodeStyleManager = JavaCodeStyleManager.getInstance(project);
    this.codeStyleManager = CodeStyleManager.getInstance(project);
}
 
Example 4
Source File: FieldNamePolicyTest.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
    super.setUp();
    final Project project = getProject();
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    underTest = new FieldNamePolicy(codeStyleManager);
}
 
Example 5
Source File: ParameterNamePolicyTest.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
    super.setUp();
    final Project project = getProject();
    final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
    underTest = new ParameterNamePolicy(codeStyleManager);
}
 
Example 6
Source File: AbstractFileProvider.java    From CodeGen with MIT License 5 votes vote down vote up
protected PsiFile createFile(Project project, @NotNull PsiDirectory psiDirectory, String fileName, String context, FileType fileType) {
    PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText(fileName, fileType, context);
    // reformat class
    CodeStyleManager.getInstance(project).reformat(psiFile);
    if (psiFile instanceof PsiJavaFile) {
        JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
        styleManager.optimizeImports(psiFile);
        styleManager.shortenClassReferences(psiFile);
    }
    // TODO: 加入覆盖判断
    psiDirectory.add(psiFile);
    return psiFile;
}
 
Example 7
Source File: Processor.java    From GsonFormat with Apache License 2.0 5 votes vote down vote up
protected void formatJavCode(PsiClass cls) {
    if (cls == null) {
        return;
    }
    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(cls.getProject());
    styleManager.optimizeImports(cls.getContainingFile());
    styleManager.shortenClassReferences(cls);
}
 
Example 8
Source File: CodeGenerator.java    From ParcelablePlease with Apache License 2.0 5 votes vote down vote up
/**
 * Generate and insert the Parcel and ParcelablePlease code
 */
public void generate() {

  PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiClass.getProject());
  JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(psiClass.getProject());

  // Clear any previous
  clearPrevious();

  // Implements parcelable
  makeClassImplementParcelable(elementFactory, styleManager);

  // @ParcelablePlease Annotation
  addAnnotation(elementFactory, styleManager);

  // Creator
  PsiField creatorField = elementFactory.createFieldFromText(generateCreator(), psiClass);

  // Describe contents method
  PsiMethod describeContentsMethod =
      elementFactory.createMethodFromText(generateDescribeContents(), psiClass);

  // Method for writing to the parcel
  PsiMethod writeToParcelMethod =
      elementFactory.createMethodFromText(generateWriteToParcel(), psiClass);

  styleManager.shortenClassReferences(
      psiClass.addBefore(describeContentsMethod, psiClass.getLastChild()));

  styleManager.shortenClassReferences(
      psiClass.addBefore(writeToParcelMethod, psiClass.getLastChild()));

  styleManager.shortenClassReferences(psiClass.addBefore(creatorField, psiClass.getLastChild()));
}
 
Example 9
Source File: CodeGenerator.java    From android-parcelable-intellij-plugin with Apache License 2.0 5 votes vote down vote up
public void generate() {
    PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(mClass.getProject());

    removeExistingParcelableImplementation(mClass);

    // Describe contents method
    PsiMethod describeContentsMethod = elementFactory.createMethodFromText(generateDescribeContents(), mClass);
    // Method for writing to the parcel
    PsiMethod writeToParcelMethod = elementFactory.createMethodFromText(generateWriteToParcel(mFields), mClass);

    // Default constructor if needed
    String defaultConstructorString = generateDefaultConstructor(mClass);
    PsiMethod defaultConstructor = null;

    if (defaultConstructorString != null) {
        defaultConstructor = elementFactory.createMethodFromText(defaultConstructorString, mClass);
    }

    // Constructor
    PsiMethod constructor = elementFactory.createMethodFromText(generateConstructor(mFields, mClass), mClass);
    // CREATOR
    PsiField creatorField = elementFactory.createFieldFromText(generateStaticCreator(mClass), mClass);

    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(mClass.getProject());

    // Shorten all class references
    styleManager.shortenClassReferences(mClass.addBefore(describeContentsMethod, mClass.getLastChild()));
    styleManager.shortenClassReferences(mClass.addBefore(writeToParcelMethod, mClass.getLastChild()));

    // Only adds if available
    if (defaultConstructor != null) {
        styleManager.shortenClassReferences(mClass.addBefore(defaultConstructor, mClass.getLastChild()));
    }

    styleManager.shortenClassReferences(mClass.addBefore(constructor, mClass.getLastChild()));
    styleManager.shortenClassReferences(mClass.addBefore(creatorField, mClass.getLastChild()));

    makeClassImplementParcelable(elementFactory);
}
 
Example 10
Source File: ProjectModule.java    From json2java4idea with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Provides
@Singleton
public JavaCodeStyleManager provideCodeStyleManager(@Nonnull Project project) {
    return JavaCodeStyleManager.getInstance(project);
}
 
Example 11
Source File: PropertyProcessor.java    From data-mediator with Apache License 2.0 4 votes vote down vote up
private void generateInternal(PsiClass mPsiClass, ClassInfo info) {
    if(mPsiClass.getName() == null){
        Util.log("mPsiClass.getName() == null");
        return;
    }
    final Project project = mPsiClass.getProject();
    //delete if exist
    PsiClass psiClass_pre = JavaPsiFacade.getInstance(project).findClass(getSuperClassAsInterfaceName(mPsiClass),
            GlobalSearchScope.projectScope(project));
    if(psiClass_pre != null && psiClass_pre.isValid()){
        if(!psiClass_pre.isWritable()){
            Util.log("the previous PsiClass (" + psiClass_pre.getQualifiedName() + ") can write. will be ignored.");
            return;
        }
        psiClass_pre.delete();
    }

    final String name = "I" + mPsiClass.getName();
    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
    PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);

    PsiElement parent = mPsiClass.getParent();
    if(parent instanceof PsiClass){
        Util.log("start nested class.");
        PsiClass psic = elementFactory.createInterface(name);
        psic.getModifierList().addAnnotation("com.heaven7.java.data.mediator.Fields(value ={\n"
                + buildFieldAnnotations(info.getPropertyInfos())+ "\n} , generateJsonAdapter = false)");
        if (!addExtendInterfaces(info, styleManager, elementFactory, psic)) {
            return;
        }
        styleManager.shortenClassReferences(parent.addAfter(psic, mPsiClass));
    }else{
        PsiDirectory dir = mPsiClass.getContainingFile().getContainingDirectory();
        PsiClass psiClass = createJavaFile(name, "@com.heaven7.java.data.mediator.Fields(value ={\n"
                                    + buildFieldAnnotations(info.getPropertyInfos())
                + "\n}, generateJsonAdapter = false) "
                + "public interface " + name + "{}");
        if (!addExtendInterfaces(info, styleManager, elementFactory, psiClass)) {
            return;
        }
        styleManager.shortenClassReferences(psiClass);
        dir.add(psiClass);
    }
}
 
Example 12
Source File: PropertyGenerator.java    From data-mediator with Apache License 2.0 4 votes vote down vote up
/**
 * 1, add Override for super properties.
 * 2, generate super.
 * 3, remove fields/methods which have no annotation of @Keep and @ImplMethod.
 */
void generate() {
    final Project project = mPsiClass.getProject();
    PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
    //remove exist method
    removeExistingImpl(mPsiClass);

    List<PsiMethod> methods = new ArrayList<>();
    List<PsiField> fields = new ArrayList<>();

    //generate PROP_selected if possible.
    if(mHasSelectable) {
        fields.add(createConstantField(mPsiClass, elementFactory, Property.PROP_selected));
    }
    //generate for current properties.
    generateProperties(elementFactory, mProps, methods, fields, false);

    final PsiMethod anchor = methods.get(methods.size() - 1);
    PsiComment doc = null;
    if (mSuperFields != null && !mSuperFields.isEmpty()) {
        doc = elementFactory.createCommentFromText(
                "/* \n================== start methods from super properties =============== \n" +
                        "======================================================================= */",
                null);
        //generate for super properties
        generateProperties(elementFactory, mSuperFields, methods, fields, true);
    }

    JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
    for (PsiField pf : fields) {
        styleManager.shortenClassReferences(pf);
        mPsiClass.add(pf);
    }
    for (PsiMethod psi : methods) {
        styleManager.shortenClassReferences(mPsiClass.addBefore(psi, mPsiClass.getLastChild()));
        if (psi == anchor && doc != null) {
            mPsiClass.addBefore(doc, mPsiClass.getLastChild());
        }
    }
    //extend Poolable.
    TypeInterfaceExtend__Poolable poolable = new TypeInterfaceExtend__Poolable();
    if (!poolable.isSuperClassHas(mPsiClass)) {
        poolable.makeInterfaceExtend(mPsiClass, elementFactory, styleManager);
    }
}
 
Example 13
Source File: PolygeneConcernUtil.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@NotNull
public static PsiAnnotation addOrReplaceConcernAnnotation( @NotNull PsiModifierListOwner modifierListOwner,
                                                           @NotNull PsiClass concernClassToAdd )
{
    Project project = modifierListOwner.getProject();
    JavaPsiFacade psiFacade = JavaPsiFacade.getInstance( project );
    PsiElementFactory factory = psiFacade.getElementFactory();
    PsiAnnotation existingConcernsAnnotation = findAnnotation( modifierListOwner, QUALIFIED_NAME_CONCERNS );

    boolean isReplace = false;
    PsiAnnotation newConcernsAnnotation;
    if( existingConcernsAnnotation != null )
    {
        // Check duplicate
        List<PsiAnnotationMemberValue> concernsValues = getConcernsAnnotationValue( existingConcernsAnnotation );
        for( PsiAnnotationMemberValue concernValue : concernsValues )
        {
            PsiJavaCodeReferenceElement concernClassReference = getConcernClassReference( concernValue );
            if( concernClassReference == null )
            {
                continue;
            }

            PsiElement concernClass = concernClassReference.resolve();
            if( concernClassToAdd.equals( concernClass ) )
            {
                return existingConcernsAnnotation;
            }
        }

        isReplace = true;
    }

    String concernAnnotationText = createConcernAnnotationText( existingConcernsAnnotation, concernClassToAdd );
    newConcernsAnnotation =
        factory.createAnnotationFromText( concernAnnotationText, modifierListOwner );

    if( isReplace )
    {
        // Replace @Concerns instead
        existingConcernsAnnotation.replace( newConcernsAnnotation );
    }
    else
    {
        // @Concerns doesn't exists, add it as first child
        PsiModifierList modifierList = modifierListOwner.getModifierList();
        modifierList.addBefore( newConcernsAnnotation, modifierList.getFirstChild() );
    }

    // Shorten all class references if possible
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance( project );
    codeStyleManager.shortenClassReferences( newConcernsAnnotation );

    return newConcernsAnnotation;
}
 
Example 14
Source File: PolygeneMixinUtil.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
@NotNull
public static PsiAnnotation addOrReplaceMixinAnnotation( @NotNull PsiModifierListOwner modifierListOwner,
                                                         @NotNull PsiClass mixinClassToAdd )
{
    Project project = modifierListOwner.getProject();
    JavaPsiFacade psiFacade = JavaPsiFacade.getInstance( project );
    PsiElementFactory factory = psiFacade.getElementFactory();
    PsiAnnotation existingMixinsAnnotation = findAnnotation( modifierListOwner, QUALIFIED_NAME_MIXINS );

    boolean isReplace = false;
    PsiAnnotation newMixinsAnnotation;
    if( existingMixinsAnnotation != null )
    {
        // Check duplicate
        List<PsiAnnotationMemberValue> mixinsValues = getMixinsAnnotationValue( existingMixinsAnnotation );
        for( PsiAnnotationMemberValue mixinValue : mixinsValues )
        {
            PsiJavaCodeReferenceElement mixinClassReference = getMixinClassReference( mixinValue );
            if( mixinClassReference == null )
            {
                continue;
            }

            PsiElement mixinClass = mixinClassReference.resolve();
            if( mixinClassToAdd.equals( mixinClass ) )
            {
                return existingMixinsAnnotation;
            }
        }

        isReplace = true;
    }

    String mixinsAnnotationText = createMixinsAnnotationText( existingMixinsAnnotation, mixinClassToAdd );
    newMixinsAnnotation = factory.createAnnotationFromText( mixinsAnnotationText, modifierListOwner );

    if( isReplace )
    {
        // Replace @Mixins instead
        existingMixinsAnnotation.replace( newMixinsAnnotation );
    }
    else
    {
        // @Mixins doesn't exists, add it as first child
        PsiModifierList modifierList = modifierListOwner.getModifierList();
        modifierList.addBefore( newMixinsAnnotation, modifierList.getFirstChild() );
    }

    // Shorten all class references if possible
    JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance( project );
    codeStyleManager.shortenClassReferences( newMixinsAnnotation );

    return newMixinsAnnotation;
}