Example usage for com.intellij.openapi.ui DialogWrapper CANCEL_EXIT_CODE

List of usage examples for com.intellij.openapi.ui DialogWrapper CANCEL_EXIT_CODE

Introduction

In this page you can find the example usage for com.intellij.openapi.ui DialogWrapper CANCEL_EXIT_CODE.

Prototype

int CANCEL_EXIT_CODE

To view the source code for com.intellij.openapi.ui DialogWrapper CANCEL_EXIT_CODE.

Click Source Link

Document

The default exit code for "Cancel" action.

Usage

From source file:com.intellij.refactoring.memberPullUp.JavaPullUpHandler.java

License:Apache License

public boolean checkConflicts(final PullUpDialog dialog) {
    final MemberInfo[] infos = dialog.getSelectedMemberInfos();
    final PsiClass superClass = dialog.getSuperClass();
    if (!checkWritable(superClass, infos))
        return false;
    final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
    if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
        public void run() {
            final PsiDirectory targetDirectory = superClass.getContainingFile().getContainingDirectory();
            final PsiJavaPackage targetPackage = targetDirectory != null
                    ? JavaDirectoryService.getInstance().getPackage(targetDirectory)
                    : null;/*from  w  w w  .  j  a v  a 2s  .  com*/
            conflicts.putAllValues(PullUpConflictsUtil.checkConflicts(infos, mySubclass, superClass,
                    targetPackage, targetDirectory, dialog.getContainmentVerifier()));
        }
    }, RefactoringBundle.message("detecting.possible.conflicts"), true, myProject))
        return false;
    if (!conflicts.isEmpty()) {
        ConflictsDialog conflictsDialog = new ConflictsDialog(myProject, conflicts);
        conflictsDialog.show();
        final boolean ok = conflictsDialog.isOK();
        if (!ok && conflictsDialog.isShowConflicts())
            dialog.close(DialogWrapper.CANCEL_EXIT_CODE);
        return ok;
    }
    return true;
}

From source file:com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil.java

License:Apache License

/**
 * @param elements should contain PsiDirectories or PsiFiles only if adjustElements == null
 *//* www . j a v  a  2s.  c om*/
public static void doMove(final Project project, final PsiElement[] elements, final PsiElement[] targetElement,
        final MoveCallback moveCallback, final Function<PsiElement[], PsiElement[]> adjustElements) {
    if (adjustElements == null) {
        for (PsiElement element : elements) {
            if (!(element instanceof PsiFile) && !(element instanceof PsiDirectory)) {
                throw new IllegalArgumentException("unexpected element type: " + element);
            }
        }
    }

    final PsiDirectory targetDirectory = resolveToDirectory(project, targetElement[0]);
    if (targetElement[0] != null && targetDirectory == null)
        return;

    final PsiElement[] newElements = adjustElements != null ? adjustElements.fun(elements) : elements;

    final PsiDirectory initialTargetDirectory = getInitialTargetDirectory(targetDirectory, elements);

    final MoveFilesOrDirectoriesDialog.Callback doRun = new MoveFilesOrDirectoriesDialog.Callback() {
        @Override
        public void run(final MoveFilesOrDirectoriesDialog moveDialog) {
            CommandProcessor.getInstance().executeCommand(project, new Runnable() {
                @Override
                public void run() {
                    final PsiDirectory targetDirectory = moveDialog != null ? moveDialog.getTargetDirectory()
                            : initialTargetDirectory;

                    LOG.assertTrue(targetDirectory != null);
                    targetElement[0] = targetDirectory;

                    PsiManager manager = PsiManager.getInstance(project);
                    try {
                        final int[] choice = elements.length > 1 || elements[0] instanceof PsiDirectory
                                ? new int[] { -1 }
                                : null;
                        final List<PsiElement> els = new ArrayList<PsiElement>();
                        for (int i = 0, newElementsLength = newElements.length; i < newElementsLength; i++) {
                            final PsiElement psiElement = newElements[i];
                            if (psiElement instanceof PsiFile) {
                                final PsiFile file = (PsiFile) psiElement;
                                final boolean fileExist = ApplicationManager.getApplication()
                                        .runWriteAction(new Computable<Boolean>() {
                                            @Override
                                            public Boolean compute() {
                                                return CopyFilesOrDirectoriesHandler.checkFileExist(
                                                        targetDirectory, choice, file, file.getName(), "Move");
                                            }
                                        });
                                if (fileExist)
                                    continue;
                            }
                            checkMove(psiElement, targetDirectory);
                            els.add(psiElement);
                        }
                        final Runnable callback = new Runnable() {
                            @Override
                            public void run() {
                                if (moveDialog != null)
                                    moveDialog.close(DialogWrapper.CANCEL_EXIT_CODE);
                            }
                        };
                        if (els.isEmpty()) {
                            callback.run();
                            return;
                        }
                        new MoveFilesOrDirectoriesProcessor(project, els.toArray(new PsiElement[els.size()]),
                                targetDirectory,
                                RefactoringSettings.getInstance().MOVE_SEARCH_FOR_REFERENCES_FOR_FILE, false,
                                false, moveCallback, callback).run();
                    } catch (IncorrectOperationException e) {
                        CommonRefactoringUtil.showErrorMessage(RefactoringBundle.message("error.title"),
                                e.getMessage(), "refactoring.moveFile", project);
                    }
                }
            }, MoveHandler.REFACTORING_NAME, null);
        }
    };

    if (ApplicationManager.getApplication().isUnitTestMode()) {
        doRun.run(null);
    } else {
        final MoveFilesOrDirectoriesDialog moveDialog = new MoveFilesOrDirectoriesDialog(project, doRun);
        moveDialog.setData(newElements, initialTargetDirectory, "refactoring.moveFile");
        moveDialog.show();
    }
}

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

License:Apache License

private static void rename(PsiElement element, final Project project, PsiElement nameSuggestionContext,
        Editor editor, String defaultName) {
    RenamePsiElementProcessor processor = RenamePsiElementProcessor.forElement(element);
    element = processor.substituteElementToRename(element, editor);
    if (element == null || !canRename(project, editor, element))
        return;//from  w  w  w .j a  va2  s .c o m

    final RenameDialog dialog = processor.createRenameDialog(project, element, nameSuggestionContext, editor);

    if (defaultName == null && ApplicationManager.getApplication().isUnitTestMode()) {
        String[] strings = dialog.getSuggestedNames();
        if (strings != null && strings.length > 0) {
            Arrays.sort(strings);
            defaultName = strings[0];
        } else {
            defaultName = "undefined"; // need to avoid show dialog in test
        }
    }

    if (defaultName != null) {
        try {
            dialog.performRename(defaultName);
        } finally {
            dialog.close(DialogWrapper.CANCEL_EXIT_CODE); // to avoid dialog leak
        }
    } else {
        dialog.show();
    }
}

From source file:com.intellij.refactoring.safeDelete.SafeDeleteHandler.java

License:Apache License

public static void invoke(final Project project, PsiElement[] elements, @Nullable Module module,
        boolean checkDelegates, @Nullable final Runnable successRunnable) {
    for (PsiElement element : elements) {
        if (!SafeDeleteProcessor.validElement(element)) {
            return;
        }//from   w w  w . j a v  a  2  s . c  o  m
    }
    final PsiElement[] temptoDelete = PsiTreeUtil.filterAncestors(elements);
    Set<PsiElement> elementsSet = new HashSet<PsiElement>(Arrays.asList(temptoDelete));
    Set<PsiElement> fullElementsSet = new LinkedHashSet<PsiElement>();

    if (checkDelegates) {
        for (PsiElement element : temptoDelete) {
            boolean found = false;
            for (SafeDeleteProcessorDelegate delegate : Extensions
                    .getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) {
                if (delegate.handlesElement(element)) {
                    found = true;
                    Collection<? extends PsiElement> addElements = delegate instanceof SafeDeleteProcessorDelegateBase
                            ? ((SafeDeleteProcessorDelegateBase) delegate).getElementsToSearch(element, module,
                                    elementsSet)
                            : delegate.getElementsToSearch(element, elementsSet);
                    if (addElements == null)
                        return;
                    fullElementsSet.addAll(addElements);
                    break;
                }
            }
            if (!found) {
                fullElementsSet.add(element);
            }
        }
    } else {
        ContainerUtil.addAll(fullElementsSet, temptoDelete);
    }

    if (!CommonRefactoringUtil.checkReadOnlyStatusRecursively(project, fullElementsSet, true))
        return;

    final PsiElement[] elementsToDelete = PsiUtilCore.toPsiElementArray(fullElementsSet);

    if (ApplicationManager.getApplication().isUnitTestMode()) {
        RefactoringSettings settings = RefactoringSettings.getInstance();
        SafeDeleteProcessor.createInstance(project, null, elementsToDelete,
                settings.SAFE_DELETE_SEARCH_IN_COMMENTS, settings.SAFE_DELETE_SEARCH_IN_NON_JAVA, true).run();
        if (successRunnable != null)
            successRunnable.run();
    } else {
        final SafeDeleteDialog.Callback callback = new SafeDeleteDialog.Callback() {
            @Override
            public void run(final SafeDeleteDialog dialog) {
                SafeDeleteProcessor.createInstance(project, new Runnable() {
                    @Override
                    public void run() {
                        if (successRunnable != null) {
                            successRunnable.run();
                        }
                        dialog.close(DialogWrapper.CANCEL_EXIT_CODE);
                    }
                }, elementsToDelete, dialog.isSearchInComments(), dialog.isSearchForTextOccurences(), true)
                        .run();
            }

        };

        SafeDeleteDialog dialog = new SafeDeleteDialog(project, elementsToDelete, callback);
        dialog.show();
    }
}

From source file:com.microsoft.azure.hdinsight.serverexplore.ui.AddNewClusterFrom.java

License:Open Source License

private void addActionListener() {
    Okbutton.addActionListener(new ActionListener() {
        @Override/*from  ww  w . j a  v  a2  s .c o m*/
        public void actionPerformed(ActionEvent e) {
            synchronized (AddNewClusterFrom.class) {
                isCarryOnNextStep = true;
                errorMessage = null;
                errorMessageField.setVisible(false);

                String clusterNameOrUrl = clusterNameFiled.getText().trim();
                userName = userNameField.getText().trim();
                storageName = storageNameField.getText().trim();

                storageKey = storageKeyTextField.getText().trim();

                password = String.valueOf(passwordField.getPassword());

                if (StringHelper.isNullOrWhiteSpace(clusterNameOrUrl)
                        || StringHelper.isNullOrWhiteSpace(storageName)
                        || StringHelper.isNullOrWhiteSpace(storageKey)
                        || StringHelper.isNullOrWhiteSpace(userName)
                        || StringHelper.isNullOrWhiteSpace(password)) {
                    errorMessage = "Cluster Name, Storage Key, User Name, or Password shouldn't be empty";
                    isCarryOnNextStep = false;
                } else {
                    clusterName = getClusterName(clusterNameOrUrl);

                    if (clusterName == null) {
                        errorMessage = "Wrong cluster name or endpoint";
                        isCarryOnNextStep = false;
                    } else {
                        int status = ClusterManagerEx.getInstance()
                                .isHDInsightAdditionalStorageExist(clusterName, storageName);
                        if (status == 1) {
                            errorMessage = "Cluster already exist in current list";
                            isCarryOnNextStep = false;
                        } else if (status == 2) {
                            errorMessage = "Default storage account is required";
                            isCarryOnNextStep = false;
                        }
                    }
                }

                if (isCarryOnNextStep) {
                    getStorageAccount();
                }

                if (isCarryOnNextStep) {
                    if (storageAccount != null) {
                        HDInsightAdditionalClusterDetail hdInsightAdditionalClusterDetail = new HDInsightAdditionalClusterDetail(
                                clusterName, userName, password, storageAccount);
                        ClusterManagerEx.getInstance()
                                .addHDInsightAdditionalCluster(hdInsightAdditionalClusterDetail);
                        hdInsightModule.refreshWithoutAsync();
                    }
                    close(DialogWrapper.OK_EXIT_CODE, true);
                } else {
                    errorMessageField.setText(errorMessage);
                    errorMessageField.setVisible(true);
                }
            }
        }
    });

    cancelButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            close(DialogWrapper.CANCEL_EXIT_CODE, true);
        }
    });
}

From source file:com.microsoft.intellij.forms.ManageSubscriptionForm.java

License:Open Source License

@Override
public void doCancelAction() {
    try {//from  w  ww.ja  va 2 s .  co  m
        java.util.List<String> selectedList = new ArrayList<String>();

        TableModel model = subscriptionTable.getModel();

        for (int i = 0; i < model.getRowCount(); i++) {
            Boolean selected = (Boolean) model.getValueAt(i, 0);

            if (selected) {
                selectedList.add(model.getValueAt(i, 2).toString());
            }
        }

        AzureManagerImpl.getManager().setSelectedSubscriptions(selectedList);

        //Saving the project is necessary to save the changes on the PropertiesComponent
        if (project != null) {
            project.save();
        }

        close(DialogWrapper.CANCEL_EXIT_CODE, false);
    } catch (AzureCmdException e) {
        DefaultLoader.getUIHelper().showException(
                "An error occurred while attempting to set the selected " + "subscriptions.", e,
                "Azure Services Explorer - Error Setting Selected Subscriptions", false, true);
    }
}

From source file:com.microsoft.intellij.forms.ManageSubscriptionPanel.java

License:Open Source License

public void doCancelAction() {
    try {/*from   w ww  .ja v  a  2s .  c o m*/
        java.util.List<String> selectedList = new ArrayList<String>();

        TableModel model = subscriptionTable.getModel();

        for (int i = 0; i < model.getRowCount(); i++) {
            Boolean selected = (Boolean) model.getValueAt(i, 0);

            if (selected) {
                selectedList.add(model.getValueAt(i, 2).toString());
            }
        }

        AzureManagerImpl.getManager().setSelectedSubscriptions(selectedList);

        //Saving the project is necessary to save the changes on the PropertiesComponent
        //            if (project != null) {
        //                project.save();
        //            }
        if (myDialog != null) {
            myDialog.close(DialogWrapper.CANCEL_EXIT_CODE, false);
        }
    } catch (AzureCmdException e) {
        String msg = "An error occurred while attempting to set the selected subscriptions." + "\n"
                + String.format(message("webappExpMsg"), e.getMessage());
        PluginUtil.displayErrorDialogAndLog(message("errTtl"), msg, e);
    }
}

From source file:com.microsoft.intellij.helpers.activityConfiguration.office365CustomWizardParameter.Office365ConfigForm.java

License:Open Source License

private void fillApps(final String selectedAppId) {
    final Office365ConfigForm office365ConfigForm = this;

    ApplicationManager.getApplication().invokeAndWait(new Runnable() {
        @Override/*from ww w . j a v a 2s  . co  m*/
        public void run() {
            cmbApps.setRenderer(new StringComboBoxItemRenderer());
            cmbApps.setModel(new DefaultComboBoxModel(new String[] { "(loading...)" }));
            cmbApps.setEnabled(false);

            ReadOnlyCellTableModel messageTableModel = new ReadOnlyCellTableModel();
            messageTableModel.addColumn("Message");
            Vector<String> vector = new Vector<String>();
            vector.add("(loading... )");
            messageTableModel.addRow(vector);
            tblAppPermissions.setModel(messageTableModel);
        }
    }, ModalityState.any());

    final Office365Manager manager = Office365ManagerImpl.getManager();

    try {
        if (!manager.authenticated()) {
            manager.authenticate();

            // if we still don't have an authentication token then the
            // user has cancelled out of login; so we cancel out of this
            // wizard
            if (!manager.authenticated()) {
                ApplicationManager.getApplication().invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        office365ConfigForm.close(DialogWrapper.CANCEL_EXIT_CODE);
                    }
                }, ModalityState.any());
                return;
            }
        }

        Futures.addCallback(manager.getApplicationList(), new FutureCallback<List<Application>>() {
            @Override
            public void onSuccess(final List<Application> applications) {
                ApplicationManager.getApplication().invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        if (applications.size() > 0) {
                            cmbApps.setRenderer(new ListCellRendererWrapper<Application>() {
                                @Override
                                public void customize(JList jList, Application application, int i, boolean b,
                                        boolean b2) {
                                    setText(application.getdisplayName());
                                }
                            });

                            cmbApps.setModel(new DefaultComboBoxModel(applications.toArray()));
                            cmbApps.setEnabled(true);

                            int selectedIndex = 0;
                            if (!StringHelper.isNullOrWhiteSpace(selectedAppId)) {
                                selectedIndex = Iterables.indexOf(applications, new Predicate<Application>() {
                                    @Override
                                    public boolean apply(Application application) {
                                        return application.getappId().equals(selectedAppId);
                                    }
                                });
                            }
                            cmbApps.setSelectedIndex(Math.max(0, selectedIndex));
                        } else {
                            cmbApps.setRenderer(new StringComboBoxItemRenderer());
                            cmbApps.setModel(new DefaultComboBoxModel(new String[] { "No apps configured)" }));
                            cmbApps.setEnabled(false);

                            ReadOnlyCellTableModel messageTableModel = new ReadOnlyCellTableModel();
                            messageTableModel.addColumn("Message");
                            Vector<String> vector = new Vector<String>();
                            vector.add("There are no applications configured.");
                            messageTableModel.addRow(vector);
                            tblAppPermissions.setModel(messageTableModel);
                            //tblAppPermissions.setEnabled(false);
                        }
                    }
                }, ModalityState.any());
            }

            @Override
            public void onFailure(final Throwable throwable) {
                ApplicationManager.getApplication().invokeAndWait(new Runnable() {
                    @Override
                    public void run() {
                        DefaultLoader.getUIHelper().showException(
                                "An error occurred while attempting to fetch the " + "list of applications.",
                                throwable, "Microsoft Cloud Services For Android - Error Fetching Applications",
                                false, true);
                    }
                }, ModalityState.any());
            }
        });
    } catch (Throwable throwable) {
        DefaultLoader.getUIHelper().showException(
                "An error occurred while attempting to authenticate with Office 365.", throwable,
                "Microsoft Cloud Services For Android - Error Authenticating O365", false, true);
    }
}

From source file:com.theoryinpractice.testng.TestNGFramework.java

License:Apache License

@Override
protected PsiMethod findOrCreateSetUpMethod(PsiClass clazz) throws IncorrectOperationException {
    PsiMethod method = findSetUpMethod(clazz);
    if (method != null)
        return method;

    final PsiManager manager = clazz.getManager();
    final PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    String setUpName = "setUp";
    PsiMethod patternMethod = createSetUpPatternMethod(factory);
    PsiMethod inClass = clazz.findMethodBySignature(patternMethod, false);
    if (inClass != null) {
        int exit = ApplicationManager.getApplication().isUnitTestMode() ? DialogWrapper.OK_EXIT_CODE
                : Messages.showYesNoDialog(
                        "Method \'" + setUpName + "\' already exist but is not annotated as @BeforeMethod.",
                        CommonBundle.getWarningTitle(), "Annotate", "Create new method",
                        Messages.getWarningIcon());
        if (exit == DialogWrapper.OK_EXIT_CODE) {
            new AddAnnotationFix(BeforeMethod.class.getName(), inClass).invoke(inClass.getProject(), null,
                    inClass.getContainingFile());
            return inClass;
        } else if (exit == DialogWrapper.CANCEL_EXIT_CODE) {
            inClass = null;//ww w  .j  a  v a 2s . c o  m
            int i = 0;
            while (clazz.findMethodBySignature(patternMethod, false) != null) {
                patternMethod.setName(setUpName + (++i));
            }
            setUpName = patternMethod.getName();
        }
    }

    final PsiClass superClass = clazz.getSuperClass();
    if (superClass != null) {
        final PsiMethod[] methods = superClass.findMethodsBySignature(patternMethod, false);
        if (methods.length > 0) {
            final PsiModifierList modifierList = methods[0].getModifierList();
            if (!modifierList.hasModifierProperty(PsiModifier.PRIVATE)) { //do not override private method
                @NonNls
                String pattern = "@" + BeforeMethod.class.getName() + "\n";
                if (modifierList.hasModifierProperty(PsiModifier.PROTECTED)) {
                    pattern += "protected ";
                } else if (modifierList.hasModifierProperty(PsiModifier.PUBLIC)) {
                    pattern += "public ";
                }
                patternMethod = factory.createMethodFromText(
                        pattern + "void " + setUpName + "() throws Exception {\nsuper." + setUpName + "();\n}",
                        null);
            }
        }
    }

    final PsiMethod[] psiMethods = clazz.getMethods();

    PsiMethod testMethod = null;
    for (PsiMethod psiMethod : psiMethods) {
        if (inClass == null && AnnotationUtil.isAnnotated(psiMethod, BeforeMethod.class.getName(), false)) {
            inClass = psiMethod;
        }
        if (testMethod == null && AnnotationUtil.isAnnotated(psiMethod, Test.class.getName(), false)
                && !psiMethod.hasModifierProperty(PsiModifier.PRIVATE)) {
            testMethod = psiMethod;
        }
    }
    if (inClass == null) {
        final PsiMethod psiMethod;
        if (testMethod != null) {
            psiMethod = (PsiMethod) clazz.addBefore(patternMethod, testMethod);
        } else {
            psiMethod = (PsiMethod) clazz.add(patternMethod);
        }
        JavaCodeStyleManager.getInstance(clazz.getProject()).shortenClassReferences(clazz);
        return psiMethod;
    } else if (inClass.getBody() == null) {
        return (PsiMethod) inClass.replace(patternMethod);
    }
    return inClass;
}

From source file:com.vladsch.MissingInActions.actions.MultiplePasteActionBase.java

License:Apache License

@Override
final public void actionPerformed(final AnActionEvent e) {
    Component component = e.getData(PlatformDataKeys.CONTEXT_COMPONENT);
    if (!(component instanceof JComponent))
        return;//from  w  w w . j  a  v a 2 s  . c  o m

    final ApplicationSettings settings = ApplicationSettings.getInstance();
    final DataContext dataContext = e.getDataContext();
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
    final JComponent focusedComponent = (JComponent) component;
    final CopyPasteManagerEx copyPasteManager = CopyPasteManagerEx.getInstanceEx();
    final HashMap<Transferable, ClipboardCaretContent> listEntryCarets = new HashMap<>();
    final boolean canCreateMultiCarets = editor != null && editor.getCaretModel().supportsMultipleCarets()
            && getCreateWithCaretsName(editor.getCaretModel().getCaretCount()) != null;
    final MultiPasteOptionsPane myEmptyContentDescription = new MultiPasteOptionsPane();
    final Shortcut[] moveLineUp = CommonUIShortcuts.getMoveLineUp().getShortcuts();
    final Shortcut[] moveLineDown = CommonUIShortcuts.getMoveLineDown().getShortcuts();
    final boolean[] inContentManipulation = new boolean[] { false };
    final boolean[] recreateCarets = new boolean[] { false };
    final HashMap<Transferable, String> stringTooLongSuffix = new HashMap<>();
    final DelayedRunner delayedRunner = new DelayedRunner();

    // Can change according to settings later
    // myEolText = "?";

    //noinspection unchecked
    final ContentChooser<Transferable>[] choosers = new ContentChooser[] { null };
    AwtRunnable listUpdater = new AwtRunnable(true, () -> {
        if (choosers[0] != null)
            choosers[0].updateListContents();
    });

    choosers[0] = new ContentChooser<Transferable>(project, getContentChooserTitle(editor, focusedComponent),
            true, true) {
        @Override
        protected String getStringRepresentationFor(final Transferable content) {
            //return (String) content.getTransferData(DataFlavor.stringFlavor);
            return getStringRep(editor, content, settings.isMultiPasteShowEolInViewer(), false, true);
        }

        @NotNull
        @Override
        protected String getShortStringFor(final Transferable content, final String fullString) {
            ClipboardCaretContent caretContent = getCaretContent(content);
            final int caretCount = caretContent == null ? 1 : caretContent.getCaretCount();
            String contentText = getStringRep(editor, content, false, false, false);
            String eolText = settings.isMultiPasteShowEolInList() && contentText.endsWith("\n")
                    && (caretCount == 1 || caretContent.allFullLines()) ? myEolText : "";
            stringTooLongSuffix.put(content, eolText);
            return String.format("[%d] %s", caretCount, super.getShortStringFor(content, contentText));
        }

        @NotNull
        @Override
        protected String getShortStringTooLongSuffix(Transferable content) {
            final String s = stringTooLongSuffix.get(content);
            return super.getShortStringTooLongSuffix(content) + (s == null ? "" : s);
        }

        @Override
        protected Editor createIdeaEditor(final String text) {
            delayedRunner.runAll();

            final Editor viewer = super.createIdeaEditor(text);
            final EditorSettings settings = viewer.getSettings();
            settings.setFoldingOutlineShown(false);
            settings.setIndentGuidesShown(false);
            settings.setLeadingWhitespaceShown(true);
            settings.setLineMarkerAreaShown(true);
            settings.setLineNumbersShown(true);
            settings.setTrailingWhitespaceShown(true);
            return viewer;
        }

        @Override
        protected void updateViewerForSelection(@NotNull final Editor viewer,
                @NotNull List<Transferable> allContents, @NotNull int[] selectedIndices) {
            if (viewer.getDocument().getTextLength() > 0) {
                // can create highlights in the editor to separate carets
                final ClipboardCaretContent caretContent;
                final Transferable content;
                if (selectedIndices.length > 1) {
                    // combine indices
                    content = EditHelpers.getMergedTransferable(editor, allContents, selectedIndices, true);
                    caretContent = ClipboardCaretContent.studyTransferable(editor, content);
                } else {
                    int index = selectedIndices[0];
                    content = allContents.get(index);
                    caretContent = getCaretContent(content);
                }

                assert caretContent != null;

                // convert multi caret text to \n separated ranges
                final String[] texts = caretContent.getTexts();
                if (texts != null) {
                    updateEditorHighlightRegions(viewer, caretContent, settings.isMultiPasteShowEolInViewer());

                    final FocusAdapter focusAdapter = new FocusAdapter() {
                        @Override
                        public void focusGained(final FocusEvent e) {
                            WriteCommandAction.runWriteCommandAction(viewer.getProject(), () -> {
                                final Document document = viewer.getDocument();
                                document.setReadOnly(false);
                                document.replaceString(0, document.getTextLength(),
                                        getStringRep(editor, content, false, true, false));
                                document.setReadOnly(true);
                                updateEditorHighlightRegions(viewer, caretContent, false);
                            });
                        }

                        @Override
                        public void focusLost(final FocusEvent e) {
                            final Document document = viewer.getDocument();
                            final int textLength = document.getTextLength();
                            if (textLength > 0) {
                                WriteCommandAction.runWriteCommandAction(viewer.getProject(), () -> {
                                    document.setReadOnly(false);
                                    document.replaceString(0, document.getTextLength(), getStringRep(editor,
                                            content, settings.isMultiPasteShowEolInViewer(), false, true));
                                    document.setReadOnly(true);
                                    updateEditorHighlightRegions(viewer, caretContent,
                                            settings.isMultiPasteShowEolInViewer());
                                });
                            }
                        }
                    };

                    viewer.getContentComponent().addFocusListener(focusAdapter);
                    delayedRunner.addRunnable(() -> {
                        viewer.getContentComponent().removeFocusListener(focusAdapter);
                    });
                }
            }
        }

        private void updateEditorHighlightRegions(@NotNull Editor viewer, ClipboardCaretContent caretContent,
                boolean multiPasteShowEolInViewer) {
            final TextRange[] textRanges = caretContent.getTextRanges();
            final int iMax = textRanges.length;
            MarkupModelEx markupModel = (MarkupModelEx) DocumentMarkupModel.forDocument(viewer.getDocument(),
                    project, true);
            final GutterIconRenderer charLinesSelection = new CaretIconRenderer(
                    PluginIcons.Clipboard_char_lines_caret);
            final GutterIconRenderer charSelection = new CaretIconRenderer(PluginIcons.Clipboard_char_caret);
            final GutterIconRenderer lineSelection = new CaretIconRenderer(PluginIcons.Clipboard_line_caret);
            int offset = 0;

            markupModel.removeAllHighlighters();

            for (int i = 0; i < iMax; i++) {
                final TextRange range = textRanges[i];
                final int startOffset = range.getStartOffset() + offset;
                offset += caretContent.isFullLine(i) && !multiPasteShowEolInViewer && i == iMax - 1 ? 0 : 1;
                RangeHighlighter highlighter = markupModel
                        .addLineHighlighter(viewer.offsetToLogicalPosition(startOffset).line, 1, null);
                highlighter.setGutterIconRenderer(caretContent.isFullLine(i) ? lineSelection
                        : caretContent.isCharLine(i) ? charLinesSelection : charSelection);
            }
        }

        @Override
        protected List<Transferable> getContents() {
            final Transferable[] contents = copyPasteManager.getAllContents();
            final ArrayList<Transferable> list = new ArrayList<>();
            list.addAll(Arrays.asList(contents));
            list.removeIf(content -> {
                if (content instanceof StringSelection) {
                    try {
                        final String data = (String) content.getTransferData(DataFlavor.stringFlavor);
                        return data.isEmpty();
                    } catch (UnsupportedFlavorException e1) {
                        LOG.error("", e1);
                    } catch (IOException e1) {
                        LOG.error("", e1);
                    }
                }
                return false;
            });
            return list;
        }

        @NotNull
        @Override
        public String getSelectedText() {
            if (choosers[0] == null) {
                return super.getSelectedText();
            } else {
                final int[] selectedIndices = choosers[0].getSelectedIndices();
                if (selectedIndices.length > 1) {
                    // combine indices
                    Transferable content = EditHelpers.getMergedTransferable(editor,
                            choosers[0].getAllContents(), selectedIndices, true);
                    return getStringRep(editor, content, settings.isMultiPasteShowEolInViewer(), false, true);
                } else {
                    return super.getSelectedText();
                }
            }
        }

        @Override
        protected void removeContentAt(final Transferable content) {
            copyPasteManager.removeContent(content);
            listEntryCarets.remove(content);
        }

        @Override
        protected void listKeyPressed(final KeyEvent event) {
            ContentChooser<Transferable> chooser = choosers[0];
            if (event.getKeyCode() != 0 && chooser != null) {
                if (event.getKeyCode() == KeyEvent.VK_UP && (event.getModifiers() & KeyEvent.ALT_MASK) != 0) {
                    // move selection up
                    moveSelections(chooser, true);
                    event.consume();
                } else if (event.getKeyCode() == KeyEvent.VK_DOWN
                        && (event.getModifiers() & KeyEvent.ALT_MASK) != 0) {
                    moveSelections(chooser, false);
                    event.consume();
                }
            }
        }

        @NotNull
        @Override
        protected Action[] createActions() {
            Action[] actions = super.createActions();
            if (canCreateMultiCarets) {
                Action[] multiCaretActions = new Action[actions.length + 1];
                System.arraycopy(actions, 0, multiCaretActions, 0, actions.length);
                Action createWithMultiCarets = new OkAction() {
                    @Override
                    protected void doAction(final ActionEvent e) {
                        recreateCarets[0] = true;
                        super.doAction(e);
                    }
                };
                final String name = getCreateWithCaretsName(editor.getCaretModel().getCaretCount());
                createWithMultiCarets.putValue(Action.NAME,
                        name == null ? Bundle.message("content-chooser.add-with-carets.label") : name);
                multiCaretActions[actions.length] = createWithMultiCarets;
                return multiCaretActions;
            }
            return actions;
        }

        @NotNull
        @Override
        protected Action[] createLeftSideActions() {
            Action showOptionsAction = new OkAction() {
                @Override
                protected void doAction(final ActionEvent e) {
                    final boolean showOptions = !settings.isMultiPasteShowOptions();
                    settings.setMultiPasteShowOptions(showOptions);
                    putValue(Action.NAME, showOptions ? Bundle.message("content-chooser.hide-options.label")
                            : Bundle.message("content-chooser.show-options.label"));
                    myEmptyContentDescription.myPanel.setVisible(showOptions);
                }
            };

            final boolean showOptions = settings.isMultiPasteShowOptions();
            showOptionsAction.putValue(Action.NAME,
                    showOptions ? Bundle.message("content-chooser.hide-options.label")
                            : Bundle.message("content-chooser.show-options.label"));
            return new Action[] { showOptionsAction };
        }

        @Nullable
        @Override
        protected JComponent getAboveEditorComponent() {
            String copyShortcut = CommonUIShortcuts
                    .getNthShortcutText(ActionManager.getInstance().getAction(IdeActions.ACTION_COPY), 1);
            String deleteShortcut = CommonUIShortcuts
                    .getNthShortcutText(ActionManager.getInstance().getAction(IdeActions.ACTION_DELETE), 1);
            String moveLineUpShortcut = CommonUIShortcuts.getNthShortcutText(
                    ActionManager.getInstance().getAction(CommonUIShortcuts.ACTION_MOVE_LINE_UP_ACTION), 2);
            String moveLineDownShortcut = CommonUIShortcuts.getNthShortcutText(
                    ActionManager.getInstance().getAction(CommonUIShortcuts.ACTION_MOVE_LINE_DOWN_ACTION), 2);
            if (!copyShortcut.isEmpty())
                copyShortcut = String.format(" (%s)", copyShortcut);
            if (!deleteShortcut.isEmpty())
                deleteShortcut = String.format(" (%s)", deleteShortcut);
            if (!moveLineUpShortcut.isEmpty())
                moveLineUpShortcut = String.format(" (%s)", moveLineUpShortcut);
            if (!moveLineDownShortcut.isEmpty())
                moveLineDownShortcut = String.format(" (%s)", moveLineDownShortcut);
            String bannerSlogan = Bundle.indexedMessage("content-chooser.above-editor.description",
                    copyShortcut, deleteShortcut, moveLineUpShortcut, moveLineDownShortcut);
            myEmptyContentDescription.setContentBody(
                    Utils.join(bannerSlogan.split("\n"), "<ul align='left'>", "</ul>", "<li>", "</li>"));
            myEmptyContentDescription.setSettingsChangedRunnable(() -> {
                if (choosers[0] != null) {
                    final int[] indices = choosers[0].getSelectedIndices();
                    choosers[0].updateListContents();
                    choosers[0].setSelectedIndices(indices);
                }
            });

            myEmptyContentDescription.myPanel.setVisible(settings.isMultiPasteShowOptions());
            return myEmptyContentDescription.myPanel;
        }

        private void moveSelections(final ContentChooser<Transferable> chooser, boolean moveUp) {
            final int[] indices = chooser.getSelectedIndices();
            final List<Transferable> allContents = new ArrayList<>(chooser.getAllContents());
            boolean allConsecutive = true;
            int firstIndex = -1;
            int lastIndex = -1;

            for (int index : indices) {
                if (firstIndex == -1) {
                    firstIndex = index;
                    lastIndex = index;
                } else {
                    if (lastIndex + 1 != index) {
                        allConsecutive = false;
                    }
                    lastIndex = index;
                }
            }

            List<Transferable> moved = new ArrayList<>();

            int anchorIndex = moveUp ? firstIndex : lastIndex;
            for (int index : indices) {
                if (allConsecutive || index != anchorIndex) {
                    moved.add(allContents.get(index));
                }
            }

            if (!allConsecutive) {
                allContents.removeAll(moved);
                allContents.addAll(anchorIndex + (moveUp ? 1 : 0), moved);
                reOrderContentList(allContents);
            } else {
                final int size = lastIndex - firstIndex + 1;
                final int halfSize = size / 2;
                if (moveUp) {
                    if (firstIndex <= 0) {
                        // reverse
                        if (halfSize > 0) {
                            for (int i = 0; i < halfSize; i++) {
                                Transferable first = allContents.get(firstIndex + i);
                                Transferable last = allContents.get(lastIndex - i);
                                allContents.set(firstIndex + i, last);
                                allContents.set(lastIndex - i, first);
                            }
                            reOrderContentList(allContents);
                        }
                    } else {
                        allContents.removeAll(moved);
                        allContents.addAll(firstIndex - 1, moved);
                        reOrderContentList(allContents);
                        anchorIndex = firstIndex - 1;
                    }
                } else {
                    if (lastIndex + 1 >= allContents.size()) {
                        // reverse order
                        if (halfSize > 0) {
                            for (int i = 0; i < halfSize; i++) {
                                Transferable first = allContents.get(firstIndex + i);
                                Transferable last = allContents.get(lastIndex - i);
                                allContents.set(firstIndex + i, last);
                                allContents.set(lastIndex - i, first);
                            }
                            reOrderContentList(allContents);
                        }
                    } else {
                        allContents.removeAll(moved);
                        allContents.addAll(lastIndex + 2 - moved.size(), moved);
                        reOrderContentList(allContents);
                        anchorIndex = lastIndex + 1;
                    }
                }
            }

            chooser.updateListContents();
            int index = 0;
            if (moveUp) {
                for (int i = anchorIndex; index < indices.length; i++)
                    indices[index++] = i;
            } else {
                for (int i = anchorIndex; index < indices.length; i--)
                    indices[index++] = i;
            }
            chooser.setSelectedIndices(indices);
        }

        private void reOrderContentList(@NotNull List<Transferable> allContents) {
            inContentManipulation[0] = true;
            try {
                int iMax = allContents.size();
                Transferable[] currentOrder = copyPasteManager.getAllContents();
                int i;
                for (i = iMax; i-- > 0;) {
                    if (currentOrder[i] != allContents.get(i))
                        break;
                }

                for (i++; i-- > 0;) {
                    copyPasteManager.moveContentToStackTop(allContents.get(i));
                }
            } finally {
                inContentManipulation[0] = false;
            }
        }

        @Override
        protected Icon getListEntryIcon(@NotNull final Transferable content) {
            final ClipboardCaretContent caretContent = getCaretContent(content);
            return caretContent != null && caretContent.getCaretCount() > 1 ? PluginIcons.Clipboard_carets
                    : PluginIcons.Clipboard_text;
        }

        @Nullable
        private ClipboardCaretContent getCaretContent(final @NotNull Transferable content) {
            ClipboardCaretContent caretContent = listEntryCarets.get(content);
            if (!listEntryCarets.containsKey(content)) {
                caretContent = ClipboardCaretContent.studyTransferable(editor, content);
                listEntryCarets.put(content, caretContent);
            }
            return caretContent;
        }
    };

    final ContentChooser<Transferable> chooser = choosers[0];
    final CopyPasteManager.ContentChangedListener contentChangedListener = new CopyPasteManager.ContentChangedListener() {
        @Override
        public void contentChanged(@Nullable final Transferable oldTransferable,
                final Transferable newTransferable) {
            if (!inContentManipulation[0]) {
                listUpdater.run();
            }
        }
    };

    try {
        copyPasteManager.addContentChangedListener(contentChangedListener);
        if (!chooser.getAllContents().isEmpty()) {
            chooser.show();
        } else {
            chooser.close(DialogWrapper.CANCEL_EXIT_CODE);
        }
    } finally {
        copyPasteManager.removeContentChangedListener(contentChangedListener);
    }

    if (chooser.isOK()) {
        final int[] selectedIndices = chooser.getSelectedIndices();
        if (selectedIndices.length == 1) {
            copyPasteManager.moveContentToStackTop(chooser.getAllContents().get(selectedIndices[0]));
        } else {
            copyPasteManager.setContents(
                    EditHelpers.getMergedTransferable(editor, chooser.getAllContents(), selectedIndices, true));
        }

        if (editor != null) {
            if (editor.isViewer())
                return;

            final AnAction pasteAction = getPasteAction(editor, recreateCarets[0]);

            AnActionEvent newEvent = new AnActionEvent(e.getInputEvent(),
                    DataManager.getInstance().getDataContext(focusedComponent), e.getPlace(),
                    e.getPresentation(), ActionManager.getInstance(), e.getModifiers());

            pasteAction.actionPerformed(newEvent);
        } else {
            final Action pasteAction = getPasteAction(focusedComponent);
            if (pasteAction != null) {
                pasteAction
                        .actionPerformed(new ActionEvent(focusedComponent, ActionEvent.ACTION_PERFORMED, ""));
            }
        }
    }
}