use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.
the class ImportToggleAliasIntention method doInvoke.
@Override
public void doInvoke(@NotNull final Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
// sanity check: isAvailable must have set it.
final IntentionState state = IntentionState.fromContext(editor, file);
//
// we set in in the source
final String target_name;
// we replace it in the source
final String remove_name;
PyReferenceExpression reference = sure(state.myImportElement.getImportReferenceExpression());
// search for references to us with the right name
try {
String imported_name = PyPsiUtils.toPath(reference);
if (state.myAlias != null) {
// have to remove alias, rename everything to original
target_name = imported_name;
remove_name = state.myAlias;
} else {
// ask for and add alias
Application application = ApplicationManager.getApplication();
if (application != null && !application.isUnitTestMode()) {
String alias = Messages.showInputDialog(project, PyBundle.message("INTN.alias.for.$0.dialog.title", imported_name), "Add Alias", Messages.getQuestionIcon(), "", new InputValidator() {
@Override
public boolean checkInput(String inputString) {
return PyNames.isIdentifier(inputString);
}
@Override
public boolean canClose(String inputString) {
return PyNames.isIdentifier(inputString);
}
});
if (alias == null) {
return;
}
target_name = alias;
} else {
// test mode
target_name = "alias";
}
remove_name = imported_name;
}
final PsiElement referee = reference.getReference().resolve();
if (referee != null && imported_name != null) {
final Collection<PsiReference> references = new ArrayList<>();
final ScopeOwner scope = PsiTreeUtil.getParentOfType(state.myImportElement, ScopeOwner.class);
PsiTreeUtil.processElements(scope, new PsiElementProcessor() {
public boolean execute(@NotNull PsiElement element) {
getReferences(element);
if (element instanceof PyStringLiteralExpression) {
final PsiLanguageInjectionHost host = (PsiLanguageInjectionHost) element;
final List<Pair<PsiElement, TextRange>> files = InjectedLanguageManager.getInstance(project).getInjectedPsiFiles(host);
if (files != null) {
for (Pair<PsiElement, TextRange> pair : files) {
final PsiElement first = pair.getFirst();
if (first instanceof ScopeOwner) {
final ScopeOwner scopeOwner = (ScopeOwner) first;
PsiTreeUtil.processElements(scopeOwner, new PsiElementProcessor() {
public boolean execute(@NotNull PsiElement element) {
getReferences(element);
return true;
}
});
}
}
}
}
return true;
}
private void getReferences(PsiElement element) {
if (element instanceof PyReferenceExpression && PsiTreeUtil.getParentOfType(element, PyImportElement.class) == null) {
PyReferenceExpression ref = (PyReferenceExpression) element;
if (remove_name.equals(PyPsiUtils.toPath(ref))) {
// filter out other names that might resolve to our target
PsiElement resolved = ref.getReference().resolve();
if (resolved == referee)
references.add(ref.getReference());
}
}
}
});
// no references here is OK by us.
if (showConflicts(project, findDefinitions(target_name, references, Collections.<PsiElement>emptySet()), target_name, null)) {
// got conflicts
return;
}
// alter the import element
PyElementGenerator generator = PyElementGenerator.getInstance(project);
final LanguageLevel languageLevel = LanguageLevel.forElement(state.myImportElement);
if (state.myAlias != null) {
// remove alias
ASTNode node = sure(state.myImportElement.getNode());
ASTNode parent = sure(node.getTreeParent());
// this is the reference
node = sure(node.getFirstChildNode());
// things past the reference: space, 'as', and alias
node = sure(node.getTreeNext());
parent.removeRange(node, null);
} else {
// add alias
ASTNode my_ielt_node = sure(state.myImportElement.getNode());
PyImportElement fountain = generator.createFromText(languageLevel, PyImportElement.class, "import foo as " + target_name, new int[] { 0, 2 });
// at import elt
ASTNode graft_node = sure(fountain.getNode());
// at ref
graft_node = sure(graft_node.getFirstChildNode());
// space
graft_node = sure(graft_node.getTreeNext());
my_ielt_node.addChild((ASTNode) graft_node.clone());
// 'as'
graft_node = sure(graft_node.getTreeNext());
my_ielt_node.addChild((ASTNode) graft_node.clone());
// space
graft_node = sure(graft_node.getTreeNext());
my_ielt_node.addChild((ASTNode) graft_node.clone());
// alias
graft_node = sure(graft_node.getTreeNext());
my_ielt_node.addChild((ASTNode) graft_node.clone());
}
// alter references
for (PsiReference ref : references) {
ASTNode ref_name_node = sure(sure(ref.getElement()).getNode());
ASTNode parent = sure(ref_name_node.getTreeParent());
ASTNode new_name_node = generator.createExpressionFromText(languageLevel, target_name).getNode();
assert new_name_node != null;
parent.replaceChild(ref_name_node, new_name_node);
}
}
} catch (IncorrectOperationException ignored) {
PyUtil.showBalloon(project, PyBundle.message("QFIX.action.failed"), MessageType.WARNING);
}
}
use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.
the class GrCreateSubclassAction method createSubclassGroovy.
@Nullable
public static PsiClass createSubclassGroovy(final GrTypeDefinition psiClass, final PsiDirectory targetDirectory, final String className) {
final Project project = psiClass.getProject();
final Ref<GrTypeDefinition> targetClass = new Ref<>();
new WriteCommandAction(project, getTitle(psiClass), getTitle(psiClass)) {
@Override
protected void run(@NotNull Result result) throws Throwable {
IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
final GrTypeParameterList oldTypeParameterList = psiClass.getTypeParameterList();
try {
targetClass.set(CreateClassActionBase.createClassByType(targetDirectory, className, PsiManager.getInstance(project), psiClass, GroovyTemplates.GROOVY_CLASS, true));
} catch (final IncorrectOperationException e) {
ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(project, CodeInsightBundle.message("intention.error.cannot.create.class.message", className) + "\n" + e.getLocalizedMessage(), CodeInsightBundle.message("intention.error.cannot.create.class.title")));
return;
}
startTemplate(oldTypeParameterList, project, psiClass, targetClass.get(), false);
}
}.execute();
if (targetClass.get() == null)
return null;
if (!ApplicationManager.getApplication().isUnitTestMode() && !psiClass.hasTypeParameters()) {
final Editor editor = CodeInsightUtil.positionCursorAtLBrace(project, targetClass.get().getContainingFile(), targetClass.get());
if (editor == null)
return targetClass.get();
chooseAndImplement(psiClass, project, targetClass.get(), editor);
}
return targetClass.get();
}
use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.
the class GrIntroduceClosureParameterProcessor method insertDeclaration.
private GrVariableDeclaration insertDeclaration(GrVariable original, GrVariableDeclaration declaration) {
if (original instanceof GrField) {
final PsiClass containingClass = ((GrField) original).getContainingClass();
LOG.assertTrue(containingClass != null);
return (GrVariableDeclaration) containingClass.addBefore(declaration, original.getParent());
}
final GrStatementOwner block;
if (original instanceof PsiParameter) {
final PsiElement container = original.getParent().getParent();
if (container instanceof GrMethod) {
block = ((GrMethod) container).getBlock();
} else if (container instanceof GrClosableBlock) {
block = (GrCodeBlock) container;
} else if (container instanceof GrForStatement) {
final GrStatement body = ((GrForStatement) container).getBody();
if (body instanceof GrBlockStatement) {
block = ((GrBlockStatement) body).getBlock();
} else {
GrBlockStatement blockStatement = myFactory.createBlockStatement();
LOG.assertTrue(blockStatement != null);
if (body != null) {
blockStatement.getBlock().addStatementBefore((GrStatement) body.copy(), null);
blockStatement = (GrBlockStatement) body.replace(blockStatement);
} else {
blockStatement = (GrBlockStatement) container.add(blockStatement);
}
block = blockStatement.getBlock();
}
} else {
throw new IncorrectOperationException();
}
LOG.assertTrue(block != null);
return (GrVariableDeclaration) block.addStatementBefore(declaration, null);
}
PsiElement parent = original.getParent();
LOG.assertTrue(parent instanceof GrVariableDeclaration);
final PsiElement pparent = parent.getParent();
if (pparent instanceof GrIfStatement) {
if (((GrIfStatement) pparent).getThenBranch() == parent) {
block = ((GrIfStatement) pparent).replaceThenBranch(myFactory.createBlockStatement()).getBlock();
} else {
block = ((GrIfStatement) pparent).replaceElseBranch(myFactory.createBlockStatement()).getBlock();
}
parent = block.addStatementBefore(((GrVariableDeclaration) parent), null);
} else if (pparent instanceof GrLoopStatement) {
block = ((GrLoopStatement) pparent).replaceBody(myFactory.createBlockStatement()).getBlock();
parent = block.addStatementBefore(((GrVariableDeclaration) parent), null);
} else {
LOG.assertTrue(pparent instanceof GrStatementOwner);
block = (GrStatementOwner) pparent;
}
return (GrVariableDeclaration) block.addStatementBefore(declaration, (GrStatement) parent);
}
use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.
the class GroovyIntroduceParameterMethodUsagesProcessor method processChangeMethodSignature.
@Override
public boolean processChangeMethodSignature(IntroduceParameterData data, UsageInfo usage, UsageInfo[] usages) throws IncorrectOperationException {
if (!(usage.getElement() instanceof GrMethod) || !isGroovyUsage(usage))
return true;
GrMethod method = (GrMethod) usage.getElement();
final FieldConflictsResolver fieldConflictsResolver = new FieldConflictsResolver(data.getParameterName(), method.getBlock());
final MethodJavaDocHelper javaDocHelper = new MethodJavaDocHelper(method);
final PsiParameter[] parameters = method.getParameterList().getParameters();
data.getParametersToRemove().forEachDescending(new TIntProcedure() {
@Override
public boolean execute(final int paramNum) {
try {
PsiParameter param = parameters[paramNum];
PsiDocTag tag = javaDocHelper.getTagForParameter(param);
if (tag != null) {
tag.delete();
}
param.delete();
} catch (IncorrectOperationException e) {
LOG.error(e);
}
return true;
}
});
addParameter(method, javaDocHelper, data.getForcedType(), data.getParameterName(), data.isDeclareFinal(), data.getProject());
fieldConflictsResolver.fix();
return false;
}
use of com.intellij.util.IncorrectOperationException in project intellij-community by JetBrains.
the class CustomCreateProperty method generateCreateComponentsMethod.
public static void generateCreateComponentsMethod(final PsiClass aClass) {
final PsiFile psiFile = aClass.getContainingFile();
if (psiFile == null)
return;
final VirtualFile vFile = psiFile.getVirtualFile();
if (vFile == null)
return;
if (!FileModificationService.getInstance().prepareFileForWrite(psiFile))
return;
final Ref<SmartPsiElementPointer> refMethod = new Ref<>();
CommandProcessor.getInstance().executeCommand(aClass.getProject(), () -> ApplicationManager.getApplication().runWriteAction(() -> {
PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory();
try {
PsiMethod method = factory.createMethodFromText("private void " + AsmCodeGenerator.CREATE_COMPONENTS_METHOD_NAME + "() { \n // TODO: place custom component creation code here \n }", aClass);
final PsiMethod psiMethod = (PsiMethod) aClass.add(method);
refMethod.set(SmartPointerManager.getInstance(aClass.getProject()).createSmartPsiElementPointer(psiMethod));
CodeStyleManager.getInstance(aClass.getProject()).reformat(psiMethod);
} catch (IncorrectOperationException e) {
LOG.error(e);
}
}), null, null);
if (!refMethod.isNull()) {
SwingUtilities.invokeLater(() -> {
final PsiMethod element = (PsiMethod) refMethod.get().getElement();
if (element != null) {
final PsiCodeBlock body = element.getBody();
assert body != null;
final PsiComment comment = PsiTreeUtil.getChildOfType(body, PsiComment.class);
if (comment != null) {
new OpenFileDescriptor(comment.getProject(), vFile, comment.getTextOffset()).navigate(true);
}
}
});
}
}
Aggregations