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:org.intellij.images.actions.EditExternallyAction.java

License:Apache License

public void actionPerformed(AnActionEvent e) {
    Project project = e.getData(CommonDataKeys.PROJECT);
    VirtualFile[] files = e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);
    Options options = OptionsManager.getInstance().getOptions();
    String executablePath = options.getExternalEditorOptions().getExecutablePath();
    if (StringUtil.isEmpty(executablePath)) {
        Messages.showErrorDialog(project, ImagesBundle.message("error.empty.external.editor.path"),
                ImagesBundle.message("error.title.empty.external.editor.path"));
        OptionsConfigurabe.show(project);
    } else {/*from   w w w .  j  av  a 2 s  .  c  o  m*/
        if (files != null) {
            Map<String, String> env = EnvironmentUtil.getEnvironmentMap();
            for (String varName : env.keySet()) {
                if (SystemInfo.isWindows) {
                    executablePath = StringUtil.replace(executablePath, "%" + varName + "%", env.get(varName),
                            true);
                } else {
                    executablePath = StringUtil.replace(executablePath, "${" + varName + "}", env.get(varName),
                            false);
                }
            }
            executablePath = FileUtil.toSystemDependentName(executablePath);
            File executable = new File(executablePath);
            GeneralCommandLine commandLine = new GeneralCommandLine();
            final String path = executable.exists() ? executable.getAbsolutePath() : executablePath;
            if (SystemInfo.isMac) {
                commandLine.setExePath(ExecUtil.getOpenCommandPath());
                commandLine.addParameter("-a");
                commandLine.addParameter(path);
            } else {
                commandLine.setExePath(path);
            }

            ImageFileTypeManager typeManager = ImageFileTypeManager.getInstance();
            for (VirtualFile file : files) {
                if (file.isInLocalFileSystem() && typeManager.isImage(file)) {
                    commandLine.addParameter(VfsUtilCore.virtualToIoFile(file).getAbsolutePath());
                }
            }
            commandLine.setWorkDirectory(new File(executablePath).getParentFile());

            try {
                commandLine.createProcess();
            } catch (ExecutionException ex) {
                Messages.showErrorDialog(project, ex.getLocalizedMessage(),
                        ImagesBundle.message("error.title.launching.external.editor"));
                OptionsConfigurabe.show(project);
            }
        }
    }
}

From source file:org.intellij.lang.xpath.xslt.quickfix.DownloadManager.java

License:Apache License

public void fetch(@NotNull final String location) throws DownloadException {
    if (resourceManager.getResourceLocation(location, myProject) != location) {
        return;//w ww .  ja  va  2  s . c o m
    }

    myProgress.setText("Downloading " + location);

    File file = null;
    try {
        file = HttpRequests.request(location).connect(new HttpRequests.RequestProcessor<File>() {
            @Override
            public File process(@NotNull HttpRequests.Request request) throws IOException {
                String name = Integer.toHexString(System.identityHashCode(this)) + "_"
                        + Integer.toHexString(location.hashCode()) + "_"
                        + location.substring(location.lastIndexOf('/') + 1);
                return request.saveToFile(
                        new File(myResourcePath, name.lastIndexOf('.') == -1 ? name + ".xml" : name),
                        myProgress);
            }
        });

        try {
            //noinspection unchecked
            final Set<String>[] resourceDependencies = new Set[1];
            final VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
            if (vf != null) {
                PsiFile psiFile = PsiManager.getInstance(myProject).findFile(vf);
                if (psiFile != null && isAccepted(psiFile)) {
                    resourceDependencies[0] = getResourceDependencies(psiFile);
                    resourceManager.addResource(location, file.getAbsolutePath());
                } else {
                    ApplicationManager.getApplication().invokeLater(
                            () -> Messages.showErrorDialog(myProject,
                                    "Not a valid file: " + vf.getPresentableUrl(), "Download Problem"),
                            myProject.getDisposed());
                }
            }

            if (resourceDependencies[0] != null) {
                for (String s : resourceDependencies[0]) {
                    myProgress.checkCanceled();
                    myProgress.setFraction(0);
                    fetch(s);
                }
            }
        } catch (Error err) {
            Throwable e = err.getCause();
            if (e instanceof InvocationTargetException) {
                Throwable targetException = ((InvocationTargetException) e).getTargetException();
                if (targetException instanceof RuntimeException) {
                    throw (RuntimeException) targetException;
                } else if (targetException instanceof IOException) {
                    throw (IOException) targetException;
                } else if (!(targetException instanceof InterruptedException)) {
                    Logger.getInstance(getClass().getName()).error(e);
                }
            } else if (!(e instanceof InterruptedException)) {
                throw err;
            }
        }
    } catch (IOException e) {
        throw new DownloadException(location, e);
    } finally {
        if (file != null && resourceManager.getResourceLocation(location, myProject) == location) {
            // something went wrong. get rid of the file
            FileUtil.delete(file);
        }
    }
}

From source file:org.intellij.plugins.intelliLang.inject.AbstractLanguageInjectionSupport.java

License:Apache License

@Nullable
protected static BaseInjection showDefaultInjectionUI(final Project project, BaseInjection injection) {
    final BaseInjectionPanel panel = new BaseInjectionPanel(injection, project);
    panel.reset();//from  www .  j av a 2s  .c  o  m
    final DialogBuilder builder = new DialogBuilder(project);
    LanguageInjectionSupport support = InjectorUtils.findInjectionSupport(injection.getSupportId());
    if (support != null && support instanceof AbstractLanguageInjectionSupport) {
        builder.setHelpId(((AbstractLanguageInjectionSupport) support).getHelpId());
    }
    builder.addOkAction();
    builder.addCancelAction();
    builder.setDimensionServiceKey("#org.intellij.plugins.intelliLang.inject.config.ui.BaseInjectionDialog");
    builder.setCenterPanel(panel.getComponent());
    builder.setTitle(EditInjectionSettingsAction.EDIT_INJECTION_TITLE);
    builder.setOkOperation(new Runnable() {
        public void run() {
            try {
                panel.apply();
                builder.getDialogWrapper().close(DialogWrapper.OK_EXIT_CODE);
            } catch (Exception e) {
                final Throwable cause = e.getCause();
                final String message = e.getMessage() + (cause != null ? "\n  " + cause.getMessage() : "");
                Messages.showErrorDialog(project, message, "Unable to Save");
            }
        }
    });
    if (builder.show() == DialogWrapper.OK_EXIT_CODE) {
        return injection;
    }
    return null;
}

From source file:org.intellij.plugins.intelliLang.InjectionsSettingsUI.java

License:Apache License

private DefaultActionGroup createActions() {
    final Consumer<BaseInjection> consumer = new Consumer<BaseInjection>() {
        @Override//from  w  w  w  .  j a v  a2  s .  c  om
        public void consume(final BaseInjection injection) {
            addInjection(injection);
        }
    };
    final Factory<BaseInjection> producer = new NullableFactory<BaseInjection>() {
        @Override
        public BaseInjection create() {
            final InjInfo info = getSelectedInjection();
            return info == null ? null : info.injection;
        }
    };
    for (LanguageInjectionSupport support : InjectorUtils.getActiveInjectionSupports()) {
        ContainerUtil.addAll(myAddActions, support.createAddActions(myProject, consumer));
        final AnAction action = support.createEditAction(myProject, producer);
        myEditActions.put(support.getId(),
                action == null ? AbstractLanguageInjectionSupport.createDefaultEditAction(myProject, producer)
                        : action);
        mySupports.put(support.getId(), support);
    }
    Collections.sort(myAddActions, new Comparator<AnAction>() {
        @Override
        public int compare(final AnAction o1, final AnAction o2) {
            return Comparing.compare(o1.getTemplatePresentation().getText(),
                    o2.getTemplatePresentation().getText());
        }
    });

    final DefaultActionGroup group = new DefaultActionGroup();
    final AnAction addAction = new AnAction("Add", "Add", IconUtil.getAddIcon()) {
        @Override
        public void update(final AnActionEvent e) {
            e.getPresentation().setEnabled(!myAddActions.isEmpty());
        }

        @Override
        public void actionPerformed(final AnActionEvent e) {
            performAdd(e);
        }
    };
    final AnAction removeAction = new AnAction("Remove", "Remove", PlatformIcons.DELETE_ICON) {
        @Override
        public void update(final AnActionEvent e) {
            boolean enabled = false;
            for (InjInfo info : getSelectedInjections()) {
                if (!info.bundled) {
                    enabled = true;
                    break;
                }
            }
            e.getPresentation().setEnabled(enabled);
        }

        @Override
        public void actionPerformed(final AnActionEvent e) {
            performRemove();
        }
    };

    final AnAction editAction = new AnAction("Edit", "Edit", PlatformIcons.PROPERTIES_ICON) {
        @Override
        public void update(final AnActionEvent e) {
            final AnAction action = getEditAction();
            e.getPresentation().setEnabled(action != null);
            if (action != null) {
                action.update(e);
            }
        }

        @Override
        public void actionPerformed(final AnActionEvent e) {
            performEditAction(e);
        }
    };
    final AnAction copyAction = new AnAction("Duplicate", "Duplicate", PlatformIcons.COPY_ICON) {
        @Override
        public void update(final AnActionEvent e) {
            final AnAction action = getEditAction();
            e.getPresentation().setEnabled(action != null);
            if (action != null) {
                action.update(e);
            }
        }

        @Override
        public void actionPerformed(final AnActionEvent e) {
            final InjInfo injection = getSelectedInjection();
            if (injection != null) {
                addInjection(injection.injection.copy());
                //performEditAction(e);
            }
        }
    };
    group.add(addAction);
    group.add(removeAction);
    group.add(copyAction);
    group.add(editAction);

    addAction.registerCustomShortcutSet(CommonShortcuts.INSERT, myInjectionsTable);
    removeAction.registerCustomShortcutSet(CommonShortcuts.DELETE, myInjectionsTable);
    editAction.registerCustomShortcutSet(CommonShortcuts.ENTER, myInjectionsTable);

    group.addSeparator();
    group.add(new AnAction("Enable Selected Injections", "Enable Selected Injections",
            PlatformIcons.SELECT_ALL_ICON) {
        @Override
        public void actionPerformed(final AnActionEvent e) {
            performSelectedInjectionsEnabled(true);
        }
    });
    group.add(new AnAction("Disable Selected Injections", "Disable Selected Injections",
            PlatformIcons.UNSELECT_ALL_ICON) {
        @Override
        public void actionPerformed(final AnActionEvent e) {
            performSelectedInjectionsEnabled(false);
        }
    });

    new AnAction("Toggle") {
        @Override
        public void actionPerformed(final AnActionEvent e) {
            performToggleAction();
        }
    }.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0)),
            myInjectionsTable);

    if (myInfos.length > 1) {
        group.addSeparator();
        final AnAction shareAction = new AnAction("Make Global", null, PlatformIcons.IMPORT_ICON) {
            @Override
            public void actionPerformed(final AnActionEvent e) {
                final List<InjInfo> injections = getSelectedInjections();
                final CfgInfo cfg = getTargetCfgInfo(injections);
                if (cfg == null) {
                    return;
                }
                for (InjInfo info : injections) {
                    if (info.cfgInfo == cfg) {
                        continue;
                    }
                    if (info.bundled) {
                        continue;
                    }
                    info.cfgInfo.injectionInfos.remove(info);
                    cfg.addInjection(info.injection);
                }
                final int[] selectedRows = myInjectionsTable.getSelectedRows();
                myInjectionsTable.getListTableModel().setItems(getInjInfoList(myInfos));
                TableUtil.selectRows(myInjectionsTable, selectedRows);
            }

            @Override
            public void update(final AnActionEvent e) {
                final CfgInfo cfg = getTargetCfgInfo(getSelectedInjections());
                e.getPresentation().setEnabled(cfg != null);
                e.getPresentation().setText(cfg == getDefaultCfgInfo() ? "Make Global" : "Move to Project");
                super.update(e);
            }

            @Nullable
            private CfgInfo getTargetCfgInfo(final List<InjInfo> injections) {
                CfgInfo cfg = null;
                for (InjInfo info : injections) {
                    if (info.bundled) {
                        continue;
                    }
                    if (cfg == null) {
                        cfg = info.cfgInfo;
                    } else if (cfg != info.cfgInfo) {
                        return info.cfgInfo;
                    }
                }
                if (cfg == null) {
                    return cfg;
                }
                for (CfgInfo info : myInfos) {
                    if (info != cfg) {
                        return info;
                    }
                }
                throw new AssertionError();
            }
        };
        shareAction.registerCustomShortcutSet(
                new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, InputEvent.SHIFT_DOWN_MASK)),
                myInjectionsTable);
        group.add(shareAction);
    }
    group.addSeparator();
    group.add(new AnAction("Import", "Import", AllIcons.Actions.Install) {
        @Override
        public void actionPerformed(final AnActionEvent e) {
            doImportAction(e.getDataContext());
            updateCountLabel();
        }
    });
    group.add(new AnAction("Export", "Export", AllIcons.Actions.Export) {
        @Override
        public void actionPerformed(final AnActionEvent e) {
            final List<BaseInjection> injections = getInjectionList(getSelectedInjections());
            final VirtualFileWrapper wrapper = FileChooserFactory.getInstance()
                    .createSaveFileDialog(
                            new FileSaverDescriptor("Export Selected " + "Injections to File...", "", "xml"),
                            myProject)
                    .save(null, null);
            if (wrapper == null) {
                return;
            }
            final Configuration configuration = new Configuration();
            configuration.setInjections(injections);
            final Document document = new Document(configuration.getState());
            try {
                JDOMUtil.writeDocument(document, wrapper.getFile(), "\n");
            } catch (IOException ex) {
                final String msg = ex.getLocalizedMessage();
                Messages.showErrorDialog(myProject, msg != null && msg.length() > 0 ? msg : ex.toString(),
                        "Export Failed");
            }
        }

        @Override
        public void update(final AnActionEvent e) {
            e.getPresentation().setEnabled(!getSelectedInjections().isEmpty());
        }
    });

    return group;
}

From source file:org.intellij.plugins.intelliLang.InjectionsSettingsUI.java

License:Apache License

private void doImportAction(final DataContext dataContext) {
    final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, true, false, true, false) {
        @Override/*w ww . j a v a  2  s  .  c om*/
        public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) {
            return super.isFileVisible(file, showHiddenFiles) && (file.isDirectory()
                    || "xml".equals(file.getExtension()) || file.getFileType() instanceof ArchiveFileType);
        }

        @Override
        public boolean isFileSelectable(VirtualFile file) {
            return "xml".equalsIgnoreCase(file.getExtension());
        }
    };
    descriptor
            .setDescription("Please select the configuration file (usually named IntelliLang.xml) to import.");
    descriptor.setTitle("Import Configuration");

    descriptor.putUserData(LangDataKeys.MODULE_CONTEXT, LangDataKeys.MODULE.getData(dataContext));

    final SplitterProportionsData splitterData = new SplitterProportionsDataImpl();
    splitterData.externalizeFromDimensionService("IntelliLang.ImportSettingsKey.SplitterProportions");

    final VirtualFile file = FileChooser.chooseFile(descriptor, myProject, null);
    if (file == null) {
        return;
    }
    try {
        final Configuration cfg = Configuration.load(file.getInputStream());
        if (cfg == null) {
            Messages.showWarningDialog(myProject,
                    "The selected file does not contain any importable configuration.", "Nothing to Import");
            return;
        }
        final CfgInfo info = getDefaultCfgInfo();
        final Map<String, Set<InjInfo>> currentMap = ContainerUtil.classify(info.injectionInfos.iterator(),
                new Convertor<InjInfo, String>() {
                    @Override
                    public String convert(final InjInfo o) {
                        return o.injection.getSupportId();
                    }
                });
        final List<BaseInjection> originalInjections = new ArrayList<BaseInjection>();
        final List<BaseInjection> newInjections = new ArrayList<BaseInjection>();
        //// remove duplicates
        //for (String supportId : InjectorUtils.getActiveInjectionSupportIds()) {
        //  final Set<BaseInjection> currentInjections = currentMap.get(supportId);
        //  if (currentInjections == null) continue;
        //  for (BaseInjection injection : currentInjections) {
        //    Configuration.importInjections(newInjections, Collections.singleton(injection), originalInjections, newInjections);
        //  }
        //}
        //myInjections.clear();
        //myInjections.addAll(newInjections);

        for (String supportId : InjectorUtils.getActiveInjectionSupportIds()) {
            ArrayList<InjInfo> list = new ArrayList<InjInfo>(
                    ObjectUtils.notNull(currentMap.get(supportId), Collections.<InjInfo>emptyList()));
            final List<BaseInjection> currentInjections = getInjectionList(list);
            final List<BaseInjection> importingInjections = cfg.getInjections(supportId);
            if (currentInjections == null) {
                newInjections.addAll(importingInjections);
            } else {
                Configuration.importInjections(currentInjections, importingInjections, originalInjections,
                        newInjections);
            }
        }
        info.replace(originalInjections, newInjections);
        myInjectionsTable.getListTableModel().setItems(getInjInfoList(myInfos));
        final int n = newInjections.size();
        if (n > 1) {
            Messages.showInfoMessage(myProject, n + " entries have been successfully imported",
                    "Import Successful");
        } else if (n == 1) {
            Messages.showInfoMessage(myProject, "One entry has been successfully imported",
                    "Import Successful");
        } else {
            Messages.showInfoMessage(myProject, "No new entries have been imported", "Import");
        }
    } catch (Exception ex) {
        Configuration.LOG.error(ex);

        final String msg = ex.getLocalizedMessage();
        Messages.showErrorDialog(myProject, msg != null && msg.length() > 0 ? msg : ex.toString(),
                "Import Failed");
    }
}

From source file:org.intellij.plugins.ui.MessageHandler.java

License:Open Source License

public void showErrorDialog(String message, String title) {
    Messages.showErrorDialog(project, message, title);
}

From source file:org.intellij.plugins.xpathView.search.FindByXPathAction.java

License:Apache License

private static boolean validateExpression(Project project, String expression) {
    try {/*www. ja v  a  2  s. c o m*/
        //noinspection unchecked
        XPathSupport.getInstance().createXPath(null, expression,
                Collections.<org.intellij.plugins.xpathView.util.Namespace>emptyList());
        return true;
    } catch (XPathSyntaxException e) {
        Messages.showErrorDialog(project, e.getMultilineMessage(), "XPath Syntax Error");
    } catch (JaxenException e) {
        Messages.showErrorDialog(project, e.getMessage(), "XPath Error");
    }
    return false;
}

From source file:org.intellij.plugins.xpathView.ui.EditContextDialog.java

License:Apache License

protected void doOKAction() {
    stopVarEditing();/*from   w w w  .  j  av a 2s . c  o m*/
    stopNamespaceEditing();

    final List<Expression> expressions = myVariableTableModel.getExpressions();
    for (int i = 0; i < expressions.size(); i++) {
        final Expression expression = expressions.get(i);
        final String name = (String) myVariableTableModel.getValueAt(i, 0);

        final String expr = expression.getExpression();
        if ((expr == null || expr.trim().length() == 0) && (name == null || name.trim().length() == 0)) {
            continue;
        }
        final String error = getError(expression);
        if (error != null) {
            Messages.showErrorDialog(expression.getFile().getProject(),
                    "Error in XPath Expression for Variable '" + name + "': " + error, "XPath Error");
            myVariableTable.getSelectionModel().setSelectionInterval(i, i);
            return;
        }
    }
    super.doOKAction();
}

From source file:org.jetbrains.android.actions.CreateResourceFileAction.java

License:Apache License

@NotNull
private static PsiElement[] doCreateFileResource(@NotNull AndroidFacet facet,
        @NotNull final ResourceType resType, @Nullable String resName, @Nullable String rootElement,
        @Nullable FolderConfiguration config, boolean chooseResName, @Nullable String dialogTitle) {
    final CreateResourceFileAction action = getInstance();

    final String subdirName;
    final Module selectedModule;
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        subdirName = resType.getName();//from w  ww.  j a v a2  s. c om
        selectedModule = facet.getModule();
    } else {
        final MyDialog dialog = new MyDialog(facet, action.mySubactions.values(), resType, resName, rootElement,
                config, chooseResName, action, facet.getModule(), true);
        if (dialogTitle != null) {
            dialog.setTitle(dialogTitle);
        }
        dialog.show();
        if (!dialog.isOK()) {
            return PsiElement.EMPTY_ARRAY;
        }
        if (chooseResName) {
            resName = dialog.getFileName();
        }
        subdirName = dialog.getSubdirName();
        selectedModule = dialog.getSelectedModule();
    }
    final AndroidFacet selectedFacet = AndroidFacet.getInstance(selectedModule);
    LOG.assertTrue(selectedFacet != null);

    final VirtualFile resourceDir = selectedFacet.getPrimaryResourceDir();
    final Project project = facet.getModule().getProject();
    final PsiDirectory psiResDir = resourceDir != null
            ? PsiManager.getInstance(project).findDirectory(resourceDir)
            : null;

    if (psiResDir == null) {
        Messages.showErrorDialog(project,
                "Cannot find resource directory for module " + selectedFacet.getModule().getName(),
                CommonBundle.getErrorTitle());
        return PsiElement.EMPTY_ARRAY;
    }
    final String finalResName = resName;

    final PsiElement[] elements = ApplicationManager.getApplication()
            .runWriteAction(new Computable<PsiElement[]>() {
                @Nullable
                @Override
                public PsiElement[] compute() {
                    MyInputValidator validator = action.createValidator(project, psiResDir, subdirName);
                    return validator.checkInput(finalResName) && validator.canClose(finalResName)
                            ? validator.getCreatedElements()
                            : null;
                }
            });
    return elements != null ? elements : PsiElement.EMPTY_ARRAY;
}

From source file:org.jetbrains.android.actions.CreateResourceFileDialog.java

License:Apache License

@Override
protected void doOKAction() {
    String fileName = myFileNameField.getText().trim();
    final CreateTypedResourceFileAction action = getSelectedAction();
    assert action != null;

    if (fileName.length() == 0) {
        Messages.showErrorDialog(myPanel, AndroidBundle.message("file.name.not.specified.error"),
                CommonBundle.getErrorTitle());
        return;/* w  w w  .  j  ava 2  s  .co m*/
    }

    if (!action.isChooseTagName() && getRootElement().length() == 0) {
        Messages.showErrorDialog(myPanel, AndroidBundle.message("root.element.not.specified.error"),
                CommonBundle.getErrorTitle());
        return;
    }

    final String subdirName = getSubdirName();
    if (subdirName.length() == 0) {
        Messages.showErrorDialog(myPanel, AndroidBundle.message("directory.not.specified.error"),
                CommonBundle.getErrorTitle());
        return;
    }

    final String errorMessage = getNameError(fileName);
    if (errorMessage != null) {
        Messages.showErrorDialog(myPanel, errorMessage, CommonBundle.getErrorTitle());
        return;
    }
    myValidator = createValidator(subdirName);
    if (myValidator == null || myValidator.checkInput(fileName) && myValidator.canClose(fileName)) {
        super.doOKAction();
    }
}