diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/dom/generator/JetBrainsEmitter.java b/plugin/src/main/java/org/jetbrains/idea/devkit/dom/generator/JetBrainsEmitter.java index 4e7fc606..e883ed6c 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/dom/generator/JetBrainsEmitter.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/dom/generator/JetBrainsEmitter.java @@ -38,6 +38,7 @@ public class JetBrainsEmitter implements Emitter { static final boolean REPLACE_TYPES_WITH_INTERFACES = true; private String AUTHOR = null; + @Override public void emit(FileManager fileManager, ModelDesc model, File outputRoot) { final NamespaceDesc nsdDef = model.nsdMap.get(""); final Set simpleTypes = new TreeSet<>(); @@ -95,7 +96,7 @@ public void generateClass(FileManager fileManager, TypeDesc td, ModelDesc model, } } for (FieldDesc fd : td.fdMap.values()) { - if (fd.simpleTypesString != null && fd.simpleTypesString.indexOf(":fully-qualified-classType;") != -1) { + if (fd.simpleTypesString != null && fd.simpleTypesString.contains(":fully-qualified-classType;")) { externalClasses.add("com.intellij.psi.PsiClass"); } if (fd.contentQualifiedName != null && fd.contentQualifiedName.indexOf('.') > 0) { @@ -119,7 +120,7 @@ public void generateClass(FileManager fileManager, TypeDesc td, ModelDesc model, out.println("// DTD/Schema : " + nsd.name); } out.println(""); - if (NOT_COMPARE_MODE && pkgName != null && pkgName.length() > 0) { + if (NOT_COMPARE_MODE && pkgName != null && !pkgName.isEmpty()) { out.println("package " + pkgName + ";"); } out.println(); @@ -264,44 +265,44 @@ public void generateClass(FileManager fileManager, TypeDesc td, ModelDesc model, String newType = field.clType < 0 ? elementType : type; String converterString = null; if (field.simpleTypesString != null) { - if (field.simpleTypesString.indexOf(":fully-qualified-classType;") != -1) { // localType, remoteType, etc. + if (field.simpleTypesString.contains(":fully-qualified-classType;")) { // localType, remoteType, etc. newType = "PsiClass"; //converterString = (JB_OFF ? "//" : "")+"\t@Convert (PsiClassReferenceConverter.class)"; } - else if (field.simpleTypesString.indexOf(":ejb-linkType;") != -1) { + else if (field.simpleTypesString.contains(":ejb-linkType;")) { } - else if (field.simpleTypesString.indexOf(":ejb-ref-nameType;") != -1) { // jndi-nameType + else if (field.simpleTypesString.contains(":ejb-ref-nameType;")) { // jndi-nameType } - else if (field.simpleTypesString.indexOf(":pathType;") != -1) { + else if (field.simpleTypesString.contains(":pathType;")) { } - else if (field.simpleTypesString.indexOf(":java-identifierType;") != -1) { + else if (field.simpleTypesString.contains(":java-identifierType;")) { //out.println((JB_OFF ? "//" : "") +"\t@Convert (JavaIdentifierConverter.class)"); } - else if (field.simpleTypesString.indexOf(":QName;") != -1) { + else if (field.simpleTypesString.contains(":QName;")) { // ??? } - else if (field.simpleTypesString.indexOf(":integer;") != -1) { // BigDecimal + else if (field.simpleTypesString.contains(":integer;")) { // BigDecimal newType = REPLACE_TYPES_WITH_INTERFACES ? "Integer" : "int"; } - else if (field.simpleTypesString.indexOf(":int;") != -1) { + else if (field.simpleTypesString.contains(":int;")) { newType = REPLACE_TYPES_WITH_INTERFACES ? "Integer" : "int"; } - else if (field.simpleTypesString.indexOf(":byte;") != -1) { + else if (field.simpleTypesString.contains(":byte;")) { newType = REPLACE_TYPES_WITH_INTERFACES ? "Byte" : "byte"; } - else if (field.simpleTypesString.indexOf(":short;") != -1) { + else if (field.simpleTypesString.contains(":short;")) { newType = REPLACE_TYPES_WITH_INTERFACES ? "Short" : "short"; } - else if (field.simpleTypesString.indexOf(":long;") != -1) { + else if (field.simpleTypesString.contains(":long;")) { newType = REPLACE_TYPES_WITH_INTERFACES ? "Long" : "long"; } - else if (field.simpleTypesString.indexOf(":float;") != -1) { + else if (field.simpleTypesString.contains(":float;")) { newType = REPLACE_TYPES_WITH_INTERFACES ? "Float" : "float"; } - else if (field.simpleTypesString.indexOf(":double;") != -1) { + else if (field.simpleTypesString.contains(":double;")) { newType = REPLACE_TYPES_WITH_INTERFACES ? "Double" : "double"; } - else if (field.simpleTypesString.indexOf(":boolean;") != -1) { // true-falseType + else if (field.simpleTypesString.contains(":boolean;")) { // true-falseType newType = REPLACE_TYPES_WITH_INTERFACES ? "Boolean" : "boolean"; } for (int idx = 0; idx != -1; ) { @@ -470,7 +471,7 @@ else if (!name.equals(field.name)) { try { out.close(); } - catch (Exception ex) { + catch (Exception ignore) { } fileManager.releaseOutputFile(outFile); } @@ -531,7 +532,7 @@ private void generateSuper(FileManager fileManager, NamespaceDesc nsd, ModelDesc out.close(); } } - catch (Exception ex) { + catch (Exception ignore) { } fileManager.releaseOutputFile(outFile); } @@ -662,7 +663,7 @@ else if ((fd.clType == -FieldDesc.OBJ || fd.clType == -FieldDesc.STR) try { out.close(); } - catch (Exception ex) { + catch (Exception ignore) { } fileManager.releaseOutputFile(outFile); } @@ -680,7 +681,7 @@ public static void printDocumentation(PrintWriter out, String str, String prefix } public static String toPresentationName(String typeName) { - StringBuffer sb = new StringBuffer(typeName.length() + 10); + StringBuilder sb = new StringBuilder(typeName.length() + 10); boolean prevUp = true; for (int i = 0; i < typeName.length(); i++) { char c = typeName.charAt(i); diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/DescriptionCheckerUtil.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/DescriptionCheckerUtil.java index c2ae90cf..32a0ddec 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/DescriptionCheckerUtil.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/DescriptionCheckerUtil.java @@ -32,43 +32,44 @@ import java.util.List; public class DescriptionCheckerUtil { - @Nonnull - @RequiredReadAction - public static PsiDirectory[] getDescriptionsDirs(Module module, DescriptionType descriptionType) { - List dirs = new ArrayList<>(); - ModuleRootManager manager = ModuleRootManager.getInstance(module); - PsiManager psiManager = PsiManager.getInstance(module.getProject()); + @Nonnull + @RequiredReadAction + public static PsiDirectory[] getDescriptionsDirs(Module module, DescriptionType descriptionType) { + List dirs = new ArrayList<>(); + ModuleRootManager manager = ModuleRootManager.getInstance(module); + PsiManager psiManager = PsiManager.getInstance(module.getProject()); - for (ContentFolder folder : manager.getContentFolders(LanguageContentFolderScopes.production())) { - VirtualFile file = folder.getFile(); - if (file == null) { - continue; - } + for (ContentFolder folder : manager.getContentFolders(LanguageContentFolderScopes.production())) { + VirtualFile file = folder.getFile(); + if (file == null) { + continue; + } - VirtualFile childDir = file.findFileByRelativePath(descriptionType.getDescriptionFolder()); - if (childDir != null) { - PsiDirectory dir = psiManager.findDirectory(childDir); - if (dir != null) { - dirs.add(dir); + VirtualFile childDir = file.findFileByRelativePath(descriptionType.getDescriptionFolder()); + if (childDir != null) { + PsiDirectory dir = psiManager.findDirectory(childDir); + if (dir != null) { + dirs.add(dir); + } + } } - } - } - return dirs.toArray(PsiDirectory.EMPTY_ARRAY); - } + return dirs.toArray(PsiDirectory.EMPTY_ARRAY); + } - @Nullable - public static String getDescriptionDirName(PsiClass aClass) { - String descriptionDir = ""; - PsiClass each = aClass; - while (each != null) { - String name = each.getName(); - if (StringUtil.isEmptyOrSpaces(name)) { - return null; - } - descriptionDir = name + descriptionDir; - each = each.getContainingClass(); + @Nullable + @RequiredReadAction + public static String getDescriptionDirName(PsiClass aClass) { + String descriptionDir = ""; + PsiClass each = aClass; + while (each != null) { + String name = each.getName(); + if (StringUtil.isEmptyOrSpaces(name)) { + return null; + } + descriptionDir = name + descriptionDir; + each = each.getContainingClass(); + } + return descriptionDir; } - return descriptionDir; - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/DescriptionType.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/DescriptionType.java index d10d51f6..ed5dddee 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/DescriptionType.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/DescriptionType.java @@ -26,57 +26,69 @@ import java.util.Set; public enum DescriptionType { - INTENTION(Set.of("com.intellij.codeInsight.intention.IntentionAction", "consulo.language.editor.intention.IntentionAction"), - "intentionDescriptions", - true), - INSPECTION(Set.of("com.intellij.codeInspection.InspectionProfileEntry", - "consulo.language.editor.inspection.scheme.InspectionProfileEntry"), - "inspectionDescriptions", false), - POSTFIX_TEMPLATES(Set.of("com.intellij.codeInsight.template.postfix.templates.PostfixTemplate", - "consulo.language.editor.postfixTemplate.PostfixTemplate"), - "postfixTemplates", true); + INTENTION( + Set.of("com.intellij.codeInsight.intention.IntentionAction", "consulo.language.editor.intention.IntentionAction"), + "intentionDescriptions", + true + ), + INSPECTION( + Set.of( + "com.intellij.codeInspection.InspectionProfileEntry", + "consulo.language.editor.inspection.scheme.InspectionProfileEntry" + ), + "inspectionDescriptions", + false + ), + POSTFIX_TEMPLATES( + Set.of( + "com.intellij.codeInsight.template.postfix.templates.PostfixTemplate", + "consulo.language.editor.postfixTemplate.PostfixTemplate" + ), + "postfixTemplates", + true + ); - private final Set myClassNames; - private final String myDescriptionFolder; - private final boolean myFixedDescriptionFilename; + private final Set myClassNames; + private final String myDescriptionFolder; + private final boolean myFixedDescriptionFilename; - DescriptionType(Set classes, String descriptionFolder, boolean fixedDescriptionFilename) { - myClassNames = classes; - myDescriptionFolder = descriptionFolder; - myFixedDescriptionFilename = fixedDescriptionFilename; - } + DescriptionType(Set classes, String descriptionFolder, boolean fixedDescriptionFilename) { + myClassNames = classes; + myDescriptionFolder = descriptionFolder; + myFixedDescriptionFilename = fixedDescriptionFilename; + } - @Nonnull - public Set getClassNames() { - return myClassNames; - } + @Nonnull + public Set getClassNames() { + return myClassNames; + } - public String getDescriptionFolder() { - return myDescriptionFolder; - } + public String getDescriptionFolder() { + return myDescriptionFolder; + } - public boolean isFixedDescriptionFilename() { - return myFixedDescriptionFilename; - } + public boolean isFixedDescriptionFilename() { + return myFixedDescriptionFilename; + } - @Nullable - public PsiClass findClass(@Nonnull Project project, @Nonnull GlobalSearchScope scope) { - JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); - for (String className : myClassNames) { - PsiClass aClass = psiFacade.findClass(className, scope); - if (aClass != null) { - return aClass; - } + @Nullable + public PsiClass findClass(@Nonnull Project project, @Nonnull GlobalSearchScope scope) { + JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); + for (String className : myClassNames) { + PsiClass aClass = psiFacade.findClass(className, scope); + if (aClass != null) { + return aClass; + } + } + return null; } - return null; - } - public boolean isInheritor(PsiClass psiClass) { - for (String className : myClassNames) { - if (InheritanceUtil.isInheritor(psiClass, className)) { - return true; - } + public boolean isInheritor(PsiClass psiClass) { + for (String className : myClassNames) { + if (InheritanceUtil.isInheritor(psiClass, className)) { + return true; + } + } + return false; } - return false; - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/DevKitEntryPoints.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/DevKitEntryPoints.java index 5aea4cfa..513dc67d 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/DevKitEntryPoints.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/DevKitEntryPoints.java @@ -29,29 +29,28 @@ */ @ExtensionImpl public class DevKitEntryPoints implements ImplicitUsageProvider { - private static final String domClassName = DomElement.class.getName(); + private static final String domClassName = DomElement.class.getName(); - @Override - public boolean isImplicitUsage(PsiElement element) { - if (element instanceof PsiClass psiClass) { - if (InheritanceUtil.isInheritor(psiClass, domClassName)) { - return true; - } - } - - if (element instanceof PsiField || element instanceof PsiMethod || element instanceof PsiClass) { - return AnnotationUtil.isAnnotated((PsiModifierListOwner)element, UsedInPlugin.class.getName(), 0); + @Override + public boolean isImplicitUsage(PsiElement element) { + if (element instanceof PsiClass psiClass && InheritanceUtil.isInheritor(psiClass, domClassName)) { + return true; + } + + //noinspection SimplifiableIfStatement + if (element instanceof PsiField || element instanceof PsiMethod || element instanceof PsiClass) { + return AnnotationUtil.isAnnotated((PsiModifierListOwner)element, UsedInPlugin.class.getName(), 0); + } + return false; } - return false; - } - @Override - public boolean isImplicitRead(PsiElement element) { - return false; - } + @Override + public boolean isImplicitRead(PsiElement element) { + return false; + } - @Override - public boolean isImplicitWrite(PsiElement element) { - return false; - } + @Override + public boolean isImplicitWrite(PsiElement element) { + return false; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/InspectionDescriptionInfo.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/InspectionDescriptionInfo.java index b401d9e0..2f298df1 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/InspectionDescriptionInfo.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/InspectionDescriptionInfo.java @@ -17,6 +17,7 @@ import com.intellij.java.language.psi.PsiClass; import com.intellij.java.language.psi.PsiMethod; +import consulo.annotation.access.RequiredReadAction; import consulo.language.editor.inspection.InspectionTool; import consulo.language.psi.PsiDirectory; import consulo.language.psi.PsiFile; @@ -29,71 +30,74 @@ public class InspectionDescriptionInfo { - private final String myFilename; - private final PsiMethod myMethod; - private final PsiFile myDescriptionFile; + private final String myFilename; + private final PsiMethod myMethod; + private final PsiFile myDescriptionFile; - private InspectionDescriptionInfo(String filename, @Nullable PsiMethod method, @Nullable PsiFile descriptionFile) { - myFilename = filename; - myMethod = method; - myDescriptionFile = descriptionFile; - } - - public static InspectionDescriptionInfo create(Module module, PsiClass psiClass) { - PsiMethod method = PsiUtil.findNearestMethod("getShortName", psiClass); - if (method != null && DescriptionType.INSPECTION.getClassNames().contains(method.getContainingClass().getQualifiedName())) { - method = null; + private InspectionDescriptionInfo(String filename, @Nullable PsiMethod method, @Nullable PsiFile descriptionFile) { + myFilename = filename; + myMethod = method; + myDescriptionFile = descriptionFile; } - final String filename = - method == null ? InspectionTool.getShortName(psiClass.getName()) : PsiUtil.getReturnedLiteral(method, psiClass); + @RequiredReadAction + public static InspectionDescriptionInfo create(Module module, PsiClass psiClass) { + PsiMethod method = PsiUtil.findNearestMethod("getShortName", psiClass); + if (method != null && DescriptionType.INSPECTION.getClassNames().contains(method.getContainingClass().getQualifiedName())) { + method = null; + } - PsiFile descriptionFile = resolveInspectionDescriptionFile(module, filename); - return new InspectionDescriptionInfo(filename, method, descriptionFile); - } + final String filename = method == null + ? InspectionTool.getShortName(psiClass.getName()) + : PsiUtil.getReturnedLiteral(method, psiClass); - @Nullable - private static PsiFile resolveInspectionDescriptionFile(Module module, @Nullable String filename) { - if (filename == null) { - return null; + PsiFile descriptionFile = resolveInspectionDescriptionFile(module, filename); + return new InspectionDescriptionInfo(filename, method, descriptionFile); } - for (PsiDirectory description : DescriptionCheckerUtil.getDescriptionsDirs(module, DescriptionType.INSPECTION)) { - final PsiFile file = description.findFile(filename + ".html"); - if (file == null) { - continue; - } - final VirtualFile vf = file.getVirtualFile(); - if (vf == null) { - continue; - } - if (vf.getNameWithoutExtension().equals(filename)) { - return PsiManager.getInstance(module.getProject()).findFile(vf); - } + @Nullable + @RequiredReadAction + private static PsiFile resolveInspectionDescriptionFile(Module module, @Nullable String filename) { + if (filename == null) { + return null; + } + + for (PsiDirectory description : DescriptionCheckerUtil.getDescriptionsDirs(module, DescriptionType.INSPECTION)) { + final PsiFile file = description.findFile(filename + ".html"); + if (file == null) { + continue; + } + final VirtualFile vf = file.getVirtualFile(); + if (vf == null) { + continue; + } + if (vf.getNameWithoutExtension().equals(filename)) { + return PsiManager.getInstance(module.getProject()).findFile(vf); + } + } + return null; } - return null; - } - public boolean isValid() { - return myFilename != null; - } + public boolean isValid() { + return myFilename != null; + } - public String getFilename() { - assert isValid(); - return myFilename; - } + public String getFilename() { + assert isValid(); + return myFilename; + } - @Nullable - public PsiMethod getShortNameMethod() { - return myMethod; - } + @Nullable + public PsiMethod getShortNameMethod() { + return myMethod; + } - @Nullable - public PsiFile getDescriptionFile() { - return myDescriptionFile; - } + @Nullable + public PsiFile getDescriptionFile() { + return myDescriptionFile; + } - public boolean hasDescriptionFile() { - return getDescriptionFile() != null; - } + public boolean hasDescriptionFile() { + return getDescriptionFile() != null; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/InspectionDescriptionNotFoundInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/InspectionDescriptionNotFoundInspection.java index 545aa8bb..5a36bc8e 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/InspectionDescriptionNotFoundInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/InspectionDescriptionNotFoundInspection.java @@ -28,7 +28,6 @@ import consulo.language.psi.PsiElementVisitor; import consulo.language.psi.PsiFile; import consulo.language.psi.scope.GlobalSearchScope; -import consulo.language.util.ModuleUtilCore; import consulo.module.Module; import consulo.module.content.ModuleRootManager; import consulo.project.Project; @@ -49,169 +48,147 @@ * @author Konstantin Bulenkov */ @ExtensionImpl -public class InspectionDescriptionNotFoundInspection extends InternalInspection -{ - @Override - public PsiElementVisitor buildInternalVisitor(@Nonnull ProblemsHolder holder, boolean isOnTheFly) - { - return new JavaElementVisitor() - { - @Override - public void visitClass(PsiClass aClass) - { - checkClass(aClass, holder); - } - }; - } - - @RequiredReadAction - private void checkClass(PsiClass psiClass, ProblemsHolder holder) - { - final Project project = psiClass.getProject(); - final PsiIdentifier nameIdentifier = psiClass.getNameIdentifier(); - final Module module = ModuleUtilCore.findModuleForPsiElement(psiClass); - - if(nameIdentifier == null || module == null || !PsiUtil.isInstantiable(psiClass)) - { - return; - } - - final PsiClass base = DescriptionType.INSPECTION.findClass(project, GlobalSearchScope.allScope(project)); - - if(base == null || !psiClass.isInheritor(base, true) || isPathMethodsAreOverridden(psiClass)) - { - return; - } - - PsiMethod method = findNearestMethod("getShortName", psiClass); - if(method != null && DescriptionType.INSPECTION.getClassNames().contains(method.getContainingClass().getQualifiedName())) - { - method = null; - } - final String filename = - method == null ? InspectionTool.getShortName(psiClass.getName()) : PsiUtil.getReturnedLiteral(method, psiClass); - if(filename == null) - { - return; - } - - for(PsiDirectory description : getInspectionDescriptionsDirs(module)) - { - final PsiFile file = description.findFile(filename + ".html"); - if(file == null) - { - continue; - } - final VirtualFile vf = file.getVirtualFile(); - if(vf == null) - { - continue; - } - if(vf.getNameWithoutExtension().equals(filename)) - { - return; - } - } - - final PsiElement problem = getProblemElement(psiClass, method); - holder.registerProblem(problem == null ? nameIdentifier : problem, "Inspection does not have a description", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - new CreateHtmlDescriptionFix(filename, module, false)); - } - - @Nullable - private static PsiElement getProblemElement(PsiClass aClass, @Nullable PsiMethod method) - { - if(method != null && method.getContainingClass() == aClass) - { - return PsiUtil.getReturnedExpression(method); - } - else - { - return aClass.getNameIdentifier(); - } - } - - private static boolean isPathMethodsAreOverridden(PsiClass aClass) - { - return !(isLastMethodDefinitionIn("getStaticDescription", DescriptionType.INSPECTION.getClassNames(), aClass) && - isLastMethodDefinitionIn("getDescriptionUrl", DescriptionType.INSPECTION.getClassNames(), aClass) && - isLastMethodDefinitionIn("getDescriptionContextClass", DescriptionType.INSPECTION.getClassNames(), aClass) && - isLastMethodDefinitionIn("getDescriptionFileName", DescriptionType.INSPECTION.getClassNames(), aClass)); - } - - private static boolean isLastMethodDefinitionIn(@Nonnull String methodName, @Nonnull Set classFQN, PsiClass cls) - { - if(cls == null) - { - return false; - } - for(PsiMethod method : cls.getMethods()) - { - if(method.getName().equals(methodName)) - { - final PsiClass containingClass = method.getContainingClass(); - return containingClass != null && classFQN.contains(containingClass.getQualifiedName()); - } - } - return isLastMethodDefinitionIn(methodName, classFQN, cls.getSuperClass()); - } - - public static List getPotentialRoots(Module module) - { - final PsiDirectory[] dirs = getInspectionDescriptionsDirs(module); - final List result = new ArrayList<>(); - if(dirs.length != 0) - { - for(PsiDirectory dir : dirs) - { - final PsiDirectory parent = dir.getParentDirectory(); - if(parent != null) - { - result.add(parent.getVirtualFile()); - } - } - } - else - { - ContainerUtil.addAll(result, ModuleRootManager.getInstance(module).getContentFolderFiles(LanguageContentFolderScopes.productionAndTest())); - } - return result; - } - - @RequiredReadAction - public static PsiDirectory[] getInspectionDescriptionsDirs(Module module) - { - return DescriptionCheckerUtil.getDescriptionsDirs(module, DescriptionType.INSPECTION); - } - - @Nullable - private static PsiMethod findNearestMethod(String name, @Nullable PsiClass cls) - { - if(cls == null) - { - return null; - } - for(PsiMethod method : cls.getMethods()) - { - if(method.getParameterList().getParametersCount() == 0 && method.getName().equals(name)) - { - return method.getModifierList().hasModifierProperty(PsiModifier.ABSTRACT) ? null : method; - } - } - return findNearestMethod(name, cls.getSuperClass()); - } - - @Nls - @Nonnull - public String getDisplayName() - { - return "Inspection Description Checker"; - } - - @Nonnull - public String getShortName() - { - return "InspectionDescriptionNotFoundInspection"; - } +public class InspectionDescriptionNotFoundInspection extends InternalInspection { + @Override + public PsiElementVisitor buildInternalVisitor(@Nonnull ProblemsHolder holder, boolean isOnTheFly) { + return new JavaElementVisitor() { + @Override + @RequiredReadAction + public void visitClass(@Nonnull PsiClass aClass) { + checkClass(aClass, holder); + } + }; + } + + @RequiredReadAction + private void checkClass(PsiClass psiClass, ProblemsHolder holder) { + final Project project = psiClass.getProject(); + final PsiIdentifier nameIdentifier = psiClass.getNameIdentifier(); + final Module module = psiClass.getModule(); + + if (nameIdentifier == null || module == null || !PsiUtil.isInstantiable(psiClass)) { + return; + } + + final PsiClass base = DescriptionType.INSPECTION.findClass(project, GlobalSearchScope.allScope(project)); + + if (base == null || !psiClass.isInheritor(base, true) || isPathMethodsAreOverridden(psiClass)) { + return; + } + + PsiMethod method = findNearestMethod("getShortName", psiClass); + if (method != null && DescriptionType.INSPECTION.getClassNames().contains(method.getContainingClass().getQualifiedName())) { + method = null; + } + final String filename = method == null + ? InspectionTool.getShortName(psiClass.getName()) + : PsiUtil.getReturnedLiteral(method, psiClass); + if (filename == null) { + return; + } + + for (PsiDirectory description : getInspectionDescriptionsDirs(module)) { + final PsiFile file = description.findFile(filename + ".html"); + if (file == null) { + continue; + } + final VirtualFile vf = file.getVirtualFile(); + if (vf == null) { + continue; + } + if (vf.getNameWithoutExtension().equals(filename)) { + return; + } + } + + final PsiElement problem = getProblemElement(psiClass, method); + holder.registerProblem( + problem == null ? nameIdentifier : problem, + "Inspection does not have a description", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + new CreateHtmlDescriptionFix(filename, module, false) + ); + } + + @Nullable + private static PsiElement getProblemElement(PsiClass aClass, @Nullable PsiMethod method) { + if (method != null && method.getContainingClass() == aClass) { + return PsiUtil.getReturnedExpression(method); + } + else { + return aClass.getNameIdentifier(); + } + } + + private static boolean isPathMethodsAreOverridden(PsiClass aClass) { + return !(isLastMethodDefinitionIn("getStaticDescription", DescriptionType.INSPECTION.getClassNames(), aClass) + && isLastMethodDefinitionIn("getDescriptionUrl", DescriptionType.INSPECTION.getClassNames(), aClass) + && isLastMethodDefinitionIn("getDescriptionContextClass", DescriptionType.INSPECTION.getClassNames(), aClass) + && isLastMethodDefinitionIn("getDescriptionFileName", DescriptionType.INSPECTION.getClassNames(), aClass)); + } + + private static boolean isLastMethodDefinitionIn(@Nonnull String methodName, @Nonnull Set classFQN, PsiClass cls) { + if (cls == null) { + return false; + } + for (PsiMethod method : cls.getMethods()) { + if (method.getName().equals(methodName)) { + final PsiClass containingClass = method.getContainingClass(); + return containingClass != null && classFQN.contains(containingClass.getQualifiedName()); + } + } + return isLastMethodDefinitionIn(methodName, classFQN, cls.getSuperClass()); + } + + @RequiredReadAction + public static List getPotentialRoots(Module module) { + final PsiDirectory[] dirs = getInspectionDescriptionsDirs(module); + final List result = new ArrayList<>(); + if (dirs.length != 0) { + for (PsiDirectory dir : dirs) { + final PsiDirectory parent = dir.getParentDirectory(); + if (parent != null) { + result.add(parent.getVirtualFile()); + } + } + } + else { + ContainerUtil.addAll( + result, + ModuleRootManager.getInstance(module).getContentFolderFiles(LanguageContentFolderScopes.productionAndTest()) + ); + } + return result; + } + + @RequiredReadAction + public static PsiDirectory[] getInspectionDescriptionsDirs(Module module) { + return DescriptionCheckerUtil.getDescriptionsDirs(module, DescriptionType.INSPECTION); + } + + @Nullable + private static PsiMethod findNearestMethod(String name, @Nullable PsiClass cls) { + if (cls == null) { + return null; + } + for (PsiMethod method : cls.getMethods()) { + if (method.getParameterList().getParametersCount() == 0 && method.getName().equals(name)) { + return method.getModifierList().hasModifierProperty(PsiModifier.ABSTRACT) ? null : method; + } + } + return findNearestMethod(name, cls.getSuperClass()); + } + + @Nls + @Nonnull + @Override + public String getDisplayName() { + return "Inspection Description Checker"; + } + + @Nonnull + @Override + public String getShortName() { + return "InspectionDescriptionNotFoundInspection"; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/IntentionDescriptionNotFoundInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/IntentionDescriptionNotFoundInspection.java index 20561476..885b4351 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/IntentionDescriptionNotFoundInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/IntentionDescriptionNotFoundInspection.java @@ -19,14 +19,15 @@ import com.intellij.java.language.psi.JavaPsiFacade; import com.intellij.java.language.psi.PsiClass; import com.intellij.java.language.psi.PsiIdentifier; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.content.LanguageContentFolderScopes; import consulo.language.editor.inspection.ProblemHighlightType; import consulo.language.editor.inspection.ProblemsHolder; import consulo.language.editor.intention.IntentionAction; +import consulo.language.editor.intention.SyntheticIntentionAction; import consulo.language.psi.*; import consulo.language.psi.scope.GlobalSearchScope; -import consulo.language.util.ModuleUtilCore; import consulo.module.Module; import consulo.module.content.ModuleRootManager; import consulo.project.Project; @@ -47,164 +48,152 @@ * @author Konstantin Bulenkov */ @ExtensionImpl -public class IntentionDescriptionNotFoundInspection extends InternalInspection -{ - private static final String INTENTION = IntentionAction.class.getName(); - private static final String INSPECTION_DESCRIPTIONS = "intentionDescriptions"; - - @Override - public PsiElementVisitor buildInternalVisitor(@Nonnull ProblemsHolder holder, boolean isOnTheFly) - { - return new JavaElementVisitor() - { - @Override - public void visitClass(PsiClass aClass) - { - checkClass(aClass, holder, isOnTheFly); - } - }; - } - - private void checkClass(PsiClass psiClass, ProblemsHolder holder, boolean isOnTheFly) - { - final Project project = psiClass.getProject(); - final PsiIdentifier nameIdentifier = psiClass.getNameIdentifier(); - final Module module = ModuleUtilCore.findModuleForPsiElement(psiClass); - - if(nameIdentifier == null || module == null || !PsiUtil.isInstantiable(psiClass)) - { - return; - } - - final PsiClass base = JavaPsiFacade.getInstance(project).findClass(INTENTION, GlobalSearchScope.allScope(project)); - - if(base == null || !psiClass.isInheritor(base, true)) - { - return; - } - - String descriptionDir = getDescriptionDirName(psiClass); - if(StringUtil.isEmptyOrSpaces(descriptionDir)) - { - return; - } - - for(PsiDirectory description : getIntentionDescriptionsDirs(module)) - { - PsiDirectory dir = description.findSubdirectory(descriptionDir); - if(dir == null) - { - continue; - } - final PsiFile descr = dir.findFile("description.html"); - if(descr != null) - { - if(!hasBeforeAndAfterTemplate(dir.getVirtualFile())) - { - PsiElement problem = psiClass.getNameIdentifier(); - holder.registerProblem(problem == null ? nameIdentifier : problem, - "Intention must have 'before.*.template' and 'after.*.template' beside 'description.html'", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING); - } - - return; - } - } - - - final PsiElement problem = psiClass.getNameIdentifier(); - holder.registerProblem(problem == null ? nameIdentifier : problem, "Intention does not have a description", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new CreateHtmlDescriptionFix(descriptionDir, module, true)); - } - - @Nullable - private static String getDescriptionDirName(PsiClass aClass) - { - String descriptionDir = ""; - PsiClass each = aClass; - while(each != null) - { - String name = each.getName(); - if(StringUtil.isEmptyOrSpaces(name)) - { - return null; - } - descriptionDir = name + descriptionDir; - each = each.getContainingClass(); - } - return descriptionDir; - } - - private static boolean hasBeforeAndAfterTemplate(@Nonnull VirtualFile dir) - { - boolean hasBefore = false; - boolean hasAfter = false; - - for(VirtualFile file : dir.getChildren()) - { - String name = file.getName(); - if(name.endsWith(".template")) - { - if(name.startsWith("before.")) - { - hasBefore = true; - } - else if(name.startsWith("after.")) - { - hasAfter = true; - } - } - } - - return hasBefore && hasAfter; - } - - public static List getPotentialRoots(Module module) - { - final PsiDirectory[] dirs = getIntentionDescriptionsDirs(module); - final List result = new ArrayList(); - if(dirs.length != 0) - { - for(PsiDirectory dir : dirs) - { - final PsiDirectory parent = dir.getParentDirectory(); - if(parent != null) - { - result.add(parent.getVirtualFile()); - } - } - } - else - { - ContainerUtil.addAll(result, - ModuleRootManager.getInstance(module).getContentFolderFiles(LanguageContentFolderScopes.productionAndTest())); - } - return result; - } - - public static PsiDirectory[] getIntentionDescriptionsDirs(Module module) - { - final PsiPackage aPackage = JavaPsiFacade.getInstance(module.getProject()).findPackage(INSPECTION_DESCRIPTIONS); - if(aPackage != null) - { - return aPackage.getDirectories(GlobalSearchScope.moduleWithDependenciesScope(module)); - } - else - { - return PsiDirectory.EMPTY_ARRAY; - } - } - - @Nls - @Nonnull - public String getDisplayName() - { - return "Intention Description Checker"; - } - - @Nonnull - public String getShortName() - { - return "IntentionDescriptionNotFoundInspection"; - } +public class IntentionDescriptionNotFoundInspection extends InternalInspection { + private static final String INTENTION = IntentionAction.class.getName(); + private static final String SYNTHETIC_INTENTION = SyntheticIntentionAction.class.getName(); + private static final String INSPECTION_DESCRIPTIONS = "intentionDescriptions"; + + @Override + public PsiElementVisitor buildInternalVisitor(@Nonnull ProblemsHolder holder, boolean isOnTheFly) { + return new JavaElementVisitor() { + @Override + @RequiredReadAction + public void visitClass(@Nonnull PsiClass aClass) { + checkClass(aClass, holder, isOnTheFly); + } + }; + } + + @RequiredReadAction + private void checkClass(PsiClass psiClass, ProblemsHolder holder, boolean isOnTheFly) { + final Project project = psiClass.getProject(); + final PsiIdentifier nameIdentifier = psiClass.getNameIdentifier(); + final Module module = psiClass.getModule(); + + if (nameIdentifier == null || module == null || !PsiUtil.isInstantiable(psiClass)) { + return; + } + + final PsiClass base = JavaPsiFacade.getInstance(project).findClass(INTENTION, GlobalSearchScope.allScope(project)); + + if (base == null || !psiClass.isInheritor(base, true)) { + return; + } + + final PsiClass ignoredBase = JavaPsiFacade.getInstance(project).findClass(SYNTHETIC_INTENTION, GlobalSearchScope.allScope(project)); + if (ignoredBase != null && psiClass.isInheritor(ignoredBase, true)) { + return; + } + + String descriptionDir = getDescriptionDirName(psiClass); + if (StringUtil.isEmptyOrSpaces(descriptionDir)) { + return; + } + + for (PsiDirectory description : getIntentionDescriptionsDirs(module)) { + PsiDirectory dir = description.findSubdirectory(descriptionDir); + if (dir == null) { + continue; + } + final PsiFile descr = dir.findFile("description.html"); + if (descr != null) { + if (!hasBeforeAndAfterTemplate(dir.getVirtualFile())) { + PsiElement problem = psiClass.getNameIdentifier(); + holder.registerProblem( + problem == null ? nameIdentifier : problem, + "Intention must have 'before.*.template' and 'after.*.template' beside 'description.html'", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING + ); + } + + return; + } + } + + final PsiElement problem = psiClass.getNameIdentifier(); + holder.registerProblem( + problem == null ? nameIdentifier : problem, + "Intention does not have a description", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + new CreateHtmlDescriptionFix(descriptionDir, module, true) + ); + } + + @Nullable + @RequiredReadAction + private static String getDescriptionDirName(PsiClass aClass) { + String descriptionDir = ""; + PsiClass each = aClass; + while (each != null) { + String name = each.getName(); + if (StringUtil.isEmptyOrSpaces(name)) { + return null; + } + descriptionDir = name + descriptionDir; + each = each.getContainingClass(); + } + return descriptionDir; + } + + private static boolean hasBeforeAndAfterTemplate(@Nonnull VirtualFile dir) { + boolean hasBefore = false; + boolean hasAfter = false; + + for (VirtualFile file : dir.getChildren()) { + String name = file.getName(); + if (name.endsWith(".template")) { + if (name.startsWith("before.")) { + hasBefore = true; + } + else if (name.startsWith("after.")) { + hasAfter = true; + } + } + } + + return hasBefore && hasAfter; + } + + public static List getPotentialRoots(Module module) { + final PsiDirectory[] dirs = getIntentionDescriptionsDirs(module); + final List result = new ArrayList<>(); + if (dirs.length != 0) { + for (PsiDirectory dir : dirs) { + final PsiDirectory parent = dir.getParentDirectory(); + if (parent != null) { + result.add(parent.getVirtualFile()); + } + } + } + else { + ContainerUtil.addAll( + result, + ModuleRootManager.getInstance(module).getContentFolderFiles(LanguageContentFolderScopes.productionAndTest()) + ); + } + return result; + } + + public static PsiDirectory[] getIntentionDescriptionsDirs(Module module) { + final PsiPackage aPackage = JavaPsiFacade.getInstance(module.getProject()).findPackage(INSPECTION_DESCRIPTIONS); + if (aPackage != null) { + return aPackage.getDirectories(GlobalSearchScope.moduleWithDependenciesScope(module)); + } + else { + return PsiDirectory.EMPTY_ARRAY; + } + } + + @Nls + @Nonnull + @Override + public String getDisplayName() { + return "Intention Description Checker"; + } + + @Nonnull + @Override + public String getShortName() { + return "IntentionDescriptionNotFoundInspection"; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/PluginXmlDomInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/PluginXmlDomInspection.java index 5374b480..078275f0 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/PluginXmlDomInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/PluginXmlDomInspection.java @@ -29,25 +29,27 @@ */ @ExtensionImpl public class PluginXmlDomInspection extends BasicDomElementsInspection { - public PluginXmlDomInspection() { - super(IdeaPlugin.class); - } + public PluginXmlDomInspection() { + super(IdeaPlugin.class); + } - @Nls - @Nonnull - public String getGroupDisplayName() { - return DevKitLocalize.inspectionsGroupName().get(); - } + @Nls + @Nonnull + @Override + public String getGroupDisplayName() { + return DevKitLocalize.inspectionsGroupName().get(); + } - @Nls - @Nonnull - public String getDisplayName() { - return "Plugin.xml Validity"; - } + @Nls + @Nonnull + @Override + public String getDisplayName() { + return "Plugin.xml Validity"; + } - @NonNls - @Nonnull - public String getShortName() { - return "PluginXmlValidity"; - } + @Nonnull + @Override + public String getShortName() { + return "PluginXmlValidity"; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/StatefulEpInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/StatefulEpInspection.java index bd0959df..65c2c3ff 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/StatefulEpInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/StatefulEpInspection.java @@ -35,72 +35,55 @@ import javax.annotation.Nonnull; @ExtensionImpl -public class StatefulEpInspection extends InternalInspection -{ - @Nonnull - @Override - public String getDisplayName() - { - return "Stateful Extension"; - } +public class StatefulEpInspection extends InternalInspection { + @Nonnull + @Override + public String getDisplayName() { + return "Stateful Extension"; + } - @Override - public PsiElementVisitor buildInternalVisitor(@Nonnull ProblemsHolder holder, boolean isOnTheFly) - { - return new JavaElementVisitor() - { - @Override - public void visitField(PsiField field) - { - checkField(field, holder); - } - }; - } + @Override + public PsiElementVisitor buildInternalVisitor(@Nonnull ProblemsHolder holder, boolean isOnTheFly) { + return new JavaElementVisitor() { + @Override + public void visitField(@Nonnull PsiField field) { + checkField(field, holder); + } + }; + } - private void checkField(PsiField field, ProblemsHolder holder) - { - PsiClass psiClass = field.getContainingClass(); - if(psiClass == null) - { - return; - } + private void checkField(PsiField field, ProblemsHolder holder) { + PsiClass psiClass = field.getContainingClass(); + if (psiClass == null) { + return; + } - final boolean isQuickFix = InheritanceUtil.isInheritor(psiClass, LocalQuickFix.class.getCanonicalName()); - if(isQuickFix || AnnotationUtil.isAnnotated(psiClass, ValhallaClasses.Impl, 0)) - { - final boolean isProjectComponent = isProjectServiceOrComponent(psiClass); + final boolean isQuickFix = InheritanceUtil.isInheritor(psiClass, LocalQuickFix.class.getCanonicalName()); + if (isQuickFix || AnnotationUtil.isAnnotated(psiClass, ValhallaClasses.Impl, 0)) { + final boolean isProjectComponent = isProjectServiceOrComponent(psiClass); - for(Class c : new Class[]{ - PsiElement.class, - PsiReference.class, - Project.class - }) - { - if(c == Project.class && (field.hasModifierProperty(PsiModifier.FINAL) || isProjectComponent)) - { - continue; - } - String message; - if(c != PsiElement.class) - { - message = "Don't use " + c.getSimpleName() + " as a field in extension"; - } - else - { - message = "Potential memory leak: don't hold PsiElement, use SmartPsiElementPointer instead" + (isQuickFix ? "; also see LocalQuickFixOnPsiElement" : ""); - } + for (Class c : new Class[]{PsiElement.class, PsiReference.class, Project.class}) { + if (c == Project.class && (field.hasModifierProperty(PsiModifier.FINAL) || isProjectComponent)) { + continue; + } + String message; + if (c != PsiElement.class) { + message = "Don't use " + c.getSimpleName() + " as a field in extension"; + } + else { + message = "Potential memory leak: don't hold PsiElement, use SmartPsiElementPointer instead" + + (isQuickFix ? "; also see LocalQuickFixOnPsiElement" : ""); + } - if(InheritanceUtil.isInheritor(field.getType(), c.getCanonicalName())) - { - holder.registerProblem(field, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); - } - } - } - } + if (InheritanceUtil.isInheritor(field.getType(), c.getCanonicalName())) { + holder.registerProblem(field, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); + } + } + } + } - private static boolean isProjectServiceOrComponent(PsiClass psiClass) - { - // TODO check ServiceAPI - return true; - } + private static boolean isProjectServiceOrComponent(PsiClass psiClass) { + // TODO check ServiceAPI + return true; + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/TitleCapitalizationInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/TitleCapitalizationInspection.java index d8d28984..6ddf67c8 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/TitleCapitalizationInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/TitleCapitalizationInspection.java @@ -20,6 +20,8 @@ import com.intellij.java.language.psi.util.PropertyUtil; import com.intellij.lang.properties.psi.Property; import com.intellij.lang.properties.references.PropertyReference; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.annotation.component.ExtensionImpl; import consulo.fileChooser.FileChooserDescriptor; import consulo.language.editor.inspection.*; @@ -47,245 +49,250 @@ */ @ExtensionImpl public class TitleCapitalizationInspection extends BaseJavaLocalInspectionTool { - @Override - public boolean isEnabledByDefault() { - return true; - } + @Override + public boolean isEnabledByDefault() { + return true; + } - @Nls - @Nonnull - @Override - public String getGroupDisplayName() { - return "Plugin DevKit"; - } + @Nls + @Nonnull + @Override + public String getGroupDisplayName() { + return "Plugin DevKit"; + } - @Nls - @Nonnull - @Override - public String getDisplayName() { - return "Incorrect dialog title capitalization"; - } + @Nls + @Nonnull + @Override + public String getDisplayName() { + return "Incorrect dialog title capitalization"; + } - @Nonnull - @Override - public String getShortName() { - return "DialogTitleCapitalization"; - } + @Nonnull + @Override + public String getShortName() { + return "DialogTitleCapitalization"; + } - @Nonnull - @Override - public PsiElementVisitor buildVisitorImpl(@Nonnull ProblemsHolder holder, - boolean isOnTheFly, - LocalInspectionToolSession session, - Object o) { - return new JavaElementVisitor() { - @Override - public void visitMethodCallExpression(PsiMethodCallExpression expression) { - PsiReferenceExpression methodExpression = expression.getMethodExpression(); - String calledName = methodExpression.getReferenceName(); - if (calledName == null) return; - if ("setTitle".equals(calledName)) { - if (!isMethodOfClass(expression, DialogWrapper.class.getName(), FileChooserDescriptor.class.getName())) return; - PsiExpression[] args = expression.getArgumentList().getExpressions(); - if (args.length == 0) { - return; - } - String titleValue = getTitleValue(args[0]); - if (!hasTitleCapitalization(titleValue)) { - holder.registerProblem(args[0], - "Dialog title '" + titleValue + "' is not properly capitalized. It should have title capitalization", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new TitleCapitalizationFix(titleValue)); - } - } - else if (calledName.startsWith("show") && (calledName.endsWith("Dialog") || calledName.endsWith("Message"))) { - if (!isMethodOfClass(expression, Messages.class.getName())) return; - PsiExpression[] args = expression.getArgumentList().getExpressions(); - PsiMethod psiMethod = expression.resolveMethod(); - assert psiMethod != null; - PsiParameter[] parameters = psiMethod.getParameterList().getParameters(); - for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) { - PsiParameter parameter = parameters[i]; - if ("title".equals(parameter.getName()) && i < args.length) { - String titleValue = getTitleValue(args[i]); - if (!hasTitleCapitalization(titleValue)) { - holder.registerProblem(args[i], "Message title '" + - titleValue + - "' is not properly capitalized. It should have title capitalization", - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new TitleCapitalizationFix(titleValue)); - } - break; + @Nonnull + @Override + public PsiElementVisitor buildVisitorImpl( + @Nonnull ProblemsHolder holder, + boolean isOnTheFly, + LocalInspectionToolSession session, + Object o + ) { + return new JavaElementVisitor() { + @Override + @RequiredReadAction + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + PsiReferenceExpression methodExpression = expression.getMethodExpression(); + String calledName = methodExpression.getReferenceName(); + if (calledName == null) { + return; + } + if ("setTitle".equals(calledName)) { + if (!isMethodOfClass(expression, DialogWrapper.class.getName(), FileChooserDescriptor.class.getName())) { + return; + } + PsiExpression[] args = expression.getArgumentList().getExpressions(); + if (args.length == 0) { + return; + } + String titleValue = getTitleValue(args[0]); + if (!hasTitleCapitalization(titleValue)) { + holder.registerProblem( + args[0], + "Dialog title '" + titleValue + "' is not properly capitalized. " + + "It should have title capitalization", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new TitleCapitalizationFix(titleValue) + ); + } + } + else if (calledName.startsWith("show") + && (calledName.endsWith("Dialog") || calledName.endsWith("Message"))) { + if (!isMethodOfClass(expression, Messages.class.getName())) { + return; + } + PsiExpression[] args = expression.getArgumentList().getExpressions(); + PsiMethod psiMethod = expression.resolveMethod(); + assert psiMethod != null; + PsiParameter[] parameters = psiMethod.getParameterList().getParameters(); + for (int i = 0, parametersLength = parameters.length; i < parametersLength; i++) { + PsiParameter parameter = parameters[i]; + if ("title".equals(parameter.getName()) && i < args.length) { + String titleValue = getTitleValue(args[i]); + if (!hasTitleCapitalization(titleValue)) { + holder.registerProblem( + args[i], + "Message title '" + titleValue + "' is not properly capitalized. " + + "It should have title capitalization", + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + new TitleCapitalizationFix(titleValue) + ); + } + break; + } + } + } } - } - } - } - }; - } - - private static boolean isMethodOfClass(PsiMethodCallExpression expression, String... classNames) { - PsiMethod psiMethod = expression.resolveMethod(); - if (psiMethod == null) { - return false; + }; } - PsiClass containingClass = psiMethod.getContainingClass(); - if (containingClass == null) { - return false; - } - String name = containingClass.getQualifiedName(); - return ArrayUtil.contains(name, classNames); - } - @Nullable - private static String getTitleValue(PsiExpression arg) { - if (arg instanceof PsiLiteralExpression) { - Object value = ((PsiLiteralExpression)arg).getValue(); - if (value instanceof String) { - return (String)value; - } - } - if (arg instanceof PsiMethodCallExpression) { - PsiMethod psiMethod = ((PsiMethodCallExpression)arg).resolveMethod(); - PsiExpression returnValue = PropertyUtil.getGetterReturnExpression(psiMethod); - if (returnValue != null) { - return getTitleValue(returnValue); - } - Property propertyArgument = getPropertyArgument((PsiMethodCallExpression)arg); - if (propertyArgument != null) { - return propertyArgument.getUnescapedValue(); - } - } - if (arg instanceof PsiReferenceExpression) { - PsiElement result = ((PsiReferenceExpression)arg).resolve(); - if (result instanceof PsiVariable && ((PsiVariable)result).hasModifierProperty(PsiModifier.FINAL)) { - return getTitleValue(((PsiVariable)result).getInitializer()); - } + private static boolean isMethodOfClass(PsiMethodCallExpression expression, String... classNames) { + PsiMethod psiMethod = expression.resolveMethod(); + if (psiMethod == null) { + return false; + } + PsiClass containingClass = psiMethod.getContainingClass(); + if (containingClass == null) { + return false; + } + String name = containingClass.getQualifiedName(); + return ArrayUtil.contains(name, classNames); } - return null; - } - @Nullable - private static Property getPropertyArgument(PsiMethodCallExpression arg) { - PsiExpression[] args = arg.getArgumentList().getExpressions(); - if (args.length > 0) { - PsiReference[] references = args[0].getReferences(); - for (PsiReference reference : references) { - if (reference instanceof PropertyReference) { - ResolveResult[] resolveResults = ((PropertyReference)reference).multiResolve(false); - if (resolveResults.length == 1 && resolveResults[0].isValidResult()) { - PsiElement element = resolveResults[0].getElement(); - if (element instanceof Property) { - return (Property)element; + @Nullable + @RequiredReadAction + private static String getTitleValue(PsiExpression arg) { + if (arg instanceof PsiLiteralExpression argLiteralExpr) { + if (argLiteralExpr.getValue() instanceof String strValue) { + return strValue; } - } } - } + if (arg instanceof PsiMethodCallExpression argCallExpr) { + PsiMethod psiMethod = argCallExpr.resolveMethod(); + PsiExpression returnValue = PropertyUtil.getGetterReturnExpression(psiMethod); + if (returnValue != null) { + return getTitleValue(returnValue); + } + Property propertyArgument = getPropertyArgument(argCallExpr); + if (propertyArgument != null) { + return propertyArgument.getUnescapedValue(); + } + } + if (arg instanceof PsiReferenceExpression argRefExpr + && argRefExpr.resolve() instanceof PsiVariable resultVariable + && resultVariable.hasModifierProperty(PsiModifier.FINAL)) { + return getTitleValue(resultVariable.getInitializer()); + } + return null; } - return null; - } - private static boolean hasTitleCapitalization(String value) { - if (value == null) { - return true; + @Nullable + private static Property getPropertyArgument(PsiMethodCallExpression arg) { + PsiExpression[] args = arg.getArgumentList().getExpressions(); + if (args.length > 0) { + PsiReference[] references = args[0].getReferences(); + for (PsiReference reference : references) { + if (reference instanceof PropertyReference propertyReference) { + ResolveResult[] resolveResults = propertyReference.multiResolve(false); + if (resolveResults.length == 1 && resolveResults[0].isValidResult() + && resolveResults[0].getElement() instanceof Property property) { + return property; + } + } + } + } + return null; } - value = value.replace("&", ""); - return StringUtil.wordsToBeginFromUpperCase(value).equals(value); - } - - private static class TitleCapitalizationFix implements LocalQuickFix { - private final String myTitleValue; - - public TitleCapitalizationFix(String titleValue) { - myTitleValue = titleValue; + private static boolean hasTitleCapitalization(String value) { + if (value == null) { + return true; + } + value = value.replace("&", ""); + return StringUtil.wordsToBeginFromUpperCase(value).equals(value); } - @Nonnull - @Override - public String getName() { - return "Properly capitalize '" + myTitleValue + '\''; - } + private static class TitleCapitalizationFix implements LocalQuickFix { - public final void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - final PsiElement problemElement = descriptor.getPsiElement(); - if (problemElement == null || !problemElement.isValid()) { - return; - } - if (isQuickFixOnReadOnlyFile(problemElement)) { - return; - } - try { - doFix(project, problemElement); - } - catch (IncorrectOperationException e) { - final Class aClass = getClass(); - final String className = aClass.getName(); - final Logger logger = Logger.getInstance(className); - logger.error(e); - } - } + private final String myTitleValue; - protected void doFix(Project project, PsiElement element) throws IncorrectOperationException { - if (element instanceof PsiLiteralExpression) { - final PsiLiteralExpression literalExpression = (PsiLiteralExpression)element; - final Object value = literalExpression.getValue(); - if (!(value instanceof String)) { - return; + public TitleCapitalizationFix(String titleValue) { + myTitleValue = titleValue; } - final String string = (String)value; - final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); - final PsiExpression newExpression = - factory.createExpressionFromText('"' + StringUtil.wordsToBeginFromUpperCase(string) + '"', element); - literalExpression.replace(newExpression); - } - else if (element instanceof PsiMethodCallExpression) { - final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)element; - final PsiMethod method = methodCallExpression.resolveMethod(); - final PsiExpression returnValue = PropertyUtil.getGetterReturnExpression(method); - if (returnValue != null) { - doFix(project, returnValue); - } - final Property property = getPropertyArgument(methodCallExpression); - if (property == null) { - return; - } - final String value = property.getUnescapedValue(); - if (value == null) { - return; + + @Nonnull + @Override + public String getName() { + return "Properly capitalize '" + myTitleValue + '\''; } - final String capitalizedString = StringUtil.wordsToBeginFromUpperCase(value); - property.setValue(capitalizedString); - } - else if (element instanceof PsiReferenceExpression) { - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)element; - final PsiElement target = referenceExpression.resolve(); - if (!(target instanceof PsiVariable)) { - return; + + @Override + @RequiredWriteAction + public final void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + final PsiElement problemElement = descriptor.getPsiElement(); + if (problemElement == null || !problemElement.isValid()) { + return; + } + if (isQuickFixOnReadOnlyFile(problemElement)) { + return; + } + try { + doFix(project, problemElement); + } + catch (IncorrectOperationException e) { + final Class aClass = getClass(); + final String className = aClass.getName(); + final Logger logger = Logger.getInstance(className); + logger.error(e); + } } - final PsiVariable variable = (PsiVariable)target; - if (variable.hasModifierProperty(PsiModifier.FINAL)) { - doFix(project, variable.getInitializer()); + + @RequiredWriteAction + protected void doFix(Project project, PsiElement element) throws IncorrectOperationException { + if (element instanceof PsiLiteralExpression literalExpression) { + if (literalExpression.getValue() instanceof String strValue) { + final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); + final PsiExpression newExpression = + factory.createExpressionFromText('"' + StringUtil.wordsToBeginFromUpperCase(strValue) + '"', element); + literalExpression.replace(newExpression); + } + } + else if (element instanceof PsiMethodCallExpression methodCallExpression) { + final PsiMethod method = methodCallExpression.resolveMethod(); + final PsiExpression returnValue = PropertyUtil.getGetterReturnExpression(method); + if (returnValue != null) { + doFix(project, returnValue); + } + final Property property = getPropertyArgument(methodCallExpression); + if (property == null) { + return; + } + final String value = property.getUnescapedValue(); + if (value == null) { + return; + } + final String capitalizedString = StringUtil.wordsToBeginFromUpperCase(value); + property.setValue(capitalizedString); + } + else if (element instanceof PsiReferenceExpression referenceExpression) { + if (referenceExpression.resolve() instanceof PsiVariable variable && variable.hasModifierProperty(PsiModifier.FINAL)) { + doFix(project, variable.getInitializer()); + } + } } - } - } - protected static boolean isQuickFixOnReadOnlyFile(PsiElement problemElement) { - final PsiFile containingPsiFile = problemElement.getContainingFile(); - if (containingPsiFile == null) { - return false; - } - final VirtualFile virtualFile = containingPsiFile.getVirtualFile(); - if (virtualFile == null) { - return false; - } - final Project project = problemElement.getProject(); - final ReadonlyStatusHandler handler = ReadonlyStatusHandler.getInstance(project); - final ReadonlyStatusHandler.OperationStatus status = handler.ensureFilesWritable(virtualFile); - return status.hasReadonlyFiles(); - } + protected static boolean isQuickFixOnReadOnlyFile(PsiElement problemElement) { + final PsiFile containingPsiFile = problemElement.getContainingFile(); + if (containingPsiFile == null) { + return false; + } + final VirtualFile virtualFile = containingPsiFile.getVirtualFile(); + if (virtualFile == null) { + return false; + } + final Project project = problemElement.getProject(); + final ReadonlyStatusHandler handler = ReadonlyStatusHandler.getInstance(project); + final ReadonlyStatusHandler.OperationStatus status = handler.ensureFilesWritable(virtualFile); + return status.hasReadonlyFiles(); + } - @Nonnull - @Override - public String getFamilyName() { - return "Properly capitalize"; + @Nonnull + @Override + public String getFamilyName() { + return "Properly capitalize"; + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/DontUseNewPairInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/DontUseNewPairInspection.java index e5b03f80..32ade7f5 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/DontUseNewPairInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/DontUseNewPairInspection.java @@ -32,44 +32,44 @@ */ @ExtensionImpl public class DontUseNewPairInspection extends InternalInspection { - private static final String PAIR_FQN = Pair.class.getName(); + private static final String PAIR_FQN = Pair.class.getName(); - @Nonnull - @Override - public String getDisplayName() { - return "Don't use constructor of Pair class"; - } + @Nonnull + @Override + public String getDisplayName() { + return "Don't use constructor of Pair class"; + } - @Override - public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, boolean isOnTheFly) { - return new JavaElementVisitor() { - @Override - public void visitNewExpression(@Nonnull PsiNewExpression expression) { - final PsiType type = expression.getType(); - final PsiExpressionList params = expression.getArgumentList(); - if (type instanceof PsiClassType - && ((PsiClassType)type).rawType().equalsToText(PAIR_FQN) - && params != null - && expression.getArgumentList() != null - ) { - final PsiType[] types = ((PsiClassType)type).getParameters(); - if (Arrays.equals(types, params.getExpressionTypes())) { - holder.registerProblem( - expression, - LocalizeValue.localizeTODO("Replace with Pair.create()").get(), - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - new ChangeToPairCreateQuickFix() - ); - } - } - super.visitNewExpression(expression); - } - }; - } + @Override + public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, boolean isOnTheFly) { + return new JavaElementVisitor() { + @Override + public void visitNewExpression(@Nonnull PsiNewExpression expression) { + final PsiType type = expression.getType(); + final PsiExpressionList params = expression.getArgumentList(); + if (type instanceof PsiClassType classType + && classType.rawType().equalsToText(PAIR_FQN) + && params != null + && expression.getArgumentList() != null + ) { + final PsiType[] types = ((PsiClassType)type).getParameters(); + if (Arrays.equals(types, params.getExpressionTypes())) { + holder.registerProblem( + expression, + LocalizeValue.localizeTODO("Replace with Pair.create()").get(), + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + new ChangeToPairCreateQuickFix() + ); + } + } + super.visitNewExpression(expression); + } + }; + } - @Nonnull - @Override - public String getShortName() { - return "DontUsePairConstructor"; - } + @Nonnull + @Override + public String getShortName() { + return "DontUsePairConstructor"; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/FileEqualsUsageInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/FileEqualsUsageInspection.java index 51c94132..6d9a3cba 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/FileEqualsUsageInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/FileEqualsUsageInspection.java @@ -16,7 +16,9 @@ package org.jetbrains.idea.devkit.inspections.internal; import com.intellij.java.language.psi.*; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; +import consulo.java.language.module.util.JavaClassNames; import consulo.language.editor.inspection.ProblemHighlightType; import consulo.language.editor.inspection.ProblemsHolder; import consulo.language.psi.PsiElement; @@ -26,41 +28,38 @@ @ExtensionImpl public class FileEqualsUsageInspection extends InternalInspection { - private static final String MESSAGE = - "Do not use File.equals/hashCode/compareTo as they don't honor case-sensitivity on MacOS. " + "Please use " + - "FileUtil.filesEquals/fileHashCode/compareFiles instead"; + private static final String MESSAGE = + "Do not use File.equals/hashCode/compareTo as they don't honor case-sensitivity on MacOS. " + + "Please use FileUtil.filesEquals/fileHashCode/compareFiles instead"; - @Override - @Nonnull - public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, boolean isOnTheFly) { - return new JavaElementVisitor() { - @Override - public void visitMethodCallExpression(PsiMethodCallExpression expression) { - PsiReferenceExpression methodExpression = expression.getMethodExpression(); - PsiElement resolved = methodExpression.resolve(); - if (!(resolved instanceof PsiMethod)) { - return; - } + @Override + @Nonnull + public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, boolean isOnTheFly) { + return new JavaElementVisitor() { + @Override + @RequiredReadAction + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + PsiReferenceExpression methodExpression = expression.getMethodExpression(); + PsiElement resolved = methodExpression.resolve(); + if (resolved instanceof PsiMethod method) { + PsiClass clazz = method.getContainingClass(); + if (clazz == null) { + return; + } - PsiMethod method = (PsiMethod)resolved; + String methodName = method.getName(); + if (JavaClassNames.JAVA_IO_FILE.equals(clazz.getQualifiedName()) + && ("equals".equals(methodName) || "compareTo".equals(methodName) || "hashCode".equals(methodName))) { + holder.registerProblem(methodExpression, MESSAGE, ProblemHighlightType.LIKE_DEPRECATED); + } + } + } + }; + } - PsiClass clazz = method.getContainingClass(); - if (clazz == null) { - return; - } - - String methodName = method.getName(); - if (CommonClassNames.JAVA_IO_FILE.equals(clazz.getQualifiedName()) && ("equals".equals(methodName) || "compareTo".equals(methodName) - || "hashCode".equals(methodName))) { - holder.registerProblem(methodExpression, MESSAGE, ProblemHighlightType.LIKE_DEPRECATED); - } - } - }; - } - - @Nonnull - @Override - public String getDisplayName() { - return "File.equals() usage"; - } + @Nonnull + @Override + public String getDisplayName() { + return "File.equals() usage"; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/InternalInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/InternalInspection.java index 7277d099..34a06673 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/InternalInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/InternalInspection.java @@ -26,35 +26,33 @@ import javax.annotation.Nonnull; public abstract class InternalInspection extends BaseJavaLocalInspectionTool { - @Nonnull - @Override - public String getGroupDisplayName() { - return DevKitLocalize.inspectionsGroupName().get(); - } + @Nonnull + @Override + public String getGroupDisplayName() { + return DevKitLocalize.inspectionsGroupName().get(); + } - @Override - public boolean isEnabledByDefault() { - return true; - } + @Override + public boolean isEnabledByDefault() { + return true; + } - @Nonnull - @Override - public PsiElementVisitor buildVisitorImpl( - @Nonnull ProblemsHolder holder, - boolean isOnTheFly, - LocalInspectionToolSession session, - Object o - ) { - if (!isAllowed(holder)) { - return PsiElementVisitor.EMPTY_VISITOR; + @Nonnull + @Override + @RequiredReadAction + public PsiElementVisitor buildVisitorImpl( + @Nonnull ProblemsHolder holder, + boolean isOnTheFly, + LocalInspectionToolSession session, + Object o + ) { + return isAllowed(holder) ? buildInternalVisitor(holder, isOnTheFly) : PsiElementVisitor.EMPTY_VISITOR; } - return buildInternalVisitor(holder, isOnTheFly); - } - @RequiredReadAction - protected boolean isAllowed(ProblemsHolder holder) { - return PluginModuleUtil.isConsuloOrPluginProject(holder.getFile()); - } + @RequiredReadAction + protected boolean isAllowed(ProblemsHolder holder) { + return PluginModuleUtil.isConsuloOrPluginProject(holder.getFile()); + } - public abstract PsiElementVisitor buildInternalVisitor(@Nonnull ProblemsHolder holder, boolean isOnTheFly); + public abstract PsiElementVisitor buildInternalVisitor(@Nonnull ProblemsHolder holder, boolean isOnTheFly); } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UndesirableClassUsageInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UndesirableClassUsageInspection.java index c315a70b..da6462c8 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UndesirableClassUsageInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UndesirableClassUsageInspection.java @@ -19,6 +19,7 @@ import com.intellij.java.language.psi.PsiClass; import com.intellij.java.language.psi.PsiJavaCodeReferenceElement; import com.intellij.java.language.psi.PsiNewExpression; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.application.util.query.QueryExecutor; import consulo.language.editor.inspection.ProblemHighlightType; @@ -39,51 +40,56 @@ @ExtensionImpl public class UndesirableClassUsageInspection extends InternalInspection { - private static final Map CLASSES = new HashMap(); + private static final Map CLASSES = new HashMap<>(); - static { - CLASSES.put(JList.class.getName(), JBList.class.getName()); - CLASSES.put(JTable.class.getName(), JBTable.class.getName()); - CLASSES.put(JTree.class.getName(), Tree.class.getName()); - CLASSES.put(JScrollPane.class.getName(), JBScrollPane.class.getName()); - CLASSES.put(QueryExecutor.class.getName(), QueryExecutorBase.class.getName()); - CLASSES.put(BufferedImage.class.getName(), "UIUtil.createImage()"); - } + static { + CLASSES.put(JList.class.getName(), JBList.class.getName()); + CLASSES.put(JTable.class.getName(), JBTable.class.getName()); + CLASSES.put(JTree.class.getName(), Tree.class.getName()); + CLASSES.put(JScrollPane.class.getName(), JBScrollPane.class.getName()); + CLASSES.put(QueryExecutor.class.getName(), QueryExecutorBase.class.getName()); + CLASSES.put(BufferedImage.class.getName(), "UIUtil.createImage()"); + } - @Nonnull - @Override - public String getDisplayName() { - return "Undesirable class usage"; - } + @Nonnull + @Override + public String getDisplayName() { + return "Undesirable class usage"; + } - @Override - @Nonnull - public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, boolean isOnTheFly) { - return new JavaElementVisitor() { - @Override - public void visitNewExpression(PsiNewExpression expression) { - PsiJavaCodeReferenceElement ref = expression.getClassReference(); - if (ref == null) { - return; - } + @Override + @Nonnull + public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, boolean isOnTheFly) { + return new JavaElementVisitor() { + @Override + @RequiredReadAction + public void visitNewExpression(@Nonnull PsiNewExpression expression) { + PsiJavaCodeReferenceElement ref = expression.getClassReference(); + if (ref == null) { + return; + } - PsiElement res = ref.resolve(); - if (res == null) { - return; - } + PsiElement res = ref.resolve(); + if (res == null) { + return; + } - String name = ((PsiClass)res).getQualifiedName(); - if (name == null) { - return; - } + String name = ((PsiClass)res).getQualifiedName(); + if (name == null) { + return; + } - String replacement = CLASSES.get(name); - if (replacement == null) { - return; - } + String replacement = CLASSES.get(name); + if (replacement == null) { + return; + } - holder.registerProblem(expression, "Please use '" + replacement + "' instead", ProblemHighlightType.LIKE_DEPRECATED); - } - }; - } + holder.registerProblem( + expression, + "Please use '" + replacement + "' instead", + ProblemHighlightType.LIKE_DEPRECATED + ); + } + }; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UnsafeVfsRecursionInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UnsafeVfsRecursionInspection.java index 84eb565c..55b43e7e 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UnsafeVfsRecursionInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UnsafeVfsRecursionInspection.java @@ -17,6 +17,7 @@ import com.intellij.java.language.psi.*; import com.intellij.java.language.psi.util.InheritanceUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.editor.inspection.ProblemsHolder; import consulo.language.psi.PsiElement; @@ -31,64 +32,63 @@ @ExtensionImpl public class UnsafeVfsRecursionInspection extends InternalInspection { - private static final String VIRTUAL_FILE_CLASS_NAME = VirtualFile.class.getName(); - private static final String GET_CHILDREN_METHOD_NAME = "getChildren"; + private static final String VIRTUAL_FILE_CLASS_NAME = VirtualFile.class.getName(); + private static final String GET_CHILDREN_METHOD_NAME = "getChildren"; - private static final String MESSAGE = "VirtualFile.getChildren() is called from a recursive method. " + - "This may cause an endless loop on cyclic symlinks. " + - "Please use VfsUtilCore.visitChildrenRecursively() instead."; + private static final String MESSAGE = "VirtualFile.getChildren() is called from a recursive method. " + + "This may cause an endless loop on cyclic symlinks. " + + "Please use VfsUtilCore.visitChildrenRecursively() instead."; - @Nonnull - @Override - public String getDisplayName() { - return "Unsafe VFS recursion"; - } + @Nonnull + @Override + public String getDisplayName() { + return "Unsafe VFS recursion"; + } - @Nonnull - @Override - public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, final boolean isOnTheFly) { - return new JavaElementVisitor() { - @Override - public void visitMethodCallExpression(final PsiMethodCallExpression expression) { - final Project project = expression.getProject(); - final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); + @Nonnull + @Override + public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, final boolean isOnTheFly) { + return new JavaElementVisitor() { + @Override + @RequiredReadAction + public void visitMethodCallExpression(@Nonnull final PsiMethodCallExpression expression) { + final Project project = expression.getProject(); + final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); - final PsiReferenceExpression methodRef = expression.getMethodExpression(); - if (!GET_CHILDREN_METHOD_NAME.equals(methodRef.getReferenceName())) { - return; - } - final PsiElement methodElement = methodRef.resolve(); - if (!(methodElement instanceof PsiMethod)) { - return; - } - final PsiMethod method = (PsiMethod)methodElement; - final PsiClass aClass = method.getContainingClass(); - final PsiClass virtualFileClass = facade.findClass(VIRTUAL_FILE_CLASS_NAME, GlobalSearchScope.allScope(project)); - if (!InheritanceUtil.isInheritorOrSelf(aClass, virtualFileClass, true)) { - return; - } + final PsiReferenceExpression methodRef = expression.getMethodExpression(); + if (!GET_CHILDREN_METHOD_NAME.equals(methodRef.getReferenceName())) { + return; + } + final PsiElement methodElement = methodRef.resolve(); + if (methodElement instanceof PsiMethod method) { + final PsiClass aClass = method.getContainingClass(); + final PsiClass virtualFileClass = facade.findClass(VIRTUAL_FILE_CLASS_NAME, GlobalSearchScope.allScope(project)); + if (!InheritanceUtil.isInheritorOrSelf(aClass, virtualFileClass, true)) { + return; + } - final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(expression, PsiMethod.class); - if (containingMethod == null) { - return; - } - final String containingMethodName = containingMethod.getName(); - final Ref result = Ref.create(); - containingMethod.accept(new JavaRecursiveElementVisitor() { - @Override - public void visitMethodCallExpression(final PsiMethodCallExpression expression2) { - if (expression2 != expression && - containingMethodName.equals(expression2.getMethodExpression().getReferenceName()) && - expression2.resolveMethod() == containingMethod) { - result.set(Boolean.TRUE); - } - } - }); + final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(expression, PsiMethod.class); + if (containingMethod == null) { + return; + } + final String containingMethodName = containingMethod.getName(); + final Ref result = Ref.create(); + containingMethod.accept(new JavaRecursiveElementVisitor() { + @Override + public void visitMethodCallExpression(@Nonnull final PsiMethodCallExpression expression2) { + if (expression2 != expression + && containingMethodName.equals(expression2.getMethodExpression().getReferenceName()) + && expression2.resolveMethod() == containingMethod) { + result.set(Boolean.TRUE); + } + } + }); - if (!result.isNull()) { - holder.registerProblem(expression, MESSAGE); - } - } - }; - } + if (!result.isNull()) { + holder.registerProblem(expression, MESSAGE); + } + } + } + }; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseCoupleInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseCoupleInspection.java index da514253..87454d20 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseCoupleInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseCoupleInspection.java @@ -16,10 +16,10 @@ package org.jetbrains.idea.devkit.inspections.internal; import com.intellij.java.language.psi.*; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.editor.inspection.ProblemHighlightType; import consulo.language.editor.inspection.ProblemsHolder; -import consulo.language.psi.PsiElement; import consulo.language.psi.PsiElementVisitor; import consulo.language.psi.PsiReference; import consulo.util.lang.Pair; @@ -35,58 +35,60 @@ */ @ExtensionImpl public class UseCoupleInspection extends InternalInspection { - private static final String PAIR_FQN = Pair.class.getName(); + private static final String PAIR_FQN = Pair.class.getName(); - @Nonnull - @Override - public String getDisplayName() { - return "org.jetbrains.idea.devkit.inspections.internal.UseCoupleInspection"; - } + @Nonnull + @Override + public String getDisplayName() { + return "org.jetbrains.idea.devkit.inspections.internal.UseCoupleInspection"; + } - @Override - public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, boolean isOnTheFly) { - return new JavaElementVisitor() { + @Override + public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, boolean isOnTheFly) { + return new JavaElementVisitor() { + @Override + public void visitTypeElement(@Nonnull PsiTypeElement type) { + final String canonicalText = type.getType().getCanonicalText(); + if (canonicalText.startsWith(PAIR_FQN)) { + if (canonicalText.contains("<") && canonicalText.endsWith(">")) { + String genericTypes = + canonicalText.substring(canonicalText.indexOf('<') + 1, canonicalText.length() - 1); + final List types = StringUtil.split(genericTypes, ","); + if (types.size() == 2 && StringUtil.equals(types.get(0), types.get(1))) { + final List parts = StringUtil.split(types.get(0), "."); + String typeName = parts.get(parts.size() - 1); + final String name = "Change to Couple<" + typeName + ">"; + holder.registerProblem(type, name, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new UseCoupleQuickFix(name)); + } + } - @Override - public void visitTypeElement(PsiTypeElement type) { - final String canonicalText = type.getType().getCanonicalText(); - if (canonicalText.startsWith(PAIR_FQN)) { - if (canonicalText.contains("<") && canonicalText.endsWith(">")) { - String genericTypes = canonicalText.substring(canonicalText.indexOf('<') + 1, canonicalText.length() - 1); - final List types = StringUtil.split(genericTypes, ","); - if (types.size() == 2 && StringUtil.equals(types.get(0), types.get(1))) { - final List parts = StringUtil.split(types.get(0), "."); - String typeName = parts.get(parts.size() - 1); - final String name = "Change to Couple<" + typeName + ">"; - holder.registerProblem(type, name, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new UseCoupleQuickFix(name)); + } + super.visitTypeElement(type); } - } - - } - super.visitTypeElement(type); - } - @Override - public void visitMethodCallExpression(PsiMethodCallExpression expression) { - if (expression.getText().startsWith("Pair.create")) { - final PsiReference reference = expression.getMethodExpression().getReference(); - if (reference != null) { - final PsiElement method = reference.resolve(); - if (method instanceof PsiMethod) { - final PsiClass psiClass = ((PsiMethod)method).getContainingClass(); - if (psiClass != null && PAIR_FQN.equals(psiClass.getQualifiedName())) { - final PsiType[] types = expression.getArgumentList().getExpressionTypes(); - if (types.length == 2 && Objects.equals(types[0], types[1])) { - final String name = "Change to Couple.of"; - holder.registerProblem(expression, name, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new UseCoupleQuickFix(name)); + @Override + @RequiredReadAction + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { + if (expression.getText().startsWith("Pair.create")) { + final PsiReference reference = expression.getMethodExpression().getReference(); + if (reference != null && reference.resolve() instanceof PsiMethod method) { + final PsiClass psiClass = method.getContainingClass(); + if (psiClass != null && PAIR_FQN.equals(psiClass.getQualifiedName())) { + final PsiType[] types = expression.getArgumentList().getExpressionTypes(); + if (types.length == 2 && Objects.equals(types[0], types[1])) { + final String name = "Change to Couple.of"; + holder.registerProblem( + expression, + name, + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + new UseCoupleQuickFix(name) + ); + } + } + } } - } + super.visitMethodCallExpression(expression); } - } - } - super.visitMethodCallExpression(expression); - } - }; - } - + }; + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseDPIAwareInsetsInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseDPIAwareInsetsInspection.java index 1ce388df..7d351f14 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseDPIAwareInsetsInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseDPIAwareInsetsInspection.java @@ -37,63 +37,61 @@ */ @ExtensionImpl public class UseDPIAwareInsetsInspection extends InternalInspection { - @Nonnull - @Override - public String getDisplayName() { - return "Use DPI-aware insets"; - } + @Nonnull + @Override + public String getDisplayName() { + return "Use DPI-aware insets"; + } - @Override - public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, final boolean isOnTheFly) { - return new JavaElementVisitor() { - @Override - public void visitNewExpression(PsiNewExpression expression) { - final ProblemDescriptor - descriptor = checkNewExpression(expression, holder.getManager(), isOnTheFly); - if (descriptor != null) { - holder.registerProblem(descriptor); - } - super.visitNewExpression(expression); - } - }; - } + @Override + public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, final boolean isOnTheFly) { + return new JavaElementVisitor() { + @Override + public void visitNewExpression(@Nonnull PsiNewExpression expression) { + final ProblemDescriptor descriptor = checkNewExpression(expression, holder.getManager(), isOnTheFly); + if (descriptor != null) { + holder.registerProblem(descriptor); + } + super.visitNewExpression(expression); + } + }; + } - @Nullable - private static ProblemDescriptor checkNewExpression(PsiNewExpression expression, InspectionManager manager, boolean isOnTheFly) { - final Project project = manager.getProject(); - final PsiType type = expression.getType(); - final PsiExpressionList arguments = expression.getArgumentList(); - if (type != null && arguments != null && type.equalsToText("java.awt.Insets")) { - if (expression.getParent() instanceof PsiExpressionList) { - PsiElement parent = expression.getParent(); - PsiElement superParent = parent.getParent(); - if (superParent instanceof PsiMethodCallExpression) { - PsiType methodType = ((PsiMethodCallExpression)superParent).getType(); - if (methodType != null && methodType.equalsToText(JBInsets.class.getName())) { - return null; - } + @Nullable + private static ProblemDescriptor checkNewExpression(PsiNewExpression expression, InspectionManager manager, boolean isOnTheFly) { + final Project project = manager.getProject(); + final PsiType type = expression.getType(); + final PsiExpressionList arguments = expression.getArgumentList(); + if (type != null && arguments != null && type.equalsToText("java.awt.Insets")) { + if (expression.getParent() instanceof PsiExpressionList expressionList + && expressionList.getParent() instanceof PsiMethodCallExpression methodCallExpression) { + PsiType methodType = methodCallExpression.getType(); + if (methodType != null && methodType.equalsToText(JBInsets.class.getName())) { + return null; + } + } + final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); + final PsiResolveHelper resolveHelper = PsiResolveHelper.getInstance(project); + final PsiClass jbuiClass = facade.findClass(JBUI.class.getName(), GlobalSearchScope.allScope(project)); + if (jbuiClass != null && resolveHelper.isAccessible(jbuiClass, expression, jbuiClass)) { + final PsiElement parent = expression.getParent(); + if (parent instanceof PsiExpressionList && parent.getParent() instanceof PsiNewExpression newExpression) { + final PsiType parentType = newExpression.getType(); + if (parentType == null || JBInsets.class.getName().equals(parentType.getCanonicalText())) { + return null; + } + } + if (arguments.getExpressions().length == 4) { + return manager.createProblemDescriptor( + expression, + "Replace with JBUI.insets(...)", + new ConvertToJBInsetsQuickFix(), + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + isOnTheFly + ); + } + } } - } - final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); - final PsiClass jbuiClass = facade.findClass(JBUI.class.getName(), GlobalSearchScope.allScope(project)); - if (jbuiClass != null && facade.getResolveHelper().isAccessible(jbuiClass, expression, jbuiClass)) { - final PsiElement parent = expression.getParent(); - if (parent instanceof PsiExpressionList && parent.getParent() instanceof PsiNewExpression) { - final PsiType parentType = ((PsiNewExpression)parent.getParent()).getType(); - if (parentType == null || JBInsets.class.getName().equals(parentType.getCanonicalText())) { - return null; - } - } - if (arguments.getExpressions().length == 4) { - return manager.createProblemDescriptor(expression, - "Replace with JBUI.insets(...)", - new ConvertToJBInsetsQuickFix(), - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - isOnTheFly); - } - } + return null; } - return null; - } - } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseGrayInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseGrayInspection.java index 4f47f0e3..d3e80d90 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseGrayInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseGrayInspection.java @@ -38,94 +38,98 @@ */ @ExtensionImpl public class UseGrayInspection extends InternalInspection { - @Nonnull - @Override - public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, final boolean isOnTheFly) { - return new JavaElementVisitor() { - @Override - public void visitNewExpression(PsiNewExpression expression) { - final ProblemDescriptor descriptor = checkNewExpression(expression, holder.getManager(), isOnTheFly); - if (descriptor != null) { - holder.registerProblem(descriptor); - } - } - }; - } - - @Nullable - private static ProblemDescriptor checkNewExpression(PsiNewExpression expression, InspectionManager manager, boolean isOnTheFly) { - final Project project = manager.getProject(); - final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); - final PsiClass grayClass = facade.findClass(Gray.class.getName(), GlobalSearchScope.allScope(project)); - final PsiType type = expression.getType(); - if (type != null && grayClass != null) { - final PsiExpressionList arguments = expression.getArgumentList(); - if (arguments != null) { - final PsiExpression[] expressions = arguments.getExpressions(); - if (expressions.length == 3 && "java.awt.Color".equals(type.getCanonicalText())) { - if (!facade.getResolveHelper().isAccessible(grayClass, expression, grayClass)) { - return null; - } - final PsiExpression r = expressions[0]; - final PsiExpression g = expressions[1]; - final PsiExpression b = expressions[2]; - if (r instanceof PsiLiteralExpression && g instanceof PsiLiteralExpression && b instanceof PsiLiteralExpression) { - final Object red = JavaConstantExpressionEvaluator.computeConstantExpression(r, false); - final Object green = JavaConstantExpressionEvaluator.computeConstantExpression(g, false); - final Object blue = JavaConstantExpressionEvaluator.computeConstantExpression(b, false); - if (NullUtils.notNull(red, green, blue)) { - try { - int rr = Integer.parseInt(red.toString()); - int gg = Integer.parseInt(green.toString()); - int bb = Integer.parseInt(blue.toString()); - if (rr == gg && gg == bb && 0 <= rr && rr < 256) { - return manager.createProblemDescriptor(expression, - "Convert to Gray._" + rr, - new ConvertToGrayQuickFix(rr), - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - isOnTheFly); + @Nonnull + @Override + public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, final boolean isOnTheFly) { + return new JavaElementVisitor() { + @Override + public void visitNewExpression(@Nonnull PsiNewExpression expression) { + final ProblemDescriptor descriptor = checkNewExpression(expression, holder.getManager(), isOnTheFly); + if (descriptor != null) { + holder.registerProblem(descriptor); } - } - catch (Exception ignore) { - } } - } - } - else if (expressions.length == 1 && "com.intellij.ui.Gray".equals(type.getCanonicalText())) { - final PsiExpression e = expressions[0]; - if (e instanceof PsiLiteralExpression) { - final Object literal = JavaConstantExpressionEvaluator.computeConstantExpression(e, false); - if (literal != null) { - try { - int num = Integer.parseInt(literal.toString()); - if (0 <= num && num < 256) { - return manager.createProblemDescriptor(expression, - "Convert to Gray_" + num, - new ConvertToGrayQuickFix(num), - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, - isOnTheFly); + }; + } + + @Nullable + private static ProblemDescriptor checkNewExpression(PsiNewExpression expression, InspectionManager manager, boolean isOnTheFly) { + final Project project = manager.getProject(); + final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); + final PsiClass grayClass = facade.findClass(Gray.class.getName(), GlobalSearchScope.allScope(project)); + final PsiType type = expression.getType(); + if (type != null && grayClass != null) { + final PsiExpressionList arguments = expression.getArgumentList(); + if (arguments != null) { + final PsiExpression[] expressions = arguments.getExpressions(); + if (expressions.length == 3 && "java.awt.Color".equals(type.getCanonicalText())) { + if (!PsiResolveHelper.getInstance(project).isAccessible(grayClass, expression, grayClass)) { + return null; + } + final PsiExpression r = expressions[0]; + final PsiExpression g = expressions[1]; + final PsiExpression b = expressions[2]; + if (r instanceof PsiLiteralExpression && g instanceof PsiLiteralExpression && b instanceof PsiLiteralExpression) { + final Object red = JavaConstantExpressionEvaluator.computeConstantExpression(r, false); + final Object green = JavaConstantExpressionEvaluator.computeConstantExpression(g, false); + final Object blue = JavaConstantExpressionEvaluator.computeConstantExpression(b, false); + if (NullUtils.notNull(red, green, blue)) { + try { + int rr = Integer.parseInt(red.toString()); + int gg = Integer.parseInt(green.toString()); + int bb = Integer.parseInt(blue.toString()); + if (rr == gg && gg == bb && 0 <= rr && rr < 256) { + return manager.createProblemDescriptor( + expression, + "Convert to Gray._" + rr, + new ConvertToGrayQuickFix(rr), + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + isOnTheFly + ); + } + } + catch (Exception ignore) { + } + } + } + } + else if (expressions.length == 1 && "com.intellij.ui.Gray".equals(type.getCanonicalText())) { + final PsiExpression e = expressions[0]; + if (e instanceof PsiLiteralExpression) { + final Object literal = JavaConstantExpressionEvaluator.computeConstantExpression(e, false); + if (literal != null) { + try { + int num = Integer.parseInt(literal.toString()); + if (0 <= num && num < 256) { + return manager.createProblemDescriptor( + expression, + "Convert to Gray_" + num, + new ConvertToGrayQuickFix(num), + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + isOnTheFly + ); + } + } + catch (Exception ignore) { + } + } + } } - } - catch (Exception ignore) { - } } - } } - } + return null; } - return null; - } - @Nls - @Nonnull - @Override - public String getDisplayName() { - return "Using new Color(a,a,a)"; - } + @Nls + @Nonnull + @Override + public String getDisplayName() { + return "Using new Color(a,a,a)"; + } - @Nonnull - @Override - public String getShortName() { - return "InspectionUsingGrayColors"; - } + @Nonnull + @Override + public String getShortName() { + return "InspectionUsingGrayColors"; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseJBColorInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseJBColorInspection.java index 893743d1..1a7c2514 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseJBColorInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UseJBColorInspection.java @@ -16,12 +16,12 @@ package org.jetbrains.idea.devkit.inspections.internal; import com.intellij.java.language.psi.*; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.editor.inspection.ProblemHighlightType; import consulo.language.editor.inspection.ProblemsHolder; import consulo.language.editor.inspection.scheme.InspectionManager; -import consulo.language.psi.PsiElement; import consulo.language.psi.PsiElementVisitor; import consulo.language.psi.scope.GlobalSearchScope; import consulo.project.Project; @@ -39,84 +39,94 @@ */ @ExtensionImpl public class UseJBColorInspection extends InternalInspection { - @Nonnull - @Override - public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, final boolean isOnTheFly) { - return new JavaElementVisitor() { - @Override - public void visitNewExpression(PsiNewExpression expression) { - final ProblemDescriptor descriptor = checkNewExpression(expression, holder.getManager(), isOnTheFly); - if (descriptor != null) { - holder.registerProblem(descriptor); - } - super.visitNewExpression(expression); - } - - @Override - public void visitReferenceExpression(PsiReferenceExpression expression) { - super.visitReferenceExpression(expression); - final PsiElement colorField = expression.resolve(); - if (colorField != null && colorField instanceof PsiField && ((PsiField)colorField).hasModifierProperty(PsiModifier.STATIC)) { - final PsiClass colorClass = ((PsiField)colorField).getContainingClass(); - if (colorClass != null && Color.class.getName().equals(colorClass.getQualifiedName())) { - String text = expression.getText(); - if (text.contains(".")) { - text = text.substring(text.lastIndexOf('.')); + @Nonnull + @Override + public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, final boolean isOnTheFly) { + return new JavaElementVisitor() { + @Override + public void visitNewExpression(@Nonnull PsiNewExpression expression) { + final ProblemDescriptor descriptor = checkNewExpression(expression, holder.getManager(), isOnTheFly); + if (descriptor != null) { + holder.registerProblem(descriptor); + } + super.visitNewExpression(expression); } - if (text.startsWith(".")) { - text = text.substring(1); + + @Override + @RequiredReadAction + public void visitReferenceExpression(@Nonnull PsiReferenceExpression expression) { + super.visitReferenceExpression(expression); + if (expression.resolve() instanceof PsiField colorField && colorField.hasModifierProperty(PsiModifier.STATIC)) { + final PsiClass colorClass = colorField.getContainingClass(); + if (colorClass != null && Color.class.getName().equals(colorClass.getQualifiedName())) { + String text = expression.getText(); + if (text.contains(".")) { + text = text.substring(text.lastIndexOf('.')); + } + if (text.startsWith(".")) { + text = text.substring(1); + } + if (text.equalsIgnoreCase("lightGray")) { + text = "LIGHT_GRAY"; + } + else if (text.equalsIgnoreCase("darkGray")) { + text = "DARK_GRAY"; + } + final ProblemDescriptor descriptor = holder.getManager().createProblemDescriptor( + expression, + "Change to JBColor." + text.toUpperCase(), + new ConvertToJBColorConstantQuickFix(text.toUpperCase()), + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + isOnTheFly + ); + holder.registerProblem(descriptor); + } + } } - if (text.equalsIgnoreCase("lightGray")) { - text = "LIGHT_GRAY"; + }; + } + + @Nullable + private static ProblemDescriptor checkNewExpression(PsiNewExpression expression, InspectionManager manager, boolean isOnTheFly) { + final Project project = manager.getProject(); + final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); + final PsiClass jbColorClass = facade.findClass(JBColor.class.getName(), GlobalSearchScope.allScope(project)); + final PsiType type = expression.getType(); + if (type != null && jbColorClass != null) { + if (!PsiResolveHelper.getInstance(project).isAccessible(jbColorClass, expression, jbColorClass)) { + return null; } - else if (text.equalsIgnoreCase("darkGray")) { - text = "DARK_GRAY"; + final PsiExpressionList arguments = expression.getArgumentList(); + if (arguments != null && "java.awt.Color".equals(type.getCanonicalText())) { + if (expression.getParent() instanceof PsiExpressionList expressionList + && expressionList.getParent() instanceof PsiNewExpression newExpression) { + final PsiType parentType = newExpression.getType(); + if (parentType == null || JBColor.class.getName().equals(parentType.getCanonicalText())) { + return null; + } + } + return manager.createProblemDescriptor( + expression, + "Replace with JBColor", + new ConvertToJBColorQuickFix(), + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, + isOnTheFly + ); } - final ProblemDescriptor descriptor = holder.getManager() - .createProblemDescriptor(expression, "Change to JBColor." + text.toUpperCase(), - new ConvertToJBColorConstantQuickFix(text.toUpperCase()), - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly); - holder.registerProblem(descriptor); - } } - } - }; - } - - @Nullable - private static ProblemDescriptor checkNewExpression(PsiNewExpression expression, InspectionManager manager, boolean isOnTheFly) { - final Project project = manager.getProject(); - final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); - final PsiClass jbColorClass = facade.findClass(JBColor.class.getName(), GlobalSearchScope.allScope(project)); - final PsiType type = expression.getType(); - if (type != null && jbColorClass != null) { - if (!facade.getResolveHelper().isAccessible(jbColorClass, expression, jbColorClass)) return null; - final PsiExpressionList arguments = expression.getArgumentList(); - if (arguments != null) { - if ("java.awt.Color".equals(type.getCanonicalText())) { - final PsiElement parent = expression.getParent(); - if (parent instanceof PsiExpressionList && parent.getParent() instanceof PsiNewExpression) { - final PsiType parentType = ((PsiNewExpression)parent.getParent()).getType(); - if (parentType == null || JBColor.class.getName().equals(parentType.getCanonicalText())) return null; - } - return manager.createProblemDescriptor(expression, "Replace with JBColor", new ConvertToJBColorQuickFix(), - ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly); - } - } + return null; } - return null; - } - @Nls - @Nonnull - @Override - public String getDisplayName() { - return "Use Darcula aware JBColor"; - } + @Nls + @Nonnull + @Override + public String getDisplayName() { + return "Use Darcula aware JBColor"; + } - @Nonnull - @Override - public String getShortName() { - return "UseJBColor"; - } + @Nonnull + @Override + public String getShortName() { + return "UseJBColor"; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UsePrimitiveTypesInspection.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UsePrimitiveTypesInspection.java index 3c415ea9..28f4210a 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UsePrimitiveTypesInspection.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/internal/UsePrimitiveTypesInspection.java @@ -19,6 +19,7 @@ import com.intellij.java.language.psi.util.PsiUtil; import com.siyeh.IntentionPowerPackBundle; import com.siyeh.ig.PsiReplacementUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.ast.IElementType; import consulo.language.editor.inspection.LocalQuickFix; @@ -28,115 +29,113 @@ import consulo.language.psi.PsiElementVisitor; import consulo.project.Project; import org.jetbrains.annotations.Nls; -import org.jetbrains.annotations.NonNls; import javax.annotation.Nonnull; @ExtensionImpl public class UsePrimitiveTypesInspection extends InternalInspection { - @Override - public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, final boolean isOnTheFly) { - return new JavaElementVisitor() { - @Override - public void visitBinaryExpression(PsiBinaryExpression expression) { - super.visitBinaryExpression(expression); - final IElementType tokenType = expression.getOperationTokenType(); - if (tokenType.equals(JavaTokenType.EQEQ) || tokenType.equals(JavaTokenType.NE)) { - final PsiExpression lOperand = expression.getLOperand(); - final PsiExpression rOperand = expression.getROperand(); - if (rOperand != null && (isPrimitiveTypeRef(lOperand) || isPrimitiveTypeRef(rOperand))) { - final String name; - if (JavaTokenType.NE.equals(tokenType)) { - name = IntentionPowerPackBundle.message("replace.equality.with.not.equals.intention.name"); - } - else { - name = IntentionPowerPackBundle.message("replace.equality.with.equals.intention.name"); + @Override + public PsiElementVisitor buildInternalVisitor(@Nonnull final ProblemsHolder holder, final boolean isOnTheFly) { + return new JavaElementVisitor() { + @Override + public void visitBinaryExpression(@Nonnull PsiBinaryExpression expression) { + super.visitBinaryExpression(expression); + final IElementType tokenType = expression.getOperationTokenType(); + if (JavaTokenType.EQEQ.equals(tokenType) || JavaTokenType.NE.equals(tokenType)) { + final PsiExpression lOperand = expression.getLOperand(); + final PsiExpression rOperand = expression.getROperand(); + if (rOperand != null && (isPrimitiveTypeRef(lOperand) || isPrimitiveTypeRef(rOperand))) { + final String name; + if (JavaTokenType.NE.equals(tokenType)) { + name = IntentionPowerPackBundle.message("replace.equality.with.not.equals.intention.name"); + } + else { + name = IntentionPowerPackBundle.message("replace.equality.with.equals.intention.name"); + } + holder.registerProblem( + expression.getOperationSign(), + "Primitive types should be compared with .equals", + new ReplaceEqualityWithEqualsFix(name) + ); + } + } } - holder.registerProblem(expression.getOperationSign(), - "Primitive types should be compared with .equals", - new ReplaceEqualityWithEqualsFix(name)); - } - } - } - }; - } - - private static boolean isPrimitiveTypeRef(PsiExpression expression) { - if (expression instanceof PsiReferenceExpression) { - final PsiElement target = ((PsiReferenceExpression)expression).resolve(); - if (target instanceof PsiField) { - final PsiClass containingClass = ((PsiField)target).getContainingClass(); - return containingClass != null && - PsiType.class.getName().equals(containingClass.getQualifiedName()) && - !"NULL".equals(((PsiField)target).getName()); - } - } - return false; - } - - @Nonnull - @Override - public String getDisplayName() { - return "Use .equals with primitive types"; - } - - private static class ReplaceEqualityWithEqualsFix implements LocalQuickFix { - private final String myName; - - public ReplaceEqualityWithEqualsFix(String name) { - myName = name; + }; } - @Nls - @Nonnull - @Override - public String getName() { - return myName; + @RequiredReadAction + private static boolean isPrimitiveTypeRef(PsiExpression expression) { + if (expression instanceof PsiReferenceExpression referenceExpression && referenceExpression.resolve() instanceof PsiField field) { + final PsiClass containingClass = field.getContainingClass(); + return containingClass != null + && PsiType.class.getName().equals(containingClass.getQualifiedName()) + && !"NULL".equals(field.getName()); + } + return false; } - @Nls @Nonnull @Override - public String getFamilyName() { - return "Replace equality with .equals"; + public String getDisplayName() { + return "Use .equals with primitive types"; } - @Override - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - final PsiElement psiElement = descriptor.getPsiElement(); - if (psiElement instanceof PsiJavaToken) { + private static class ReplaceEqualityWithEqualsFix implements LocalQuickFix { + private final String myName; - final IElementType tokenType = ((PsiJavaToken)psiElement).getTokenType(); - final String prefix; - if (tokenType.equals(JavaTokenType.EQEQ)) { - prefix = ""; + public ReplaceEqualityWithEqualsFix(String name) { + myName = name; } - else if (tokenType.equals(JavaTokenType.NE)) { - prefix = "!"; + + @Nls + @Nonnull + @Override + public String getName() { + return myName; } - else { - return; + + @Nls + @Nonnull + @Override + public String getFamilyName() { + return "Replace equality with .equals"; } - final PsiElement parent = psiElement.getParent(); - if (parent instanceof PsiBinaryExpression) { - final PsiExpression rOperand = ((PsiBinaryExpression)parent).getROperand(); - final PsiExpression lOperand = ((PsiBinaryExpression)parent).getLOperand(); - if (rOperand != null) { - final boolean flip = isPrimitiveTypeRef(rOperand); - if (flip || isPrimitiveTypeRef(lOperand)) { - final String rText = PsiUtil.skipParenthesizedExprUp(rOperand).getText(); - final String lText = PsiUtil.skipParenthesizedExprUp(lOperand).getText(); + @Override + @RequiredReadAction + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + final PsiElement psiElement = descriptor.getPsiElement(); + if (psiElement instanceof PsiJavaToken javaToken) { + final IElementType tokenType = javaToken.getTokenType(); + final String prefix; + if (JavaTokenType.EQEQ.equals(tokenType)) { + prefix = ""; + } + else if (JavaTokenType.NE.equals(tokenType)) { + prefix = "!"; + } + else { + return; + } + + if (psiElement.getParent() instanceof PsiBinaryExpression binaryExpression) { + final PsiExpression rOperand = binaryExpression.getROperand(); + final PsiExpression lOperand = binaryExpression.getLOperand(); + if (rOperand != null) { + final boolean flip = isPrimitiveTypeRef(rOperand); + if (flip || isPrimitiveTypeRef(lOperand)) { + final String rText = PsiUtil.skipParenthesizedExprUp(rOperand).getText(); + final String lText = PsiUtil.skipParenthesizedExprUp(lOperand).getText(); - final String lhText = flip ? rText : lText; - final String rhText = flip ? lText : rText; + final String lhText = flip ? rText : lText; + final String rhText = flip ? lText : rText; - @NonNls final String expString = prefix + lhText + ".equals(" + rhText + ')'; - PsiReplacementUtil.replaceExpression((PsiBinaryExpression)parent, expString); + final String expString = prefix + lhText + ".equals(" + rhText + ')'; + PsiReplacementUtil.replaceExpression(binaryExpression, expString); + } + } + } } - } } - } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/AbstractRegisterFix.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/AbstractRegisterFix.java index d793a79a..3485cd64 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/AbstractRegisterFix.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/AbstractRegisterFix.java @@ -28,11 +28,11 @@ import consulo.logging.Logger; import consulo.module.Module; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.awt.Messages; import consulo.ui.ex.awt.UIUtil; import consulo.undoRedo.CommandProcessor; import consulo.xml.psi.xml.XmlFile; -import org.jetbrains.annotations.NonNls; import org.jetbrains.idea.devkit.util.ChooseModulesDialog; import org.jetbrains.idea.devkit.util.DescriptorUtil; @@ -40,78 +40,89 @@ import java.util.List; abstract class AbstractRegisterFix implements LocalQuickFix, DescriptorUtil.Patcher { - protected final PsiClass myClass; - private static final Logger LOG = Logger.getInstance(AbstractRegisterFix.class); + protected final PsiClass myClass; + private static final Logger LOG = Logger.getInstance(AbstractRegisterFix.class); - public AbstractRegisterFix(PsiClass klass) { - myClass = klass; - } + public AbstractRegisterFix(PsiClass klass) { + myClass = klass; + } - @Nonnull - public String getFamilyName() { - return DevKitLocalize.inspectionsComponentNotRegisteredQuickfixFamily().get(); - } + @Nonnull + @Override + public String getFamilyName() { + return DevKitLocalize.inspectionsComponentNotRegisteredQuickfixFamily().get(); + } - @Nonnull - public String getName() { - return DevKitLocalize.inspectionsComponentNotRegisteredQuickfixName(getType()).get(); - } + @Nonnull + @Override + public String getName() { + return DevKitLocalize.inspectionsComponentNotRegisteredQuickfixName(getType()).get(); + } - protected abstract String getType(); + protected abstract String getType(); - // copy of com.intellij.ide.actions.CreateElementActionBase.filterMessage() - protected static String filterMessage(String message) { - if (message == null) return null; - @NonNls final String ioExceptionPrefix = "java.io.IOException:"; - if (message.startsWith(ioExceptionPrefix)) { - message = message.substring(ioExceptionPrefix.length()); + // copy of com.intellij.ide.actions.CreateElementActionBase.filterMessage() + protected static String filterMessage(String message) { + if (message == null) { + return null; + } + final String ioExceptionPrefix = "java.io.IOException:"; + if (message.startsWith(ioExceptionPrefix)) { + message = message.substring(ioExceptionPrefix.length()); + } + return message; } - return message; - } - - public void applyFix(@Nonnull final Project project, @Nonnull ProblemDescriptor descriptor) { - if (!FileModificationService.getInstance().preparePsiElementForWrite(descriptor.getPsiElement())) return; - final PsiFile psiFile = myClass.getContainingFile(); - LOG.assertTrue(psiFile != null); - final Module module = ModuleUtilCore.findModuleForFile(psiFile.getVirtualFile(), project); - Runnable command = () -> { - try { - if (ModuleUtilCore.getExtension(module, PluginModuleExtension.class) != null) { - final XmlFile pluginXml = PluginModuleUtil.getPluginXml(module); - if (pluginXml != null) { - DescriptorUtil.patchPluginXml(AbstractRegisterFix.this, myClass, pluginXml); - } + @Override + @RequiredUIAccess + public void applyFix(@Nonnull final Project project, @Nonnull ProblemDescriptor descriptor) { + if (!FileModificationService.getInstance().preparePsiElementForWrite(descriptor.getPsiElement())) { + return; } - else { - List modules = PluginModuleUtil.getCandidateModules(module); - if (modules.size() > 1) { - final ChooseModulesDialog dialog = new ChooseModulesDialog(project, modules, getName()); - dialog.show(); + final PsiFile psiFile = myClass.getContainingFile(); + LOG.assertTrue(psiFile != null); + final Module module = ModuleUtilCore.findModuleForFile(psiFile.getVirtualFile(), project); - if (!dialog.isOK()) { - return; - } - modules = dialog.getSelectedModules(); - } - final XmlFile[] pluginXmls = new XmlFile[modules.size()]; - for (int i = 0; i < pluginXmls.length; i++) { - pluginXmls[i] = PluginModuleUtil.getPluginXml(modules.get(i)); - } + Runnable command = () -> { + try { + if (ModuleUtilCore.getExtension(module, PluginModuleExtension.class) != null) { + final XmlFile pluginXml = PluginModuleUtil.getPluginXml(module); + if (pluginXml != null) { + DescriptorUtil.patchPluginXml(AbstractRegisterFix.this, myClass, pluginXml); + } + } + else { + //noinspection RequiredXAction + List modules = PluginModuleUtil.getCandidateModules(module); + if (modules.size() > 1) { + final ChooseModulesDialog dialog = new ChooseModulesDialog(project, modules, getName()); + //noinspection RequiredXAction + dialog.show(); - DescriptorUtil.patchPluginXml(AbstractRegisterFix.this, myClass, pluginXmls); - } - CommandProcessor.getInstance().markCurrentCommandAsGlobal(project); - } - catch (IncorrectOperationException e) { - Messages.showMessageDialog( - project, - filterMessage(e.getMessage()), - DevKitLocalize.inspectionsComponentNotRegisteredQuickfixError(getType()).get(), - UIUtil.getErrorIcon() - ); - } - }; - CommandProcessor.getInstance().executeCommand(project, command, getName(), null); - } + if (!dialog.isOK()) { + return; + } + modules = dialog.getSelectedModules(); + } + final XmlFile[] pluginXmls = new XmlFile[modules.size()]; + for (int i = 0; i < pluginXmls.length; i++) { + pluginXmls[i] = PluginModuleUtil.getPluginXml(modules.get(i)); + } + + DescriptorUtil.patchPluginXml(AbstractRegisterFix.this, myClass, pluginXmls); + } + CommandProcessor.getInstance().markCurrentCommandAsGlobal(project); + } + catch (IncorrectOperationException e) { + //noinspection RequiredXAction + Messages.showMessageDialog( + project, + filterMessage(e.getMessage()), + DevKitLocalize.inspectionsComponentNotRegisteredQuickfixError(getType()).get(), + UIUtil.getErrorIcon() + ); + } + }; + CommandProcessor.getInstance().executeCommand(project, command, getName(), null); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/BaseFix.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/BaseFix.java index 067bdf9a..a09f1989 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/BaseFix.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/BaseFix.java @@ -24,6 +24,7 @@ import consulo.language.util.IncorrectOperationException; import consulo.logging.Logger; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.awt.Messages; import consulo.ui.ex.awt.UIUtil; import consulo.virtualFileSystem.ReadonlyStatusHandler; @@ -35,46 +36,50 @@ * @author swr */ abstract class BaseFix implements LocalQuickFix { - protected final PsiElement myElement; - protected final boolean myOnTheFly; + protected final PsiElement myElement; + protected final boolean myOnTheFly; - protected BaseFix(PsiElement element, boolean onTheFly) { - myElement = element; - myOnTheFly = onTheFly; - } + protected BaseFix(PsiElement element, boolean onTheFly) { + myElement = element; + myOnTheFly = onTheFly; + } - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - // can happen during batch-inspection if resolution has already been applied - // to plugin.xml or java class - if (!myElement.isValid()) return; + @Override + @RequiredUIAccess + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + // can happen during batch-inspection if resolution has already been applied + // to plugin.xml or java class + if (!myElement.isValid()) { + return; + } - final boolean external = descriptor.getPsiElement().getContainingFile() != myElement.getContainingFile(); - if (external) { - final PsiClass clazz = PsiTreeUtil.getParentOfType(myElement, PsiClass.class, false); - final ReadonlyStatusHandler readonlyStatusHandler = ReadonlyStatusHandler.getInstance(project); - final VirtualFile[] files = new VirtualFile[]{myElement.getContainingFile().getVirtualFile()}; - final ReadonlyStatusHandler.OperationStatus status = readonlyStatusHandler.ensureFilesWritable(files); + final boolean external = descriptor.getPsiElement().getContainingFile() != myElement.getContainingFile(); + if (external) { + final PsiClass clazz = PsiTreeUtil.getParentOfType(myElement, PsiClass.class, false); + final ReadonlyStatusHandler readonlyStatusHandler = ReadonlyStatusHandler.getInstance(project); + final VirtualFile[] files = new VirtualFile[]{myElement.getContainingFile().getVirtualFile()}; + final ReadonlyStatusHandler.OperationStatus status = readonlyStatusHandler.ensureFilesWritable(files); - if (status.hasReadonlyFiles()) { - final String className = clazz != null ? clazz.getQualifiedName() : myElement.getContainingFile().getName(); + if (status.hasReadonlyFiles()) { + final String className = clazz != null ? clazz.getQualifiedName() : myElement.getContainingFile().getName(); - Messages.showMessageDialog( - project, - DevKitLocalize.inspectionsRegistrationProblemsQuickfixReadOnly(className).get(), - getName(), - UIUtil.getErrorIcon() - ); - return; - } - } + Messages.showMessageDialog( + project, + DevKitLocalize.inspectionsRegistrationProblemsQuickfixReadOnly(className).get(), + getName(), + UIUtil.getErrorIcon() + ); + return; + } + } - try { - doFix(project, descriptor, external); - } - catch (IncorrectOperationException e) { - Logger.getInstance("#" + getClass().getName()).error(e); + try { + doFix(project, descriptor, external); + } + catch (IncorrectOperationException e) { + Logger.getInstance("#" + getClass().getName()).error(e); + } } - } - protected abstract void doFix(Project project, ProblemDescriptor descriptor, boolean external) throws IncorrectOperationException; + protected abstract void doFix(Project project, ProblemDescriptor descriptor, boolean external) throws IncorrectOperationException; } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ChangeToPairCreateQuickFix.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ChangeToPairCreateQuickFix.java index 516ed055..377a9f4f 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ChangeToPairCreateQuickFix.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ChangeToPairCreateQuickFix.java @@ -32,22 +32,22 @@ * @author Konstantin Bulenkov */ public class ChangeToPairCreateQuickFix extends LocalQuickFixBase { - public ChangeToPairCreateQuickFix() { - super("Change to Pair.create(..., ...)"); - } + public ChangeToPairCreateQuickFix() { + super("Change to Pair.create(..., ...)"); + } - @Override - @RequiredReadAction - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - PsiElement element = descriptor.getPsiElement(); - if (element == null) { - return; + @Override + @RequiredReadAction + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + PsiElement element = descriptor.getPsiElement(); + if (element == null) { + return; + } + String text = element.getText(); + String newText = Pair.class.getName() + ".create(" + text.substring(text.indexOf('(') + 1); + PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); + PsiExpression expression = factory.createExpressionFromText(newText, element.getContext()); + PsiElement newElement = element.replace(expression); + JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); } - String text = element.getText(); - String newText = Pair.class.getName() + ".create(" + text.substring(text.indexOf('(') + 1); - PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); - PsiExpression expression = factory.createExpressionFromText(newText, element.getContext()); - PsiElement newElement = element.replace(expression); - JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); - } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToGrayQuickFix.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToGrayQuickFix.java index 37bdd1f6..cff1739b 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToGrayQuickFix.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToGrayQuickFix.java @@ -19,6 +19,7 @@ import com.intellij.java.language.psi.PsiElementFactory; import com.intellij.java.language.psi.PsiExpression; import com.intellij.java.language.psi.codeStyle.JavaCodeStyleManager; +import consulo.annotation.access.RequiredReadAction; import consulo.language.editor.inspection.LocalQuickFixBase; import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiElement; @@ -30,19 +31,20 @@ * @author Konstantin Bulenkov */ public class ConvertToGrayQuickFix extends LocalQuickFixBase { - private final int myNum; + private final int myNum; - public ConvertToGrayQuickFix(int num) { - super("Convert to Gray._" + num, "Convert to Gray"); - myNum = num; - } + public ConvertToGrayQuickFix(int num) { + super("Convert to Gray._" + num, "Convert to Gray"); + myNum = num; + } - @Override - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - final PsiElement element = descriptor.getPsiElement(); - final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); - final PsiExpression expression = factory.createExpressionFromText("com.intellij.ui.Gray._" + myNum, element.getContext()); - final PsiElement newElement = element.replace(expression); - JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); - } + @Override + @RequiredReadAction + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + final PsiElement element = descriptor.getPsiElement(); + final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); + final PsiExpression expression = factory.createExpressionFromText("com.intellij.ui.Gray._" + myNum, element.getContext()); + final PsiElement newElement = element.replace(expression); + JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToJBColorConstantQuickFix.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToJBColorConstantQuickFix.java index 59dab72e..cd323e9d 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToJBColorConstantQuickFix.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToJBColorConstantQuickFix.java @@ -19,6 +19,7 @@ import com.intellij.java.language.psi.PsiElementFactory; import com.intellij.java.language.psi.PsiExpression; import com.intellij.java.language.psi.codeStyle.JavaCodeStyleManager; +import consulo.annotation.access.RequiredReadAction; import consulo.language.editor.inspection.LocalQuickFixBase; import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiElement; @@ -31,20 +32,21 @@ * @author Konstantin Bulenkov */ public class ConvertToJBColorConstantQuickFix extends LocalQuickFixBase { - private final String myConstantName; + private final String myConstantName; - public ConvertToJBColorConstantQuickFix(String constantName) { - super("Convert to JBColor." + constantName, "Convert to JBColor"); - myConstantName = constantName; - } + public ConvertToJBColorConstantQuickFix(String constantName) { + super("Convert to JBColor." + constantName, "Convert to JBColor"); + myConstantName = constantName; + } - @Override - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - final PsiElement element = descriptor.getPsiElement(); - final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); - final String jbColorConstant = String.format("%s.%s", JBColor.class.getName(), myConstantName); - final PsiExpression expression = factory.createExpressionFromText(jbColorConstant, element.getContext()); - final PsiElement newElement = element.replace(expression); - JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); - } + @Override + @RequiredReadAction + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + final PsiElement element = descriptor.getPsiElement(); + final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); + final String jbColorConstant = String.format("%s.%s", JBColor.class.getName(), myConstantName); + final PsiExpression expression = factory.createExpressionFromText(jbColorConstant, element.getContext()); + final PsiElement newElement = element.replace(expression); + JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToJBColorQuickFix.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToJBColorQuickFix.java index 892fe17b..d3e73873 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToJBColorQuickFix.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToJBColorQuickFix.java @@ -19,6 +19,7 @@ import com.intellij.java.language.psi.PsiElementFactory; import com.intellij.java.language.psi.PsiExpression; import com.intellij.java.language.psi.codeStyle.JavaCodeStyleManager; +import consulo.annotation.access.RequiredReadAction; import consulo.codeEditor.Editor; import consulo.language.editor.inspection.LocalQuickFixBase; import consulo.language.editor.inspection.ProblemDescriptor; @@ -33,22 +34,23 @@ * @author Konstantin Bulenkov */ public class ConvertToJBColorQuickFix extends LocalQuickFixBase { - public ConvertToJBColorQuickFix() { - super("Convert to JBColor"); - } + public ConvertToJBColorQuickFix() { + super("Convert to JBColor"); + } - @Override - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - final PsiElement element = descriptor.getPsiElement(); - final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); - final String newJBColor = String.format("new %s(%s, new java.awt.Color())", JBColor.class.getName(), element.getText()); - final PsiExpression expression = factory.createExpressionFromText(newJBColor, element.getContext()); - final PsiElement newElement = element.replace(expression); - final PsiElement el = JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); - final int offset = el.getTextOffset() + el.getText().length() - 2; - final Editor editor = PsiUtilBase.findEditor(el); - if (editor != null) { - editor.getCaretModel().moveToOffset(offset); + @Override + @RequiredReadAction + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + final PsiElement element = descriptor.getPsiElement(); + final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); + final String newJBColor = String.format("new %s(%s, new java.awt.Color())", JBColor.class.getName(), element.getText()); + final PsiExpression expression = factory.createExpressionFromText(newJBColor, element.getContext()); + final PsiElement newElement = element.replace(expression); + final PsiElement el = JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); + final int offset = el.getTextOffset() + el.getText().length() - 2; + final Editor editor = PsiUtilBase.findEditor(el); + if (editor != null) { + editor.getCaretModel().moveToOffset(offset); + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToJBInsetsQuickFix.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToJBInsetsQuickFix.java index b2af2c37..0245c0e6 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToJBInsetsQuickFix.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ConvertToJBInsetsQuickFix.java @@ -17,6 +17,7 @@ import com.intellij.java.language.psi.*; import com.intellij.java.language.psi.codeStyle.JavaCodeStyleManager; +import consulo.annotation.access.RequiredReadAction; import consulo.codeEditor.Editor; import consulo.language.editor.inspection.LocalQuickFixBase; import consulo.language.editor.inspection.ProblemDescriptor; @@ -31,69 +32,70 @@ * @author Konstantin Bulenkov */ public class ConvertToJBInsetsQuickFix extends LocalQuickFixBase { - public ConvertToJBInsetsQuickFix() { - super("Convert to JBUI.insets(...)"); - } + public ConvertToJBInsetsQuickFix() { + super("Convert to JBUI.insets(...)"); + } - @Override - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - final PsiNewExpression newExpression = (PsiNewExpression)descriptor.getPsiElement(); - PsiExpressionList list = newExpression.getArgumentList(); - String text = null; - if (list != null && list.getExpressions().length == 4) { - String top = list.getExpressions()[0].getText(); - String left = list.getExpressions()[1].getText(); - String bottom = list.getExpressions()[2].getText(); - String right = list.getExpressions()[3].getText(); + @Override + @RequiredReadAction + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + final PsiNewExpression newExpression = (PsiNewExpression)descriptor.getPsiElement(); + PsiExpressionList list = newExpression.getArgumentList(); + String text = null; + if (list != null && list.getExpressions().length == 4) { + String top = list.getExpressions()[0].getText(); + String left = list.getExpressions()[1].getText(); + String bottom = list.getExpressions()[2].getText(); + String right = list.getExpressions()[3].getText(); - if (isZero(top, left, bottom, right)) { - text = "emptyInsets()"; - } - else if (isZero(left, bottom, right)) { - text = "insetsTop(" + top + ")"; - } - else if (isZero(top, bottom, right)) { - text = "insetsLeft(" + left + ")"; - } - else if (isZero(top, left, right)) { - text = "insetsBottom(" + bottom + ")"; - } - else if (isZero(top, left, bottom)) { - text = "insetsRight(" + right + ")"; - } - else if (top.equals(left) && left.equals(bottom) && bottom.equals(right) && right.equals(top)) { - text = "insets(" + top + ")"; - } - else if (top.equals(bottom) && right.equals(left)) { - text = String.format("insets(%s, %s)", top, left); - } - else { - text = String.format("insets(%s, %s, %s, %s)", top, left, bottom, right); - } + if (isZero(top, left, bottom, right)) { + text = "emptyInsets()"; + } + else if (isZero(left, bottom, right)) { + text = "insetsTop(" + top + ")"; + } + else if (isZero(top, bottom, right)) { + text = "insetsLeft(" + left + ")"; + } + else if (isZero(top, left, right)) { + text = "insetsBottom(" + bottom + ")"; + } + else if (isZero(top, left, bottom)) { + text = "insetsRight(" + right + ")"; + } + else if (top.equals(left) && left.equals(bottom) && bottom.equals(right) && right.equals(top)) { + text = "insets(" + top + ")"; + } + else if (top.equals(bottom) && right.equals(left)) { + text = String.format("insets(%s, %s)", top, left); + } + else { + text = String.format("insets(%s, %s, %s, %s)", top, left, bottom, right); + } - text = JBUI.class.getName() + "." + text; + text = JBUI.class.getName() + "." + text; - final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); - final PsiExpression expression = factory.createExpressionFromText(text, newExpression.getContext()); - final PsiElement newElement = newExpression.replace(expression); - final PsiElement el = JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); - final int offset = el.getTextOffset() + el.getText().length() - 2; - final Editor editor = PsiUtilBase.findEditor(el); - if (editor != null) { - editor.getCaretModel().moveToOffset(offset); - } + final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); + final PsiExpression expression = factory.createExpressionFromText(text, newExpression.getContext()); + final PsiElement newElement = newExpression.replace(expression); + final PsiElement el = JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); + final int offset = el.getTextOffset() + el.getText().length() - 2; + final Editor editor = PsiUtilBase.findEditor(el); + if (editor != null) { + editor.getCaretModel().moveToOffset(offset); + } + } } - } - private static boolean isZero(String... args) { - if (args.length == 0) { - return false; - } - for (String arg : args) { - if (!"0".equals(arg)) { - return false; - } + private static boolean isZero(String... args) { + if (args.length == 0) { + return false; + } + for (String arg : args) { + if (!"0".equals(arg)) { + return false; + } + } + return true; } - return true; - } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/CreateHtmlDescriptionFix.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/CreateHtmlDescriptionFix.java index 3a35c0ae..ad511346 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/CreateHtmlDescriptionFix.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/CreateHtmlDescriptionFix.java @@ -44,7 +44,6 @@ import consulo.util.collection.ArrayUtil; import consulo.virtualFileSystem.VirtualFile; import consulo.virtualFileSystem.util.VirtualFileUtil; -import org.jetbrains.annotations.NonNls; import org.jetbrains.idea.devkit.inspections.InspectionDescriptionNotFoundInspection; import org.jetbrains.idea.devkit.inspections.IntentionDescriptionNotFoundInspection; @@ -59,140 +58,141 @@ * @author Konstantin Bulenkov */ public class CreateHtmlDescriptionFix implements LocalQuickFix, Iconable { - private final String myFilename; - private final Module myModule; - @NonNls - private static final String TEMPLATE_NAME = "InspectionDescription.html"; - private final boolean isIntention; + private final String myFilename; + private final Module myModule; + private static final String TEMPLATE_NAME = "InspectionDescription.html"; + private final boolean isIntention; - public CreateHtmlDescriptionFix(String filename, Module module, boolean isIntention) { - myModule = module; - this.isIntention = isIntention; - myFilename = isIntention ? filename : filename + ".html"; - } - - @Override - @Nonnull - public String getName() { - return DevKitLocalize.createDescriptionFile().get(); - } + public CreateHtmlDescriptionFix(String filename, Module module, boolean isIntention) { + myModule = module; + this.isIntention = isIntention; + myFilename = isIntention ? filename : filename + ".html"; + } - @Override - @Nonnull - public String getFamilyName() { - return "DevKit"; - } + @Override + @Nonnull + public String getName() { + return DevKitLocalize.createDescriptionFile().get(); + } - @Override - @RequiredUIAccess - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - final List virtualFiles = - isIntention ? IntentionDescriptionNotFoundInspection.getPotentialRoots(myModule) : InspectionDescriptionNotFoundInspection.getPotentialRoots( - myModule); - final VirtualFile[] roots = prepare(VirtualFileUtil.toVirtualFileArray(virtualFiles)); - if (roots.length == 1) { - Application.get().runWriteAction(() -> createDescription(roots[0])); + @Override + @Nonnull + public String getFamilyName() { + return "DevKit"; } - else { - List options = new ArrayList<>(); - for (VirtualFile file : roots) { - String path = file.getPresentableUrl() + File.separator + getDescriptionFolderName() + File.separator + myFilename; - if (isIntention) { - path += File.separator + "description.html"; + + @Override + @RequiredUIAccess + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + final List virtualFiles = + isIntention ? IntentionDescriptionNotFoundInspection.getPotentialRoots(myModule) : InspectionDescriptionNotFoundInspection.getPotentialRoots( + myModule); + final VirtualFile[] roots = prepare(VirtualFileUtil.toVirtualFileArray(virtualFiles)); + if (roots.length == 1) { + Application.get().runWriteAction(() -> createDescription(roots[0])); + } + else { + List options = new ArrayList<>(); + for (VirtualFile file : roots) { + String path = file.getPresentableUrl() + File.separator + getDescriptionFolderName() + File.separator + myFilename; + if (isIntention) { + path += File.separator + "description.html"; + } + options.add(path); + } + final JBList files = new JBList<>(ArrayUtil.toStringArray(options)); + files.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + final JBPopup popup = JBPopupFactory.getInstance() + .createPopupChooserBuilder(options) + .setTitle(DevKitLocalize.selectTargetLocationOfDescription(myFilename).get()) + .setItemChosenCallback(desc -> { + final int index = files.getSelectedIndex(); + if (0 <= index && index < roots.length) { + //noinspection RequiredXAction + Application.get().runWriteAction(() -> createDescription(roots[index])); + } + }) + .createPopup(); + final Editor editor = FileEditorManager.getInstance(myModule.getProject()).getSelectedTextEditor(); + if (editor == null) { + return; + } + EditorPopupHelper.getInstance().showPopupInBestPositionFor(editor, popup); } - options.add(path); - } - final JBList files = new JBList(ArrayUtil.toStringArray(options)); - files.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - final JBPopup popup = JBPopupFactory.getInstance() - .createPopupChooserBuilder(options) - .setTitle(DevKitLocalize.selectTargetLocationOfDescription(myFilename).get()) - .setItemChosenCallback(desc -> { - final int index = files.getSelectedIndex(); - if (0 <= index && index < roots.length) { - //noinspection RequiredXAction - Application.get().runWriteAction(() -> createDescription(roots[index])); - } - }) - .createPopup(); - final Editor editor = FileEditorManager.getInstance(myModule.getProject()).getSelectedTextEditor(); - if (editor == null) { - return; - } - EditorPopupHelper.getInstance().showPopupInBestPositionFor(editor, popup); } - } - @RequiredReadAction - private void createDescription(VirtualFile root) { - if (!root.isDirectory()) { - return; - } - final PsiManager psiManager = PsiManager.getInstance(myModule.getProject()); - final PsiDirectory psiRoot = psiManager.findDirectory(root); - PsiDirectory descrRoot = null; - if (psiRoot == null) { - return; - } - for (PsiDirectory dir : psiRoot.getSubdirectories()) { - if (getDescriptionFolderName().equals(dir.getName())) { - descrRoot = dir; - break; - } - } + @RequiredReadAction + private void createDescription(VirtualFile root) { + if (!root.isDirectory()) { + return; + } + final PsiManager psiManager = PsiManager.getInstance(myModule.getProject()); + final PsiDirectory psiRoot = psiManager.findDirectory(root); + PsiDirectory descrRoot = null; + if (psiRoot == null) { + return; + } + for (PsiDirectory dir : psiRoot.getSubdirectories()) { + if (getDescriptionFolderName().equals(dir.getName())) { + descrRoot = dir; + break; + } + } - try { - descrRoot = descrRoot == null ? psiRoot.createSubdirectory(getDescriptionFolderName()) : descrRoot; - if (isIntention) { - PsiDirectory dir = descrRoot.findSubdirectory(myFilename); - if (dir == null) { - descrRoot = descrRoot.createSubdirectory(myFilename); + try { + descrRoot = descrRoot == null ? psiRoot.createSubdirectory(getDescriptionFolderName()) : descrRoot; + if (isIntention) { + PsiDirectory dir = descrRoot.findSubdirectory(myFilename); + if (dir == null) { + descrRoot = descrRoot.createSubdirectory(myFilename); + } + } + final FileTemplate descrTemplate = FileTemplateManager.getInstance(myModule.getProject()).getJ2eeTemplate(TEMPLATE_NAME); + final PsiElement template = FileTemplateUtil.createFromTemplate( + descrTemplate, + isIntention ? "description.html" : myFilename, + (Map)null, + descrRoot + ); + if (template instanceof PsiFile) { + final VirtualFile file = ((PsiFile)template).getVirtualFile(); + if (file != null) { + FileEditorManager.getInstance(myModule.getProject()).openFile(file, true); + } + } } - } - final FileTemplate descrTemplate = FileTemplateManager.getInstance(myModule.getProject()).getJ2eeTemplate(TEMPLATE_NAME); - final PsiElement template = FileTemplateUtil.createFromTemplate(descrTemplate, - isIntention ? "description.html" : myFilename, - (Map)null, - descrRoot); - if (template instanceof PsiFile) { - final VirtualFile file = ((PsiFile)template).getVirtualFile(); - if (file != null) { - FileEditorManager.getInstance(myModule.getProject()).openFile(file, true); + catch (Exception e) {// } - } - } - catch (Exception e) {// } - } - @Override - public Image getIcon(int flags) { - return ImageEffects.layered(AllIcons.FileTypes.Html, AllIcons.Actions.New); - } - - private VirtualFile[] prepare(VirtualFile[] roots) { - List found = new ArrayList<>(); - for (VirtualFile root : roots) { - if (containsDescriptionDir(root)) { - found.add(root); - } + @Override + public Image getIcon(int flags) { + return ImageEffects.layered(AllIcons.FileTypes.Html, AllIcons.Actions.New); } - return found.size() > 0 ? VirtualFileUtil.toVirtualFileArray(found) : roots; - } - private boolean containsDescriptionDir(VirtualFile root) { - if (!root.isDirectory()) { - return false; + private VirtualFile[] prepare(VirtualFile[] roots) { + List found = new ArrayList<>(); + for (VirtualFile root : roots) { + if (containsDescriptionDir(root)) { + found.add(root); + } + } + return found.size() > 0 ? VirtualFileUtil.toVirtualFileArray(found) : roots; } - for (VirtualFile file : root.getChildren()) { - if (file.isDirectory() && getDescriptionFolderName().equals(file.getName())) { - return true; - } + + private boolean containsDescriptionDir(VirtualFile root) { + if (!root.isDirectory()) { + return false; + } + for (VirtualFile file : root.getChildren()) { + if (file.isDirectory() && getDescriptionFolderName().equals(file.getName())) { + return true; + } + } + return false; } - return false; - } - private String getDescriptionFolderName() { - return isIntention ? "intentionDescriptions" : "inspectionDescriptions"; - } + private String getDescriptionFolderName() { + return isIntention ? "intentionDescriptions" : "inspectionDescriptions"; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ExtensionPointCandidate.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ExtensionPointCandidate.java index 7267d65f..60a4afdb 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ExtensionPointCandidate.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/ExtensionPointCandidate.java @@ -19,27 +19,27 @@ * @author yole */ class ExtensionPointCandidate { - public final String epName; - public final String attributeName; - public final String tagName; - public final String beanClassName; + public final String epName; + public final String attributeName; + public final String tagName; + public final String beanClassName; - ExtensionPointCandidate(String epName, String attributeName, String tagName, String beanClassName) { - this.epName = epName; - this.attributeName = attributeName; - this.tagName = tagName; - this.beanClassName = beanClassName; - } + ExtensionPointCandidate(String epName, String attributeName, String tagName, String beanClassName) { + this.epName = epName; + this.attributeName = attributeName; + this.tagName = tagName; + this.beanClassName = beanClassName; + } - ExtensionPointCandidate(String epName) { - this.epName = epName; - this.attributeName = "implementation"; - this.tagName = null; - this.beanClassName = null; - } + ExtensionPointCandidate(String epName) { + this.epName = epName; + this.attributeName = "implementation"; + this.tagName = null; + this.beanClassName = null; + } - @Override - public String toString() { - return epName; - } + @Override + public String toString() { + return epName; + } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/RegisterActionFix.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/RegisterActionFix.java index bf0af03e..c1383157 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/RegisterActionFix.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/RegisterActionFix.java @@ -20,6 +20,7 @@ import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.util.IncorrectOperationException; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.xml.psi.xml.XmlFile; import org.jetbrains.idea.devkit.actions.NewActionDialog; import org.jetbrains.idea.devkit.util.ActionType; @@ -27,36 +28,40 @@ import javax.annotation.Nonnull; public class RegisterActionFix extends AbstractRegisterFix { - private NewActionDialog myDialog; + private NewActionDialog myDialog; - public RegisterActionFix(PsiClass klass) { - super(klass); - } + public RegisterActionFix(PsiClass klass) { + super(klass); + } - protected String getType() { - return DevKitLocalize.newMenuActionText().get(); - } + @Override + protected String getType() { + return DevKitLocalize.newMenuActionText().get(); + } - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - try { - myDialog = new NewActionDialog(myClass); - myDialog.show(); + @Override + @RequiredUIAccess + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + try { + myDialog = new NewActionDialog(myClass); + myDialog.show(); - if (myDialog.isOK()) { - super.applyFix(project, descriptor); - } + if (myDialog.isOK()) { + super.applyFix(project, descriptor); + } + } + finally { + myDialog = null; + } } - finally { - myDialog = null; - } - } - public void patchPluginXml(XmlFile pluginXml, PsiClass aClass) throws IncorrectOperationException { - if (ActionType.GROUP.isOfType(aClass)) { - ActionType.GROUP.patchPluginXml(pluginXml, aClass, myDialog); - } - else { - ActionType.ACTION.patchPluginXml(pluginXml, aClass, myDialog); + @Override + public void patchPluginXml(XmlFile pluginXml, PsiClass aClass) throws IncorrectOperationException { + if (ActionType.GROUP.isOfType(aClass)) { + ActionType.GROUP.patchPluginXml(pluginXml, aClass, myDialog); + } + else { + ActionType.ACTION.patchPluginXml(pluginXml, aClass, myDialog); + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/UseCoupleQuickFix.java b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/UseCoupleQuickFix.java index 299175c9..32956ac5 100644 --- a/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/UseCoupleQuickFix.java +++ b/plugin/src/main/java/org/jetbrains/idea/devkit/inspections/quickfix/UseCoupleQuickFix.java @@ -33,28 +33,28 @@ * @author Konstantin Bulenkov */ public class UseCoupleQuickFix extends LocalQuickFixBase { - - public UseCoupleQuickFix(String text) { - super(text); - } - - @Override - @RequiredReadAction - public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { - final PsiElement element = descriptor.getPsiElement(); - final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); - final PsiElement newElement; - if (element instanceof PsiTypeElement psiTypeElement) { - final String canonicalText = psiTypeElement.getType().getCanonicalText(); - final String type = canonicalText.substring(canonicalText.indexOf('<') + 1, canonicalText.indexOf(',')); - final PsiTypeElement newType = factory.createTypeElementFromText(Couple.class.getName() + "<" + type + ">", element.getContext()); - newElement = element.replace(newType); + public UseCoupleQuickFix(String text) { + super(text); } - else { - final String text = Couple.class.getName() + ".of" + element.getText().substring("Pair.create".length()); - final PsiExpression expression = factory.createExpressionFromText(text, element.getContext()); - newElement = element.replace(expression); + + @Override + @RequiredReadAction + public void applyFix(@Nonnull Project project, @Nonnull ProblemDescriptor descriptor) { + final PsiElement element = descriptor.getPsiElement(); + final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); + final PsiElement newElement; + if (element instanceof PsiTypeElement psiTypeElement) { + final String canonicalText = psiTypeElement.getType().getCanonicalText(); + final String type = canonicalText.substring(canonicalText.indexOf('<') + 1, canonicalText.indexOf(',')); + final PsiTypeElement newType = + factory.createTypeElementFromText(Couple.class.getName() + "<" + type + ">", element.getContext()); + newElement = element.replace(newType); + } + else { + final String text = Couple.class.getName() + ".of" + element.getText().substring("Pair.create".length()); + final PsiExpression expression = factory.createExpressionFromText(text, element.getContext()); + newElement = element.replace(expression); + } + JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); } - JavaCodeStyleManager.getInstance(project).shortenClassReferences(newElement); - } } \ No newline at end of file