use of com.intellij.codeInsight.intention.AddAnnotationFix in project android by JetBrains.
the class AddTargetApiQuickFix method apply.
@SuppressWarnings("unchecked")
@Override
public void apply(@NotNull PsiElement startElement, @NotNull PsiElement endElement, @NotNull AndroidQuickfixContexts.Context context) {
// Find nearest method or class; can't add @TargetApi on modifier list owners like variable declarations
@SuppressWarnings("unchecked") PsiModifierListOwner container = PsiTreeUtil.getParentOfType(startElement, PsiMethod.class, PsiClass.class);
if (container == null) {
// XML file? Set attribute
XmlTag element = PsiTreeUtil.getParentOfType(startElement, XmlTag.class, false);
if (element != null) {
XmlFile file = PsiTreeUtil.getParentOfType(element, XmlFile.class, false);
if (file != null) {
AndroidResourceUtil.ensureNamespaceImported(file, TOOLS_URI, null);
String codeName = SdkVersionInfo.getBuildCode(myApi);
if (codeName == null) {
codeName = Integer.toString(myApi);
} else {
codeName = codeName.toLowerCase(Locale.US);
}
element.setAttribute(ATTR_TARGET_API, TOOLS_URI, codeName);
}
}
return;
}
while (container != null && container instanceof PsiAnonymousClass) {
container = PsiTreeUtil.getParentOfType(container, PsiMethod.class, true, PsiClass.class);
}
if (container == null) {
return;
}
if (!FileModificationService.getInstance().preparePsiElementForWrite(container)) {
return;
}
final PsiModifierList modifierList = container.getModifierList();
if (modifierList != null) {
Project project = startElement.getProject();
PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
String fqcn = myRequiresApi ? REQUIRES_API_ANNOTATION : FQCN_TARGET_API;
String annotationText;
if (myRequiresApi) {
annotationText = "@" + fqcn + "(api=" + getAnnotationValue(true) + ")";
} else {
annotationText = "@" + fqcn + "(" + getAnnotationValue(true) + ")";
}
PsiAnnotation newAnnotation = elementFactory.createAnnotationFromText(annotationText, container);
PsiAnnotation annotation = AnnotationUtil.findAnnotation(container, FQCN_TARGET_API);
if (annotation != null && annotation.isPhysical()) {
annotation.replace(newAnnotation);
} else {
PsiNameValuePair[] attributes = newAnnotation.getParameterList().getAttributes();
AddAnnotationFix fix = new AddAnnotationFix(fqcn, container, attributes);
fix.invoke(project, null, /*editor*/
container.getContainingFile());
}
}
}
Aggregations