List of usage examples for com.intellij.openapi.ui Messages showErrorDialog
public static void showErrorDialog(@Nullable Component component, String message, @NotNull @Nls(capitalization = Nls.Capitalization.Title) String title)
From source file:com.intellij.codeInsight.generation.surroundWith.JavaWithTryCatchSurrounder.java
License:Apache License
@Override public TextRange surroundStatements(Project project, Editor editor, PsiElement container, PsiElement[] statements) throws IncorrectOperationException { PsiManager manager = PsiManager.getInstance(project); PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); statements = SurroundWithUtil.moveDeclarationsOut(container, statements, true); if (statements.length == 0) { return null; }/*from w w w. j a v a 2s . c o m*/ List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(statements); if (exceptions.isEmpty()) { exceptions = ExceptionUtil.getThrownExceptions(statements); if (exceptions.isEmpty()) { exceptions = Collections.singletonList( factory.createTypeByFQClassName("java.lang.Exception", container.getResolveScope())); } } @NonNls StringBuilder buffer = new StringBuilder(); buffer.append("try{\n}"); for (PsiClassType exception : exceptions) { buffer.append("catch(Exception e){\n}"); } if (myGenerateFinally) { buffer.append("finally{\n}"); } String text = buffer.toString(); PsiTryStatement tryStatement = (PsiTryStatement) factory.createStatementFromText(text, null); tryStatement = (PsiTryStatement) CodeStyleManager.getInstance(project).reformat(tryStatement); tryStatement = (PsiTryStatement) container.addAfter(tryStatement, statements[statements.length - 1]); PsiCodeBlock tryBlock = tryStatement.getTryBlock(); SurroundWithUtil.indentCommentIfNecessary(tryBlock, statements); tryBlock.addRange(statements[0], statements[statements.length - 1]); PsiCatchSection[] catchSections = tryStatement.getCatchSections(); for (int i = 0; i < exceptions.size(); i++) { PsiClassType exception = exceptions.get(i); String[] nameSuggestions = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, exception).names; String name = codeStyleManager.suggestUniqueVariableName(nameSuggestions[0], tryBlock, false); PsiCatchSection catchSection; try { catchSection = factory.createCatchSection(exception, name, null); } catch (IncorrectOperationException e) { Messages.showErrorDialog(project, CodeInsightBundle.message("surround.with.try.catch.incorrect.template.message"), CodeInsightBundle.message("surround.with.try.catch.incorrect.template.title")); return null; } catchSection = (PsiCatchSection) catchSections[i].replace(catchSection); codeStyleManager.shortenClassReferences(catchSection); } container.deleteChildRange(statements[0], statements[statements.length - 1]); PsiCodeBlock firstCatch = tryStatement.getCatchBlocks()[0]; return SurroundWithUtil.getRangeToSelect(firstCatch); }
From source file:com.intellij.codeInsight.intention.impl.CopyAbstractMethodImplementationHandler.java
License:Apache License
public void invoke() { ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { @Override/*from w w w. j a v a2 s .c o m*/ public void run() { searchExistingImplementations(); } }, CodeInsightBundle.message("searching.for.implementations"), false, myProject); if (mySourceMethods.isEmpty()) { Messages.showErrorDialog(myProject, CodeInsightBundle.message("copy.abstract.method.no.existing.implementations.found"), CodeInsightBundle.message("copy.abstract.method.title")); return; } if (mySourceMethods.size() == 1) { copyImplementation(mySourceMethods.get(0)); } else { Collections.sort(mySourceMethods, new Comparator<PsiMethod>() { @Override public int compare(final PsiMethod o1, final PsiMethod o2) { PsiClass c1 = o1.getContainingClass(); PsiClass c2 = o2.getContainingClass(); return Comparing.compare(c1.getName(), c2.getName()); } }); final PsiMethod[] methodArray = mySourceMethods.toArray(new PsiMethod[mySourceMethods.size()]); final JList list = new JBList(methodArray); list.setCellRenderer(new MethodCellRenderer(true)); final Runnable runnable = new Runnable() { @Override public void run() { int index = list.getSelectedIndex(); if (index < 0) return; PsiMethod element = (PsiMethod) list.getSelectedValue(); copyImplementation(element); } }; new PopupChooserBuilder(list).setTitle(CodeInsightBundle.message("copy.abstract.method.popup.title")) .setItemChoosenCallback(runnable).createPopup().showInBestPositionFor(myEditor); } }
From source file:com.intellij.codeInsight.intention.impl.CreateSubclassAction.java
License:Apache License
public static PsiClass createSubclass(final PsiClass psiClass, final PsiDirectory targetDirectory, final String className) { final Project project = psiClass.getProject(); final PsiClass[] targetClass = new PsiClass[1]; new WriteCommandAction(project, getTitle(psiClass), getTitle(psiClass)) { @Override//from w w w . j a v a 2 s . c o m protected void run(Result result) throws Throwable { IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace(); final PsiTypeParameterList oldTypeParameterList = psiClass.getTypeParameterList(); try { targetClass[0] = JavaDirectoryService.getInstance().createClass(targetDirectory, className); } catch (final IncorrectOperationException e) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { 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[0], false); } }.execute(); if (targetClass[0] == null) return null; if (!ApplicationManager.getApplication().isUnitTestMode() && !psiClass.hasTypeParameters()) { final Editor editor = CodeInsightUtil.positionCursor(project, targetClass[0].getContainingFile(), targetClass[0].getLBrace()); if (editor == null) return targetClass[0]; chooseAndImplement(psiClass, project, targetClass[0], editor); } return targetClass[0]; }
From source file:com.intellij.codeInspection.ex.DisableInspectionToolAction.java
License:Apache License
@Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { final InspectionProjectProfileManager profileManager = InspectionProjectProfileManager .getInstance(file.getProject()); InspectionProfile inspectionProfile = profileManager.getInspectionProfile(); ModifiableModel model = inspectionProfile.getModifiableModel(); model.disableTool(myToolId, file);//from ww w . j a va 2 s . com try { model.commit(); } catch (IOException e) { Messages.showErrorDialog(project, e.getMessage(), CommonBundle.getErrorTitle()); } DaemonCodeAnalyzer.getInstance(project).restart(); }
From source file:com.intellij.codeInspection.i18n.I18nizeQuickFix.java
License:Apache License
@Override public void performI18nization(final PsiFile psiFile, final Editor editor, PsiLiteralExpression literalExpression, Collection<PropertiesFile> propertiesFiles, String key, String value, String i18nizedText, PsiExpression[] parameters, final PropertyCreationHandler propertyCreationHandler) throws IncorrectOperationException { Project project = psiFile.getProject(); propertyCreationHandler.createProperty(project, propertiesFiles, key, value, parameters); try {//from ww w .j a va2 s . com final PsiElement newExpression = doReplacementInJava(psiFile, editor, literalExpression, i18nizedText); reformatAndCorrectReferences(newExpression); } catch (IncorrectOperationException e) { Messages.showErrorDialog(project, CodeInsightBundle.message("inspection.i18n.expression.is.invalid.error.message"), CodeInsightBundle.message("inspection.error.dialog.title")); } }
From source file:com.intellij.codeInspection.i18n.JavaI18nizeQuickFixDialog.java
License:Apache License
public static boolean isAvailable(PsiFile file) { final Project project = file.getProject(); final String title = CodeInsightBundle.message("i18nize.dialog.error.jdk.title"); try {//from w w w . j a va2s. c o m return ResourceBundleManager.getManager(file) != null; } catch (ResourceBundleManager.ResourceBundleNotFoundException e) { final IntentionAction fix = e.getFix(); if (fix != null) { if (Messages.showOkCancelDialog(project, e.getMessage(), title, Messages.getErrorIcon()) == OK_EXIT_CODE) { try { fix.invoke(project, null, file); return false; } catch (IncorrectOperationException e1) { LOG.error(e1); } } } Messages.showErrorDialog(project, e.getMessage(), title); return false; } }
From source file:com.intellij.codeInspection.inferNullity.InferNullityAnnotationsAction.java
License:Apache License
@Override protected void analyze(@NotNull final Project project, final AnalysisScope scope) { final ProgressManager progressManager = ProgressManager.getInstance(); final int totalFiles = scope.getFileCount(); final Set<Module> modulesWithoutAnnotations = new HashSet<Module>(); final Set<Module> modulesWithLL = new HashSet<Module>(); if (!progressManager.runProcessWithProgressSynchronously(new Runnable() { @Override/* w w w . j ava 2 s.c om*/ public void run() { scope.accept(new PsiElementVisitor() { private int myFileCount = 0; final private Set<Module> processed = new HashSet<Module>(); @Override public void visitFile(PsiFile file) { myFileCount++; final ProgressIndicator progressIndicator = ProgressManager.getInstance() .getProgressIndicator(); if (progressIndicator != null) { final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null) { progressIndicator .setText2(ProjectUtil.calcRelativeToProjectPath(virtualFile, project)); } progressIndicator.setFraction(((double) myFileCount) / totalFiles); } final Module module = ModuleUtil.findModuleForPsiElement(file); if (module != null && !processed.contains(module)) { processed.add(module); if (JavaPsiFacade.getInstance(project).findClass( NullableNotNullManager.getInstance(project).getDefaultNullable(), GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module)) == null) { modulesWithoutAnnotations.add(module); } if (PsiUtil.getLanguageLevel(file).compareTo(LanguageLevel.JDK_1_5) < 0) { modulesWithLL.add(module); } } } }); } }, "Check applicability...", true, project)) { return; } if (!modulesWithLL.isEmpty()) { Messages.showErrorDialog(project, "Infer Nullity Annotations requires the project language level be set to 1.5 or greater.", INFER_NULLITY_ANNOTATIONS); return; } if (!modulesWithoutAnnotations.isEmpty()) { final Library annotationsLib = LibraryUtil .findLibraryByClass(NullableNotNullManager.getInstance(project).getDefaultNullable(), project); if (annotationsLib != null) { String message = "Module" + (modulesWithoutAnnotations.size() == 1 ? " " : "s "); message += StringUtil.join(modulesWithoutAnnotations, new Function<Module, String>() { @Override public String fun(Module module) { return module.getName(); } }, ", "); message += (modulesWithoutAnnotations.size() == 1 ? " doesn't" : " don't"); message += " refer to the existing '" + annotationsLib.getName() + "' library with IDEA nullity annotations. Would you like to add the dependenc"; message += (modulesWithoutAnnotations.size() == 1 ? "y" : "ies") + " now?"; if (Messages.showOkCancelDialog(project, message, INFER_NULLITY_ANNOTATIONS, Messages.getErrorIcon()) == DialogWrapper.OK_EXIT_CODE) { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { for (Module module : modulesWithoutAnnotations) { ModuleRootModificationUtil.addDependency(module, annotationsLib); } } }); } } else if (Messages.showOkCancelDialog(project, "Infer Nullity Annotations requires that the nullity annotations" + " be available in all your project sources.\n\nYou will need to add annotations.jar as a library. " + "It is possible to configure custom jar in e.g. Constant Conditions & Exceptions inspection or use JetBrains annotations available in installation. " + " IntelliJ IDEA nullity annotations are freely usable and redistributable under the Apache 2.0 license. Would you like to do it now?", INFER_NULLITY_ANNOTATIONS, Messages.getErrorIcon()) == DialogWrapper.OK_EXIT_CODE) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { final LocateLibraryDialog dialog = new LocateLibraryDialog( modulesWithoutAnnotations.iterator().next(), PathManager.getLibPath(), "annotations.jar", QuickFixBundle.message("add.library.annotations.description")); dialog.show(); if (dialog.isOK()) { final String path = dialog.getResultingLibraryPath(); new WriteCommandAction(project) { @Override protected void run(final Result result) throws Throwable { for (Module module : modulesWithoutAnnotations) { OrderEntryFix.addBundledJarToRoots(project, null, module, null, AnnotationUtil.NOT_NULL, path); } } }.execute(); } } }); } return; } if (scope.checkScopeWritable(project)) return; PsiDocumentManager.getInstance(project).commitAllDocuments(); final NullityInferrer inferrer = new NullityInferrer(myAnnotateLocalVariablesCb.isSelected(), project); final PsiManager psiManager = PsiManager.getInstance(project); if (!progressManager.runProcessWithProgressSynchronously(new Runnable() { @Override public void run() { scope.accept(new PsiElementVisitor() { int myFileCount = 0; @Override public void visitFile(final PsiFile file) { myFileCount++; final VirtualFile virtualFile = file.getVirtualFile(); final FileViewProvider viewProvider = psiManager.findViewProvider(virtualFile); final Document document = viewProvider == null ? null : viewProvider.getDocument(); if (document == null || virtualFile.getFileType().isBinary()) return; //do not inspect binary files final ProgressIndicator progressIndicator = ProgressManager.getInstance() .getProgressIndicator(); if (progressIndicator != null) { if (virtualFile != null) { progressIndicator .setText2(ProjectUtil.calcRelativeToProjectPath(virtualFile, project)); } progressIndicator.setFraction(((double) myFileCount) / totalFiles); } if (file instanceof PsiJavaFile) { inferrer.collect(file); } } }); } }, INFER_NULLITY_ANNOTATIONS, true, project)) { return; } final Runnable applyRunnable = new Runnable() { @Override public void run() { new WriteCommandAction(project, INFER_NULLITY_ANNOTATIONS) { @Override protected void run(Result result) throws Throwable { if (!inferrer.nothingFoundMessage(project)) { final SequentialModalProgressTask progressTask = new SequentialModalProgressTask( project, INFER_NULLITY_ANNOTATIONS, false); progressTask.setMinIterationTime(200); progressTask.setTask(new AnnotateTask(project, inferrer, progressTask)); ProgressManager.getInstance().run(progressTask); } } }.execute(); } }; SwingUtilities.invokeLater(applyRunnable); }
From source file:com.intellij.conversion.impl.ConversionServiceImpl.java
License:Apache License
@Override @NotNull/*from ww w . j a v a2s. c o m*/ public ConversionResult convertModule(@NotNull final Project project, @NotNull final File moduleFile) { final IProjectStore stateStore = ((ProjectImpl) project).getStateStore(); final String url = stateStore.getPresentableUrl(); assert url != null : project; final String projectPath = FileUtil.toSystemDependentName(url); if (!isConversionNeeded(projectPath, moduleFile)) { return ConversionResultImpl.CONVERSION_NOT_NEEDED; } final int res = Messages.showYesNoDialog(project, IdeBundle.message("message.module.file.has.an.older.format.do.you.want.to.convert.it"), IdeBundle.message("dialog.title.convert.module"), Messages.getQuestionIcon()); if (res != Messages.YES) { return ConversionResultImpl.CONVERSION_CANCELED; } if (!moduleFile.canWrite()) { Messages.showErrorDialog(project, IdeBundle.message("error.message.cannot.modify.file.0", moduleFile.getAbsolutePath()), IdeBundle.message("dialog.title.convert.module")); return ConversionResultImpl.ERROR_OCCURRED; } try { ConversionContextImpl context = new ConversionContextImpl(projectPath); final List<ConversionRunner> runners = createConversionRunners(context, Collections.<String>emptySet()); final File backupFile = ProjectConversionUtil.backupFile(moduleFile); List<ConversionRunner> usedRunners = new ArrayList<ConversionRunner>(); for (ConversionRunner runner : runners) { if (runner.isModuleConversionNeeded(moduleFile)) { runner.convertModule(moduleFile); usedRunners.add(runner); } } context.saveFiles(Collections.singletonList(moduleFile), usedRunners); Messages.showInfoMessage(project, IdeBundle.message( "message.your.module.was.successfully.converted.br.old.version.was.saved.to.0", backupFile.getAbsolutePath()), IdeBundle.message("dialog.title.convert.module")); return new ConversionResultImpl(runners); } catch (CannotConvertException e) { LOG.info(e); Messages.showErrorDialog(IdeBundle.message("error.cannot.load.project", e.getMessage()), "Cannot Convert Module"); return ConversionResultImpl.ERROR_OCCURRED; } catch (IOException e) { LOG.info(e); return ConversionResultImpl.ERROR_OCCURRED; } }
From source file:com.intellij.conversion.impl.ui.ConvertProjectDialog.java
License:Apache License
private void showErrorMessage(final String message) { Messages.showErrorDialog(myMainPanel, message, IdeBundle.message("dialog.title.convert.project")); }
From source file:com.intellij.debugger.actions.EvaluateActionHandler.java
License:Apache License
public void perform(@NotNull final Project project, final AnActionEvent event) { final DataContext dataContext = event.getDataContext(); final DebuggerContextImpl context = DebuggerAction.getDebuggerContext(dataContext); if (context == null) { return;//from w w w . j a v a 2 s . c o m } final Editor editor = event.getData(DataKeys.EDITOR); TextWithImports editorText = DebuggerUtilsEx.getEditorText(editor); if (editorText == null) { final DebuggerTreeNodeImpl selectedNode = DebuggerAction.getSelectedNode(dataContext); final String actionName = event.getPresentation().getText(); if (selectedNode != null && selectedNode.getDescriptor() instanceof ValueDescriptorImpl) { context.getDebugProcess().getManagerThread().schedule(new DebuggerContextCommandImpl(context) { public void threadAction() { try { final TextWithImports evaluationText = DebuggerTreeNodeExpression .createEvaluationText(selectedNode, context); DebuggerInvocationUtil.swingInvokeLater(project, new Runnable() { public void run() { showEvaluationDialog(project, evaluationText); } }); } catch (final EvaluateException e1) { DebuggerInvocationUtil.swingInvokeLater(project, new Runnable() { public void run() { Messages.showErrorDialog(project, e1.getMessage(), actionName); } }); } } protected void commandCancelled() { DebuggerInvocationUtil.swingInvokeLater(project, new Runnable() { public void run() { if (selectedNode.getDescriptor() instanceof WatchItemDescriptor) { try { TextWithImports editorText = DebuggerTreeNodeExpression .createEvaluationText(selectedNode, context); showEvaluationDialog(project, editorText); } catch (EvaluateException e1) { Messages.showErrorDialog(project, e1.getMessage(), actionName); } } } }); } }); return; } } showEvaluationDialog(project, editorText); }