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

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

Introduction

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

Prototype

public static void showErrorDialog(@Nullable Component component, String message,
            @NotNull @Nls(capitalization = Nls.Capitalization.Title) String title) 

Source Link

Usage

From source file:action.ConvertToOtherLanguages.java

License:Apache License

public static void showErrorDialog(Project project, String msg) {
    Messages.showErrorDialog(project, msg, "Error");
}

From source file:bazaar4idea.util.BzrUIUtil.java

License:Apache License

/**
 * Show error associated with the specified operation
 *
 * @param project   the project//from   www .  j av a2 s  .c  o  m
 * @param message   the error description
 * @param operation the operation name
 */
public static void showOperationError(final Project project, final String operation, final String message) {
    Messages.showErrorDialog(project, message, BzrBundle.message("error.occurred.during", operation));
}

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

License:Apache License

private static void handleImportException(@Nullable Project project, @NotNull Exception e) {
    String message = String.format("Project import failed: %s", e.getMessage());
    Messages.showErrorDialog(project, message, "Import Project");
    LOG.error(e);//from   w ww  .  j a v  a 2  s  . c  om
}

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);
        }/* ww w.  java 2 s  .c om*/
        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. java 2  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.actions.license.ShowLicensesUsedAction.java

License:Apache License

@Override
public void actionPerformed(AnActionEvent e) {
    Project project = getEventProject(e);

    new Task.Backgroundable(project, "Collecting Licenses", true) {
        public String myLicenseText;

        @Override//from   w w  w .j  a  v  a  2s.  c  o m
        public void run(@NotNull ProgressIndicator indicator) {
            indicator.setIndeterminate(true);

            Path ideHome = Paths.get(PathManager.getHomePath());
            LicensesLocator locator = new LicensesLocator(ideHome, SystemInfo.isMac);
            CompletableFuture<String> cf = new LicenseTextCollector(ideHome, locator.getLicenseFiles())
                    .getLicenseText();

            while (!indicator.isCanceled()) {
                try {
                    myLicenseText = cf.get(100, TimeUnit.MILLISECONDS);
                    return;
                } catch (InterruptedException e) {
                    return;
                } catch (ExecutionException e) {
                    throw new RuntimeException(e.getCause());
                } catch (TimeoutException ignored) {
                }
            }
        }

        @Override
        public void onSuccess() {
            LicenseDialog licenseDialog = new LicenseDialog(project, myLicenseText);
            licenseDialog.init();
            try {
                licenseDialog.show();
            } catch (Exception ex) {
                Logger.getInstance(ShowLicensesUsedAction.class).error(e);
            }
        }

        @Override
        public void onError(@NotNull Exception error) {
            Messages.showErrorDialog(project, "Error collecting licenses: " + error.toString(),
                    "Show Licenses");
        }
    }.queue();
}

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

License:Apache License

@Nullable
@Override/*from   w w w  . j a  va  2  s. c om*/
protected ModelWizard createWizard(@NotNull AndroidFacet facet) {
    Module module = facet.getModule();
    Project project = module.getProject();
    AndroidModuleModel androidModel = AndroidModuleModel.get(module);
    if (androidModel != null) {
        AndroidVersion minSdkVersion = androidModel.getMinSdkVersion();
        String version = androidModel.getAndroidProject().getModelVersion();
        GradleVersion revision = GradleVersion.parse(version);

        if (revision.compareIgnoringQualifiers(VECTOR_ASSET_GENERATION_REVISION) < 0
                && (minSdkVersion == null || minSdkVersion.getApiLevel() < VECTOR_DRAWABLE_API_LEVEL)) {
            Messages.showErrorDialog(project, ERROR_MESSAGE, ERROR_TITLE);
            return null;
        }
    }

    ModelWizard.Builder wizardBuilder = new ModelWizard.Builder();
    wizardBuilder.addStep(new NewVectorAssetStep(new GenerateVectorIconModel(facet), facet));
    return wizardBuilder.build();
}

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

License:Apache License

private static void forkResourceFile(@NotNull Project project, @NotNull final ResourceFolderType folderType,
        @NotNull final VirtualFile file, @Nullable final XmlFile xmlFile, @Nullable String myNewFolder,
        @Nullable Configuration configuration, boolean open) {
    final FolderConfiguration folderConfig;
    if (myNewFolder == null) {
        // Open a file chooser to select the configuration to be created
        VirtualFile parentFolder = file.getParent();
        assert parentFolder != null;
        VirtualFile res = parentFolder.getParent();
        folderConfig = selectFolderConfig(project, res, folderType);
    } else {//from  w  w w .j ava2  s.  c om
        folderConfig = FolderConfiguration.getConfigForFolder(myNewFolder);
    }
    if (folderConfig == null) {
        return;
    }

    final Computable<Pair<String, VirtualFile>> computable = new Computable<Pair<String, VirtualFile>>() {
        @Override
        public Pair<String, VirtualFile> compute() {
            String folderName = folderConfig.getFolderName(folderType);
            try {
                VirtualFile parentFolder = file.getParent();
                assert parentFolder != null;
                VirtualFile res = parentFolder.getParent();
                VirtualFile newParentFolder = res.findChild(folderName);
                if (newParentFolder == null) {
                    newParentFolder = res.createChildDirectory(this, folderName);
                    if (newParentFolder == null) {
                        String message = String.format("Could not create folder %1$s in %2$s", folderName,
                                res.getPath());
                        return Pair.of(message, null);
                    }
                }

                final VirtualFile existing = newParentFolder.findChild(file.getName());
                if (existing != null && existing.exists()) {
                    String message = String.format("File 'res/%1$s/%2$s' already exists!", folderName,
                            file.getName());
                    return Pair.of(message, null);
                }

                // Attempt to get the document from the PSI file rather than the file on disk: get edited contents too
                String text;
                if (xmlFile != null) {
                    text = xmlFile.getText();
                } else {
                    text = StreamUtil.readText(file.getInputStream(), "UTF-8");
                }
                VirtualFile newFile = newParentFolder.createChildData(this, file.getName());
                VfsUtil.saveText(newFile, text);
                return Pair.of(null, newFile);
            } catch (IOException e2) {
                String message = String.format("Failed to create File 'res/%1$s/%2$s' : %3$s", folderName,
                        file.getName(), e2.getMessage());
                return Pair.of(message, null);
            }
        }
    };

    WriteCommandAction<Pair<String, VirtualFile>> action = new WriteCommandAction<Pair<String, VirtualFile>>(
            project, "Add Resource") {
        @Override
        protected void run(@NotNull Result<Pair<String, VirtualFile>> result) throws Throwable {
            result.setResult(computable.compute());
        }
    };
    Pair<String, VirtualFile> result = action.execute().getResultObject();

    String error = result.getFirst();
    VirtualFile newFile = result.getSecond();
    if (error != null) {
        Messages.showErrorDialog(project, error, "Create Resource");
    } else {
        // First create a compatible configuration based on the current configuration
        if (configuration != null) {
            ConfigurationManager configurationManager = configuration.getConfigurationManager();
            configurationManager.createSimilar(newFile, file);
        }

        if (open) {
            OpenFileDescriptor descriptor = new OpenFileDescriptor(project, newFile, -1);
            FileEditorManager.getInstance(project).openEditor(descriptor, true);
        }
    }
}

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

License:Apache License

@Override
public void actionPerformed(AnActionEvent e) {
    final Project project = e.getProject();
    try {//www  .  j av a2 s  . c  o m
        BufferedImage image = getImage();
        assert image != null && project != null; // enforced by update() above

        // We need to create a temp file since the image preview editor requires a real file
        File backingFile = FileUtil.createTempFile("screenshot", SdkConstants.DOT_PNG, true);
        ImageIO.write(image, SdkConstants.EXT_PNG, backingFile);

        final ScreenshotViewer viewer = new ScreenshotViewer(project, image, backingFile, null,
                getDeviceName());
        viewer.showAndGetOk().doWhenDone(new Consumer<Boolean>() {
            @Override
            public void consume(Boolean ok) {
                if (ok) {
                    File screenshot = viewer.getScreenshot();
                    VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(screenshot);
                    if (vf != null) {
                        FileEditorManager.getInstance(project).openFile(vf, true);
                    }
                }
            }
        });
    } catch (Exception ex) {
        Messages.showErrorDialog(project, AndroidBundle.message("android.ddms.screenshot.generic.error", e),
                AndroidBundle.message("android.ddms.actions.screenshot"));
    }
}

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

License:Apache License

/**
 * Launch the given AVD in the emulator.
 * @return a future with the device that was launched
 *///from w w w. ja  v a  2  s  .  com
@NotNull
public ListenableFuture<IDevice> startAvd(@Nullable final Project project, @NotNull final AvdInfo info) {
    if (!initIfNecessary()) {
        return Futures.immediateFailedFuture(new RuntimeException("No Android SDK Found"));
    }
    AccelerationErrorCode error = checkAcceleration();
    ListenableFuture<IDevice> errorResult = handleAccelerationError(project, info, error);
    if (errorResult != null) {
        return errorResult;
    }

    final File emulatorBinary = getEmulatorBinary();
    if (!emulatorBinary.isFile()) {
        IJ_LOG.error("No emulator binary found!");
        return Futures.immediateFailedFuture(new RuntimeException("No emulator binary found"));
    }

    final String avdName = info.getName();

    // TODO: The emulator stores pid of the running process inside the .lock file (userdata-qemu.img.lock in Linux and
    // userdata-qemu.img.lock/pid on Windows). We should detect whether those lock files are stale and if so, delete them without showing
    // this error. Either the emulator provides a command to do that, or we learn about its internals (qemu/android/utils/filelock.c) and
    // perform the same action here. If it is not stale, then we should show this error and if possible, bring that window to the front.
    if (myAvdManager.isAvdRunning(info, SDK_LOG)) {
        String baseFolder;
        try {
            baseFolder = myAvdManager.getBaseAvdFolder().getAbsolutePath();
        } catch (AndroidLocation.AndroidLocationException e) {
            baseFolder = "$HOME";
        }

        String message = String
                .format("AVD %1$s is already running.\n" + "If that is not the case, delete the files at\n"
                        + "   %2$s/%1$s.avd/*.lock\n" + "and try again.", avdName, baseFolder);
        Messages.showErrorDialog(project, message, "AVD Manager");
        return Futures.immediateFailedFuture(new RuntimeException(message));
    }

    GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.setExePath(emulatorBinary.getPath());

    addParameters(info, commandLine);

    EmulatorRunner runner = new EmulatorRunner(commandLine, info);
    EmulatorRunner.ProcessOutputCollector collector = new EmulatorRunner.ProcessOutputCollector();
    runner.addProcessListener(collector);

    final ProcessHandler processHandler;
    try {
        processHandler = runner.start();
    } catch (ExecutionException e) {
        IJ_LOG.error("Error launching emulator", e);
        return Futures.immediateFailedFuture(
                new RuntimeException(String.format("Error launching emulator %1$s ", avdName), e));
    }

    // If we're using qemu2, it has its own progress bar, so put ours in the background. Otherwise show it.
    final ProgressWindow p = hasQEMU2Installed()
            ? new BackgroundableProcessIndicator(project, "Launching Emulator",
                    PerformInBackgroundOption.ALWAYS_BACKGROUND, "", "", false)
            : new ProgressWindow(false, true, project);
    p.setIndeterminate(false);
    p.setDelayInMillis(0);

    // It takes >= 8 seconds to start the Emulator. Display a small progress indicator otherwise it seems like
    // the action wasn't invoked and users tend to click multiple times on it, ending up with several instances of the emulator
    ApplicationManager.getApplication().executeOnPooledThread(() -> {
        try {
            p.start();
            p.setText("Starting AVD...");
            for (double d = 0; d < 1; d += 1.0 / 80) {
                p.setFraction(d);
                //noinspection BusyWait
                Thread.sleep(100);
                if (processHandler.isProcessTerminated()) {
                    break;
                }
            }
        } catch (InterruptedException ignore) {
        } finally {
            p.stop();
            p.processFinish();
        }

        processHandler.removeProcessListener(collector);
        String message = limitErrorMessage(collector.getText());

        if (message.toLowerCase(Locale.ROOT).contains("error")
                || processHandler.isProcessTerminated() && !message.trim().isEmpty()) {
            ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(project,
                    "Cannot launch AVD in emulator.\nOutput:\n" + message, avdName));
        }
    });

    return EmulatorConnectionListener.getDeviceForEmulator(project, info.getName(), processHandler, 5,
            TimeUnit.MINUTES);
}