@NotNull private static UsageViewPresentation createPresentation( @NotNull PsiElement psiElement, @NotNull FindUsagesOptions findUsagesOptions, boolean toOpenInNewTab) { UsageViewPresentation presentation = new UsageViewPresentation(); String scopeString = findUsagesOptions.searchScope == null ? null : findUsagesOptions.searchScope.getDisplayName(); presentation.setScopeText(scopeString); String usagesString = generateUsagesString(findUsagesOptions); presentation.setUsagesString(usagesString); String title = scopeString == null ? FindBundle.message( "find.usages.of.element.panel.title", usagesString, UsageViewUtil.getLongName(psiElement)) : FindBundle.message( "find.usages.of.element.in.scope.panel.title", usagesString, UsageViewUtil.getLongName(psiElement), scopeString); presentation.setTabText(title); presentation.setTabName( FindBundle.message( "find.usages.of.element.tab.name", usagesString, UsageViewUtil.getShortName(psiElement))); presentation.setTargetsNodeText(StringUtil.capitalize(UsageViewUtil.getType(psiElement))); presentation.setOpenInNewTab(toOpenInNewTab); return presentation; }
private void setNewName(@NotNull String newName) { if (myPrimaryElement == null) { myCommandName = RefactoringBundle.message("renaming.something"); return; } myNewName = newName; myAllRenames.put(myPrimaryElement, newName); myCommandName = RefactoringBundle.message( "renaming.0.1.to.2", UsageViewUtil.getType(myPrimaryElement), UsageViewUtil.getDescriptiveName(myPrimaryElement), newName); }
@NotNull public UsageInfo[] findUsages() { myRenamers.clear(); ArrayList<UsageInfo> result = new ArrayList<UsageInfo>(); List<PsiElement> elements = new ArrayList<PsiElement>(myAllRenames.keySet()); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < elements.size(); i++) { PsiElement element = elements.get(i); final String newName = myAllRenames.get(element); final UsageInfo[] usages = RenameUtil.findUsages( element, newName, mySearchInComments, mySearchTextOccurrences, myAllRenames); final List<UsageInfo> usagesList = Arrays.asList(usages); result.addAll(usagesList); for (AutomaticRenamerFactory factory : myRenamerFactories) { if (factory.isApplicable(element)) { myRenamers.add(factory.createRenamer(element, newName, usagesList)); } } for (AutomaticRenamerFactory factory : Extensions.getExtensions(AutomaticRenamerFactory.EP_NAME)) { if (factory.getOptionName() == null && factory.isApplicable(element)) { myRenamers.add(factory.createRenamer(element, newName, usagesList)); } } } UsageInfo[] usageInfos = result.toArray(new UsageInfo[result.size()]); usageInfos = UsageViewUtil.removeDuplicatedUsages(usageInfos); return usageInfos; }
@Nullable private String verifyInnerClassDestination() { PsiClass targetClass = findTargetClass(); if (targetClass == null) return null; for (PsiElement element : myElementsToMove) { if (PsiTreeUtil.isAncestor(element, targetClass, false)) { return RefactoringBundle.message("move.class.to.inner.move.to.self.error"); } final Language targetClassLanguage = targetClass.getLanguage(); if (!element.getLanguage().equals(targetClassLanguage)) { return RefactoringBundle.message( "move.to.different.language", UsageViewUtil.getType(element), ((PsiClass) element).getQualifiedName(), targetClass.getQualifiedName()); } if (element.getLanguage().equals(Language.findLanguageByID("Groovy"))) { return RefactoringBundle.message("dont.support.inner.classes", "Groovy"); } } while (targetClass != null) { if (targetClass.getContainingClass() != null && !targetClass.hasModifierProperty(PsiModifier.STATIC)) { return RefactoringBundle.message("move.class.to.inner.nonstatic.error"); } targetClass = targetClass.getContainingClass(); } return null; }
@Override protected boolean isPreviewUsages(@NotNull UsageInfo[] usages) { if (myPreviewNonCodeUsages && UsageViewUtil.reportNonRegularUsages(usages, myProject)) { return true; } return super.isPreviewUsages(filterToBeDeleted(usages)); }
public static void checkMethodConflicts( @Nullable PsiClass aClass, PsiMethod refactoredMethod, PsiMethod prototype, final MultiMap<PsiElement, String> conflicts) { if (prototype == null) return; PsiMethod method = aClass != null ? aClass.findMethodBySignature(prototype, true) : null; if (method != null && method != refactoredMethod) { if (aClass.equals(method.getContainingClass())) { final String classDescr = aClass instanceof PsiAnonymousClass ? RefactoringBundle.message("current.class") : RefactoringUIUtil.getDescription(aClass, false); conflicts.putValue( method, RefactoringBundle.message( "method.0.is.already.defined.in.the.1", getMethodPrototypeString(prototype), classDescr)); } else { // method somewhere in base class if (JavaPsiFacade.getInstance(method.getProject()) .getResolveHelper() .isAccessible(method, aClass, null)) { String protoMethodInfo = getMethodPrototypeString(prototype); String className = CommonRefactoringUtil.htmlEmphasize( UsageViewUtil.getDescriptiveName(method.getContainingClass())); if (PsiUtil.getAccessLevel(prototype.getModifierList()) >= PsiUtil.getAccessLevel(method.getModifierList())) { boolean isMethodAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); boolean isMyMethodAbstract = refactoredMethod != null && refactoredMethod.hasModifierProperty(PsiModifier.ABSTRACT); final String conflict = isMethodAbstract != isMyMethodAbstract ? RefactoringBundle.message( "method.0.will.implement.method.of.the.base.class", protoMethodInfo, className) : RefactoringBundle.message( "method.0.will.override.a.method.of.the.base.class", protoMethodInfo, className); conflicts.putValue(method, conflict); } else { // prototype is private, will be compile-error conflicts.putValue( method, RefactoringBundle.message( "method.0.will.hide.method.of.the.base.class", protoMethodInfo, className)); } } } } }
@Override protected void performRefactoringRename(final String newName, final StartMarkAction markAction) { try { final PsiNamedElement variable = getVariable(); if (variable != null && !newName.equals(myOldName)) { if (isIdentifier(newName, variable.getLanguage())) { final PsiElement substituted = getSubstituted(); if (substituted == null) { return; } final String commandName = RefactoringBundle.message( "renaming.0.1.to.2", UsageViewUtil.getType(variable), UsageViewUtil.getDescriptiveName(variable), newName); CommandProcessor.getInstance() .executeCommand( myProject, new Runnable() { @Override public void run() { performRenameInner(substituted, newName); PsiDocumentManager.getInstance(myProject).commitAllDocuments(); } }, commandName, null); } } } finally { try { ((EditorImpl) InjectedLanguageUtil.getTopLevelEditor(myEditor)).stopDumbLater(); } finally { FinishMarkAction.finish(myProject, myEditor, markAction); } } }
protected boolean isPreviewUsages(UsageInfo[] usages) { if (myForceShowPreview) return true; if (super.isPreviewUsages(usages)) return true; if (UsageViewUtil.hasNonCodeUsages(usages)) { WindowManager.getInstance() .getStatusBar(myProject) .setInfo( RefactoringBundle.message( "occurrences.found.in.comments.strings.and.non.java.files")); return true; } return false; }
public UsageInfo[] findUsages() { ArrayList<UsageInfo> result = new ArrayList<UsageInfo>(); final PsiElement element = myChangeInfo.getMethod(); if (element instanceof PsiMethod) { final PsiMethod method = (PsiMethod) element; findSimpleUsages(method, result); final UsageInfo[] usageInfos = result.toArray(new UsageInfo[result.size()]); return UsageViewUtil.removeDuplicatedUsages(usageInfos); } return UsageInfo.EMPTY_ARRAY; }
@NotNull @Override protected UsageInfo[] findUsages() { ArrayList<UsageInfo> result = new ArrayList<UsageInfo>(); final PsiMethod toSearchFor = ((PsiMethod) mySettings.getToSearchFor()); if (!mySettings.generateDelegate()) { Collection<PsiReference> refs = MethodReferencesSearch.search( toSearchFor, GlobalSearchScope.projectScope(myProject), true) .findAll(); for (PsiReference ref1 : refs) { PsiElement ref = ref1.getElement(); if (ref instanceof PsiMethod && ((PsiMethod) ref).isConstructor()) { DefaultConstructorImplicitUsageInfo implicitUsageInfo = new DefaultConstructorImplicitUsageInfo( (PsiMethod) ref, ((PsiMethod) ref).getContainingClass(), toSearchFor); result.add(implicitUsageInfo); } else if (ref instanceof PsiClass) { result.add(new NoConstructorClassUsageInfo((PsiClass) ref)); } else if (!PsiTreeUtil.isAncestor(mySettings.getToReplaceIn(), ref, false)) { result.add(new ExternalUsageInfo(ref)); } else { result.add(new ChangedMethodCallInfo(ref)); } } } if (mySettings.replaceAllOccurrences()) { PsiElement[] exprs = GroovyIntroduceParameterUtil.getOccurrences(mySettings); for (PsiElement expr : exprs) { result.add(new InternalUsageInfo(expr)); } } else { if (mySettings.getExpression() != null) { result.add(new InternalUsageInfo(mySettings.getExpression())); } } Collection<PsiMethod> overridingMethods = OverridingMethodsSearch.search(toSearchFor, true).findAll(); for (PsiMethod overridingMethod : overridingMethods) { result.add(new UsageInfo(overridingMethod)); } final UsageInfo[] usageInfos = result.toArray(new UsageInfo[result.size()]); return UsageViewUtil.removeDuplicatedUsages(usageInfos); }
@NotNull protected UsageInfo[] findUsages() { ArrayList<UsageInfo> result = new ArrayList<UsageInfo>(); PsiMethod[] overridingMethods = OverridingMethodsSearch.search(myMethodToSearchFor, true).toArray(PsiMethod.EMPTY_ARRAY); for (PsiMethod overridingMethod : overridingMethods) { result.add(new UsageInfo(overridingMethod)); } if (!myGenerateDelegate) { PsiReference[] refs = MethodReferencesSearch.search( myMethodToSearchFor, GlobalSearchScope.projectScope(myProject), true) .toArray(PsiReference.EMPTY_ARRAY); for (PsiReference ref1 : refs) { PsiElement ref = ref1.getElement(); if (ref instanceof PsiMethod && ((PsiMethod) ref).isConstructor()) { DefaultConstructorImplicitUsageInfo implicitUsageInfo = new DefaultConstructorImplicitUsageInfo( (PsiMethod) ref, ((PsiMethod) ref).getContainingClass(), myMethodToSearchFor); result.add(implicitUsageInfo); } else if (ref instanceof PsiClass) { result.add(new NoConstructorClassUsageInfo((PsiClass) ref)); } else if (!IntroduceParameterUtil.insideMethodToBeReplaced(ref, myMethodToReplaceIn)) { result.add(new ExternalUsageInfo(ref)); } else { result.add(new ChangedMethodCallInfo(ref)); } } } if (myReplaceAllOccurences) { for (PsiElement expr : getOccurrences()) { result.add(new InternalUsageInfo(expr)); } } else { if (myExpressionToSearch != null && myExpressionToSearch.isValid()) { result.add(new InternalUsageInfo(myExpressionToSearch)); } } final UsageInfo[] usageInfos = result.toArray(new UsageInfo[result.size()]); return UsageViewUtil.removeDuplicatedUsages(usageInfos); }
protected void performRefactoring(UsageInfo[] usages) { if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, myTargetClass)) return; PsiMethod patternMethod = createMethodToAdd(); final List<PsiReference> docRefs = new ArrayList<PsiReference>(); for (UsageInfo usage : usages) { if (usage instanceof InheritorUsageInfo) { final PsiClass inheritor = ((InheritorUsageInfo) usage).getInheritor(); addMethodToClass(inheritor, patternMethod, true); } else if (usage instanceof MethodCallUsageInfo && !((MethodCallUsageInfo) usage).isInternal()) { final PsiElement expression = ((MethodCallUsageInfo) usage).getMethodCallExpression(); if (expression instanceof PsiMethodCallExpression) { correctMethodCall((PsiMethodCallExpression) expression, false); } else if (expression instanceof PsiMethodReferenceExpression) { PsiExpression newQualifier = JavaPsiFacade.getInstance(myProject) .getElementFactory() .createExpressionFromText(myTargetVariable.getType().getCanonicalText(), null); ((PsiMethodReferenceExpression) expression).setQualifierExpression(newQualifier); } } else if (usage instanceof JavadocUsageInfo) { docRefs.add(usage.getElement().getReference()); } } try { if (myTargetClass.isInterface()) patternMethod.getBody().delete(); final PsiMethod method = addMethodToClass(myTargetClass, patternMethod, false); myMethod.delete(); for (PsiReference reference : docRefs) { reference.bindToElement(method); } VisibilityUtil.fixVisibility(UsageViewUtil.toElements(usages), method, myNewVisibility); if (myOpenInEditor) { EditorHelper.openInEditor(method); } } catch (IncorrectOperationException e) { LOG.error(e); } }
@NotNull protected UsageInfo[] findUsages() { ArrayList<EncapsulateFieldUsageInfo> array = ContainerUtil.newArrayList(); for (FieldDescriptor fieldDescriptor : myFieldDescriptors) { for (final PsiReference reference : ReferencesSearch.search(fieldDescriptor.getField())) { final PsiElement element = reference.getElement(); if (element == null) continue; final EncapsulateFieldHelper helper = EncapsulateFieldHelper.getHelper(element.getLanguage()); if (helper != null) { EncapsulateFieldUsageInfo usageInfo = helper.createUsage(myDescriptor, fieldDescriptor, reference); if (usageInfo != null) { array.add(usageInfo); } } } } EncapsulateFieldUsageInfo[] usageInfos = array.toArray(new EncapsulateFieldUsageInfo[array.size()]); return UsageViewUtil.removeDuplicatedUsages(usageInfos); }
private void showUsages(final UsageInfo[] usages) { UsageViewPresentation presentation = new UsageViewPresentation(); presentation.setTabText("Safe Delete Conflicts"); presentation.setTargetsNodeText( RefactoringBundle.message("attempting.to.delete.targets.node.text")); presentation.setShowReadOnlyStatusAsRed(true); presentation.setShowCancelButton(true); presentation.setCodeUsagesString(RefactoringBundle.message("references.found.in.code")); presentation.setUsagesInGeneratedCodeString( RefactoringBundle.message("references.found.in.generated.code")); presentation.setNonCodeUsagesString( RefactoringBundle.message("occurrences.found.in.comments.strings.and.non.java.files")); presentation.setUsagesString(RefactoringBundle.message("usageView.usagesText")); UsageViewManager manager = UsageViewManager.getInstance(myProject); final UsageView usageView = showUsages(usages, presentation, manager); usageView.addPerformOperationAction( new RerunSafeDelete(myProject, myElements, usageView), RefactoringBundle.message("retry.command"), null, RefactoringBundle.message("rerun.safe.delete")); usageView.addPerformOperationAction( () -> { UsageInfo[] preprocessedUsages = usages; for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) { preprocessedUsages = delegate.preprocessUsages(myProject, preprocessedUsages); if (preprocessedUsages == null) return; } final UsageInfo[] filteredUsages = UsageViewUtil.removeDuplicatedUsages(preprocessedUsages); execute(filteredUsages); }, "Delete Anyway", RefactoringBundle.message("usageView.need.reRun"), RefactoringBundle.message("usageView.doAction")); }
@Override @NotNull protected UsageInfo[] findUsages() { List<UsageInfo> usages = Collections.synchronizedList(new ArrayList<UsageInfo>()); for (PsiElement element : myElements) { boolean handled = false; for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) { if (delegate.handlesElement(element)) { final NonCodeUsageSearchInfo filter = delegate.findUsages(element, myElements, usages); if (filter != null) { for (PsiElement nonCodeUsageElement : filter.getElementsToSearch()) { addNonCodeUsages( nonCodeUsageElement, usages, filter.getInsideDeletedCondition(), mySearchNonJava, mySearchInCommentsAndStrings); } } handled = true; break; } } if (!handled && element instanceof PsiNamedElement) { findGenericElementUsages(element, usages, myElements); addNonCodeUsages( element, usages, getDefaultInsideDeletedCondition(myElements), mySearchNonJava, mySearchInCommentsAndStrings); } } final UsageInfo[] result = usages.toArray(new UsageInfo[usages.size()]); return UsageViewUtil.removeDuplicatedUsages(result); }
@Override protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) { UsageInfo[] usages = refUsages.get(); ArrayList<String> conflicts = new ArrayList<String>(); for (PsiElement element : myElements) { for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) { if (delegate.handlesElement(element)) { Collection<String> foundConflicts = delegate instanceof SafeDeleteProcessorDelegateBase ? ((SafeDeleteProcessorDelegateBase) delegate) .findConflicts(element, myElements, usages) : delegate.findConflicts(element, myElements); if (foundConflicts != null) { conflicts.addAll(foundConflicts); } break; } } } final HashMap<PsiElement, UsageHolder> elementsToUsageHolders = sortUsages(usages); final Collection<UsageHolder> usageHolders = elementsToUsageHolders.values(); for (UsageHolder usageHolder : usageHolders) { if (usageHolder.hasUnsafeUsagesInCode()) { conflicts.add(usageHolder.getDescription()); } } if (!conflicts.isEmpty()) { final RefactoringEventData conflictData = new RefactoringEventData(); conflictData.putUserData(RefactoringEventData.CONFLICTS_KEY, conflicts); myProject .getMessageBus() .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) .conflictsDetected("refactoring.safeDelete", conflictData); if (ApplicationManager.getApplication().isUnitTestMode()) { if (!ConflictsInTestsException.isTestIgnore()) throw new ConflictsInTestsException(conflicts); } else { UnsafeUsagesDialog dialog = new UnsafeUsagesDialog(ArrayUtil.toStringArray(conflicts), myProject); if (!dialog.showAndGet()) { final int exitCode = dialog.getExitCode(); prepareSuccessful(); // dialog is always dismissed; if (exitCode == UnsafeUsagesDialog.VIEW_USAGES_EXIT_CODE) { showUsages( Arrays.stream(usages) .filter( usage -> usage instanceof SafeDeleteReferenceUsageInfo && !((SafeDeleteReferenceUsageInfo) usage).isSafeDelete()) .toArray(UsageInfo[]::new)); } return false; } else { myPreviewNonCodeUsages = false; } } } UsageInfo[] preprocessedUsages = usages; for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) { preprocessedUsages = delegate.preprocessUsages(myProject, preprocessedUsages); if (preprocessedUsages == null) return false; } final UsageInfo[] filteredUsages = UsageViewUtil.removeDuplicatedUsages(preprocessedUsages); prepareSuccessful(); // dialog is always dismissed if (filteredUsages == null) { return false; } refUsages.set(filteredUsages); return true; }
@Nullable @Override public Collection<? extends PsiElement> getElementsToSearch( @NotNull PsiElement element, @Nullable Module module, @NotNull Collection<PsiElement> allElementsToDelete) { Project project = element.getProject(); if (element instanceof PsiPackage && module != null) { final PsiDirectory[] directories = ((PsiPackage) element).getDirectories(module.getModuleScope()); if (directories.length == 0) return null; return Arrays.asList(directories); } else if (element instanceof PsiMethod) { final PsiMethod[] methods = SuperMethodWarningUtil.checkSuperMethods( (PsiMethod) element, RefactoringBundle.message("to.delete.with.usage.search"), allElementsToDelete); if (methods.length == 0) return null; final ArrayList<PsiMethod> psiMethods = new ArrayList<>(Arrays.asList(methods)); psiMethods.add((PsiMethod) element); return psiMethods; } else if (element instanceof PsiParameter && ((PsiParameter) element).getDeclarationScope() instanceof PsiMethod) { PsiMethod method = (PsiMethod) ((PsiParameter) element).getDeclarationScope(); final Set<PsiParameter> parametersToDelete = new HashSet<>(); parametersToDelete.add((PsiParameter) element); final int parameterIndex = method.getParameterList().getParameterIndex((PsiParameter) element); final List<PsiMethod> superMethods = new ArrayList<>(Arrays.asList(method.findDeepestSuperMethods())); if (superMethods.isEmpty()) { superMethods.add(method); } for (PsiMethod superMethod : superMethods) { parametersToDelete.add(superMethod.getParameterList().getParameters()[parameterIndex]); OverridingMethodsSearch.search(superMethod) .forEach( overrider -> { parametersToDelete.add( overrider.getParameterList().getParameters()[parameterIndex]); return true; }); } if (parametersToDelete.size() > 1 && !ApplicationManager.getApplication().isUnitTestMode()) { String message = RefactoringBundle.message( "0.is.a.part.of.method.hierarchy.do.you.want.to.delete.multiple.parameters", UsageViewUtil.getLongName(method)); int result = Messages.showYesNoCancelDialog( project, message, SafeDeleteHandler.REFACTORING_NAME, Messages.getQuestionIcon()); if (result == Messages.CANCEL) return null; if (result == Messages.NO) return Collections.singletonList(element); } return parametersToDelete; } else if (element instanceof PsiTypeParameter) { final PsiTypeParameterListOwner owner = ((PsiTypeParameter) element).getOwner(); if (owner instanceof PsiMethod && !owner.hasModifierProperty(PsiModifier.STATIC)) { final PsiTypeParameterList typeParameterList = owner.getTypeParameterList(); if (typeParameterList != null) { final int index = typeParameterList.getTypeParameterIndex((PsiTypeParameter) element); if (index >= 0) { final ArrayList<PsiTypeParameter> overriders = new ArrayList<>(); overriders.add((PsiTypeParameter) element); OverridingMethodsSearch.search((PsiMethod) owner) .forEach( overrider -> { final PsiTypeParameter[] typeParameters = overrider.getTypeParameters(); if (index < typeParameters.length) { overriders.add(typeParameters[index]); } return true; }); if (overriders.size() > 1) { String message = RefactoringBundle.message( "0.is.a.part.of.method.hierarchy.do.you.want.to.delete.multiple.type.parameters", UsageViewUtil.getLongName(owner)); int result = ApplicationManager.getApplication().isUnitTestMode() ? Messages.YES : Messages.showYesNoCancelDialog( project, message, SafeDeleteHandler.REFACTORING_NAME, Messages.getQuestionIcon()); if (result == Messages.CANCEL) return null; if (result == Messages.YES) return overriders; } } } } } return Collections.singletonList(element); }
private static String getNoUsagesFoundMessage(PsiElement psiElement) { String elementType = UsageViewUtil.getType(psiElement); String elementName = UsageViewUtil.getShortName(psiElement); return FindBundle.message( "find.usages.of.element_type.element_name.not.found.message", elementType, elementName); }
protected void doRun() { PsiDocumentManager.getInstance(myProject).commitAllDocuments(); final Ref<UsageInfo[]> refUsages = new Ref<>(); final Ref<Language> refErrorLanguage = new Ref<>(); final Ref<Boolean> refProcessCanceled = new Ref<>(); final Ref<Boolean> anyException = new Ref<>(); final Runnable findUsagesRunnable = new Runnable() { @Override public void run() { try { refUsages.set( DumbService.getInstance(myProject) .runReadActionInSmartMode( new Computable<UsageInfo[]>() { @Override public UsageInfo[] compute() { return findUsages(); } })); } catch (UnknownReferenceTypeException e) { refErrorLanguage.set(e.getElementLanguage()); } catch (ProcessCanceledException e) { refProcessCanceled.set(Boolean.TRUE); } catch (Throwable e) { anyException.set(Boolean.TRUE); LOG.error(e); } } }; if (!ProgressManager.getInstance() .runProcessWithProgressSynchronously( findUsagesRunnable, RefactoringBundle.message("progress.text"), true, myProject)) { return; } if (!refErrorLanguage.isNull()) { Messages.showErrorDialog( myProject, RefactoringBundle.message( "unsupported.refs.found", refErrorLanguage.get().getDisplayName()), RefactoringBundle.message("error.title")); return; } if (DumbService.isDumb(myProject)) { DumbService.getInstance(myProject) .showDumbModeNotification("Refactoring is not available until indices are ready"); return; } if (!refProcessCanceled.isNull()) { Messages.showErrorDialog( myProject, "Index corruption detected. Please retry the refactoring - indexes will be rebuilt automatically", RefactoringBundle.message("error.title")); return; } if (!anyException.isNull()) { // do not proceed if find usages fails return; } assert !refUsages.isNull() : "Null usages from processor " + this; if (!preprocessUsages(refUsages)) return; final UsageInfo[] usages = refUsages.get(); assert usages != null; UsageViewDescriptor descriptor = createUsageViewDescriptor(usages); boolean isPreview = isPreviewUsages(usages); if (!isPreview) { isPreview = !ensureElementsWritable(usages, descriptor) || UsageViewUtil.hasReadOnlyUsages(usages); if (isPreview) { StatusBarUtil.setStatusBarInfo( myProject, RefactoringBundle.message("readonly.occurences.found")); } } if (isPreview) { for (UsageInfo usage : usages) { LOG.assertTrue(usage != null, getClass()); } previewRefactoring(usages); } else { execute(usages); } }
private String getCommandName(final PsiClass subclass, String newName) { return RefactoringBundle.message( "extract.superclass.command.name", newName, UsageViewUtil.getDescriptiveName(subclass)); }
public void setData( PsiElement[] psiElements, String targetPackageName, PsiDirectory initialTargetDirectory, boolean isTargetDirectoryFixed, boolean suggestToMoveToAnotherRoot, boolean searchInComments, boolean searchForTextOccurences, String helpID) { myTargetDirectoryFixed = isTargetDirectoryFixed; mySuggestToMoveToAnotherRoot = suggestToMoveToAnotherRoot; if (targetPackageName.length() != 0) { myWithBrowseButtonReference.prependItem(targetPackageName); myClassPackageChooser.prependItem(targetPackageName); } String nameFromCallback = myMoveCallback instanceof MoveClassesOrPackagesCallback ? ((MoveClassesOrPackagesCallback) myMoveCallback).getElementsToMoveName() : null; if (nameFromCallback != null) { myNameLabel.setText(nameFromCallback); } else if (psiElements.length == 1) { PsiElement firstElement = psiElements[0]; if (firstElement instanceof PsiClass) { LOG.assertTrue(!MoveClassesOrPackagesImpl.isClassInnerOrLocal((PsiClass) firstElement)); } else { PsiElement parent = firstElement.getParent(); LOG.assertTrue(parent != null); } myNameLabel.setText( RefactoringBundle.message( "move.single.class.or.package.name.label", UsageViewUtil.getType(firstElement), UsageViewUtil.getLongName(firstElement))); } else if (psiElements.length > 1) { myNameLabel.setText( psiElements[0] instanceof PsiClass ? RefactoringBundle.message("move.specified.classes") : RefactoringBundle.message("move.specified.packages")); } selectInitialCard(); myCbSearchInComments.setSelected(searchInComments); myCbSearchTextOccurences.setSelected(searchForTextOccurences); if (initialTargetDirectory != null && JavaMoveClassesOrPackagesHandler.packageHasMultipleDirectoriesInModule( myProject, initialTargetDirectory)) { final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); final Set<VirtualFile> initialRoots = new HashSet<VirtualFile>(); collectSourceRoots(psiElements, fileIndex, initialRoots); if (initialRoots.size() > 1) { initialTargetDirectory = null; } } ((DestinationFolderComboBox) myDestinationFolderCB) .setData( myProject, initialTargetDirectory, new Pass<String>() { @Override public void pass(String s) { setErrorText(s); } }, myHavePackages ? myWithBrowseButtonReference.getChildComponent() : myClassPackageChooser.getChildComponent()); UIUtil.setEnabled( myTargetPanel, !getSourceRoots().isEmpty() && isMoveToPackage() && !isTargetDirectoryFixed, true); validateButtons(); myHelpID = helpID; }
public void setData( PsiElement[] psiElements, String targetPackageName, final PsiDirectory initialTargetDirectory, boolean isTargetDirectoryFixed, boolean searchInComments, boolean searchForTextOccurences, String helpID) { myInitialTargetDirectory = initialTargetDirectory; myTargetDirectoryFixed = isTargetDirectoryFixed; if (targetPackageName.length() != 0) { myWithBrowseButtonReference.prependItem(targetPackageName); myClassPackageChooser.prependItem(targetPackageName); } String nameFromCallback = myMoveCallback instanceof MoveClassesOrPackagesCallback ? ((MoveClassesOrPackagesCallback) myMoveCallback).getElementsToMoveName() : null; if (nameFromCallback != null) { myNameLabel.setText(nameFromCallback); } else if (psiElements.length == 1) { PsiElement firstElement = psiElements[0]; if (firstElement instanceof PsiClass) { LOG.assertTrue(!MoveClassesOrPackagesImpl.isClassInnerOrLocal((PsiClass) firstElement)); } else { PsiElement parent = firstElement.getParent(); LOG.assertTrue(parent != null); } myNameLabel.setText( RefactoringBundle.message( "move.single.class.or.package.name.label", UsageViewUtil.getType(firstElement), UsageViewUtil.getLongName(firstElement))); } else if (psiElements.length > 1) { myNameLabel.setText( psiElements[0] instanceof PsiClass ? RefactoringBundle.message("move.specified.classes") : RefactoringBundle.message("move.specified.packages")); } selectInitialCard(); myCbSearchInComments.setSelected(searchInComments); myCbSearchTextOccurences.setSelected(searchForTextOccurences); ((DestinationFolderComboBox) myDestinationFolderCB) .setData( myProject, myInitialTargetDirectory, new Pass<String>() { @Override public void pass(String s) { setErrorText(s); } }, myClassPackageChooser.getChildComponent()); UIUtil.setEnabled( myTargetPanel, getSourceRoots().length > 0 && isMoveToPackage() && !isTargetDirectoryFixed, true); validateButtons(); myHelpID = helpID; }
protected void performRefactoring(@NotNull UsageInfo[] usageInfos) { final PsiClass psiClass = buildClass(); if (psiClass == null) return; if (delegationRequired) { buildDelegate(); } myExtractEnumProcessor.performEnumConstantTypeMigration(usageInfos); final Set<PsiMember> members = new HashSet<PsiMember>(); for (PsiMethod method : methods) { final PsiMethod member = psiClass.findMethodBySignature(method, false); if (member != null) { members.add(member); } } for (PsiField field : fields) { final PsiField member = psiClass.findFieldByName(field.getName(), false); if (member != null) { members.add(member); final PsiExpression initializer = member.getInitializer(); if (initializer != null) { final boolean[] moveInitializerToConstructor = new boolean[1]; initializer.accept( new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceExpression(PsiReferenceExpression expression) { super.visitReferenceExpression(expression); final PsiElement resolved = expression.resolve(); if (resolved instanceof PsiField && !members.contains(resolved)) { moveInitializerToConstructor[0] = true; } } }); if (moveInitializerToConstructor[0]) { final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject); PsiMethod[] constructors = psiClass.getConstructors(); if (constructors.length == 0) { final PsiMethod constructor = (PsiMethod) elementFactory.createConstructor().setName(psiClass.getName()); constructors = new PsiMethod[] {(PsiMethod) psiClass.add(constructor)}; } for (PsiMethod constructor : constructors) { MoveInstanceMembersUtil.moveInitializerToConstructor( elementFactory, constructor, member); } } } } } if (myGenerateAccessors) { final NecessaryAccessorsVisitor visitor = checkNecessaryGettersSetters4SourceClass(); for (PsiField field : visitor.getFieldsNeedingGetter()) { sourceClass.add(GenerateMembersUtil.generateGetterPrototype(field)); } for (PsiField field : visitor.getFieldsNeedingSetter()) { sourceClass.add(GenerateMembersUtil.generateSetterPrototype(field)); } } super.performRefactoring(usageInfos); if (myNewVisibility == null) return; for (PsiMember member : members) { VisibilityUtil.fixVisibility(UsageViewUtil.toElements(usageInfos), member, myNewVisibility); } }
public MoveClassesOrPackagesToNewDirectoryDialog( @NotNull final PsiDirectory directory, PsiElement[] elementsToMove, boolean canShowPreserveSourceRoots, final MoveCallback moveCallback) { super(false); setTitle(MoveHandler.REFACTORING_NAME); myDirectory = directory; myElementsToMove = elementsToMove; myMoveCallback = moveCallback; myDestDirectoryField.setText( FileUtil.toSystemDependentName(directory.getVirtualFile().getPath())); final FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false); myDestDirectoryField .getButton() .addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { final VirtualFile[] files = FileChooser.chooseFiles( myDirectory.getProject(), descriptor, directory.getVirtualFile()); if (files.length == 1) { myDestDirectoryField.setText(FileUtil.toSystemDependentName(files[0].getPath())); } } }); if (elementsToMove.length == 1) { PsiElement firstElement = elementsToMove[0]; myNameLabel.setText( RefactoringBundle.message( "move.single.class.or.package.name.label", UsageViewUtil.getType(firstElement), UsageViewUtil.getLongName(firstElement))); } else if (elementsToMove.length > 1) { myNameLabel.setText( elementsToMove[0] instanceof PsiClass ? RefactoringBundle.message("move.specified.classes") : RefactoringBundle.message("move.specified.packages")); } final JavaRefactoringSettings refactoringSettings = JavaRefactoringSettings.getInstance(); mySearchInCommentsAndStringsCheckBox.setSelected(refactoringSettings.MOVE_SEARCH_IN_COMMENTS); mySearchForTextOccurrencesCheckBox.setSelected(refactoringSettings.MOVE_SEARCH_FOR_TEXT); myDestDirectoryField .getTextField() .getDocument() .addDocumentListener( new DocumentAdapter() { public void textChanged(DocumentEvent event) { setOKActionEnabled(myDestDirectoryField.getText().length() > 0); } }); if (canShowPreserveSourceRoots) { final Set<VirtualFile> sourceRoots = new HashSet<VirtualFile>(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(directory.getProject()).getFileIndex(); for (PsiElement element : elementsToMove) { if (element instanceof PsiPackage) { for (PsiDirectory psiDirectory : ((PsiPackage) element).getDirectories()) { sourceRoots.add(fileIndex.getSourceRootForFile(psiDirectory.getVirtualFile())); } } else if (element instanceof PsiClass) { final PsiDirectory psiDirectory = element.getContainingFile().getContainingDirectory(); LOG.assertTrue(psiDirectory != null); if (psiDirectory != null) { sourceRoots.add(psiDirectory.getVirtualFile()); } } } myPreserveSourceRoot.setVisible(sourceRoots.size() > 1); } init(); }
private String getCommandName() { return RefactoringBundle.message( "extract.interface.command.name", myInterfaceName, UsageViewUtil.getDescriptiveName(myClass)); }