List of usage examples for com.intellij.openapi.ui Messages showOkCancelDialog
@OkCancelResult @Deprecated public static int showOkCancelDialog(@NotNull Component parent, String message, @Nls(capitalization = Nls.Capitalization.Title) String title, Icon icon)
From source file:com.intellij.ide.RecentProjectsManagerBase.java
License:Apache License
/** * @param addClearListItem - used for detecting whether the "Clear List" action should be added * to the end of the returned list of actions * @return/*from w w w . ja v a2 s . c o m*/ */ public AnAction[] getRecentProjectsActions(boolean addClearListItem) { validateRecentProjects(); final Set<String> openedPaths = ContainerUtil.newHashSet(); for (Project openProject : ProjectManager.getInstance().getOpenProjects()) { ContainerUtil.addIfNotNull(openedPaths, getProjectPath(openProject)); } final LinkedHashSet<String> paths; synchronized (myStateLock) { paths = ContainerUtil.newLinkedHashSet(myState.recentPaths); } paths.remove(null); paths.removeAll(openedPaths); ArrayList<AnAction> actions = new ArrayList<AnAction>(); Set<String> duplicates = getDuplicateProjectNames(openedPaths, paths); for (final String path : paths) { final String projectName = getProjectName(path); String displayName; synchronized (myStateLock) { displayName = myState.names.get(path); } if (StringUtil.isEmptyOrSpaces(displayName)) { displayName = duplicates.contains(path) ? path : projectName; } // It's better don't to remove non-existent projects. Sometimes projects stored // on USB-sticks or flash-cards, and it will be nice to have them in the list // when USB device or SD-card is mounted if (new File(path).exists()) { actions.add(new ReopenProjectAction(path, projectName, displayName)); } } if (actions.isEmpty()) { return AnAction.EMPTY_ARRAY; } ArrayList<AnAction> list = new ArrayList<AnAction>(); for (AnAction action : actions) { list.add(action); } if (addClearListItem) { AnAction clearListAction = new AnAction(IdeBundle.message("action.clear.list")) { public void actionPerformed(AnActionEvent e) { final int rc = Messages.showOkCancelDialog(e.getData(CommonDataKeys.PROJECT), "Would you like to clear the list of recent projects?", "Clear Recent Projects List", Messages.getQuestionIcon()); if (rc == 0) { synchronized (myStateLock) { myState.recentPaths.clear(); } WelcomeFrame.clearRecents(); } } }; list.add(AnSeparator.getInstance()); list.add(clearListAction); } return list.toArray(new AnAction[list.size()]); }
From source file:com.intellij.lang.ant.config.impl.configuration.AnActionListEditor.java
License:Apache License
public void addRemoveButtonForAnt(final Condition<T> removeCondition, String actionName) { final ReorderableListController<T>.RemoveActionDescription description = myForm.getListActionsBuilder() .addRemoveAction(actionName); description.addPostHandler(new ReorderableListController.ActionNotification<List<T>>() { public void afterActionPerformed(List<T> list) { for (T item : list) { if (myAdded.contains(item)) { myAdded.remove(item); } else { myRemoved.add(item); }/*w w w . ja va 2s . c om*/ } } }); description.setEnableCondition(removeCondition); description.setConfirmation(new Condition<List<T>>() { public boolean value(final List<T> list) { if (list.size() == 1) { return Messages.showOkCancelDialog(description.getList(), AntBundle.message("delete.selected.ant.configuration.confirmation.text"), ExecutionBundle.message("delete.confirmation.dialog.title"), Messages.getQuestionIcon()) == 0; } else { return Messages.showOkCancelDialog(description.getList(), AntBundle.message("delete.selected.ant.configurations.confirmation.text"), ExecutionBundle.message("delete.confirmation.dialog.title"), Messages.getQuestionIcon()) == 0; } } }); description.setShowText(true); }
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//from w w w . j a v a 2 s . com 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// w w w. j a v a 2s . com 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.refactoring.changeSignature.JavaChangeSignatureDialog.java
License:Apache License
@Override protected String validateAndCommitData() { PsiManager manager = PsiManager.getInstance(myProject); PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory(); String name = getMethodName(); if (!PsiNameHelper.getInstance(manager.getProject()).isIdentifier(name)) { return RefactoringMessageUtil.getIncorrectIdentifierMessage(name); }/*from w w w.ja v a2 s.c o m*/ if (myMethod.canChangeReturnType() == MethodDescriptor.ReadWriteOption.ReadWrite) { try { ((PsiTypeCodeFragment) myReturnTypeCodeFragment).getType(); } catch (PsiTypeCodeFragment.TypeSyntaxException e) { myReturnTypeField.requestFocus(); return RefactoringBundle.message("changeSignature.wrong.return.type", myReturnTypeCodeFragment.getText()); } catch (PsiTypeCodeFragment.NoTypeException e) { myReturnTypeField.requestFocus(); return RefactoringBundle.message("changeSignature.no.return.type"); } } List<ParameterTableModelItemBase<ParameterInfoImpl>> parameterInfos = myParametersTableModel.getItems(); final int newParametersNumber = parameterInfos.size(); for (int i = 0; i < newParametersNumber; i++) { final ParameterTableModelItemBase<ParameterInfoImpl> item = parameterInfos.get(i); if (!PsiNameHelper.getInstance(manager.getProject()).isIdentifier(item.parameter.getName())) { return RefactoringMessageUtil.getIncorrectIdentifierMessage(item.parameter.getName()); } final PsiType type; try { type = ((PsiTypeCodeFragment) parameterInfos.get(i).typeCodeFragment).getType(); } catch (PsiTypeCodeFragment.TypeSyntaxException e) { return RefactoringBundle.message("changeSignature.wrong.type.for.parameter", item.typeCodeFragment.getText(), item.parameter.getName()); } catch (PsiTypeCodeFragment.NoTypeException e) { return RefactoringBundle.message("changeSignature.no.type.for.parameter", item.parameter.getName()); } item.parameter.setType(type); if (type instanceof PsiEllipsisType && i != newParametersNumber - 1) { return RefactoringBundle.message("changeSignature.vararg.not.last"); } if (item.parameter.oldParameterIndex < 0) { item.parameter.defaultValue = ApplicationManager.getApplication() .runWriteAction(new Computable<String>() { @Override public String compute() { return JavaCodeStyleManager.getInstance(myProject) .qualifyClassReferences(item.defaultValueCodeFragment).getText(); } }); String def = item.parameter.defaultValue; def = def.trim(); if (!(type instanceof PsiEllipsisType)) { try { if (!StringUtil.isEmpty(def)) { factory.createExpressionFromText(def, null); } } catch (IncorrectOperationException e) { return e.getMessage(); } } } } ThrownExceptionInfo[] exceptionInfos = myExceptionsModel.getThrownExceptions(); PsiTypeCodeFragment[] typeCodeFragments = myExceptionsModel.getTypeCodeFragments(); for (int i = 0; i < exceptionInfos.length; i++) { ThrownExceptionInfo exceptionInfo = exceptionInfos[i]; PsiTypeCodeFragment typeCodeFragment = typeCodeFragments[i]; try { PsiType type = typeCodeFragment.getType(); if (!(type instanceof PsiClassType)) { return RefactoringBundle.message("changeSignature.wrong.type.for.exception", typeCodeFragment.getText()); } PsiClassType throwable = JavaPsiFacade.getInstance(myProject).getElementFactory() .createTypeByFQClassName("java.lang.Throwable", type.getResolveScope()); if (!throwable.isAssignableFrom(type)) { return RefactoringBundle.message("changeSignature.not.throwable.type", typeCodeFragment.getText()); } exceptionInfo.setType((PsiClassType) type); } catch (PsiTypeCodeFragment.TypeSyntaxException e) { return RefactoringBundle.message("changeSignature.wrong.type.for.exception", typeCodeFragment.getText()); } catch (PsiTypeCodeFragment.NoTypeException e) { return RefactoringBundle.message("changeSignature.no.type.for.exception"); } } // warnings try { if (myMethod.canChangeReturnType() == MethodDescriptor.ReadWriteOption.ReadWrite) { if (!RefactoringUtil.isResolvableType(((PsiTypeCodeFragment) myReturnTypeCodeFragment).getType())) { if (Messages.showOkCancelDialog(myProject, RefactoringBundle.message("changeSignature.cannot.resolve.return.type", myReturnTypeCodeFragment.getText()), RefactoringBundle.message("changeSignature.refactoring.name"), Messages.getWarningIcon()) != 0) { return EXIT_SILENTLY; } } } for (ParameterTableModelItemBase<ParameterInfoImpl> item : parameterInfos) { if (!RefactoringUtil.isResolvableType(((PsiTypeCodeFragment) item.typeCodeFragment).getType())) { if (Messages.showOkCancelDialog(myProject, RefactoringBundle.message("changeSignature.cannot.resolve.parameter.type", item.typeCodeFragment.getText(), item.parameter.getName()), RefactoringBundle.message("changeSignature.refactoring" + ".name"), Messages.getWarningIcon()) != 0) { return EXIT_SILENTLY; } } } } catch (PsiTypeCodeFragment.IncorrectTypeException ignored) { } return null; }
From source file:com.intellij.refactoring.introduceField.IntroduceConstantDialog.java
License:Apache License
protected void doOKAction() { final String targetClassName = getTargetClassName(); PsiClass newClass = myParentClass;//from w w w.j a va 2 s .c om if (!"".equals(targetClassName) && !Comparing.strEqual(targetClassName, myParentClass.getQualifiedName())) { newClass = JavaPsiFacade.getInstance(myProject).findClass(targetClassName, GlobalSearchScope.projectScope(myProject)); if (newClass == null) { if (Messages.showOkCancelDialog(myProject, RefactoringBundle.message("class.does.not.exist.in.the.project"), IntroduceConstantHandler.REFACTORING_NAME, Messages.getErrorIcon()) != OK_EXIT_CODE) { return; } myDestinationClass = new BaseExpressionToFieldHandler.TargetDestination(targetClassName, myParentClass); } else { myDestinationClass = new BaseExpressionToFieldHandler.TargetDestination(newClass); } } String fieldName = getEnteredName(); String errorString = null; if ("".equals(fieldName)) { errorString = RefactoringBundle.message("no.field.name.specified"); } else if (!PsiNameHelper.getInstance(myProject).isIdentifier(fieldName)) { errorString = RefactoringMessageUtil.getIncorrectIdentifierMessage(fieldName); } else if (newClass != null && !myParentClass.getLanguage().equals(newClass.getLanguage())) { errorString = RefactoringBundle.message("move.to.different.language", UsageViewUtil.getType(myParentClass), myParentClass.getQualifiedName(), newClass.getQualifiedName()); } if (errorString != null) { CommonRefactoringUtil.showErrorMessage(IntroduceFieldHandler.REFACTORING_NAME, errorString, HelpID.INTRODUCE_FIELD, myProject); return; } if (newClass != null) { PsiField oldField = newClass.findFieldByName(fieldName, true); if (oldField != null) { int answer = Messages.showYesNoDialog(myProject, RefactoringBundle.message("field.exists", fieldName, oldField.getContainingClass().getQualifiedName()), IntroduceFieldHandler.REFACTORING_NAME, Messages.getWarningIcon()); if (answer != 0) { return; } } } JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY = getFieldVisibility(); RecentsManager.getInstance(myProject).registerRecentEntry(RECENTS_KEY, targetClassName); super.doOKAction(); }
From source file:com.intellij.refactoring.move.moveClassesOrPackages.JavaMoveClassesOrPackagesHandler.java
License:Apache License
private static void moveDirectoriesLibrariesSafe(Project project, PsiElement targetContainer, MoveCallback callback, PsiDirectory[] directories, String prompt) { final PsiJavaPackage aPackage = JavaDirectoryService.getInstance().getPackage(directories[0]); LOG.assertTrue(aPackage != null);/*w ww . j a va2s .co m*/ final PsiDirectory[] projectDirectories = aPackage.getDirectories(GlobalSearchScope.projectScope(project)); if (projectDirectories.length > 1) { int ret = Messages.showYesNoCancelDialog(project, prompt + " or all directories in project?", RefactoringBundle.message("warning.title"), RefactoringBundle.message("move.current.directory"), RefactoringBundle.message("move.directories"), CommonBundle.getCancelButtonText(), Messages.getWarningIcon()); if (ret == 0) { moveAsDirectory(project, targetContainer, callback, directories); } else if (ret == 1) { moveAsDirectory(project, targetContainer, callback, projectDirectories); } } else if (Messages.showOkCancelDialog(project, prompt + "?", RefactoringBundle.message("warning.title"), Messages.getWarningIcon()) == DialogWrapper.OK_EXIT_CODE) { moveAsDirectory(project, targetContainer, callback, directories); } }
From source file:com.intellij.refactoring.rename.DirectoryAsPackageRenameHandlerBase.java
License:Apache License
private void doRename(PsiElement element, final Project project, PsiElement nameSuggestionContext, Editor editor) {// w ww . j a v a 2 s .co m final PsiDirectory psiDirectory = (PsiDirectory) element; final T aPackage = getPackage(psiDirectory); final String qualifiedName = aPackage != null ? getQualifiedName(aPackage) : ""; if (aPackage == null || qualifiedName.length() == 0/*default package*/ || !isIdentifier(psiDirectory.getName(), project)) { PsiElementRenameHandler.rename(element, project, nameSuggestionContext, editor); } else { PsiDirectory[] directories = aPackage.getDirectories(); final VirtualFile[] virtualFiles = occursInPackagePrefixes(aPackage); if (virtualFiles.length == 0 && directories.length == 1) { PsiElementRenameHandler.rename(aPackage, project, nameSuggestionContext, editor); } else { // the directory corresponds to a package that has multiple associated directories final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex(); boolean inLib = false; for (PsiDirectory directory : directories) { inLib |= !projectFileIndex.isInContent(directory.getVirtualFile()); } final PsiDirectory[] projectDirectories = aPackage .getDirectories(GlobalSearchScope.projectScope(project)); if (inLib) { final Module module = ModuleUtilCore.findModuleForPsiElement(psiDirectory); LOG.assertTrue(module != null); PsiDirectory[] moduleDirs = null; if (nameSuggestionContext instanceof PsiPackageBase) { moduleDirs = aPackage.getDirectories(GlobalSearchScope.moduleScope(module)); if (moduleDirs.length <= 1) { moduleDirs = null; } } final String promptMessage = "Package \'" + aPackage.getName() + "\' contains directories in libraries which cannot be renamed. Do you want to rename " + (moduleDirs == null ? "current directory" : "current module directories"); if (projectDirectories.length > 0) { int ret = Messages.showYesNoCancelDialog(project, promptMessage + " or all directories in project?", RefactoringBundle.message("warning.title"), RefactoringBundle.message("rename.current.directory"), RefactoringBundle.message("rename.directories"), CommonBundle.getCancelButtonText(), Messages.getWarningIcon()); if (ret == 2) return; renameDirs(project, nameSuggestionContext, editor, psiDirectory, aPackage, ret == 0 ? (moduleDirs == null ? new PsiDirectory[] { psiDirectory } : moduleDirs) : projectDirectories); } else { if (Messages.showOkCancelDialog(project, promptMessage + "?", RefactoringBundle.message("warning.title"), Messages.getWarningIcon()) == DialogWrapper.OK_EXIT_CODE) { renameDirs(project, nameSuggestionContext, editor, psiDirectory, aPackage, psiDirectory); } } } else { final StringBuffer message = new StringBuffer(); RenameUtil.buildPackagePrefixChangedMessage(virtualFiles, message, qualifiedName); buildMultipleDirectoriesInPackageMessage(message, getQualifiedName(aPackage), directories); message.append( RefactoringBundle.message("directories.and.all.references.to.package.will.be.renamed", psiDirectory.getVirtualFile().getPresentableUrl())); int ret = Messages.showYesNoCancelDialog(project, message.toString(), RefactoringBundle.message("warning.title"), RefactoringBundle.message("rename.package.button.text"), RefactoringBundle.message("rename.directory.button.text"), CommonBundle.getCancelButtonText(), Messages.getWarningIcon()); if (ret == 0) { PsiElementRenameHandler.rename(aPackage, project, nameSuggestionContext, editor); } else if (ret == 1) { renameDirs(project, nameSuggestionContext, editor, psiDirectory, aPackage, psiDirectory); } } } } }
From source file:com.intellij.refactoring.util.duplicates.DuplicatesImpl.java
License:Apache License
private static boolean replaceMatch(final Project project, final MatchProvider provider, final Match match, @NotNull final Editor editor, final int idx, final int size, Ref<Boolean> showAll, final String confirmDuplicatePrompt, boolean skipPromptWhenOne) { final ArrayList<RangeHighlighter> highlighters = previewMatch(project, match, editor); if (!ApplicationManager.getApplication().isUnitTestMode()) { if ((!skipPromptWhenOne || size > 1) && (showAll.get() == null || !showAll.get())) { final String prompt = provider.getConfirmDuplicatePrompt(match); final ReplacePromptDialog promptDialog = new ReplacePromptDialog(false, provider.getReplaceDuplicatesTitle(idx, size), project) { @Override//from ww w . ja v a 2 s.c o m protected String getMessage() { final String message = super.getMessage(); return prompt != null ? message + prompt : message; } }; promptDialog.show(); final boolean allChosen = promptDialog.getExitCode() == FindManager.PromptResult.ALL; showAll.set(allChosen); if (allChosen && confirmDuplicatePrompt != null && prompt == null) { if (Messages.showOkCancelDialog(project, "In order to replace all occurrences method signature will be changed. Proceed?", CommonBundle.getWarningTitle(), Messages.getWarningIcon()) != DialogWrapper.OK_EXIT_CODE) return true; } if (promptDialog.getExitCode() == FindManager.PromptResult.SKIP) return false; if (promptDialog.getExitCode() == FindManager.PromptResult.CANCEL) return true; } } HighlightManager.getInstance(project).removeSegmentHighlighter(editor, highlighters.get(0)); new WriteCommandAction(project, MethodDuplicatesHandler.REFACTORING_NAME) { @Override protected void run(Result result) throws Throwable { try { provider.processMatch(match); } catch (IncorrectOperationException e) { LOG.error(e); } } }.execute(); return false; }
From source file:com.intellij.testIntegration.createTest.CreateTestAction.java
License:Apache License
@Override public void invoke(final @NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException { if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return;/* ww w .java 2 s . c o m*/ final Module srcModule = ModuleUtilCore.findModuleForPsiElement(element); final PsiClass srcClass = getContainingClass(element); if (srcClass == null) return; PsiDirectory srcDir = element.getContainingFile().getContainingDirectory(); PsiJavaPackage srcPackage = JavaDirectoryService.getInstance().getPackage(srcDir); final PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(); final HashSet<VirtualFile> testFolders = new HashSet<VirtualFile>(); checkForTestRoots(srcModule, testFolders); if (testFolders.isEmpty() && !propertiesComponent.getBoolean(CREATE_TEST_IN_THE_SAME_ROOT, false)) { if (Messages.showOkCancelDialog(project, "Create test in the same source root?", "No Test Roots Found", Messages.getQuestionIcon()) != DialogWrapper.OK_EXIT_CODE) { return; } propertiesComponent.setValue(CREATE_TEST_IN_THE_SAME_ROOT, String.valueOf(true)); } final CreateTestDialog d = new CreateTestDialog(project, getText(), srcClass, srcPackage, srcModule); d.show(); if (!d.isOK()) return; CommandProcessor.getInstance().executeCommand(project, new Runnable() { @Override public void run() { TestFramework framework = d.getSelectedTestFrameworkDescriptor(); TestGenerator generator = TestGenerators.INSTANCE.forLanguage(framework.getLanguage()); generator.generateTest(project, d); } }, CodeInsightBundle.message("intention.create.test"), this); }