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

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

Introduction

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

Prototype

@NotNull
    public static Icon getInformationIcon() 

Source Link

Usage

From source file:com.intellij.ide.util.scopeChooser.ScopeChooserConfigurable.java

License:Apache License

private void createScope(final boolean isLocal, String title, final PackageSet set) {
    final String newName = Messages.showInputDialog(myTree, IdeBundle.message("add.scope.name.label"), title,
            Messages.getInformationIcon(), createUniqueName(), new InputValidator() {
                @Override//from ww  w  .  j a  va2  s. c  o m
                public boolean checkInput(String inputString) {
                    final NamedScopesHolder holder = isLocal ? myLocalScopesManager : mySharedScopesManager;
                    for (NamedScope scope : holder.getPredefinedScopes()) {
                        if (Comparing.strEqual(scope.getName(), inputString.trim())) {
                            return false;
                        }
                    }
                    return inputString.trim().length() > 0;
                }

                @Override
                public boolean canClose(String inputString) {
                    return checkInput(inputString);
                }
            });
    if (newName != null) {
        final NamedScope scope = new NamedScope(newName, set);
        addNewScope(scope, isLocal);
    }
}

From source file:com.intellij.profile.codeInspection.ui.header.InspectionToolsConfigurable.java

License:Apache License

public InspectionToolsConfigurable(@NotNull final InspectionProjectProfileManager projectProfileManager,
        InspectionProfileManager profileManager) {
    myWholePanel = new JPanel(new BorderLayout());

    final JPanel toolbar = new JPanel(new GridBagLayout());
    toolbar.setBorder(BorderFactory.createEmptyBorder(0, 0, 7, 0));

    myPanel = new JPanel();

    myWholePanel.add(toolbar, BorderLayout.PAGE_START);
    myWholePanel.add(myPanel, BorderLayout.CENTER);

    myProfiles = new ProfilesConfigurableComboBox(new ListCellRendererWrapper<Profile>() {
        @Override//w w  w  .  ja va 2  s . c  om
        public void customize(final JList list, final Profile value, final int index, final boolean selected,
                final boolean hasFocus) {
            final SingleInspectionProfilePanel singleInspectionProfilePanel = myPanels.get(value);
            final boolean isShared = singleInspectionProfilePanel.isProfileShared();
            setIcon(isShared ? AllIcons.General.ProjectSettings : AllIcons.General.Settings);
            setText(singleInspectionProfilePanel.getCurrentProfileName());
        }
    }) {
        @Override
        public void onProfileChosen(InspectionProfileImpl inspectionProfile) {
            myLayout.show(myPanel, getCardName(inspectionProfile));
            myAuxiliaryRightPanel.showDescription(inspectionProfile.getDescription());
        }
    };
    JPanel profilesHolder = new JPanel();
    profilesHolder.setLayout(new CardLayout());

    JComponent manageButton = new ManageButton(new ManageButtonBuilder() {
        @Override
        public boolean isSharedToTeamMembers() {
            SingleInspectionProfilePanel panel = getSelectedPanel();
            return panel != null && panel.isProfileShared();
        }

        @Override
        public void setShareToTeamMembers(boolean shared) {
            final SingleInspectionProfilePanel selectedPanel = getSelectedPanel();
            LOG.assertTrue(selectedPanel != null, "No settings selectedPanel for: " + getSelectedObject());

            final String name = getSelectedPanel().getCurrentProfileName();
            for (SingleInspectionProfilePanel p : myPanels.values()) {
                if (p != selectedPanel && Comparing.equal(p.getCurrentProfileName(), name)) {
                    final boolean curShared = p.isProfileShared();
                    if (curShared == shared) {
                        Messages.showErrorDialog(
                                (shared ? "Shared" : "Application level") + " profile with same name exists.",
                                "Inspections Settings");
                        return;
                    }
                }
            }

            selectedPanel.setProfileShared(shared);
            myProfiles.repaint();
        }

        @Override
        public void copy() {
            final InspectionProfileImpl newProfile = copyToNewProfile(getSelectedObject(), getProject());
            if (newProfile != null) {
                final InspectionProfileImpl modifiableModel = (InspectionProfileImpl) newProfile
                        .getModifiableModel();
                modifiableModel.setModified(true);
                modifiableModel.setProjectLevel(false);
                addProfile(modifiableModel);
                rename(modifiableModel);
            }
        }

        @Override
        public boolean canRename() {
            final InspectionProfileImpl profile = getSelectedObject();
            return !profile.isProfileLocked();
        }

        @Override
        public void rename() {
            rename(getSelectedObject());
        }

        private void rename(@NotNull final InspectionProfileImpl inspectionProfile) {
            final String initialName = getSelectedPanel().getCurrentProfileName();
            myProfiles.showEditCard(initialName, new SaveInputComponentValidator() {
                @Override
                public void doSave(@NotNull String text) {
                    if (!text.equals(initialName)) {
                        getProfilePanel(inspectionProfile).setCurrentProfileName(text);
                    }
                    myProfiles.showComboBoxCard();
                }

                @Override
                public boolean checkValid(@NotNull String text) {
                    final SingleInspectionProfilePanel singleInspectionProfilePanel = myPanels
                            .get(inspectionProfile);
                    if (singleInspectionProfilePanel == null) {
                        return false;
                    }
                    final boolean isValid = text.equals(initialName)
                            || !hasName(text, singleInspectionProfilePanel.isProfileShared());
                    if (isValid) {
                        myAuxiliaryRightPanel.showDescription(getSelectedObject().getDescription());
                    } else {
                        myAuxiliaryRightPanel
                                .showError("Name is already in use. Please change name to unique.");
                    }
                    return isValid;
                }

                @Override
                public void cancel() {
                    myProfiles.showComboBoxCard();
                    myAuxiliaryRightPanel.showDescription(getSelectedObject().getDescription());
                }
            });
        }

        @Override
        public boolean canDelete() {
            return isDeleteEnabled(myProfiles.getSelectedProfile());
        }

        @Override
        public void delete() {
            final InspectionProfileImpl selectedProfile = myProfiles.getSelectedProfile();
            myProfiles.getModel().removeElement(selectedProfile);
            myDeletedProfiles.add(selectedProfile);
        }

        @Override
        public boolean canEditDescription() {
            return true;
        }

        @Override
        public void editDescription() {
            myAuxiliaryRightPanel.editDescription(getSelectedObject().getDescription());
        }

        @Override
        public boolean hasDescription() {
            return !StringUtil.isEmpty(getSelectedObject().getDescription());
        }

        @Override
        public void export() {
            final FileChooserDescriptor descriptor = FileChooserDescriptorFactory
                    .createSingleFolderDescriptor();
            descriptor.setDescription("Choose directory to store profile file");
            FileChooser.chooseFile(descriptor, getProject(), myWholePanel, null, new Consumer<VirtualFile>() {
                @Override
                public void consume(VirtualFile file) {
                    final Element element = new Element("inspections");
                    try {
                        final SingleInspectionProfilePanel panel = getSelectedPanel();
                        LOG.assertTrue(panel != null);
                        final InspectionProfileImpl profile = getSelectedObject();
                        LOG.assertTrue(true);
                        profile.writeExternal(element);
                        final String filePath = FileUtil.toSystemDependentName(file.getPath()) + File.separator
                                + FileUtil.sanitizeFileName(profile.getName()) + ".xml";
                        if (new File(filePath).isFile()) {
                            if (Messages.showOkCancelDialog(myWholePanel,
                                    "File \'" + filePath + "\' already exist. Do you want to overwrite it?",
                                    "Warning", Messages.getQuestionIcon()) != Messages.OK) {
                                return;
                            }
                        }
                        JDOMUtil.writeDocument(new Document(element), filePath,
                                SystemProperties.getLineSeparator());
                    } catch (WriteExternalException e1) {
                        LOG.error(e1);
                    } catch (IOException e1) {
                        LOG.error(e1);
                    }
                }
            });
        }

        @Override
        public void doImport() {
            final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, false, false, false,
                    false) {
                @Override
                public boolean isFileSelectable(VirtualFile file) {
                    return file.getFileType().equals(InternalStdFileTypes.XML);
                }
            };
            descriptor.setDescription("Choose profile file");
            FileChooser.chooseFile(descriptor, getProject(), myWholePanel, null, new Consumer<VirtualFile>() {
                @Override
                public void consume(VirtualFile file) {
                    if (file == null)
                        return;
                    InspectionProfileImpl profile = new InspectionProfileImpl("TempProfile",
                            InspectionToolRegistrar.getInstance(), myProfileManager);
                    try {
                        Element rootElement = JDOMUtil.loadDocument(VfsUtilCore.virtualToIoFile(file))
                                .getRootElement();
                        if (Comparing.strEqual(rootElement.getName(), "component")) {//import right from .idea/inspectProfiles/xxx.xml
                            rootElement = rootElement.getChildren().get(0);
                        }
                        final Set<String> levels = new HashSet<String>();
                        for (Object o : rootElement.getChildren("inspection_tool")) {
                            final Element inspectElement = (Element) o;
                            levels.add(inspectElement.getAttributeValue("level"));
                            for (Object s : inspectElement.getChildren("scope")) {
                                levels.add(((Element) s).getAttributeValue("level"));
                            }
                        }
                        for (Iterator<String> iterator = levels.iterator(); iterator.hasNext();) {
                            String level = iterator.next();
                            if (myProfileManager.getOwnSeverityRegistrar().getSeverity(level) != null) {
                                iterator.remove();
                            }
                        }
                        if (!levels.isEmpty()) {
                            if (Messages.showYesNoDialog(myWholePanel,
                                    "Undefined severities detected: " + StringUtil.join(levels, ", ")
                                            + ". Do you want to create them?",
                                    "Warning", Messages.getWarningIcon()) == Messages.YES) {
                                for (String level : levels) {
                                    final TextAttributes textAttributes = CodeInsightColors.WARNINGS_ATTRIBUTES
                                            .getDefaultAttributes();
                                    HighlightInfoType.HighlightInfoTypeImpl info = new HighlightInfoType.HighlightInfoTypeImpl(
                                            new HighlightSeverity(level, 50),
                                            TextAttributesKey.createTextAttributesKey(level));
                                    myProfileManager.getOwnSeverityRegistrar().registerSeverity(
                                            new SeverityRegistrar.SeverityBasedTextAttributes(
                                                    textAttributes.clone(), info),
                                            textAttributes.getErrorStripeColor());
                                }
                            }
                        }
                        profile.readExternal(rootElement);
                        profile.setProjectLevel(false);
                        profile.initInspectionTools(getProject());
                        if (getProfilePanel(profile) != null) {
                            if (Messages.showOkCancelDialog(myWholePanel,
                                    "Profile with name \'" + profile.getName()
                                            + "\' already exists. Do you want to overwrite it?",
                                    "Warning", Messages.getInformationIcon()) != Messages.OK) {
                                return;
                            }
                        }
                        final ModifiableModel model = profile.getModifiableModel();
                        model.setModified(true);
                        addProfile((InspectionProfileImpl) model);

                        //TODO myDeletedProfiles ? really need this
                        myDeletedProfiles.remove(profile);
                    } catch (InvalidDataException e1) {
                        LOG.error(e1);
                    } catch (JDOMException e1) {
                        LOG.error(e1);
                    } catch (IOException e1) {
                        LOG.error(e1);
                    }
                }
            });
        }
    }).build();

    myAuxiliaryRightPanel = new AuxiliaryRightPanel(new AuxiliaryRightPanel.DescriptionSaveListener() {
        @Override
        public void saveDescription(@NotNull String description) {
            final InspectionProfileImpl inspectionProfile = getSelectedObject();
            if (!Comparing.strEqual(description, inspectionProfile.getDescription())) {
                inspectionProfile.setDescription(description);
                inspectionProfile.setModified(true);
            }
            myAuxiliaryRightPanel.showDescription(description);
        }

        @Override
        public void cancel() {
            myAuxiliaryRightPanel.showDescription(getSelectedObject().getDescription());
        }
    });

    toolbar.add(new JLabel(HEADER_TITLE), new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.WEST,
            GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0));

    toolbar.add(myProfiles.getHintLabel(), new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.WEST,
            GridBagConstraints.VERTICAL, new Insets(0, 6, 6, 0), 0, 0));
    toolbar.add(myProfiles, new GridBagConstraints(1, 1, 1, 1, 0, 1.0, GridBagConstraints.WEST,
            GridBagConstraints.VERTICAL, new Insets(0, 6, 0, 0), 0, 0));

    toolbar.add(manageButton, new GridBagConstraints(2, 1, 1, 1, 0, 0, GridBagConstraints.WEST,
            GridBagConstraints.VERTICAL, new Insets(0, 10, 0, 0), 0, 0));

    toolbar.add(myAuxiliaryRightPanel.getHintLabel(), new GridBagConstraints(3, 0, 1, 1, 0, 0,
            GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0, 15, 6, 0), 0, 0));
    toolbar.add(myAuxiliaryRightPanel, new GridBagConstraints(3, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
            GridBagConstraints.BOTH, new Insets(0, 15, 0, 0), 0, 0));

    ((InspectionManagerEx) InspectionManager.getInstance(projectProfileManager.getProject()))
            .buildInspectionSearchIndexIfNecessary();
    myProjectProfileManager = projectProfileManager;
    myProfileManager = profileManager;
}

From source file:com.intellij.profile.codeInspection.ui.InspectionToolsConfigurable.java

License:Apache License

public InspectionToolsConfigurable(@NotNull final InspectionProjectProfileManager projectProfileManager,
        InspectionProfileManager profileManager) {
    ((InspectionManagerEx) InspectionManager.getInstance(projectProfileManager.getProject()))
            .buildInspectionSearchIndexIfNecessary();
    myAddButton.addActionListener(new ActionListener() {
        @Override/*from  ww w .j a va 2 s  . c  o m*/
        public void actionPerformed(ActionEvent e) {
            final Set<String> existingProfileNames = myPanels.keySet();
            final ModifiableModel model = SingleInspectionProfilePanel.createNewProfile(-1, getSelectedObject(),
                    myWholePanel, "", existingProfileNames, projectProfileManager.getProject());
            if (model != null) {
                addProfile((InspectionProfileImpl) model);
                myDeletedProfiles.remove(getProfilePrefix(model) + model.getName());
                myDeleteButton.setEnabled(true);
            }
        }
    });

    myDeleteButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final InspectionProfileImpl selectedProfile = (InspectionProfileImpl) myProfiles.getSelectedItem();
            ((DefaultComboBoxModel) myProfiles.getModel()).removeElement(selectedProfile);
            myDeletedProfiles.add(getProfilePrefix(selectedProfile) + selectedProfile.getName());
            myDeleteButton.setEnabled(isDeleteEnabled(selectedProfile));
        }
    });

    final Project project = projectProfileManager.getProject();
    myImportButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, false, false, false,
                    false) {
                @Override
                public boolean isFileSelectable(VirtualFile file) {
                    return file.getFileType().equals(StdFileTypes.XML);
                }
            };
            descriptor.setDescription("Choose profile file");
            FileChooser.chooseFile(descriptor, project, myWholePanel, null, new Consumer<VirtualFile>() {
                @Override
                public void consume(VirtualFile file) {
                    if (file == null)
                        return;
                    InspectionProfileImpl profile = new InspectionProfileImpl("TempProfile",
                            InspectionToolRegistrar.getInstance(), myProfileManager);
                    try {
                        Element rootElement = JDOMUtil.loadDocument(VfsUtilCore.virtualToIoFile(file))
                                .getRootElement();
                        if (Comparing.strEqual(rootElement.getName(), "component")) {//import right from .idea/inspectProfiles/xxx.xml
                            rootElement = rootElement.getChildren().get(0);
                        }
                        final Set<String> levels = new HashSet<String>();
                        for (Object o : rootElement.getChildren("inspection_tool")) {
                            final Element inspectElement = (Element) o;
                            levels.add(inspectElement.getAttributeValue("level"));
                            for (Object s : inspectElement.getChildren("scope")) {
                                levels.add(((Element) s).getAttributeValue("level"));
                            }
                        }
                        for (Iterator<String> iterator = levels.iterator(); iterator.hasNext();) {
                            String level = iterator.next();
                            if (myProfileManager.getOwnSeverityRegistrar().getSeverity(level) != null) {
                                iterator.remove();
                            }
                        }
                        if (!levels.isEmpty()) {
                            if (Messages.showYesNoDialog(myWholePanel,
                                    "Undefined severities detected: " + StringUtil.join(levels, ", ")
                                            + ". Do you want to create them?",
                                    "Warning", Messages.getWarningIcon()) == Messages.YES) {
                                for (String level : levels) {
                                    final TextAttributes textAttributes = CodeInsightColors.WARNINGS_ATTRIBUTES
                                            .getDefaultAttributes();
                                    HighlightInfoType.HighlightInfoTypeImpl info = new HighlightInfoType.HighlightInfoTypeImpl(
                                            new HighlightSeverity(level, 50),
                                            com.intellij.openapi.editor.colors.TextAttributesKey
                                                    .createTextAttributesKey(level));
                                    myProfileManager.getOwnSeverityRegistrar().registerSeverity(
                                            new SeverityRegistrar.SeverityBasedTextAttributes(
                                                    textAttributes.clone(), info),
                                            textAttributes.getErrorStripeColor());
                                }
                            }
                        }
                        profile.readExternal(rootElement);
                        profile.setLocal(true);
                        profile.initInspectionTools(project);
                        if (getProfilePanel(profile) != null) {
                            if (Messages.showOkCancelDialog(myWholePanel,
                                    "Profile with name \'" + profile.getName()
                                            + "\' already exists. Do you want to overwrite it?",
                                    "Warning", Messages.getInformationIcon()) != Messages.OK)
                                return;
                        }
                        final ModifiableModel model = profile.getModifiableModel();
                        model.setModified(true);
                        addProfile((InspectionProfileImpl) model);
                        myDeletedProfiles.remove(getProfilePrefix(profile) + profile.getName());
                        myDeleteButton.setEnabled(true);
                    } catch (InvalidDataException e1) {
                        LOG.error(e1);
                    } catch (JDOMException e1) {
                        LOG.error(e1);
                    } catch (IOException e1) {
                        LOG.error(e1);
                    }
                }
            });
        }
    });

    myExportButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final FileChooserDescriptor descriptor = FileChooserDescriptorFactory
                    .createSingleFolderDescriptor();
            descriptor.setDescription("Choose directory to store profile file");
            FileChooser.chooseFile(descriptor, project, myWholePanel, null, new Consumer<VirtualFile>() {
                @Override
                public void consume(VirtualFile file) {
                    final Element element = new Element("inspections");
                    try {
                        final SingleInspectionProfilePanel panel = getSelectedPanel();
                        LOG.assertTrue(panel != null);
                        final InspectionProfileImpl profile = (InspectionProfileImpl) panel
                                .getSelectedProfile();
                        profile.writeExternal(element);
                        final String filePath = FileUtil.toSystemDependentName(file.getPath()) + File.separator
                                + FileUtil.sanitizeFileName(profile.getName()) + ".xml";
                        if (new File(filePath).isFile()) {
                            if (Messages.showOkCancelDialog(myWholePanel,
                                    "File \'" + filePath + "\' already exist. Do you want to overwrite it?",
                                    "Warning", Messages.getQuestionIcon()) != Messages.OK)
                                return;
                        }
                        JDOMUtil.writeDocument(new Document(element), filePath,
                                SystemProperties.getLineSeparator());
                    } catch (WriteExternalException e1) {
                        LOG.error(e1);
                    } catch (IOException e1) {
                        LOG.error(e1);
                    }
                }
            });

        }
    });

    myCopyButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final Set<String> existingProfileNames = myPanels.keySet();
            final InspectionProfileImpl model = (InspectionProfileImpl) SingleInspectionProfilePanel
                    .createNewProfile(0, getSelectedObject(), myWholePanel, "", existingProfileNames, project);
            if (model != null) {
                final InspectionProfileImpl modifiableModel = (InspectionProfileImpl) model
                        .getModifiableModel();
                modifiableModel.setModified(true);
                addProfile(modifiableModel);
                myDeletedProfiles.remove(getProfilePrefix(model) + model.getName());
                myDeleteButton.setEnabled(true);
            }
        }
    });

    myProjectProfileManager = projectProfileManager;
    myProfileManager = profileManager;

    myJBScrollPane.setBorder(null);
}

From source file:com.intellij.profile.codeInspection.ui.ProfilesComboBox.java

License:Apache License

public void createProfilesCombo(final Profile selectedProfile, final Set<Profile> availableProfiles,
        final ProfileManager profileManager) {
    reloadProfiles(profileManager, availableProfiles, selectedProfile);

    setRenderer(new DefaultListCellRenderer() {
        @Override//w  w w  .ja  va2 s  .  c  o  m
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            final Component rendererComponent = super.getListCellRendererComponent(list, value, index,
                    isSelected, cellHasFocus);
            if (value instanceof Profile) {
                final Profile profile = (Profile) value;
                setText(profile.getName());
                setIcon(profile.isLocal() ? AllIcons.General.Settings : AllIcons.General.ProjectSettings);
            } else if (value instanceof String) {
                setText((String) value);
            }
            return rendererComponent;
        }
    });
    addItemListener(new ItemListener() {
        private Object myDeselectedItem = null;

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (myFrozenProfilesCombo)
                return; //do not update during reloading
            if (ItemEvent.SELECTED == e.getStateChange()) {
                final Object item = e.getItem();
                if (profileManager instanceof ProjectProfileManager && item instanceof Profile
                        && ((Profile) item).isLocal()) {
                    if (Messages.showOkCancelDialog(
                            InspectionsBundle.message("inspection.new.profile.ide.to.project.warning.message"),
                            InspectionsBundle.message("inspection.new.profile.ide.to.project.warning.title"),
                            Messages.getErrorIcon()) == DialogWrapper.OK_EXIT_CODE) {
                        final String newName = Messages.showInputDialog(
                                InspectionsBundle.message("inspection.new.profile.text"),
                                InspectionsBundle.message("inspection.new.profile.dialog.title"),
                                Messages.getInformationIcon());
                        final Object selectedItem = getSelectedItem();
                        if (newName != null && newName.length() > 0 && selectedItem instanceof Profile) {
                            if (ArrayUtil.find(profileManager.getAvailableProfileNames(), newName) == -1
                                    && ArrayUtil.find(
                                            InspectionProfileManager.getInstance().getAvailableProfileNames(),
                                            newName) == -1) {
                                saveNewProjectProfile(newName, (Profile) selectedItem, profileManager);
                                return;
                            } else {
                                Messages.showErrorDialog(
                                        InspectionsBundle.message("inspection.unable.to.create.profile.message",
                                                newName),
                                        InspectionsBundle
                                                .message("inspection.unable.to.create.profile.dialog.title"));
                            }
                        }
                    }
                    setSelectedItem(myDeselectedItem);
                }
            } else {
                myDeselectedItem = e.getItem();
            }
        }
    });
}

From source file:com.intellij.refactoring.extractMethod.ExtractMethodHelper.java

License:Apache License

private static void replaceDuplicates(PsiElement callElement, Editor editor,
        Consumer<Pair<SimpleMatch, PsiElement>> replacer, List<SimpleMatch> duplicates) {
    if (duplicates.size() > 0) {
        final String message = RefactoringBundle.message(
                "0.has.detected.1.code.fragments.in.this.file.that.can.be.replaced.with.a.call.to.extracted.method",
                ApplicationNamesInfo.getInstance().getProductName(), duplicates.size());
        final boolean isUnittest = ApplicationManager.getApplication().isUnitTestMode();
        final Project project = callElement.getProject();
        final int exitCode = !isUnittest ? Messages.showYesNoDialog(project, message,
                RefactoringBundle.message("refactoring.extract.method.dialog.title"),
                Messages.getInformationIcon()) : Messages.YES;
        if (exitCode == Messages.YES) {
            boolean replaceAll = false;
            final Map<SimpleMatch, RangeHighlighter> highlighterMap = new HashMap<SimpleMatch, RangeHighlighter>();
            for (SimpleMatch match : duplicates) {
                final Pair<SimpleMatch, PsiElement> replacement = Pair.create(match, callElement);
                if (!replaceAll) {
                    highlightInEditor(project, match, editor, highlighterMap);

                    int promptResult = FindManager.PromptResult.ALL;
                    //noinspection ConstantConditions
                    if (!isUnittest) {
                        ReplacePromptDialog promptDialog = new ReplacePromptDialog(false,
                                RefactoringBundle.message("replace.fragment"), project);
                        promptDialog.show();
                        promptResult = promptDialog.getExitCode();
                    }/*  www .  j ava  2  s.  c om*/
                    if (promptResult == FindManager.PromptResult.SKIP) {
                        final HighlightManager highlightManager = HighlightManager.getInstance(project);
                        final RangeHighlighter highlighter = highlighterMap.get(match);
                        if (highlighter != null)
                            highlightManager.removeSegmentHighlighter(editor, highlighter);
                        continue;
                    }
                    if (promptResult == FindManager.PromptResult.CANCEL)
                        break;

                    if (promptResult == FindManager.PromptResult.OK) {
                        replaceDuplicate(project, replacer, replacement);
                    } else if (promptResult == FindManager.PromptResult.ALL) {
                        replaceDuplicate(project, replacer, replacement);
                        replaceAll = true;
                    }
                } else {
                    replaceDuplicate(project, replacer, replacement);
                }
            }
        }
    }
}

From source file:com.intellij.refactoring.lang.ExtractIncludeFileBase.java

License:Apache License

private void replaceDuplicates(final String includePath, final List<IncludeDuplicate<T>> duplicates,
        final Editor editor, final Project project) {
    if (duplicates.size() > 0) {
        final String message = RefactoringBundle.message(
                "idea.has.found.fragments.that.can.be.replaced.with.include.directive",
                ApplicationNamesInfo.getInstance().getProductName());
        final int exitCode = Messages.showYesNoDialog(project, message, getRefactoringName(),
                Messages.getInformationIcon());
        if (exitCode == Messages.YES) {
            CommandProcessor.getInstance().executeCommand(project, new Runnable() {
                @Override//w  w w.j  a  v a 2 s  .  c  om
                public void run() {
                    boolean replaceAll = false;
                    for (IncludeDuplicate<T> pair : duplicates) {
                        if (!replaceAll) {

                            highlightInEditor(project, pair, editor);

                            ReplacePromptDialog promptDialog = new ReplacePromptDialog(false,
                                    RefactoringBundle.message("replace.fragment"), project);
                            promptDialog.show();
                            final int promptResult = promptDialog.getExitCode();
                            if (promptResult == FindManager.PromptResult.SKIP)
                                continue;
                            if (promptResult == FindManager.PromptResult.CANCEL)
                                break;

                            if (promptResult == FindManager.PromptResult.OK) {
                                doReplaceRange(includePath, pair.getStart(), pair.getEnd());
                            } else if (promptResult == FindManager.PromptResult.ALL) {
                                doReplaceRange(includePath, pair.getStart(), pair.getEnd());
                                replaceAll = true;
                            } else {
                                LOG.error("Unknown return status");
                            }
                        } else {
                            doReplaceRange(includePath, pair.getStart(), pair.getEnd());
                        }
                    }
                }
            }, RefactoringBundle.message("remove.duplicates.command"), null);
        }
    }
}

From source file:com.intellij.tasks.impl.TaskManagerImpl.java

License:Apache License

@Override
public boolean testConnection(final TaskRepository repository) {

    TestConnectionTask task = new TestConnectionTask("Test connection") {
        @Override/*from   w ww  .ja v a  2  s.  co  m*/
        public void run(@Nonnull ProgressIndicator indicator) {
            indicator.setText("Connecting to " + repository.getUrl() + "...");
            indicator.setFraction(0);
            indicator.setIndeterminate(true);
            try {
                myConnection = repository.createCancellableConnection();
                if (myConnection != null) {
                    Future<Exception> future = ApplicationManager.getApplication()
                            .executeOnPooledThread(myConnection);
                    while (true) {
                        try {
                            myException = future.get(100, TimeUnit.MILLISECONDS);
                            return;
                        } catch (TimeoutException ignore) {
                            try {
                                indicator.checkCanceled();
                            } catch (ProcessCanceledException e) {
                                myException = e;
                                myConnection.cancel();
                                return;
                            }
                        } catch (Exception e) {
                            myException = e;
                            return;
                        }
                    }
                } else {
                    try {
                        repository.testConnection();
                    } catch (Exception e) {
                        LOG.info(e);
                        myException = e;
                    }
                }
            } catch (Exception e) {
                myException = e;
            }
        }
    };
    ProgressManager.getInstance().run(task);
    Exception e = task.myException;
    if (e == null) {
        myBadRepositories.remove(repository);
        Messages.showMessageDialog(myProject, "Connection is successful", "Connection",
                Messages.getInformationIcon());
    } else if (!(e instanceof ProcessCanceledException)) {
        String message = e.getMessage();
        if (e instanceof UnknownHostException) {
            message = "Unknown host: " + message;
        }
        if (message == null) {
            LOG.error(e);
            message = "Unknown error";
        }
        Messages.showErrorDialog(myProject, StringUtil.capitalize(message), "Error");
    }
    return e == null;
}

From source file:com.intellij.uiDesigner.snapShooter.CreateSnapShotAction.java

License:Apache License

public void actionPerformed(AnActionEvent e) {
    final Project project = e.getData(CommonDataKeys.PROJECT);
    final IdeView view = e.getData(LangDataKeys.IDE_VIEW);
    if (project == null || view == null) {
        return;//  www . j  a v a 2s. co m
    }

    final PsiDirectory dir = view.getOrChooseDirectory();
    if (dir == null)
        return;

    final SnapShotClient client = new SnapShotClient();
    List<RunnerAndConfigurationSettings> appConfigurations = new ArrayList<RunnerAndConfigurationSettings>();
    RunnerAndConfigurationSettings snapshotConfiguration = null;
    boolean connected = false;

    ApplicationConfigurationType cfgType = ApplicationConfigurationType.getInstance();
    List<RunnerAndConfigurationSettings> racsi = RunManager.getInstance(project)
            .getConfigurationSettingsList(cfgType);

    for (RunnerAndConfigurationSettings config : racsi) {
        if (config.getConfiguration() instanceof ApplicationConfiguration) {
            ApplicationConfiguration appConfig = (ApplicationConfiguration) config.getConfiguration();
            appConfigurations.add(config);
            if (appConfig.ENABLE_SWING_INSPECTOR) {
                SnapShooterConfigurationSettings settings = SnapShooterConfigurationSettings.get(appConfig);
                snapshotConfiguration = config;
                if (settings.getLastPort() > 0) {
                    try {
                        client.connect(settings.getLastPort());
                        connected = true;
                    } catch (IOException ex) {
                        connected = false;
                    }
                }
            }
            if (connected)
                break;
        }
    }

    if (snapshotConfiguration == null) {
        snapshotConfiguration = promptForSnapshotConfiguration(project, appConfigurations);
        if (snapshotConfiguration == null)
            return;
    }

    if (!connected) {
        int rc = Messages.showYesNoDialog(project, UIDesignerBundle.message("snapshot.run.prompt"),
                UIDesignerBundle.message("snapshot.title"), Messages.getQuestionIcon());
        if (rc == 1)
            return;
        final ApplicationConfiguration appConfig = (ApplicationConfiguration) snapshotConfiguration
                .getConfiguration();
        final SnapShooterConfigurationSettings settings = SnapShooterConfigurationSettings.get(appConfig);
        settings.setNotifyRunnable(new Runnable() {
            public void run() {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        Messages.showMessageDialog(project, UIDesignerBundle.message("snapshot.prepare.notice"),
                                UIDesignerBundle.message("snapshot.title"), Messages.getInformationIcon());
                        try {
                            client.connect(settings.getLastPort());
                        } catch (IOException ex) {
                            Messages.showMessageDialog(project,
                                    UIDesignerBundle.message("snapshot.connection.error"),
                                    UIDesignerBundle.message("snapshot.title"), Messages.getErrorIcon());
                            return;
                        }
                        runSnapShooterSession(client, project, dir, view);
                    }
                });
            }
        });

        try {
            final ProgramRunner runner = RunnerRegistry.getInstance().getRunner(DefaultRunExecutor.EXECUTOR_ID,
                    appConfig);
            LOG.assertTrue(runner != null, "Runner MUST not be null!");
            Executor executor = DefaultRunExecutor.getRunExecutorInstance();
            runner.execute(new ExecutionEnvironment(executor, runner, snapshotConfiguration, project));
        } catch (ExecutionException ex) {
            Messages.showMessageDialog(project, UIDesignerBundle.message("snapshot.run.error", ex.getMessage()),
                    UIDesignerBundle.message("snapshot.title"), Messages.getErrorIcon());
        }
    } else {
        runSnapShooterSession(client, project, dir, view);
    }
}

From source file:com.intellij.uiDesigner.snapShooter.CreateSnapShotAction.java

License:Apache License

private static void runSnapShooterSession(final SnapShotClient client, final Project project,
        final PsiDirectory dir, final IdeView view) {
    try {/*w  w w  . ja  va2  s  .  c  om*/
        client.suspendSwing();
    } catch (IOException e1) {
        Messages.showMessageDialog(project, UIDesignerBundle.message("snapshot.connection.error"),
                UIDesignerBundle.message("snapshot.title"), Messages.getInformationIcon());
        return;
    }

    final MyDialog dlg = new MyDialog(project, client, dir);
    dlg.show();
    if (dlg.getExitCode() == DialogWrapper.OK_EXIT_CODE) {
        final int id = dlg.getSelectedComponentId();
        final Ref<Object> result = new Ref<Object>();
        ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
            public void run() {
                try {
                    result.set(client.createSnapshot(id));
                } catch (Exception ex) {
                    result.set(ex);
                }
            }
        }, UIDesignerBundle.message("progress.creating.snapshot"), false, project);

        String snapshot = null;
        if (result.get() instanceof String) {
            snapshot = (String) result.get();
        } else {
            Exception ex = (Exception) result.get();
            Messages.showMessageDialog(project,
                    UIDesignerBundle.message("snapshot.create.error", ex.getMessage()),
                    UIDesignerBundle.message("snapshot.title"), Messages.getErrorIcon());
        }

        if (snapshot != null) {
            final String snapshot1 = snapshot;
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                public void run() {
                    CommandProcessor.getInstance().executeCommand(project, new Runnable() {
                        public void run() {
                            try {
                                PsiFile formFile = PsiFileFactory.getInstance(dir.getProject())
                                        .createFileFromText(
                                                dlg.getFormName() + GuiFormFileType.DOT_DEFAULT_EXTENSION,
                                                snapshot1);
                                formFile = (PsiFile) dir.add(formFile);
                                formFile.getVirtualFile().setCharset(CharsetToolkit.UTF8_CHARSET);
                                formFile.getViewProvider().getDocument().setText(snapshot1);
                                view.selectElement(formFile);
                            } catch (IncorrectOperationException ex) {
                                Messages.showMessageDialog(project,
                                        UIDesignerBundle.message("snapshot.save.error", ex.getMessage()),
                                        UIDesignerBundle.message("snapshot.title"), Messages.getErrorIcon());
                            }
                        }
                    }, "", null);
                }
            });
        }
    }

    try {
        client.resumeSwing();
    } catch (IOException ex) {
        Messages.showErrorDialog(project, UIDesignerBundle.message("snapshot.connection.broken"),
                UIDesignerBundle.message("snapshot.title"));
    }

    client.dispose();
}

From source file:com.intellij.uiDesigner.snapShooter.CreateSnapShotAction.java

License:Apache License

@Nullable
private static RunnerAndConfigurationSettings promptForSnapshotConfiguration(final Project project,
        final List<RunnerAndConfigurationSettings> configurations) {
    if (configurations.isEmpty()) {
        Messages.showMessageDialog(project, UIDesignerBundle.message("snapshot.no.configuration.error"),
                UIDesignerBundle.message("snapshot.title"), Messages.getInformationIcon());
        return null;
    }/*from   w  ww.j a  va 2  s  .com*/

    for (int i = configurations.size() - 1; i >= 0; i--) {
        final JreVersionDetector detector = new JreVersionDetector();
        final ApplicationConfiguration configuration = (ApplicationConfiguration) configurations.get(i)
                .getConfiguration();
        if (!detector.isJre50Configured(configuration) && !detector.isModuleJre50Configured(configuration)) {
            configurations.remove(i);
        }
    }

    if (configurations.isEmpty()) {
        Messages.showMessageDialog(project,
                UIDesignerBundle.message("snapshot.no.compatible.configuration.error"),
                UIDesignerBundle.message("snapshot.title"), Messages.getInformationIcon());
        return null;
    }

    final RunnerAndConfigurationSettings snapshotConfiguration;
    if (configurations.size() == 1) {
        final int rc = Messages.showYesNoDialog(project,
                UIDesignerBundle.message("snapshot.confirm.configuration.prompt",
                        configurations.get(0).getConfiguration().getName()),
                UIDesignerBundle.message("snapshot.title"), Messages.getQuestionIcon());
        if (rc == 1) {
            return null;
        }
        snapshotConfiguration = configurations.get(0);
    } else {
        String[] names = new String[configurations.size()];
        for (int i = 0; i < configurations.size(); i++) {
            names[i] = configurations.get(i).getConfiguration().getName();
        }
        int rc = Messages.showChooseDialog(project,
                UIDesignerBundle.message("snapshot.choose.configuration.prompt"),
                UIDesignerBundle.message("snapshot.title"), Messages.getQuestionIcon(), names, names[0]);
        if (rc < 0)
            return null;
        snapshotConfiguration = configurations.get(rc);
    }
    ((ApplicationConfiguration) snapshotConfiguration.getConfiguration()).ENABLE_SWING_INSPECTOR = true;
    return snapshotConfiguration;
}