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

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

Introduction

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

Prototype

@YesNoCancelResult
public static int showYesNoCancelDialog(String message,
        @NotNull @Nls(capitalization = Nls.Capitalization.Title) String title, @NotNull String yes,
        @NotNull String no, @NotNull String cancel, Icon icon,
        @Nullable DialogWrapper.DoNotAskOption doNotAskOption) 

Source Link

Document

Use this method only if you do not know project or component

Usage

From source file:com.eugenePetrenko.idea.dependencies.actions.OnModuleAction.java

License:Apache License

@Nullable
private AnalyzeStrategy decideStrategy(@NotNull final Project project, @NotNull final Module[] modules) {
    boolean suggestExpand = modules.length != WITH_EXPORT_DEPENDENCIES.collectAllModules(project,
            modules).length;//  www.ja  v  a  2 s.co  m
    if (!suggestExpand)
        return WITH_EXPORT_DEPENDENCIES;

    int result = Messages.showYesNoCancelDialog(project,
            "There are some modules with exported dependencies.\n"
                    + "It's required to include more modules to the list "
                    + "in order to analyze exported dependencies.\n\n" + "Do you like to include more modules?",
            "Unused Dependencies", "Include Modules", "Skip Exports", "Cancel", null);
    switch (result) {
    case Messages.YES:
        return WITH_EXPORT_DEPENDENCIES;
    case Messages.NO:
        return SKIP_EXPORT_DEPENDENCIES;
    default:
        return null;
    }
}

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

License:Apache License

public void actionPerformed(AnActionEvent e) {
    final Application app = ApplicationManager.getApplication();
    final boolean mac = Messages.canShowMacSheetPanel();
    String[] options = new String[3];
    options[0] = app.isRestartCapable() ? "Invalidate and Restart" : "Invalidate and Exit";
    options[1] = mac ? "Cancel" : "Invalidate";
    options[2] = mac ? "Invalidate" : "Cancel";

    int result = Messages.showYesNoCancelDialog(e.getData(CommonDataKeys.PROJECT),
            "The caches will be invalidated and rebuilt on the next startup.\n"
                    + "WARNING: Local History will be also cleared.\n\n" + "Would you like to continue?\n\n",
            "Invalidate Caches", options[0], options[1], options[2], Messages.getWarningIcon());

    if (result == -1 || result == (mac ? 1 : 2)) {
        return;/* ww w.  j  a  v  a2 s  . co  m*/
    }
    FSRecords.invalidateCaches();
    if (result == 0)
        app.restart();
}

From source file:com.intellij.ide.impl.ProjectUtil.java

License:Apache License

/**
 * @return {@link com.intellij.ide.GeneralSettings#OPEN_PROJECT_SAME_WINDOW}
 *         {@link com.intellij.ide.GeneralSettings#OPEN_PROJECT_NEW_WINDOW}
 *         {@link com.intellij.openapi.ui.Messages#CANCEL} - if user canceled the dialog
 * @param isNewProject/*from  w  w w  . j a  v  a  2s .  c o m*/
 */
public static int confirmOpenNewProject(boolean isNewProject) {
    final GeneralSettings settings = GeneralSettings.getInstance();
    int confirmOpenNewProject = settings.getConfirmOpenNewProject();
    if (confirmOpenNewProject == GeneralSettings.OPEN_PROJECT_ASK) {
        if (isNewProject) {
            int exitCode = Messages.showYesNoDialog(IdeBundle.message("prompt.open.project.in.new.frame"),
                    IdeBundle.message("title.new.project"), IdeBundle.message("button.existingframe"),
                    IdeBundle.message("button.newframe"), Messages.getQuestionIcon(),
                    new ProjectNewWindowDoNotAskOption());
            return exitCode == 0 ? GeneralSettings.OPEN_PROJECT_SAME_WINDOW
                    : GeneralSettings.OPEN_PROJECT_NEW_WINDOW;
        } else {
            int exitCode = Messages.showYesNoCancelDialog(IdeBundle.message("prompt.open.project.in.new.frame"),
                    IdeBundle.message("title.open.project"), IdeBundle.message("button.existingframe"),
                    IdeBundle.message("button.newframe"), CommonBundle.getCancelButtonText(),
                    Messages.getQuestionIcon(), new ProjectNewWindowDoNotAskOption());
            return exitCode == 0 ? GeneralSettings.OPEN_PROJECT_SAME_WINDOW
                    : exitCode == 1 ? GeneralSettings.OPEN_PROJECT_NEW_WINDOW : Messages.CANCEL;
        }
    }
    return confirmOpenNewProject;
}

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

License:Apache License

public static void exportTextToFile(Project project, String fileName, String textToExport) {
    String prepend = "";
    File file = new File(fileName);
    if (file.exists()) {
        int result = Messages.showYesNoCancelDialog(project,
                IdeBundle.message("error.text.file.already.exists", fileName),
                IdeBundle.message("title.warning"), IdeBundle.message("action.overwrite"),
                IdeBundle.message("action.append"), CommonBundle.getCancelButtonText(),
                Messages.getWarningIcon());

        if (result != 1 && result != 0) {
            return;
        }/*w ww. j a v a  2 s. c o  m*/
        if (result == 1) {
            char[] buf = new char[(int) file.length()];
            try {
                FileReader reader = new FileReader(fileName);
                try {
                    reader.read(buf, 0, (int) file.length());
                    prepend = new String(buf) + SystemProperties.getLineSeparator();
                } finally {
                    reader.close();
                }
            } catch (IOException e) {
            }
        }
    }

    try {
        FileWriter writer = new FileWriter(fileName);
        try {
            writer.write(prepend + textToExport);
        } finally {
            writer.close();
        }
    } catch (IOException e) {
        Messages.showMessageDialog(project, IdeBundle.message("error.writing.to.file", fileName),
                CommonBundle.getErrorTitle(), Messages.getErrorIcon());
    }
}

From source file:com.intellij.projectImport.ProjectOpenProcessorBase.java

License:Apache License

@Override
@Nullable//w w w .  j  av a 2  s.c  o  m
public Project doOpenProject(@NotNull VirtualFile virtualFile, Project projectToClose,
        boolean forceOpenInNewFrame) {
    try {
        getBuilder().setUpdate(false);
        final WizardContext wizardContext = new WizardContext(null);
        if (virtualFile.isDirectory()) {
            final String[] supported = getSupportedExtensions();
            for (VirtualFile file : getFileChildren(virtualFile)) {
                if (canOpenFile(file, supported)) {
                    virtualFile = file;
                    break;
                }
            }
        }

        wizardContext.setProjectFileDirectory(virtualFile.getParent().getPath());

        if (!doQuickImport(virtualFile, wizardContext))
            return null;

        if (wizardContext.getProjectName() == null) {
            wizardContext.setProjectName(IdeBundle.message("project.import.default.name.dotIdea", getName()));
        }

        final String dotIdeaFilePath = wizardContext.getProjectFileDirectory() + File.separator
                + Project.DIRECTORY_STORE_FOLDER;

        File dotIdeaFile = new File(dotIdeaFilePath);

        String pathToOpen = dotIdeaFile.getParent();

        boolean shouldOpenExisting = false;
        if (!ApplicationManager.getApplication().isHeadlessEnvironment() && dotIdeaFile.exists()) {
            String existingName = "an existing project";

            int result = Messages.showYesNoCancelDialog(projectToClose,
                    IdeBundle.message("project.import.open.existing", existingName, pathToOpen,
                            virtualFile.getName()),
                    IdeBundle.message("title.open.project"),
                    IdeBundle.message("project.import.open.existing.openExisting"),
                    IdeBundle.message("project.import.open.existing.reimport"),
                    CommonBundle.message("button.cancel"), Messages.getQuestionIcon());
            if (result == Messages.CANCEL)
                return null;
            shouldOpenExisting = result == Messages.OK;
        }

        final Project projectToOpen;
        if (shouldOpenExisting) {
            try {
                projectToOpen = ProjectManagerEx.getInstanceEx().loadProject(pathToOpen);
            } catch (IOException e) {
                return null;
            } catch (JDOMException e) {
                return null;
            } catch (InvalidDataException e) {
                return null;
            }
        } else {
            projectToOpen = ProjectManagerEx.getInstanceEx().newProject(wizardContext.getProjectName(),
                    pathToOpen, true, false);

            if (projectToOpen == null || !getBuilder().validate(projectToClose, projectToOpen)) {
                return null;
            }

            projectToOpen.save();

            getBuilder().commit(projectToOpen, null, ModulesProvider.EMPTY_MODULES_PROVIDER);
        }

        if (!forceOpenInNewFrame) {
            NewProjectUtilPlatform.closePreviousProject(projectToClose);
        }
        ProjectUtil.updateLastProjectLocation(pathToOpen);
        ProjectManagerEx.getInstanceEx().openProject(projectToOpen);

        return projectToOpen;
    } finally {
        getBuilder().cleanup();
    }
}

From source file:com.intellij.refactoring.move.moveClassesOrPackages.JavaMoveClassesOrPackagesHandler.java

License:Apache License

private static void moveDirectoriesLibrariesSafe(Project project, PsiElement targetContainer,
        MoveCallback callback, PsiDirectory[] directories, String prompt) {
    final PsiJavaPackage aPackage = JavaDirectoryService.getInstance().getPackage(directories[0]);
    LOG.assertTrue(aPackage != null);/*w w w  .ja v  a  2 s. c om*/
    final PsiDirectory[] projectDirectories = aPackage.getDirectories(GlobalSearchScope.projectScope(project));
    if (projectDirectories.length > 1) {
        int ret = Messages.showYesNoCancelDialog(project, prompt + " or all directories in project?",
                RefactoringBundle.message("warning.title"), RefactoringBundle.message("move.current.directory"),
                RefactoringBundle.message("move.directories"), CommonBundle.getCancelButtonText(),
                Messages.getWarningIcon());
        if (ret == 0) {
            moveAsDirectory(project, targetContainer, callback, directories);
        } else if (ret == 1) {
            moveAsDirectory(project, targetContainer, callback, projectDirectories);
        }
    } else if (Messages.showOkCancelDialog(project, prompt + "?", RefactoringBundle.message("warning.title"),
            Messages.getWarningIcon()) == DialogWrapper.OK_EXIT_CODE) {
        moveAsDirectory(project, targetContainer, callback, directories);
    }
}

From source file:com.intellij.refactoring.rename.DirectoryAsPackageRenameHandlerBase.java

License:Apache License

private void doRename(PsiElement element, final Project project, PsiElement nameSuggestionContext,
        Editor editor) {// w  ww  .jav a2  s.co  m
    final PsiDirectory psiDirectory = (PsiDirectory) element;
    final T aPackage = getPackage(psiDirectory);
    final String qualifiedName = aPackage != null ? getQualifiedName(aPackage) : "";
    if (aPackage == null || qualifiedName.length() == 0/*default package*/
            || !isIdentifier(psiDirectory.getName(), project)) {
        PsiElementRenameHandler.rename(element, project, nameSuggestionContext, editor);
    } else {
        PsiDirectory[] directories = aPackage.getDirectories();
        final VirtualFile[] virtualFiles = occursInPackagePrefixes(aPackage);
        if (virtualFiles.length == 0 && directories.length == 1) {
            PsiElementRenameHandler.rename(aPackage, project, nameSuggestionContext, editor);
        } else { // the directory corresponds to a package that has multiple associated directories
            final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
            boolean inLib = false;
            for (PsiDirectory directory : directories) {
                inLib |= !projectFileIndex.isInContent(directory.getVirtualFile());
            }

            final PsiDirectory[] projectDirectories = aPackage
                    .getDirectories(GlobalSearchScope.projectScope(project));
            if (inLib) {
                final Module module = ModuleUtilCore.findModuleForPsiElement(psiDirectory);
                LOG.assertTrue(module != null);
                PsiDirectory[] moduleDirs = null;
                if (nameSuggestionContext instanceof PsiPackageBase) {
                    moduleDirs = aPackage.getDirectories(GlobalSearchScope.moduleScope(module));
                    if (moduleDirs.length <= 1) {
                        moduleDirs = null;
                    }
                }
                final String promptMessage = "Package \'" + aPackage.getName()
                        + "\' contains directories in libraries which cannot be renamed. Do you want to rename "
                        + (moduleDirs == null ? "current directory" : "current module directories");
                if (projectDirectories.length > 0) {
                    int ret = Messages.showYesNoCancelDialog(project,
                            promptMessage + " or all directories in project?",
                            RefactoringBundle.message("warning.title"),
                            RefactoringBundle.message("rename.current.directory"),
                            RefactoringBundle.message("rename.directories"), CommonBundle.getCancelButtonText(),
                            Messages.getWarningIcon());
                    if (ret == 2)
                        return;
                    renameDirs(project, nameSuggestionContext, editor, psiDirectory, aPackage,
                            ret == 0 ? (moduleDirs == null ? new PsiDirectory[] { psiDirectory } : moduleDirs)
                                    : projectDirectories);
                } else {
                    if (Messages.showOkCancelDialog(project, promptMessage + "?",
                            RefactoringBundle.message("warning.title"),
                            Messages.getWarningIcon()) == DialogWrapper.OK_EXIT_CODE) {
                        renameDirs(project, nameSuggestionContext, editor, psiDirectory, aPackage,
                                psiDirectory);
                    }
                }
            } else {
                final StringBuffer message = new StringBuffer();
                RenameUtil.buildPackagePrefixChangedMessage(virtualFiles, message, qualifiedName);
                buildMultipleDirectoriesInPackageMessage(message, getQualifiedName(aPackage), directories);
                message.append(
                        RefactoringBundle.message("directories.and.all.references.to.package.will.be.renamed",
                                psiDirectory.getVirtualFile().getPresentableUrl()));
                int ret = Messages.showYesNoCancelDialog(project, message.toString(),
                        RefactoringBundle.message("warning.title"),
                        RefactoringBundle.message("rename.package.button.text"),
                        RefactoringBundle.message("rename.directory.button.text"),
                        CommonBundle.getCancelButtonText(), Messages.getWarningIcon());
                if (ret == 0) {
                    PsiElementRenameHandler.rename(aPackage, project, nameSuggestionContext, editor);
                } else if (ret == 1) {
                    renameDirs(project, nameSuggestionContext, editor, psiDirectory, aPackage, psiDirectory);
                }
            }
        }
    }
}

From source file:com.intellij.refactoring.rename.inplace.InplaceRefactoring.java

License:Apache License

protected boolean buildTemplateAndStart(final Collection<PsiReference> refs,
        final Collection<Pair<PsiElement, TextRange>> stringUsages, final PsiElement scope,
        final PsiFile containingFile) {
    final PsiElement context = InjectedLanguageManager.getInstance(containingFile.getProject())
            .getInjectionHost(containingFile);
    myScope = context != null ? context.getContainingFile() : scope;
    final TemplateBuilderImpl builder = new TemplateBuilderImpl(myScope);

    PsiElement nameIdentifier = getNameIdentifier();
    int offset = myEditor.getCaretModel().getOffset();
    PsiElement selectedElement = getSelectedInEditorElement(nameIdentifier, refs, stringUsages, offset);

    boolean subrefOnPrimaryElement = false;
    boolean hasReferenceOnNameIdentifier = false;
    for (PsiReference ref : refs) {
        if (isReferenceAtCaret(selectedElement, ref)) {
            builder.replaceElement(ref, PRIMARY_VARIABLE_NAME, createLookupExpression(selectedElement), true);
            subrefOnPrimaryElement = true;
            continue;
        }// w w w.j  ava 2s .  c  o  m
        addVariable(ref, selectedElement, builder, offset);
        hasReferenceOnNameIdentifier |= isReferenceAtCaret(nameIdentifier, ref);
    }
    if (nameIdentifier != null) {
        hasReferenceOnNameIdentifier |= selectedElement.getTextRange().contains(nameIdentifier.getTextRange());
        if (!subrefOnPrimaryElement || !hasReferenceOnNameIdentifier) {
            addVariable(nameIdentifier, selectedElement, builder);
        }
    }
    for (Pair<PsiElement, TextRange> usage : stringUsages) {
        addVariable(usage.first, usage.second, selectedElement, builder);
    }
    addAdditionalVariables(builder);
    try {
        myMarkAction = startRename();
    } catch (final StartMarkAction.AlreadyStartedException e) {
        final Document oldDocument = e.getDocument();
        if (oldDocument != myEditor.getDocument()) {
            final int exitCode = Messages.showYesNoCancelDialog(myProject, e.getMessage(), getCommandName(),
                    "Navigate to Started", "Cancel Started", "Cancel", Messages.getErrorIcon());
            if (exitCode == Messages.CANCEL)
                return true;
            navigateToAlreadyStarted(oldDocument, exitCode);
            return true;
        } else {

            if (!ourRenamersStack.isEmpty() && ourRenamersStack.peek() == this) {
                ourRenamersStack.pop();
                if (!ourRenamersStack.empty()) {
                    myOldName = ourRenamersStack.peek().myOldName;
                }
            }

            revertState();
            final TemplateState templateState = TemplateManagerImpl
                    .getTemplateState(InjectedLanguageUtil.getTopLevelEditor(myEditor));
            if (templateState != null) {
                templateState.gotoEnd(true);
            }
        }
        return false;
    }

    beforeTemplateStart();

    new WriteCommandAction(myProject, getCommandName()) {
        @Override
        protected void run(com.intellij.openapi.application.Result result) throws Throwable {
            startTemplate(builder);
        }
    }.execute();

    if (myBalloon == null) {
        showBalloon();
    }
    return true;
}

From source file:com.intellij.uiDesigner.actions.DataBindingWizardAction.java

License:Apache License

public void actionPerformed(final AnActionEvent e) {
    final Project project;
    final VirtualFile formFile;
    GuiEditor editor = FormEditingUtil.getActiveEditor(e.getDataContext());
    assert editor != null;
    project = editor.getProject();/*ww  w  . ja  va  2 s.  co  m*/
    formFile = editor.getFile();

    try {
        final WizardData wizardData = new WizardData(project, formFile);

        final Module module = ModuleUtil.findModuleForFile(formFile, wizardData.myProject);
        LOG.assertTrue(module != null);

        final LwRootContainer[] rootContainer = new LwRootContainer[1];
        Generator.exposeForm(wizardData.myProject, formFile, rootContainer);
        final String classToBind = rootContainer[0].getClassToBind();
        if (classToBind == null) {
            Messages.showInfoMessage(project, UIDesignerBundle.message("info.form.not.bound"),
                    UIDesignerBundle.message("title.data.binding.wizard"));
            return;
        }

        final PsiClass boundClass = FormEditingUtil.findClassToBind(module, classToBind);
        if (boundClass == null) {
            Messages.showErrorDialog(project,
                    UIDesignerBundle.message("error.bound.to.not.found.class", classToBind),
                    UIDesignerBundle.message("title.data.binding.wizard"));
            return;
        }

        Generator.prepareWizardData(wizardData, boundClass);

        if (!hasBinding(rootContainer[0])) {
            Messages.showInfoMessage(project, UIDesignerBundle.message("info.no.bound.components"),
                    UIDesignerBundle.message("title.data.binding.wizard"));
            return;
        }

        if (!wizardData.myBindToNewBean) {
            final String[] variants = new String[] { UIDesignerBundle.message("action.alter.data.binding"),
                    UIDesignerBundle.message("action.bind.to.another.bean"),
                    CommonBundle.getCancelButtonText() };
            final int result = Messages.showYesNoCancelDialog(project,
                    MessageFormat.format(UIDesignerBundle.message("info.data.binding.regenerate"),
                            wizardData.myBeanClass.getQualifiedName()),
                    UIDesignerBundle.message("title.data.binding"), variants[0], variants[1], variants[2],
                    Messages.getQuestionIcon());
            if (result == 0) {
                // do nothing here
            } else if (result == 1) {
                wizardData.myBindToNewBean = true;
            } else {
                return;
            }
        }

        final DataBindingWizard wizard = new DataBindingWizard(project, formFile, wizardData);
        wizard.show();
    } catch (Generator.MyException exc) {
        Messages.showErrorDialog(project, exc.getMessage(), CommonBundle.getErrorTitle());
    }
}

From source file:com.intellij.uiDesigner.propertyInspector.editors.string.StringEditorDialog.java

License:Apache License

@Nullable
public static String saveModifiedPropertyValue(final Module module, final StringDescriptor descriptor,
        final Locale locale, final String editedValue, final PsiFile formFile) {
    final PropertiesReferenceManager manager = PropertiesReferenceManager.getInstance(module.getProject());
    final PropertiesFile propFile = manager.findPropertiesFile(module, descriptor.getDottedBundleName(),
            locale);/*w  w w  .  j a  v a  2 s.c  o m*/
    if (propFile != null) {
        final IProperty propertyByKey = propFile.findPropertyByKey(descriptor.getKey());
        if (propertyByKey instanceof Property && !editedValue.equals(propertyByKey.getValue())) {
            final Collection<PsiReference> references = findPropertyReferences((Property) propertyByKey,
                    module);

            String newKeyName = null;
            if (references.size() > 1) {
                final int rc = Messages.showYesNoCancelDialog(module.getProject(),
                        UIDesignerBundle.message("edit.text.multiple.usages", propertyByKey.getUnescapedKey(),
                                references.size()),
                        UIDesignerBundle.message("edit.text.multiple.usages.title"),
                        UIDesignerBundle.message("edit.text.change.all"),
                        UIDesignerBundle.message("edit.text.make.unique"), CommonBundle.getCancelButtonText(),
                        Messages.getWarningIcon());
                if (rc == 2) {
                    return null;
                }
                if (rc == 1) {
                    newKeyName = promptNewKeyName(module.getProject(), propFile, descriptor.getKey());
                    if (newKeyName == null)
                        return null;
                }
            }
            final ReadonlyStatusHandler.OperationStatus operationStatus = ReadonlyStatusHandler
                    .getInstance(module.getProject()).ensureFilesWritable(propFile.getVirtualFile());
            if (operationStatus.hasReadonlyFiles()) {
                return null;
            }
            final String newKeyName1 = newKeyName;
            CommandProcessor.getInstance().executeCommand(module.getProject(), new Runnable() {
                public void run() {
                    UndoUtil.markPsiFileForUndo(formFile);
                    ApplicationManager.getApplication().runWriteAction(new Runnable() {
                        public void run() {
                            PsiDocumentManager.getInstance(module.getProject()).commitAllDocuments();
                            try {
                                if (newKeyName1 != null) {
                                    propFile.addProperty(newKeyName1, editedValue);
                                } else {
                                    final IProperty propertyByKey = propFile
                                            .findPropertyByKey(descriptor.getKey());
                                    if (propertyByKey != null) {
                                        propertyByKey.setValue(editedValue);
                                    }
                                }
                            } catch (IncorrectOperationException e) {
                                LOG.error(e);
                            }
                        }
                    });
                }
            }, UIDesignerBundle.message("command.update.property"), null);
            return newKeyName;
        }
    }
    return null;
}