下面列出了com.intellij.psi.SmartPointerManager#com.intellij.usageView.UsageInfo 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected boolean showConflicts(@Nonnull MultiMap<PsiElement, String> conflicts, @Nullable final UsageInfo[] usages) {
if (!conflicts.isEmpty() && ApplicationManager.getApplication().isUnitTestMode()) {
if (!ConflictsInTestsException.isTestIgnore()) throw new ConflictsInTestsException(conflicts.values());
return true;
}
if (myPrepareSuccessfulSwingThreadCallback != null && !conflicts.isEmpty()) {
final String refactoringId = getRefactoringId();
if (refactoringId != null) {
RefactoringEventData conflictUsages = new RefactoringEventData();
conflictUsages.putUserData(RefactoringEventData.CONFLICTS_KEY, conflicts.values());
myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).conflictsDetected(refactoringId, conflictUsages);
}
final ConflictsDialog conflictsDialog = prepareConflictsDialog(conflicts, usages);
if (!conflictsDialog.showAndGet()) {
if (conflictsDialog.isShowConflicts()) prepareSuccessful();
return false;
}
}
prepareSuccessful();
return true;
}
protected List<UsageInfo> filterUsages(List<UsageInfo> infos) {
Map<PsiElement, MoveRenameUsageInfo> moveRenameInfos = new HashMap<PsiElement, MoveRenameUsageInfo>();
Set<PsiElement> usedElements = new HashSet<PsiElement>();
List<UsageInfo> result = new ArrayList<UsageInfo>(infos.size() / 2);
for (UsageInfo info : infos) {
LOG.assertTrue(info != null, getClass());
PsiElement element = info.getElement();
if (info instanceof MoveRenameUsageInfo) {
if (usedElements.contains(element)) continue;
moveRenameInfos.put(element, (MoveRenameUsageInfo)info);
}
else {
moveRenameInfos.remove(element);
usedElements.add(element);
if (!(info instanceof PossiblyIncorrectUsage) || ((PossiblyIncorrectUsage)info).isCorrect()) {
result.add(info);
}
}
}
result.addAll(moveRenameInfos.values());
return result;
}
@Test
public void testExecute_RenameFileEditRenameChanges() {
when(mockPendingChange.getChangeTypes()).thenReturn(ImmutableList.of(ServerStatusType.EDIT, ServerStatusType.RENAME));
when(mockVirtualFile.getPath()).thenReturn(CURRENT_FILE_PATH);
when(CommandUtils.getStatusForFiles(any(Project.class), eq(mockServerContext), eq(ImmutableList.of(CURRENT_FILE_PATH))))
.thenReturn(ImmutableList.of(mockPendingChange));
RenameFileDirectory.execute(mockPsiFile, NEW_FILE_NAME, usageInfos, mockListener);
verifyStatic(times(1));
CommandUtils.renameFile(eq(mockServerContext), eq(CURRENT_FILE_PATH), eq(NEW_FILE_PATH));
PersistentFS.getInstance().processEvents(any(List.class));
verify(mockListener).elementRenamed(mockPsiFile);
verifyStatic(never());
RenameUtil.doRenameGenericNamedElement(any(PsiElement.class), any(String.class), any(UsageInfo[].class), any(RefactoringElementListener.class));
}
@Override
@Nonnull
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
@Nonnull
protected UsageInfo[] findUsages() {
ArrayList<UsageInfo> result = new ArrayList<>();
for (int i = 0; i < myElementsToMove.length; i++) {
PsiElement element = myElementsToMove[i];
if (mySearchForReferences) {
for (PsiReference reference : ReferencesSearch.search(element, GlobalSearchScope.projectScope(myProject))) {
result.add(new MyUsageInfo(reference.getElement(), i, reference));
}
}
findElementUsages(result, element);
}
return result.toArray(new UsageInfo[result.size()]);
}
@Nullable
public UsageInfo getUsageInfo() {
if (myElementAnchors.length == 1) {
final PsiElement element = myElementAnchors[0].retrieve();
if (element == null || !element.isValid()) return null;
return new UsageInfo(element);
}
PsiElement parent = PsiTreeUtil.findCommonParent(getElements());
if (parent == null) return null;
int offs = parent.getTextRange().getStartOffset();
final int startOffsetInParent = getStartOffset() - offs;
final int endOffsetInParent = getEndOffset() - offs;
if (startOffsetInParent < 0) return null;
if (endOffsetInParent < startOffsetInParent) return null;
return new UsageInfo(parent, startOffsetInParent, endOffsetInParent);
}
public static void addUsagesInStringsAndComments(@Nonnull PsiElement element,
@Nonnull String stringToSearch,
@Nonnull final Collection<UsageInfo> results,
@Nonnull final UsageInfoFactory factory) {
final Object lock = new Object();
processUsagesInStringsAndComments(element, stringToSearch, false, new PairProcessor<PsiElement, TextRange>() {
@Override
public boolean process(PsiElement commentOrLiteral, TextRange textRange) {
UsageInfo usageInfo = factory.createUsageInfo(commentOrLiteral, textRange.getStartOffset(), textRange.getEndOffset());
if (usageInfo != null) {
synchronized (lock) {
results.add(usageInfo);
}
}
return true;
}
});
}
@Override
protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
for (PsiFile psiFile : myFilesToMove.keySet()) {
try {
myFilesToMove.get(psiFile).checkMove(psiFile);
}
catch (IncorrectOperationException e) {
conflicts.putValue(psiFile, e.getMessage());
}
}
for (MoveDirectoryWithClassesHelper helper : MoveDirectoryWithClassesHelper.findAll()) {
helper.preprocessUsages(myProject, myFilesToMove.keySet(), refUsages.get(), myTargetDirectory, conflicts);
}
return showConflicts(conflicts, refUsages.get());
}
public String prettyUsageMessage(UsageInfo usage) {
UsageInfo2UsageAdapter adapter = new UsageInfo2UsageAdapter(usage);
StringBuilder builder = new StringBuilder();
VirtualFile vFile = adapter.getFile();
builder.append(null != vFile ? vFile.getName() : "<unknown file>");
builder.append(", line ");
builder.append(adapter.getLine() + 1);
builder.append(':');
builder.append(adapter.getPresentation().getPlainText());
String tooltip = adapter.getPresentation().getTooltipText();
if (null != tooltip) {
builder.append(" {");
builder.append(tooltip);
builder.append("} ");
}
return builder.toString();
}
public void calcData(final Key<?> key, final DataSink sink) {
if (!isValid()) return;
if (CommonDataKeys.PSI_ELEMENT == key) {
sink.put(CommonDataKeys.PSI_ELEMENT, getElement());
}
if (UsageView.USAGE_INFO_KEY == key) {
T element = getElement();
if (element != null) {
sink.put(UsageView.USAGE_INFO_KEY, new UsageInfo(element));
}
}
}
public static void applyEdit(PsiElement elem, String newName, UsageInfo[] infos,
RefactoringElementListener listener, List<VirtualFile> openedEditors) {
Map<String, List<TextEdit>> edits = new HashMap<>();
if (elem instanceof LSPPsiElement) {
LSPPsiElement lspElem = (LSPPsiElement) elem;
if (Stream.of(infos).allMatch(info -> info.getElement() instanceof LSPPsiElement)) {
Stream.of(infos).forEach(ui -> {
Editor editor = FileUtils.editorFromVirtualFile(ui.getVirtualFile(), ui.getProject());
TextRange range = ui.getElement().getTextRange();
Range lspRange = new Range(DocumentUtils.offsetToLSPPos(editor, range.getStartOffset()),
DocumentUtils.offsetToLSPPos(editor, range.getEndOffset()));
TextEdit edit = new TextEdit(lspRange, newName);
String uri = null;
try {
uri = FileUtils.sanitizeURI(
new URL(ui.getVirtualFile().getUrl().replace(" ", FileUtils.SPACE_ENCODED)).toURI()
.toString());
} catch (MalformedURLException | URISyntaxException e) {
LOG.warn(e);
}
if (edits.keySet().contains(uri)) {
edits.get(uri).add(edit);
} else {
List<TextEdit> textEdits = new ArrayList<>();
textEdits.add(edit);
edits.put(uri, textEdits);
}
});
WorkspaceEdit workspaceEdit = new WorkspaceEdit(edits);
applyEdit(workspaceEdit, "Rename " + lspElem.getName() + " to " + newName, openedEditors);
}
}
}
public void testException() {
myFixture.configureByText("A.re", "exception Exception<caret>Name; raise(ExceptionName);");
Collection<UsageInfo> usages = myFixture.testFindUsages("A.re");
assertSize(1, usages);
assertEquals("(ExceptionName)", usages.iterator().next().getElement().getParent().getText());
}
public UsageInfo2UsageAdapter(@Nonnull final UsageInfo usageInfo) {
myUsageInfo = usageInfo;
myMergedUsageInfos = usageInfo;
ThrowableComputable<Point, RuntimeException> action = () -> {
PsiElement element = getElement();
PsiFile psiFile = usageInfo.getFile();
Document document = psiFile == null ? null : PsiDocumentManager.getInstance(getProject()).getDocument(psiFile);
int offset;
int lineNumber;
if (document == null) {
// element over light virtual file
offset = element == null ? 0 : element.getTextOffset();
lineNumber = -1;
}
else {
int startOffset = myUsageInfo.getNavigationOffset();
if (startOffset == -1) {
offset = element == null ? 0 : element.getTextOffset();
lineNumber = -1;
}
else {
offset = -1;
lineNumber = getLineNumber(document, startOffset);
}
}
return new Point(offset, lineNumber);
};
Point data = AccessRule.read(action);
myOffset = data.x;
myLineNumber = data.y;
myModificationStamp = getCurrentModificationStamp();
}
public static MultiMap<PsiElement, UsageInfo> classifyUsages(Collection<? extends PsiElement> elements, UsageInfo[] usages) {
final MultiMap<PsiElement, UsageInfo> result = new MultiMap<>();
for (UsageInfo usage : usages) {
LOG.assertTrue(usage instanceof MoveRenameUsageInfo);
if (usage.getReference() instanceof LightElement) {
continue; //filter out implicit references (e.g. from derived class to super class' default constructor)
}
MoveRenameUsageInfo usageInfo = (MoveRenameUsageInfo)usage;
if (usage instanceof RelatedUsageInfo) {
final PsiElement relatedElement = ((RelatedUsageInfo)usage).getRelatedElement();
if (elements.contains(relatedElement)) {
result.putValue(relatedElement, usage);
}
} else {
PsiElement referenced = usageInfo.getReferencedElement();
if (elements.contains(referenced)) {
result.putValue(referenced, usage);
} else if (referenced != null) {
PsiElement indirect = referenced.getNavigationElement();
if (elements.contains(indirect)) {
result.putValue(indirect, usage);
}
}
}
}
return result;
}
public void testCustomOptionReferenceUsages() {
Collection<UsageInfo> usageInfos = myFixture.testFindUsages(
"usages/CustomOptionReference.proto",
"usages/Options.proto"
);
assertEquals(1, usageInfos.size());
for (UsageInfo usageInfo : usageInfos) {
PsiElement element = usageInfo.getReference().resolve();
assertNotNull(element);
FieldNode field = (FieldNode) element;
assertEquals("stringOption", field.getFieldName());
}
}
public void testStandardOptionReferenceUsages() {
Collection<UsageInfo> usageInfos = myFixture.testFindUsages(
"usages/StandardOptionReference.proto"
);
assertEquals(1, usageInfos.size());
for (UsageInfo usageInfo : usageInfos) {
PsiElement element = usageInfo.getReference().resolve();
assertNotNull(element);
FieldNode field = (FieldNode) element;
assertEquals("jstype", field.getFieldName());
}
}
public void testMultipleReferences() {
configureFile(MULTIPLE_REFERENCES);
PsiElement element = TestReferenceUtil.getParentElementAtCaret(myFixture);
Collection<UsageInfo> usages = findBeanUsages(element);
assertEquals(5, usages.size());
assertEquals(1, countUsages(usages, BeanSelfReference.class));
assertEquals(4, countUsages(usages, BeanReference.class));
}
private Collection<UsageInfo> findBeanUsages(PsiElement element) {
PsiReference reference = element.getReference();
assertNotNull(reference);
assertEquals(BeanSelfReference.class, reference.getClass());
PsiElement target = reference.resolve();
assertNotNull(target);
assertEquals(ReferenceableIdPsiElement.class, target.getClass());
return myFixture.findUsages(target);
}
public static void inlineReference(final UsageInfo usage,
final PsiElement element,
final Map<Language, InlineHandler.Inliner> inliners) {
PsiElement usageElement = usage.getElement();
if (usageElement == null) return;
final Language language = usageElement.getLanguage();
final InlineHandler.Inliner inliner = inliners.get(language);
if (inliner != null) {
inliner.inlineUsage(usage, element);
}
}
@Override
public void postProcessUsages(UsageInfo[] usages, Function<PsiDirectory, PsiDirectory> newDirMapper) {
for (UsageInfo usage : usages) {
if (usage instanceof MyUsageInfo) {
PsiReference reference = usage.getReference();
if (reference != null) {
PsiFileSystemItem file = ((MyUsageInfo)usage).myFile;
if (file instanceof PsiDirectory) {
file = newDirMapper.fun((PsiDirectory)file);
}
reference.bindToElement(file);
}
}
}
}
public void testFindUsageFromWithOverloadedMethodToBeanDSL() {
Collection<UsageInfo> usageInfos = myFixture.testFindUsages("CompleteJavaBeanTest2Data.java", "CompleteJavaBeanRoute7TestData.java");
assertEquals(1, usageInfos.size());
final UsageInfo usageInfo = usageInfos.iterator().next();
final PsiElement referenceElement = usageInfo.getElement();
assertThat(referenceElement, instanceOf(PsiLiteralExpression.class));
assertEquals("(beanTestData, \"myOverLoadedBean\")", referenceElement.getParent().getText());
}
/**
* Delegates to JavaSafeDeleteProcessor, then removes indirect glob references which we don't want
* to block safe delete.
*/
@Nullable
@Override
public NonCodeUsageSearchInfo findUsages(
@NotNull PsiElement element,
@NotNull PsiElement[] allElementsToDelete,
@NotNull List<UsageInfo> result) {
NonCodeUsageSearchInfo superResult = super.findUsages(element, allElementsToDelete, result);
result.removeIf(BuildFileSafeDeleteProcessor::ignoreUsage);
return superResult;
}
/**
* We keep globs which reference the file directly (i.e. without wildcards), and remove all
* indirect references for the purposes of the 'safe delete' action.
*/
private static boolean ignoreUsage(UsageInfo usage) {
if (usage.getReference() instanceof GlobReference && usage instanceof SafeDeleteUsageInfo) {
PsiElement referencedElement = ((SafeDeleteUsageInfo) usage).getReferencedElement();
PsiFileSystemItem file = ResolveUtil.asFileSystemItemSearch(referencedElement);
String relativePath = getBlazePackageRelativePathToFile(file);
if (relativePath == null) {
return false;
}
return !((GlobReference) usage.getReference())
.matchesDirectly(relativePath, file.isDirectory());
}
return false;
}
private void showUsageView(@Nonnull UsageViewDescriptor viewDescriptor, @Nonnull Factory<UsageSearcher> factory, @Nonnull UsageInfo[] usageInfos) {
UsageViewManager viewManager = UsageViewManager.getInstance(myProject);
final PsiElement[] initialElements = viewDescriptor.getElements();
final UsageTarget[] targets = PsiElement2UsageTargetAdapter.convert(initialElements);
final Ref<Usage[]> convertUsagesRef = new Ref<>();
if (!ProgressManager.getInstance()
.runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(() -> convertUsagesRef.set(UsageInfo2UsageAdapter.convert(usageInfos))), "Preprocess Usages",
true, myProject)) return;
if (convertUsagesRef.isNull()) return;
final Usage[] usages = convertUsagesRef.get();
final UsageViewPresentation presentation = createPresentation(viewDescriptor, usages);
if (myUsageView == null) {
myUsageView = viewManager.showUsages(targets, usages, presentation, factory);
customizeUsagesView(viewDescriptor, myUsageView);
}
else {
myUsageView.removeUsagesBulk(myUsageView.getUsages());
((UsageViewImpl)myUsageView).appendUsagesInBulk(Arrays.asList(usages));
}
Set<UnloadedModuleDescription> unloadedModules = computeUnloadedModulesFromUseScope(viewDescriptor);
if (!unloadedModules.isEmpty()) {
myUsageView.appendUsage(new UnknownUsagesInUnloadedModules(unloadedModules));
}
}
@Override
protected boolean isPreviewUsages(@Nonnull UsageInfo[] usages) {
for (ChangeSignatureUsageProcessor processor : ChangeSignatureUsageProcessor.EP_NAME.getExtensions()) {
if (processor.shouldPreviewUsages(myChangeInfo, usages)) return true;
}
return super.isPreviewUsages(usages);
}
@Override
public void calcData(final Key<?> key, final DataSink sink) {
if (key == UsageView.USAGE_INFO_KEY) {
PsiElement element = getElement();
if (element != null && element.getTextRange() != null) {
sink.put(UsageView.USAGE_INFO_KEY, new UsageInfo(element));
}
}
else if (key == UsageView.USAGE_SCOPE) {
sink.put(UsageView.USAGE_SCOPE, myOptions.searchScope);
}
}
private UsageView showUsages(UsageInfo[] usages, UsageViewPresentation presentation, UsageViewManager manager) {
for (SafeDeleteProcessorDelegate delegate : Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) {
if (delegate instanceof SafeDeleteProcessorDelegateBase) {
final UsageView view = ((SafeDeleteProcessorDelegateBase)delegate).showUsages(usages, presentation, manager, myElements);
if (view != null) return view;
}
}
UsageTarget[] targets = new UsageTarget[myElements.length];
for (int i = 0; i < targets.length; i++) {
targets[i] = new PsiElement2UsageTargetAdapter(myElements[i]);
}
return manager.showUsages(targets, UsageInfoToUsageConverter.convert(myElements, usages), presentation);
}
/**
* @deprecated Use {@link #findUsages(FindModel, Project, Processor, FindUsagesProcessPresentation)} instead. To remove in IDEA 16
*/
@Deprecated
//@ApiStatus.ScheduledForRemoval(inVersion = "2016")
public static void findUsages(@Nonnull FindModel findModel,
@Nullable final PsiDirectory psiDirectory,
@Nonnull final Project project,
@Nonnull final Processor<? super UsageInfo> consumer,
@Nonnull FindUsagesProcessPresentation processPresentation) {
findUsages(findModel, project, consumer, processPresentation);
}
public void testFindVariableUsages() {
Collection<UsageInfo> foundUsages = myFixture.testFindUsages("Variable.xq");
assertEquals(1, foundUsages.size());
UsageInfo usageInfo = foundUsages.iterator().next();
assertChildOf(usageInfo.getElement(), XQueryFunctionDecl.class);
assertChildOf(resolved(usageInfo), XQueryVarDecl.class);
}
@Test
public void testVarDefUsage() throws Exception {
PsiElement element = configurePsiAtCaret();
Collection<UsageInfo> usages = myFixture.findUsages(element);
Assert.assertEquals(3, usages.size());
Assert.assertEquals("variable", typeNameFor(element));
Assert.assertEquals("a", descriptiveNameFor(element));
}