Example usage for com.intellij.openapi.ui Messages showYesNoDialog

List of usage examples for com.intellij.openapi.ui Messages showYesNoDialog

Introduction

In this page you can find the example usage for com.intellij.openapi.ui Messages showYesNoDialog.

Prototype

@YesNoResult
public static int showYesNoDialog(@NotNull Component parent, String message,
        @NotNull @Nls(capitalization = Nls.Capitalization.Title) String title, @Nullable Icon icon) 

Source Link

Usage

From source file:com.intellij.diagnostic.SubmitPerformanceReportAction.java

License:Apache License

@Override
public void actionPerformed(final AnActionEvent e) {
    String reportFileName = "perf_" + ApplicationInfo.getInstance().getBuild().asString() + "_"
            + SystemProperties.getUserName() + "_" + myDateFormat.format(new Date()) + ".zip";
    final File reportPath = new File(SystemProperties.getUserHome(), reportFileName);
    final File logDir = new File(PathManager.getLogPath());
    final Project project = e.getData(CommonDataKeys.PROJECT);

    final boolean[] archiveCreated = new boolean[1];
    final boolean completed = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
        @Override/* w w  w  . j a  v  a  2 s .  c  o  m*/
        public void run() {
            try {
                ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(reportPath));
                ZipUtil.addDirToZipRecursively(zip, reportPath, logDir, "", new FileFilter() {
                    @Override
                    public boolean accept(final File pathname) {
                        ProgressManager.checkCanceled();

                        if (logDir.equals(pathname.getParentFile())) {
                            return pathname.getPath().contains("threadDumps");
                        }
                        return true;
                    }
                }, null);
                zip.close();
                archiveCreated[0] = true;
            } catch (final IOException ex) {
                ApplicationManager.getApplication().invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        Messages.showErrorDialog(project,
                                "Failed to create performance report archive: " + ex.getMessage(),
                                MESSAGE_TITLE);
                    }
                });
            }
        }
    }, "Collecting Performance Report data", true, project);

    if (!completed || !archiveCreated[0]) {
        return;
    }

    int rc = Messages.showYesNoDialog(project,
            "The performance report has been saved to\n" + reportPath
                    + "\n\nWould you like to submit it to JetBrains?",
            MESSAGE_TITLE, Messages.getQuestionIcon());
    if (rc == Messages.YES) {
        ProgressManager.getInstance().run(new Task.Backgroundable(project, "Uploading Performance Report") {
            @Override
            public void run(@NotNull final ProgressIndicator indicator) {
                final String error = uploadFileToFTP(reportPath, "ftp.intellij.net", ".uploads", indicator);
                if (error != null) {
                    ApplicationManager.getApplication().invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            Messages.showErrorDialog(error, MESSAGE_TITLE);
                        }
                    });
                }
            }
        });
    }
}

From source file:com.intellij.history.integration.ui.views.HistoryDialog.java

License:Apache License

private boolean askForProceeding(Reverter r) throws IOException {
    List<String> questions = r.askUserForProceeding();
    if (questions.isEmpty())
        return true;

    return Messages.showYesNoDialog(myProject,
            message("message.do.you.want.to.proceed", formatQuestions(questions)),
            CommonBundle.getWarningTitle(), Messages.getWarningIcon()) == Messages.YES;
}

From source file:com.intellij.ide.actions.OpenFileAction.java

License:Apache License

private static void doOpenFile(@Nullable final Project project, @NotNull final List<VirtualFile> result) {
    for (final VirtualFile file : result) {
        if (file.isDirectory()) {
            Project openedProject = ProjectUtil.openOrImport(file.getPath(), project, false);
            FileChooserUtil.setLastOpenedFile(openedProject, file);
            return;
        }/*from  w w  w.  j  a v a 2 s  . com*/

        if (OpenProjectFileChooserDescriptor.isProjectFile(file)) {
            int answer = Messages.showYesNoDialog(project,
                    IdeBundle.message("message.open.file.is.project", file.getName()),
                    IdeBundle.message("title.open.project"), Messages.getQuestionIcon());
            if (answer == 0) {
                FileChooserUtil.setLastOpenedFile(ProjectUtil.openOrImport(file.getPath(), project, false),
                        file);
                return;
            }
        }

        FileType type = FileTypeChooser.getKnownFileTypeOrAssociate(file, project);
        if (type == null)
            return;

        if (project != null) {
            openFile(file, project);
        } else {
            PlatformProjectOpenProcessor processor = PlatformProjectOpenProcessor.getInstance();
            processor.doOpenProject(file, null, false);
        }
    }
}

From source file:com.intellij.ide.plugins.ActionInstallPlugin.java

License:Apache License

private boolean userConfirm(IdeaPluginDescriptor[] selection) {
    String message;//from w w  w .  j a v a2 s  .  co  m
    if (selection.length == 1) {
        if (selection[0] instanceof IdeaPluginDescriptorImpl) {
            message = IdeBundle.message("prompt.update.plugin", selection[0].getName());
        } else {
            message = IdeBundle.message("prompt.download.and.install.plugin", selection[0].getName());
        }
    } else {
        message = IdeBundle.message("prompt.install.several.plugins", selection.length);
    }

    return Messages.showYesNoDialog(host.getMainPanel(), message,
            IdeBundle.message("action.download.and.install.plugin"),
            Messages.getQuestionIcon()) == Messages.YES;
}

From source file:com.intellij.ide.plugins.UninstallPluginAction.java

License:Apache License

public static void uninstall(PluginManagerMain host, IdeaPluginDescriptor... selection) {
    String message;//  w  w  w .  j  a  v  a 2s .c  o m

    if (selection.length == 1) {
        message = IdeBundle.message("prompt.uninstall.plugin", selection[0].getName());
    } else {
        message = IdeBundle.message("prompt.uninstall.several.plugins", selection.length);
    }
    if (Messages.showYesNoDialog(host.getMainPanel(), message, IdeBundle.message("title.plugin.uninstall"),
            Messages.getQuestionIcon()) != Messages.YES)
        return;

    for (IdeaPluginDescriptor descriptor : selection) {
        IdeaPluginDescriptorImpl pluginDescriptor = (IdeaPluginDescriptorImpl) descriptor;

        boolean actualDelete = true;

        //  Get the list of plugins which depend on this one. If this list is
        //  not empty - issue warning instead of simple prompt.
        ArrayList<IdeaPluginDescriptorImpl> dependant = host.getDependentList(pluginDescriptor);
        if (dependant.size() > 0) {
            message = IdeBundle.message("several.plugins.depend.on.0.continue.to.remove",
                    pluginDescriptor.getName());
            actualDelete = (Messages.showYesNoDialog(host.getMainPanel(), message,
                    IdeBundle.message("title.plugin.uninstall"), Messages.getQuestionIcon()) == Messages.YES);
        }

        if (actualDelete) {
            uninstallPlugin(pluginDescriptor, host);
        }
    }
}

From source file:com.intellij.ide.util.DeleteHandler.java

License:Apache License

public static void deletePsiElement(final PsiElement[] elementsToDelete, final Project project,
        boolean needConfirmation) {
    if (elementsToDelete == null || elementsToDelete.length == 0)
        return;/*from w  ww .  j  ava2  s.com*/

    final PsiElement[] elements = PsiTreeUtil.filterAncestors(elementsToDelete);

    boolean safeDeleteApplicable = true;
    for (int i = 0; i < elements.length && safeDeleteApplicable; i++) {
        PsiElement element = elements[i];
        safeDeleteApplicable = SafeDeleteProcessor.validElement(element);
    }

    final boolean dumb = DumbService.getInstance(project).isDumb();
    if (safeDeleteApplicable && !dumb) {
        final Ref<Boolean> exit = Ref.create(false);
        final SafeDeleteDialog dialog = new SafeDeleteDialog(project, elements,
                new SafeDeleteDialog.Callback() {
                    @Override
                    public void run(final SafeDeleteDialog dialog) {
                        if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(project,
                                Arrays.asList(elements), true))
                            return;
                        SafeDeleteProcessor.createInstance(project, new Runnable() {
                            @Override
                            public void run() {
                                exit.set(true);
                                dialog.close(DialogWrapper.OK_EXIT_CODE);
                            }
                        }, elements, dialog.isSearchInComments(), dialog.isSearchForTextOccurences(), true)
                                .run();
                    }
                }) {
            @Override
            protected boolean isDelete() {
                return true;
            }
        };
        if (needConfirmation) {
            dialog.show();
            if (!dialog.isOK() || exit.get())
                return;
        }
    } else {
        @SuppressWarnings({ "UnresolvedPropertyKey" })
        String warningMessage = DeleteUtil.generateWarningMessage(IdeBundle.message("prompt.delete.elements"),
                elements);

        boolean anyDirectories = false;
        String directoryName = null;
        for (PsiElement psiElement : elementsToDelete) {
            if (psiElement instanceof PsiDirectory && !PsiUtilBase.isSymLink((PsiDirectory) psiElement)) {
                anyDirectories = true;
                directoryName = ((PsiDirectory) psiElement).getName();
                break;
            }
        }
        if (anyDirectories) {
            if (elements.length == 1) {
                warningMessage += IdeBundle.message("warning.delete.all.files.and.subdirectories",
                        directoryName);
            } else {
                warningMessage += IdeBundle
                        .message("warning.delete.all.files.and.subdirectories.in.the.selected.directory");
            }
        }

        if (safeDeleteApplicable && dumb) {
            warningMessage += "\n\nWarning:\n  Safe delete is not available while "
                    + ApplicationNamesInfo.getInstance().getFullProductName()
                    + " updates indices,\n  no usages will be checked.";
        }

        if (needConfirmation) {
            int result = Messages.showOkCancelDialog(project, warningMessage, IdeBundle.message("title.delete"),
                    ApplicationBundle.message("button.delete"), CommonBundle.getCancelButtonText(),
                    Messages.getQuestionIcon());
            if (result != Messages.OK)
                return;
        }
    }

    CommandProcessor.getInstance().executeCommand(project, new Runnable() {
        @Override
        public void run() {
            if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, Arrays.asList(elements),
                    false)) {
                return;
            }

            // deleted from project view or something like that.
            if (CommonDataKeys.EDITOR.getData(DataManager.getInstance().getDataContext()) == null) {
                CommandProcessor.getInstance().markCurrentCommandAsGlobal(project);
            }

            for (final PsiElement elementToDelete : elements) {
                if (!elementToDelete.isValid())
                    continue; //was already deleted
                if (elementToDelete instanceof PsiDirectory) {
                    VirtualFile virtualFile = ((PsiDirectory) elementToDelete).getVirtualFile();
                    if (virtualFile.isInLocalFileSystem() && !virtualFile.is(VFileProperty.SYMLINK)) {
                        ArrayList<VirtualFile> readOnlyFiles = new ArrayList<VirtualFile>();
                        CommonRefactoringUtil.collectReadOnlyFiles(virtualFile, readOnlyFiles);

                        if (!readOnlyFiles.isEmpty()) {
                            String message = IdeBundle.message("prompt.directory.contains.read.only.files",
                                    virtualFile.getPresentableUrl());
                            int _result = Messages.showYesNoDialog(project, message,
                                    IdeBundle.message("title.delete"), Messages.getQuestionIcon());
                            if (_result != Messages.YES)
                                continue;

                            boolean success = true;
                            for (VirtualFile file : readOnlyFiles) {
                                success = clearReadOnlyFlag(file, project);
                                if (!success)
                                    break;
                            }
                            if (!success)
                                continue;
                        }
                    }
                } else if (!elementToDelete.isWritable() && !(elementToDelete instanceof PsiFileSystemItem
                        && PsiUtilBase.isSymLink((PsiFileSystemItem) elementToDelete))) {
                    final PsiFile file = elementToDelete.getContainingFile();
                    if (file != null) {
                        final VirtualFile virtualFile = file.getVirtualFile();
                        if (virtualFile.isInLocalFileSystem()) {
                            int _result = MessagesEx.fileIsReadOnly(project, virtualFile)
                                    .setTitle(IdeBundle.message("title.delete"))
                                    .appendMessage(IdeBundle.message("prompt.delete.it.anyway")).askYesNo();
                            if (_result != Messages.YES)
                                continue;

                            boolean success = clearReadOnlyFlag(virtualFile, project);
                            if (!success)
                                continue;
                        }
                    }
                }

                try {
                    elementToDelete.checkDelete();
                } catch (IncorrectOperationException ex) {
                    Messages.showMessageDialog(project, ex.getMessage(), CommonBundle.getErrorTitle(),
                            Messages.getErrorIcon());
                    continue;
                }

                ApplicationManager.getApplication().runWriteAction(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            elementToDelete.delete();
                        } catch (final IncorrectOperationException ex) {
                            ApplicationManager.getApplication().invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    Messages.showMessageDialog(project, ex.getMessage(),
                                            CommonBundle.getErrorTitle(), Messages.getErrorIcon());
                                }
                            });
                        }
                    }
                });
            }
        }
    }, RefactoringBundle.message("safe.delete.command",
            RefactoringUIUtil.calculatePsiElementDescriptionList(elements)), null);
}

From source file:com.intellij.ide.util.PackageUtil.java

License:Apache License

/**
 * @deprecated//from   w w w .ja  v  a2  s.  c om
 */
@Nullable
public static PsiDirectory findOrCreateDirectoryForPackage(Project project, String packageName,
        PsiDirectory baseDir, boolean askUserToCreate, boolean filterSourceDirsForTestBaseDir)
        throws IncorrectOperationException {

    PsiDirectory psiDirectory = null;

    if (!"".equals(packageName)) {
        PsiJavaPackage rootPackage = findLongestExistingPackage(project, packageName);
        if (rootPackage != null) {
            int beginIndex = rootPackage.getQualifiedName().length() + 1;
            packageName = beginIndex < packageName.length() ? packageName.substring(beginIndex) : "";
            String postfixToShow = packageName.replace('.', File.separatorChar);
            if (packageName.length() > 0) {
                postfixToShow = File.separatorChar + postfixToShow;
            }
            PsiDirectory[] directories = rootPackage.getDirectories();
            if (filterSourceDirsForTestBaseDir) {
                directories = filterSourceDirectories(baseDir, project, directories);
            }
            psiDirectory = DirectoryChooserUtil.selectDirectory(project, directories, baseDir, postfixToShow);
            if (psiDirectory == null) {
                return null;
            }
        }
    }

    if (psiDirectory == null) {
        PsiDirectory[] sourceDirectories = getSourceRootDirectories(project);
        psiDirectory = DirectoryChooserUtil.selectDirectory(project, sourceDirectories, baseDir,
                File.separatorChar + packageName.replace('.', File.separatorChar));
        if (psiDirectory == null) {
            return null;
        }
    }

    String restOfName = packageName;
    boolean askedToCreate = false;
    while (restOfName.length() > 0) {
        final String name = getLeftPart(restOfName);
        PsiDirectory foundExistingDirectory = psiDirectory.findSubdirectory(name);
        if (foundExistingDirectory == null) {
            if (!askedToCreate && askUserToCreate) {
                int toCreate = Messages.showYesNoDialog(project,
                        IdeBundle.message("prompt.create.non.existing.package", packageName),
                        IdeBundle.message("title.package.not.found"), Messages.getQuestionIcon());
                if (toCreate != 0) {
                    return null;
                }
                askedToCreate = true;
            }
            psiDirectory = createSubdirectory(psiDirectory, name, project);
        } else {
            psiDirectory = foundExistingDirectory;
        }
        restOfName = cutLeftPart(restOfName);
    }
    return psiDirectory;
}

From source file:com.intellij.ide.util.PackageUtil.java

License:Apache License

@Nullable
public static PsiDirectory findOrCreateDirectoryForPackage(@NotNull Module module, String packageName,
        PsiDirectory baseDir, boolean askUserToCreate, boolean filterSourceDirsForBaseTestDirectory)
        throws IncorrectOperationException {
    final Project project = module.getProject();
    PsiDirectory psiDirectory = null;/*from www  . jav  a2  s  .co  m*/
    if (!packageName.isEmpty()) {
        PsiJavaPackage rootPackage = findLongestExistingPackage(module, packageName);
        if (rootPackage != null) {
            int beginIndex = rootPackage.getQualifiedName().length() + 1;
            packageName = beginIndex < packageName.length() ? packageName.substring(beginIndex) : "";
            String postfixToShow = packageName.replace('.', File.separatorChar);
            if (packageName.length() > 0) {
                postfixToShow = File.separatorChar + postfixToShow;
            }
            PsiDirectory[] moduleDirectories = getPackageDirectoriesInModule(rootPackage, module);
            if (filterSourceDirsForBaseTestDirectory) {
                moduleDirectories = filterSourceDirectories(baseDir, project, moduleDirectories);
            }
            psiDirectory = DirectoryChooserUtil.selectDirectory(project, moduleDirectories, baseDir,
                    postfixToShow);
            if (psiDirectory == null) {
                return null;
            }
        }
    }

    if (psiDirectory == null) {
        if (!checkSourceRootsConfigured(module, askUserToCreate)) {
            return null;
        }
        final VirtualFile[] sourceRoots = ModuleRootManager.getInstance(module).getSourceRoots();
        List<PsiDirectory> directoryList = new ArrayList<PsiDirectory>();
        for (VirtualFile sourceRoot : sourceRoots) {
            final PsiDirectory directory = PsiManager.getInstance(project).findDirectory(sourceRoot);
            if (directory != null) {
                directoryList.add(directory);
            }
        }
        PsiDirectory[] sourceDirectories = directoryList.toArray(new PsiDirectory[directoryList.size()]);
        psiDirectory = DirectoryChooserUtil.selectDirectory(project, sourceDirectories, baseDir,
                File.separatorChar + packageName.replace('.', File.separatorChar));
        if (psiDirectory == null) {
            return null;
        }
    }

    String restOfName = packageName;
    boolean askedToCreate = false;
    while (restOfName.length() > 0) {
        final String name = getLeftPart(restOfName);
        PsiDirectory foundExistingDirectory = psiDirectory.findSubdirectory(name);
        if (foundExistingDirectory == null) {
            if (!askedToCreate && askUserToCreate) {
                if (!ApplicationManager.getApplication().isUnitTestMode()) {
                    int toCreate = Messages.showYesNoDialog(project,
                            IdeBundle.message("prompt.create.non.existing.package", packageName),
                            IdeBundle.message("title.package.not.found"), Messages.getQuestionIcon());
                    if (toCreate != 0) {
                        return null;
                    }
                }
                askedToCreate = true;
            }

            final PsiDirectory psiDirectory1 = psiDirectory;
            try {
                psiDirectory = ActionRunner
                        .runInsideWriteAction(new ActionRunner.InterruptibleRunnableWithResult<PsiDirectory>() {
                            public PsiDirectory run() throws Exception {
                                return psiDirectory1.createSubdirectory(name);
                            }
                        });
            } catch (IncorrectOperationException e) {
                throw e;
            } catch (IOException e) {
                throw new IncorrectOperationException(e.toString(), e);
            } catch (Exception e) {
                LOG.error(e);
            }
        } else {
            psiDirectory = foundExistingDirectory;
        }
        restOfName = cutLeftPart(restOfName);
    }
    return psiDirectory;
}

From source file:com.intellij.internal.validation.TestMacMessagesAction.java

License:Apache License

@Override
public void actionPerformed(final AnActionEvent e) {
    new DialogWrapper(e.getProject()) {
        {/*from  ww  w. java  2 s  .  c  o  m*/
            setSize(500, 500);
            setTitle("Dialog 1");
            init();
        }

        @Nullable
        @Override
        protected JComponent createCenterPanel() {
            final JButton button = new JButton("Click me");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    new DialogWrapper(e.getProject()) {
                        {
                            setSize(400, 400);
                            setTitle("Dialog 2");
                            init();
                        }

                        @Nullable
                        @Override
                        protected JComponent createCenterPanel() {
                            final JButton b = new JButton("Click me again " + num);
                            num++;
                            b.addActionListener(new ActionListener() {
                                @Override
                                public void actionPerformed(ActionEvent e) {
                                    Messages.showYesNoDialog(b, "Blah-blah", "Error",
                                            Messages.getQuestionIcon());
                                }
                            });
                            return b;
                        }
                    }.show();
                }
            });
            return button;
        }
    }.show();
}

From source file:com.intellij.javascript.flex.refactoring.moveMembers.ActionScriptMoveMembersDialog.java

License:Apache License

@Nullable
private JSClass findOrCreateTargetClass(final String fqName) {
    final String className = StringUtil.getShortName(fqName);
    final String packageName = StringUtil.getPackageName(fqName);

    final GlobalSearchScope scope = getScope();
    final JSClassResolver resolver = JSDialectSpecificHandlersFactory
            .forLanguage(JavaScriptSupportLoader.ECMA_SCRIPT_L4).getClassResolver();
    PsiElement aClass = resolver.findClassByQName(fqName, scope);
    if (aClass instanceof JSClass)
        return (JSClass) aClass;

    if (aClass != null) {
        Messages.showErrorDialog(myProject, JSBundle.message("class.0.cannot.be.created", fqName),
                StringUtil.capitalizeWords(JSBundle.message("move.members.refactoring.name"), true));
        return null;
    }/*w  w  w.j  av  a 2  s  .c o m*/

    int answer = Messages.showYesNoDialog(myProject,
            RefactoringBundle.message("class.0.does.not.exist", fqName),
            StringUtil.capitalizeWords(JSBundle.message("move.members.refactoring.name"), true),
            Messages.getQuestionIcon());
    if (answer != Messages.YES)
        return null;

    Module module = ModuleUtilCore.findModuleForPsiElement(mySourceClass);
    PsiDirectory baseDir = PlatformPackageUtil.getDirectory(mySourceClass);
    final PsiDirectory targetDirectory = JSRefactoringUtil.chooseOrCreateDirectoryForClass(myProject, module,
            scope, packageName, className, baseDir, ThreeState.UNSURE);
    if (targetDirectory == null) {
        return null;
    }

    final Ref<Exception> error = new Ref<>();
    final Ref<JSClass> newClass = new Ref<>();
    WriteCommandAction.runWriteCommandAction(myProject,
            RefactoringBundle.message("create.class.command", fqName), null, () -> {
                try {
                    ActionScriptCreateClassOrInterfaceFix.createClass(className, packageName, targetDirectory,
                            false);
                    newClass.set((JSClass) resolver.findClassByQName(fqName, scope));
                } catch (Exception e) {
                    error.set(e);
                }
            });

    if (!error.isNull()) {
        CommonRefactoringUtil.showErrorMessage(JSBundle.message("move.members.refactoring.name"),
                error.get().getMessage(), null, myProject);
        return null;
    }
    return newClass.get();
}