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

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

Introduction

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

Prototype

@OkCancelResult
@Deprecated
public static int showOkCancelDialog(@NotNull Component parent, String message,
        @Nls(capitalization = Nls.Capitalization.Title) String title, Icon icon) 

Source Link

Usage

From source file:com.android.tools.idea.actions.AndroidInferNullityAnnotationAction.java

License:Apache License

protected boolean checkModules(@NotNull Project project, @NotNull AnalysisScope scope,
        @NotNull Map<Module, PsiFile> modules) {
    Set<Module> modulesWithoutAnnotations = new HashSet<>();
    Set<Module> modulesWithLowVersion = new HashSet<>();
    for (Module module : modules.keySet()) {
        AndroidModuleInfo info = AndroidModuleInfo.get(module);
        if (info != null && info.getBuildSdkVersion() != null
                && info.getBuildSdkVersion().getFeatureLevel() < MIN_SDK_WITH_NULLABLE) {
            modulesWithLowVersion.add(module);
        }/*from  w ww  . j a  v  a 2 s. co  m*/
        GradleBuildModel buildModel = GradleBuildModel.get(module);
        if (buildModel == null) {
            LOG.warn("Unable to find Gradle build model for module " + module.getModuleFilePath());
            continue;
        }
        boolean dependencyFound = false;
        DependenciesModel dependenciesModel = buildModel.dependencies();
        if (dependenciesModel != null) {
            for (ArtifactDependencyModel dependency : dependenciesModel.artifacts(COMPILE)) {
                String notation = dependency.compactNotation().value();
                if (notation.startsWith(SdkConstants.APPCOMPAT_LIB_ARTIFACT)
                        || notation.startsWith(SdkConstants.SUPPORT_LIB_ARTIFACT)
                        || notation.startsWith(SdkConstants.ANNOTATIONS_LIB_ARTIFACT)) {
                    dependencyFound = true;
                    break;
                }
            }
        }
        if (!dependencyFound) {
            modulesWithoutAnnotations.add(module);
        }
    }

    if (!modulesWithLowVersion.isEmpty()) {
        Messages.showErrorDialog(project,
                String.format(
                        "Infer Nullity Annotations requires the project sdk level be set to %1$d or greater.",
                        MIN_SDK_WITH_NULLABLE),
                "Infer Nullity Annotations");
        return false;
    }
    if (modulesWithoutAnnotations.isEmpty()) {
        return true;
    }
    String moduleNames = StringUtil.join(modulesWithoutAnnotations, Module::getName, ", ");
    int count = modulesWithoutAnnotations.size();
    String message = String.format(
            "The %1$s %2$s %3$sn't refer to the existing '%4$s' library with Android nullity annotations. \n\n"
                    + "Would you like to add the %5$s now?",
            pluralize("module", count), moduleNames, count > 1 ? "do" : "does",
            SupportLibrary.SUPPORT_ANNOTATIONS.getArtifactId(), pluralize("dependency", count));
    if (Messages.showOkCancelDialog(project, message, "Infer Nullity Annotations",
            Messages.getErrorIcon()) == Messages.OK) {
        LocalHistoryAction action = LocalHistory.getInstance().startAction(ADD_DEPENDENCY);
        try {
            new WriteCommandAction(project, ADD_DEPENDENCY) {
                @Override
                protected void run(@NotNull Result result) throws Throwable {
                    RepositoryUrlManager manager = RepositoryUrlManager.get();
                    String annotationsLibraryCoordinate = manager
                            .getLibraryStringCoordinate(SupportLibrary.SUPPORT_ANNOTATIONS, true);
                    for (Module module : modulesWithoutAnnotations) {
                        addDependency(module, annotationsLibraryCoordinate);
                    }
                    GradleSyncInvoker.Request request = new GradleSyncInvoker.Request()
                            .setGenerateSourcesOnSuccess(false);
                    GradleSyncInvoker.getInstance().requestProjectSync(project, request,
                            new GradleSyncListener.Adapter() {
                                @Override
                                public void syncSucceeded(@NotNull Project project) {
                                    restartAnalysis(project, scope);
                                }
                            });
                }
            }.execute();
        } finally {
            action.finish();
        }
    }
    return false;
}

From source file:com.android.tools.idea.actions.annotations.InferSupportAnnotationsAction.java

License:Apache License

protected boolean checkModules(@NotNull Project project, @NotNull AnalysisScope scope,
        @NotNull Map<Module, PsiFile> modules) {
    Set<Module> modulesWithoutAnnotations = new HashSet<>();
    Set<Module> modulesWithLowVersion = new HashSet<>();
    for (Module module : modules.keySet()) {
        AndroidModuleInfo info = AndroidModuleInfo.get(module);
        if (info != null && info.getBuildSdkVersion() != null
                && info.getBuildSdkVersion().getFeatureLevel() < MIN_SDK_WITH_NULLABLE) {
            modulesWithLowVersion.add(module);
        }/*  w ww  . j  a v  a2  s. c om*/
        GradleBuildModel buildModel = GradleBuildModel.get(module);
        if (buildModel == null) {
            Logger.getInstance(InferSupportAnnotationsAction.class)
                    .warn("Unable to find Gradle build model for module " + module.getModuleFilePath());
            continue;
        }
        boolean dependencyFound = false;
        DependenciesModel dependenciesModel = buildModel.dependencies();
        if (dependenciesModel != null) {
            for (ArtifactDependencyModel dependency : dependenciesModel.artifacts(COMPILE)) {
                String notation = dependency.compactNotation().value();
                if (notation.startsWith(SdkConstants.APPCOMPAT_LIB_ARTIFACT)
                        || notation.startsWith(SdkConstants.SUPPORT_LIB_ARTIFACT)
                        || notation.startsWith(SdkConstants.ANNOTATIONS_LIB_ARTIFACT)) {
                    dependencyFound = true;
                    break;
                }
            }
        }
        if (!dependencyFound) {
            modulesWithoutAnnotations.add(module);
        }
    }

    if (!modulesWithLowVersion.isEmpty()) {
        Messages.showErrorDialog(project,
                String.format(
                        "Infer Support Annotations requires the project sdk level be set to %1$d or greater.",
                        MIN_SDK_WITH_NULLABLE),
                "Infer Support Annotations");
        return false;
    }
    if (modulesWithoutAnnotations.isEmpty()) {
        return true;
    }
    String moduleNames = StringUtil.join(modulesWithoutAnnotations, Module::getName, ", ");
    int count = modulesWithoutAnnotations.size();
    String message = String.format(
            "The %1$s %2$s %3$sn't refer to the existing '%4$s' library with Android nullity annotations. \n\n"
                    + "Would you like to add the %5$s now?",
            pluralize("module", count), moduleNames, count > 1 ? "do" : "does",
            SupportLibrary.SUPPORT_ANNOTATIONS.getArtifactId(), pluralize("dependency", count));
    if (Messages.showOkCancelDialog(project, message, "Infer Nullity Annotations",
            Messages.getErrorIcon()) == Messages.OK) {
        LocalHistoryAction action = LocalHistory.getInstance().startAction(ADD_DEPENDENCY);
        try {
            new WriteCommandAction(project, ADD_DEPENDENCY) {
                @Override
                protected void run(@NotNull Result result) throws Throwable {
                    RepositoryUrlManager manager = RepositoryUrlManager.get();
                    String annotationsLibraryCoordinate = manager
                            .getLibraryStringCoordinate(SupportLibrary.SUPPORT_ANNOTATIONS, true);
                    for (Module module : modulesWithoutAnnotations) {
                        addDependency(module, annotationsLibraryCoordinate);
                    }
                    GradleSyncInvoker.Request request = new GradleSyncInvoker.Request()
                            .setGenerateSourcesOnSuccess(false);
                    GradleSyncInvoker.getInstance().requestProjectSync(project, request,
                            new GradleSyncListener.Adapter() {
                                @Override
                                public void syncSucceeded(@NotNull Project project) {
                                    restartAnalysis(project, scope);
                                }
                            });
                }
            }.execute();
        } finally {
            action.finish();
        }
    }
    return false;
}

From source file:com.android.tools.idea.avdmanager.AccelerationErrorSolution.java

License:Apache License

/**
 * Prompts the user to reboot now, and performs the reboot if accepted.
 * HAXM Installer may need a reboot only on Windows, so this method is intended to work only on Windows
 * and only for HAXM installer use case/*  w w w  .j  ava2s.  co m*/
 *
 * @param prompt the message to display to the user
 * @exception ExecutionException if the shutdown command fails to execute
 * @return No return value
 */
public static void promptAndReboot(@NotNull String prompt) throws ExecutionException {
    int response = Messages.showOkCancelDialog((Project) null, prompt, "Reboot Now",
            Messages.getQuestionIcon());
    if (response == Messages.OK) {
        GeneralCommandLine reboot = new ElevatedCommandLine();
        reboot.setExePath("shutdown");
        reboot.addParameters("/g", "/t", "10"); // shutdown & restart after a 10 sec delay
        reboot.setWorkDirectory(FileUtilRt.getTempDirectory());
        execute(reboot);
    }
}

From source file:com.android.tools.idea.avdmanager.AvdManagerConnection.java

License:Apache License

/**
 * Handle the {@link AccelerationErrorCode} found when attempting to start an AVD.
 * @param project/*from   ww  w  . ja v  a2s . c o  m*/
 * @param error
 * @return a future with a device that was launched delayed, or null if startAvd should proceed to start the AVD.
 */
@Nullable
private ListenableFuture<IDevice> handleAccelerationError(@Nullable final Project project,
        @NotNull final AvdInfo info, @NotNull AccelerationErrorCode error) {
    switch (error) {
    case ALREADY_INSTALLED:
        return null;
    case TOOLS_UPDATE_REQUIRED:
    case PLATFORM_TOOLS_UPDATE_ADVISED:
    case SYSTEM_IMAGE_UPDATE_ADVISED:
        // Do not block emulator from running if we need updates (run with degradated performance):
        return null;
    case NO_EMULATOR_INSTALLED:
        // report this error below
        break;
    default:
        Abi abi = Abi.getEnum(info.getAbiType());
        boolean isAvdIntel = abi == Abi.X86 || abi == Abi.X86_64;
        if (!isAvdIntel) {
            // Do not block Arm and Mips emulators from running without an accelerator:
            return null;
        }
        // report all other errors
        break;
    }
    String accelerator = SystemInfo.isLinux ? "KVM" : "Intel HAXM";
    int result = Messages.showOkCancelDialog(project,
            String.format("%1$s is required to run this AVD.\n%2$s\n\n%3$s\n", accelerator, error.getProblem(),
                    error.getSolutionMessage()),
            error.getSolution().getDescription(), AllIcons.General.WarningDialog);
    if (result != Messages.OK || error.getSolution() == AccelerationErrorSolution.SolutionCode.NONE) {
        return Futures.immediateFailedFuture(new RuntimeException("Could not start AVD"));
    }
    final SettableFuture<ListenableFuture<IDevice>> future = SettableFuture.create();
    Runnable retry = () -> future.set(startAvd(project, info));
    Runnable cancel = () -> future.setException(new RuntimeException("Retry after fixing problem by hand"));
    Runnable action = AccelerationErrorSolution.getActionForFix(error, project, retry, cancel);
    ApplicationManager.getApplication().invokeLater(action);
    return Futures.dereference(future);
}

From source file:com.android.tools.idea.gradle.dependencies.GradleDependencyManager.java

License:Apache License

private static boolean userWantToAddDependencies(@NotNull Module module,
        @NotNull Collection<GradleCoordinate> missing) {
    String libraryNames = StringUtil.join(missing, GradleCoordinate::getArtifactId, ", ");
    String message = String.format(
            "This operation requires the %1$s %2$s. \n\nWould you like to add %3$s %1$s now?",
            pluralize("library", missing.size()), libraryNames, pluralize("this", missing.size()));
    Project project = module.getProject();
    return Messages.showOkCancelDialog(project, message, "Add Project Dependency",
            Messages.getErrorIcon()) == Messages.OK;
}

From source file:com.google.cloud.tools.intellij.debugger.CloudDebuggerRunner.java

License:Apache License

private void ensureSingleDebugSession(Project project) throws RunCanceledByUserException {

    List<CloudDebugProcessState> backgroundSessions = getBackgroundDebugStates(project);
    if (backgroundSessions.size() > 0) {
        for (CloudDebugProcessState cdps : backgroundSessions) {
            cdps.setListenInBackground(false);
        }/* w  w  w.  j  av  a  2s. c  o m*/
    }

    List<CloudDebugProcess> activeDebugProcesses = getActiveDebugProcesses(project);
    if (activeDebugProcesses.size() > 0) {
        int result = Messages.showOkCancelDialog(project,
                GctBundle.getString("clouddebug.stop.and.create.new.session"),
                GctBundle.getString("clouddebug.message.title"), GoogleCloudToolsIcons.STACKDRIVER_DEBUGGER);
        if (result == Messages.OK) {
            for (CloudDebugProcess cdb : activeDebugProcesses) {
                cdb.getProcessHandler().detachProcess();
            }
        } else {
            throw new RunCanceledByUserException();
        }
    }
}

From source file:com.igormaznitsa.ideamindmap.editor.MindMapDialogProvider.java

License:Apache License

@Override
public boolean msgConfirmOkCancel(final String title, final String text) {
    return Messages.showOkCancelDialog(this.project, text, title, Messages.getQuestionIcon()) == Messages.OK;
}

From source file:com.intellij.codeInsight.actions.AbstractLayoutCodeProcessor.java

License:Apache License

private void runProcessOnFiles(final String where, final List<PsiFile> array) {
    boolean success = FileModificationService.getInstance().preparePsiElementsForWrite(array);

    if (!success) {
        List<PsiFile> writeables = new ArrayList<PsiFile>();
        for (PsiFile file : array) {
            if (file.isWritable()) {
                writeables.add(file);//from  ww  w.  j av  a  2 s .  com
            }
        }
        if (writeables.isEmpty())
            return;
        int res = Messages.showOkCancelDialog(myProject,
                CodeInsightBundle.message("error.dialog.readonly.files.message", where),
                CodeInsightBundle.message("error.dialog.readonly.files.title"), Messages.getQuestionIcon());
        if (res != Messages.OK) {
            return;
        }

        array.clear();
        array.addAll(writeables);
    }

    final Runnable[] resultRunnable = new Runnable[1];
    runLayoutCodeProcess(new Runnable() {
        @Override
        public void run() {
            resultRunnable[0] = preprocessFiles(array);
        }
    }, new Runnable() {
        @Override
        public void run() {
            if (resultRunnable[0] != null) {
                resultRunnable[0].run();
            }
        }
    }, array.size() > 1);
}

From source file:com.intellij.codeInsight.daemon.impl.quickfix.AddModuleDependencyFix.java

License:Apache License

private static void showCircularWarningAndContinue(final Project project,
        final Pair<Module, Module> circularModules, final Module classModule, final Runnable doit) {
    final String message = QuickFixBundle.message("orderEntry.fix.circular.dependency.warning",
            classModule.getName(), circularModules.getFirst().getName(), circularModules.getSecond().getName());
    if (ApplicationManager.getApplication().isUnitTestMode())
        throw new RuntimeException(message);
    ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override// w w w.j  a v a2  s. c om
        public void run() {
            if (!project.isOpen())
                return;
            int ret = Messages.showOkCancelDialog(project, message,
                    QuickFixBundle.message("orderEntry.fix.title.circular.dependency.warning"),
                    Messages.getWarningIcon());
            if (ret == 0) {
                ApplicationManager.getApplication().runWriteAction(doit);
            }
        }
    });
}

From source file:com.intellij.codeInsight.intention.impl.CreateFieldFromParameterDialog.java

License:Apache License

@Override
protected void doOKAction() {
    if (myCbFinal.isEnabled()) {
        PropertiesComponent.getInstance().setValue(PROPERTY_NAME, String.valueOf(myCbFinal.isSelected()));
    }/*w w w .  j av  a 2  s . co  m*/

    final PsiField[] fields = myTargetClass.getFields();
    for (PsiField field : fields) {
        if (field.getName().equals(getEnteredName())) {
            int result = Messages.showOkCancelDialog(getContentPane(),
                    CodeInsightBundle.message("dialog.create.field.from.parameter.already.exists.text",
                            getEnteredName()),
                    CodeInsightBundle.message("dialog.create.field.from.parameter.already.exists.title"),
                    Messages.getQuestionIcon());
            if (result == 0) {
                close(OK_EXIT_CODE);
            } else {
                return;
            }
        }
    }

    close(OK_EXIT_CODE);
}