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

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

Introduction

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

Prototype

int OK

To view the source code for com.intellij.openapi.ui Messages OK.

Click Source Link

Usage

From source file:com.intellij.find.findUsages.JavaFindUsagesHandler.java

License:Apache License

@Override
@NotNull//from w w  w  .j  av  a  2 s. com
public PsiElement[] getSecondaryElements() {
    PsiElement element = getPsiElement();
    if (ApplicationManager.getApplication().isUnitTestMode()) {
        return PsiElement.EMPTY_ARRAY;
    }
    if (element instanceof PsiField) {
        final PsiField field = (PsiField) element;
        PsiClass containingClass = field.getContainingClass();
        if (containingClass != null) {
            String fieldName = field.getName();
            final String propertyName = JavaCodeStyleManager.getInstance(getProject())
                    .variableNameToPropertyName(fieldName, VariableKind.FIELD);
            Set<PsiMethod> accessors = new THashSet<PsiMethod>();
            boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC);
            PsiMethod getter = PropertyUtil.findPropertyGetterWithType(propertyName, isStatic, field.getType(),
                    ContainerUtil.iterate(containingClass.getMethods()));
            if (getter != null) {
                accessors.add(getter);
            }
            PsiMethod setter = PropertyUtil.findPropertySetterWithType(propertyName, isStatic, field.getType(),
                    ContainerUtil.iterate(containingClass.getMethods()));
            if (setter != null) {
                accessors.add(setter);
            }
            accessors.addAll(PropertyUtil.getAccessors(containingClass, fieldName));
            if (!accessors.isEmpty()) {
                boolean containsPhysical = ContainerUtil.find(accessors, new Condition<PsiMethod>() {
                    @Override
                    public boolean value(PsiMethod psiMethod) {
                        return psiMethod.isPhysical();
                    }
                }) != null;
                final boolean doSearch = !containsPhysical || Messages.showOkCancelDialog(
                        FindBundle.message("find.field.accessors.prompt", fieldName),
                        FindBundle.message("find.field.accessors.title"), CommonBundle.getYesButtonText(),
                        CommonBundle.getNoButtonText(), Messages.getQuestionIcon()) == Messages.OK;
                if (doSearch) {
                    final Set<PsiElement> elements = new THashSet<PsiElement>();
                    for (PsiMethod accessor : accessors) {
                        ContainerUtil.addAll(elements,
                                SuperMethodWarningUtil.checkSuperMethods(accessor, ACTION_STRING));
                    }
                    return PsiUtilCore.toPsiElementArray(elements);
                }
            }
        }
    }
    return super.getSecondaryElements();
}

From source file:com.intellij.find.replaceInProject.ReplaceInProjectManager.java

License:Apache License

private boolean ensureUsagesWritable(ReplaceContext replaceContext, Collection<Usage> selectedUsages) {
    Set<VirtualFile> readOnlyFiles = null;
    for (final Usage usage : selectedUsages) {
        final VirtualFile file = ((UsageInFile) usage).getFile();

        if (file != null && !file.isWritable()) {
            if (readOnlyFiles == null)
                readOnlyFiles = new HashSet<VirtualFile>();
            readOnlyFiles.add(file);//ww w.  j a v a 2  s  .com
        }
    }

    if (readOnlyFiles != null) {
        ReadonlyStatusHandler.getInstance(myProject)
                .ensureFilesWritable(VfsUtilCore.toVirtualFileArray(readOnlyFiles));
    }

    if (hasReadOnlyUsages(selectedUsages)) {
        int result = Messages.showOkCancelDialog(replaceContext.getUsageView().getComponent(),
                FindBundle.message("find.replace.occurrences.in.read.only.files.prompt"),
                FindBundle.message("find.replace.occurrences.in.read.only.files.title"),
                Messages.getWarningIcon());
        if (result != Messages.OK) {
            return false;
        }
    }
    return true;
}

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

License:Apache License

@Override
public void actionPerformed(@Nullable AnActionEvent e) {
    ApplicationManager.getApplication().saveSettings();

    ChooseComponentsToExportDialog dialog = new ChooseComponentsToExportDialog(
            getExportableComponentsMap(true, true), true,
            IdeBundle.message("title.select.components.to.export"),
            IdeBundle.message("prompt.please.check.all.components.to.export"));
    if (!dialog.showAndGet()) {
        return;/*from  ww w . j  av a 2 s.c o  m*/
    }

    Set<ExportableComponent> markedComponents = dialog.getExportableComponents();
    if (markedComponents.isEmpty()) {
        return;
    }

    Set<File> exportFiles = new THashSet<File>(FileUtil.FILE_HASHING_STRATEGY);
    for (ExportableComponent markedComponent : markedComponents) {
        ContainerUtil.addAll(exportFiles, markedComponent.getExportFiles());
    }

    final File saveFile = dialog.getExportFile();
    try {
        if (saveFile.exists()) {
            final int ret = Messages.showOkCancelDialog(
                    IdeBundle.message("prompt.overwrite.settings.file",
                            FileUtil.toSystemDependentName(saveFile.getPath())),
                    IdeBundle.message("title.file.already.exists"), Messages.getWarningIcon());
            if (ret != Messages.OK)
                return;
        }
        final JarOutputStream output = new JarOutputStream(
                new BufferedOutputStream(new FileOutputStream(saveFile)));
        try {
            final File configPath = new File(PathManager.getConfigPath());
            final HashSet<String> writtenItemRelativePaths = new HashSet<String>();
            for (File file : exportFiles) {
                final String rPath = FileUtil.getRelativePath(configPath, file);
                assert rPath != null;
                final String relativePath = FileUtil.toSystemIndependentName(rPath);
                if (file.exists()) {
                    ZipUtil.addFileOrDirRecursively(output, saveFile, file, relativePath, null,
                            writtenItemRelativePaths);
                }
            }

            exportInstalledPlugins(saveFile, output, writtenItemRelativePaths);

            final File magicFile = new File(FileUtil.getTempDirectory(),
                    ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER);
            FileUtil.createIfDoesntExist(magicFile);
            magicFile.deleteOnExit();
            ZipUtil.addFileToZip(output, magicFile, ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER,
                    writtenItemRelativePaths, null);
        } finally {
            output.close();
        }
        ShowFilePathAction.showDialog(getEventProject(e),
                IdeBundle.message("message.settings.exported.successfully"),
                IdeBundle.message("title.export.successful"), saveFile, null);
    } catch (IOException e1) {
        Messages.showErrorDialog(IdeBundle.message("error.writing.settings", e1.toString()),
                IdeBundle.message("title.error.writing.file"));
    }
}

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

License:Apache License

private static void doImport(String path) {
    final File saveFile = new File(path);
    try {/*from w w  w  .  j  a v a 2s .c  o m*/
        if (!saveFile.exists()) {
            Messages.showErrorDialog(IdeBundle.message("error.cannot.find.file", presentableFileName(saveFile)),
                    IdeBundle.message("title.file.not.found"));
            return;
        }

        @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
        final ZipEntry magicEntry = new ZipFile(saveFile)
                .getEntry(ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER);
        if (magicEntry == null) {
            Messages.showErrorDialog(
                    IdeBundle.message("error.file.contains.no.settings.to.import",
                            presentableFileName(saveFile), promptLocationMessage()),
                    IdeBundle.message("title.invalid.file"));
            return;
        }

        MultiMap<File, ExportableComponent> fileToComponents = ExportSettingsAction
                .getExportableComponentsMap(false, true);
        List<ExportableComponent> components = getComponentsStored(saveFile, fileToComponents.values());
        fileToComponents.values().retainAll(components);
        final ChooseComponentsToExportDialog dialog = new ChooseComponentsToExportDialog(fileToComponents,
                false, IdeBundle.message("title.select.components.to.import"),
                IdeBundle.message("prompt.check.components.to.import"));
        if (!dialog.showAndGet()) {
            return;
        }

        final Set<ExportableComponent> chosenComponents = dialog.getExportableComponents();
        Set<String> relativeNamesToExtract = new HashSet<String>();
        for (final ExportableComponent chosenComponent : chosenComponents) {
            final File[] exportFiles = chosenComponent.getExportFiles();
            for (File exportFile : exportFiles) {
                final File configPath = new File(PathManager.getConfigPath());
                final String rPath = FileUtil.getRelativePath(configPath, exportFile);
                assert rPath != null;
                final String relativePath = FileUtil.toSystemIndependentName(rPath);
                relativeNamesToExtract.add(relativePath);
            }
        }

        relativeNamesToExtract.add(PluginManager.INSTALLED_TXT);

        final File tempFile = new File(PathManager.getPluginTempPath() + "/" + saveFile.getName());
        FileUtil.copy(saveFile, tempFile);
        File outDir = new File(PathManager.getConfigPath());
        final ImportSettingsFilenameFilter filenameFilter = new ImportSettingsFilenameFilter(
                relativeNamesToExtract);
        StartupActionScriptManager.ActionCommand unzip = new StartupActionScriptManager.UnzipCommand(tempFile,
                outDir, filenameFilter);
        StartupActionScriptManager.addActionCommand(unzip);
        // remove temp file
        StartupActionScriptManager.ActionCommand deleteTemp = new StartupActionScriptManager.DeleteCommand(
                tempFile);
        StartupActionScriptManager.addActionCommand(deleteTemp);

        UpdateSettings.getInstance().forceCheckForUpdateAfterRestart();

        String key = ApplicationManager.getApplication().isRestartCapable()
                ? "message.settings.imported.successfully.restart"
                : "message.settings.imported.successfully";
        final int ret = Messages.showOkCancelDialog(
                IdeBundle.message(key, ApplicationNamesInfo.getInstance().getProductName(),
                        ApplicationNamesInfo.getInstance().getFullProductName()),
                IdeBundle.message("title.restart.needed"), Messages.getQuestionIcon());
        if (ret == Messages.OK) {
            ((ApplicationEx) ApplicationManager.getApplication()).restart(true);
        }
    } catch (ZipException e1) {
        Messages.showErrorDialog(IdeBundle.message("error.reading.settings.file", presentableFileName(saveFile),
                e1.getMessage(), promptLocationMessage()), IdeBundle.message("title.invalid.file"));
    } catch (IOException e1) {
        Messages.showErrorDialog(IdeBundle.message("error.reading.settings.file.2",
                presentableFileName(saveFile), e1.getMessage()), IdeBundle.message("title.error.reading.file"));
    }
}

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

License:Apache License

public static void showDialog(Project project, String message, String title, File file,
        DialogWrapper.DoNotAskOption option) {
    if (Messages.showOkCancelDialog(project, message, title, RevealFileAction.getActionName(),
            IdeBundle.message("action.close"), Messages.getInformationIcon(), option) == Messages.OK) {
        openFile(file);// w w w.  ja v a2s  .co m
    }
}

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

License:Apache License

private void checkInstalledPluginDependencies(IdeaPluginDescriptorImpl pluginDescriptor) {
    final Set<PluginId> notInstalled = new HashSet<PluginId>();
    final Set<PluginId> disabledIds = new HashSet<PluginId>();
    final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds();
    final PluginId[] optionalDependentPluginIds = pluginDescriptor.getOptionalDependentPluginIds();
    for (PluginId id : dependentPluginIds) {
        if (ArrayUtilRt.find(optionalDependentPluginIds, id) > -1)
            continue;
        final boolean disabled = ((InstalledPluginsTableModel) pluginsModel).isDisabled(id);
        final boolean enabled = ((InstalledPluginsTableModel) pluginsModel).isEnabled(id);
        if (!enabled && !disabled) {
            notInstalled.add(id);/*from ww w. j  ava 2 s .  co  m*/
        } else if (disabled) {
            disabledIds.add(id);
        }
    }
    if (!notInstalled.isEmpty()) {
        Messages.showWarningDialog("Plugin " + pluginDescriptor.getName() + " depends on unknown plugin"
                + (notInstalled.size() > 1 ? "s " : " ")
                + StringUtil.join(notInstalled, new Function<PluginId, String>() {
                    @Override
                    public String fun(PluginId id) {
                        return id.toString();
                    }
                }, ", "), CommonBundle.getWarningTitle());
    }
    if (!disabledIds.isEmpty()) {
        final Set<IdeaPluginDescriptor> dependencies = new HashSet<IdeaPluginDescriptor>();
        for (IdeaPluginDescriptor ideaPluginDescriptor : pluginsModel.getAllPlugins()) {
            if (disabledIds.contains(ideaPluginDescriptor.getPluginId())) {
                dependencies.add(ideaPluginDescriptor);
            }
        }
        final String disabledPluginsMessage = "disabled plugin" + (dependencies.size() > 1 ? "s " : " ");
        String message = "Plugin " + pluginDescriptor.getName() + " depends on " + disabledPluginsMessage
                + StringUtil.join(dependencies, new Function<IdeaPluginDescriptor, String>() {
                    @Override
                    public String fun(IdeaPluginDescriptor ideaPluginDescriptor) {
                        return ideaPluginDescriptor.getName();
                    }
                }, ", ") + ". Enable " + disabledPluginsMessage.trim() + "?";
        if (Messages.showOkCancelDialog(myActionsPanel, message, CommonBundle.getWarningTitle(),
                Messages.getWarningIcon()) == Messages.OK) {
            ((InstalledPluginsTableModel) pluginsModel).enableRows(
                    dependencies.toArray(new IdeaPluginDescriptor[dependencies.size()]), Boolean.TRUE);
        }
    }
}

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

License:Apache License

private void warnAboutMissedDependencies(final Boolean newVal,
        final IdeaPluginDescriptor... ideaPluginDescriptors) {
    final Set<PluginId> deps = new HashSet<PluginId>();
    final List<IdeaPluginDescriptor> descriptorsToCheckDependencies = new ArrayList<IdeaPluginDescriptor>();
    if (newVal) {
        Collections.addAll(descriptorsToCheckDependencies, ideaPluginDescriptors);
    } else {//from w ww  .j  a v  a  2 s.c  o  m
        descriptorsToCheckDependencies.addAll(getAllPlugins());
        descriptorsToCheckDependencies.removeAll(Arrays.asList(ideaPluginDescriptors));

        for (Iterator<IdeaPluginDescriptor> iterator = descriptorsToCheckDependencies.iterator(); iterator
                .hasNext();) {
            IdeaPluginDescriptor descriptor = iterator.next();
            final Boolean enabled = myEnabled.get(descriptor.getPluginId());
            if (enabled == null || !enabled.booleanValue()) {
                iterator.remove();
            }
        }
    }

    for (final IdeaPluginDescriptor ideaPluginDescriptor : descriptorsToCheckDependencies) {
        PluginManager.checkDependants(ideaPluginDescriptor, new Function<PluginId, IdeaPluginDescriptor>() {
            @Override
            @Nullable
            public IdeaPluginDescriptor fun(final PluginId pluginId) {
                return PluginManager.getPlugin(pluginId);
            }
        }, new Condition<PluginId>() {
            @Override
            public boolean value(final PluginId pluginId) {
                Boolean enabled = myEnabled.get(pluginId);
                if (enabled == null) {
                    return false;
                }
                if (newVal && !enabled.booleanValue()) {
                    deps.add(pluginId);
                }

                if (!newVal) {
                    if (ideaPluginDescriptor instanceof IdeaPluginDescriptorImpl
                            && ((IdeaPluginDescriptorImpl) ideaPluginDescriptor).isDeleted())
                        return true;
                    final PluginId pluginDescriptorId = ideaPluginDescriptor.getPluginId();
                    for (IdeaPluginDescriptor descriptor : ideaPluginDescriptors) {
                        if (pluginId.equals(descriptor.getPluginId())) {
                            deps.add(pluginDescriptorId);
                            break;
                        }
                    }
                }
                return true;
            }
        });
    }
    if (!deps.isEmpty()) {
        final String listOfSelectedPlugins = StringUtil.join(ideaPluginDescriptors,
                new Function<IdeaPluginDescriptor, String>() {
                    @Override
                    public String fun(IdeaPluginDescriptor pluginDescriptor) {
                        return pluginDescriptor.getName();
                    }
                }, ", ");
        final Set<IdeaPluginDescriptor> pluginDependencies = new HashSet<IdeaPluginDescriptor>();
        final String listOfDependencies = StringUtil.join(deps, new Function<PluginId, String>() {
            @Override
            public String fun(final PluginId pluginId) {
                final IdeaPluginDescriptor pluginDescriptor = PluginManager.getPlugin(pluginId);
                assert pluginDescriptor != null;
                pluginDependencies.add(pluginDescriptor);
                return pluginDescriptor.getName();
            }
        }, "<br>");
        final String message = !newVal
                ? "<html>The following plugins <br>" + listOfDependencies + "<br>are enabled and depend"
                        + (deps.size() == 1 ? "s" : "") + " on selected plugins. "
                        + "<br>Would you like to disable them too?</html>"
                : "<html>The following plugins on which " + listOfSelectedPlugins + " depend"
                        + (ideaPluginDescriptors.length == 1 ? "s" : "") + " are disabled:<br>"
                        + listOfDependencies + "<br>Would you like to enable them?</html>";
        if (Messages.showOkCancelDialog(message,
                newVal ? "Enable Dependant Plugins" : "Disable Plugins with Dependency on this",
                Messages.getQuestionIcon()) == Messages.OK) {
            for (PluginId pluginId : deps) {
                myEnabled.put(pluginId, newVal);
            }

            updatePluginDependencies();
            hideNotApplicablePlugins(newVal,
                    pluginDependencies.toArray(new IdeaPluginDescriptor[pluginDependencies.size()]));
        }
    }
}

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

License:Apache License

/**
 * Start a new thread which downloads new list of plugins from the site in
 * the background and updates a list of plugins in the table.
 *//* w ww. j  av a 2s .c o m*/
protected void loadPluginsFromHostInBackground() {
    setDownloadStatus(true);

    new SwingWorker() {
        List<IdeaPluginDescriptor> list = null;
        List<String> errorMessages = new ArrayList<String>();

        @Override
        public Object construct() {
            try {
                list = RepositoryHelper.loadPluginsFromRepository(null);
            } catch (Exception e) {
                LOG.info(e);
                errorMessages.add(e.getMessage());
            }
            for (String host : UpdateSettings.getInstance().getStoredPluginHosts()) {
                if (!acceptHost(host))
                    continue;
                final ArrayList<PluginDownloader> downloaded = new ArrayList<PluginDownloader>();
                try {
                    UpdateChecker.checkPluginsHost(host, downloaded, false, null);
                    for (PluginDownloader downloader : downloaded) {
                        final PluginNode pluginNode = PluginDownloader.createPluginNode(host, downloader);
                        if (pluginNode != null) {
                            if (list == null)
                                list = new ArrayList<IdeaPluginDescriptor>();
                            list.add(pluginNode);
                        }
                    }
                } catch (ProcessCanceledException ignore) {
                } catch (Exception e) {
                    LOG.info(e);
                    errorMessages.add(e.getMessage());
                }
            }
            return list;
        }

        @Override
        public void finished() {
            UIUtil.invokeLaterIfNeeded(new Runnable() {
                @Override
                public void run() {
                    setDownloadStatus(false);
                    if (list != null) {
                        modifyPluginsList(list);
                        propagateUpdates(list);
                    }
                    if (!errorMessages.isEmpty()) {
                        if (Messages.OK == Messages.showOkCancelDialog(
                                IdeBundle.message("error.list.of.plugins.was.not.loaded",
                                        StringUtil.join(errorMessages, ", ")),
                                IdeBundle.message("title.plugins"), CommonBundle.message("button.retry"),
                                CommonBundle.getCancelButtonText(), Messages.getErrorIcon())) {
                            loadPluginsFromHostInBackground();
                        }
                    }
                }
            });
        }
    }.start();
}

From source file:com.intellij.ide.ui.customization.CustomizableActionsPanel.java

License:Apache License

private void editToolbarIcon(String actionId, DefaultMutableTreeNode node) {
    final AnAction anAction = ActionManager.getInstance().getAction(actionId);
    if (isToolbarAction(node) && anAction.getTemplatePresentation() != null
            && anAction.getTemplatePresentation().getIcon() == null) {
        final int exitCode = Messages.showOkCancelDialog(
                IdeBundle.message("error.adding.action.without.icon.to.toolbar"),
                IdeBundle.message("title.unable.to.add.action.without.icon.to.toolbar"),
                Messages.getInformationIcon());
        if (exitCode == Messages.OK) {
            mySelectedSchema.addIconCustomization(actionId, null);
            anAction.getTemplatePresentation().setIcon(AllIcons.Toolbar.Unknown);
            anAction.setDefaultIcon(false);
            node.setUserObject(Pair.create(actionId, AllIcons.Toolbar.Unknown));
            myActionsTree.repaint();/*  w  w  w .  j  a v a2s  .c o  m*/
            setCustomizationSchemaForCurrentProjects();
        }
    }
}

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

License:Apache License

public static void deletePsiElement(final PsiElement[] elementsToDelete, final Project project,
        boolean needConfirmation) {
    if (elementsToDelete == null || elementsToDelete.length == 0)
        return;/*from   w w  w  .  ja  v  a 2s  .  c om*/

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

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

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

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

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

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

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

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

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

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

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

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

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

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