Java 类com.intellij.psi.util.PsiUtilCore 实例源码

项目:a-file-icon-idea    文件:FileIconProvider.java   
@Nullable
@Override
public Icon getIcon(@NotNull final PsiElement psiElement, final int i) {
  Icon icon = null;

  // Only replace icons on elements representing a file
  // Prevents file icons from being assigned to classes, methods, fields, etc.
  if (psiElement instanceof PsiFile) {
    final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(psiElement);
    if (virtualFile != null) {
      final FileInfo file = new VirtualFileInfo(psiElement, virtualFile);
      icon = getIconForAssociation(file, associations.findAssociationForFile(file));
    }
  } else if (psiElement instanceof PsiDirectory) {
    icon = getDirectoryIcon((PsiDirectory) psiElement);
  }

  return icon;
}
项目:processing-idea    文件:SketchClassFilter.java   
@Override
public boolean isAccepted(PsiClass klass) {
    return ApplicationManager.getApplication().runReadAction((Computable<Boolean>) () -> {
        if (isSketchClass(klass)) {
            final CompilerConfiguration compilerConfiguration = CompilerConfiguration.getInstance(project);
            final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(klass);

            if (virtualFile == null) {
                return false;
            }

            return ! compilerConfiguration.isExcludedFromCompilation(virtualFile) &&
                    ! ProjectRootManager.getInstance(project)
                            .getFileIndex()
                            .isUnderSourceRootOfType(virtualFile, JavaModuleSourceRootTypes.RESOURCES);
        }

        return false;
    });
}
项目:intellij-ce-playground    文件:SafeDeleteProcessor.java   
public static SafeDeleteProcessor createInstance(Project project, @Nullable Runnable prepareSuccessfulCallBack,
                                                 PsiElement[] elementsToDelete, boolean isSearchInComments, boolean isSearchNonJava,
                                                 boolean askForAccessors) {
  ArrayList<PsiElement> elements = new ArrayList<PsiElement>(Arrays.asList(elementsToDelete));
  HashSet<PsiElement> elementsToDeleteSet = new HashSet<PsiElement>(Arrays.asList(elementsToDelete));

  for (PsiElement psiElement : elementsToDelete) {
    for(SafeDeleteProcessorDelegate delegate: Extensions.getExtensions(SafeDeleteProcessorDelegate.EP_NAME)) {
      if (delegate.handlesElement(psiElement)) {
        Collection<PsiElement> addedElements = delegate.getAdditionalElementsToDelete(psiElement, elementsToDeleteSet, askForAccessors);
        if (addedElements != null) {
          elements.addAll(addedElements);
        }
        break;
      }
    }
  }

  return new SafeDeleteProcessor(project, prepareSuccessfulCallBack,
                                 PsiUtilCore.toPsiElementArray(elements),
                                 isSearchInComments, isSearchNonJava);
}
项目:intellij-ce-playground    文件:GotoSuperAction.java   
@Override
public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
  PsiDocumentManager.getInstance(project).commitAllDocuments();

  int offset = editor.getCaretModel().getOffset();
  final Language language = PsiUtilCore.getLanguageAtOffset(file, offset);

  final CodeInsightActionHandler codeInsightActionHandler = CodeInsightActions.GOTO_SUPER.forLanguage(language);
  if (codeInsightActionHandler != null) {
    DumbService.getInstance(project).withAlternativeResolveEnabled(new Runnable() {
      @Override
      public void run() {
        codeInsightActionHandler.invoke(project, editor, file);
      }
    });
  }
}
项目:intellij-ce-playground    文件:TypeCorrector.java   
@Override
public PsiType visitClassType(final PsiClassType classType) {
  PsiClassType alreadyComputed = myResultMap.get(classType);
  if (alreadyComputed != null) {
    return alreadyComputed;
  }

  final PsiClassType.ClassResolveResult classResolveResult = classType.resolveGenerics();
  final PsiClass psiClass = classResolveResult.getElement();
  final PsiSubstitutor substitutor = classResolveResult.getSubstitutor();
  if (psiClass == null) return classType;

  PsiUtilCore.ensureValid(psiClass);

  final PsiClass mappedClass = mapClass(psiClass);
  if (mappedClass == null) return classType;

  PsiClassType mappedType = new PsiCorrectedClassType(classType.getLanguageLevel(),
                                                      classType,
                                                      new CorrectedResolveResult(psiClass, mappedClass, substitutor, classResolveResult));
  myResultMap.put(classType, mappedType);
  return mappedType;
}
项目:intellij-ce-playground    文件:CommentByLineCommentHandler.java   
@Nullable
private static Commenter findCommenter(Editor editor, PsiFile file, final int line) {
  final FileType fileType = file.getFileType();
  if (fileType instanceof AbstractFileType) {
    return ((AbstractFileType)fileType).getCommenter();
  }

  Document document = editor.getDocument();
  int lineStartOffset = document.getLineStartOffset(line);
  int lineEndOffset = document.getLineEndOffset(line) - 1;
  final CharSequence charSequence = document.getCharsSequence();
  lineStartOffset = CharArrayUtil.shiftForward(charSequence, lineStartOffset, " \t");
  lineEndOffset = CharArrayUtil.shiftBackward(charSequence, lineEndOffset < 0 ? 0 : lineEndOffset, " \t");
  final Language lineStartLanguage = PsiUtilCore.getLanguageAtOffset(file, lineStartOffset);
  final Language lineEndLanguage = PsiUtilCore.getLanguageAtOffset(file, lineEndOffset);
  return CommentByBlockCommentHandler.getCommenter(file, editor, lineStartLanguage, lineEndLanguage);
}
项目:intellij-ce-playground    文件:PyMoveSymbolProcessor.java   
@Nullable
private PsiElement findFirstTopLevelWithUsageAtDestination() {
  final List<PsiElement> topLevelAtDestination = ContainerUtil.mapNotNull(myUsages, new Function<UsageInfo, PsiElement>() {
    @Override
    public PsiElement fun(UsageInfo usage) {
      final PsiElement element = usage.getElement();
      if (element != null && ScopeUtil.getScopeOwner(element) == myDestinationFile && getImportStatementByElement(element) == null) {
        return findTopLevelParent(element);
      }
      return null;
    }
  });
  if (topLevelAtDestination.isEmpty()) {
    return null;
  }
  return Collections.min(topLevelAtDestination, new Comparator<PsiElement>() {
    @Override
    public int compare(PsiElement e1, PsiElement e2) {
      return PsiUtilCore.compareElementsByPosition(e1, e2);
    }
  });
}
项目:intellij-ce-playground    文件:EditSourceUtil.java   
@Nullable
public static Navigatable getDescriptor(@NotNull PsiElement element) {
  PsiElement original = getNavigatableOriginalElement(element);
  if (original != null) {
    element = original;
  }
  else if (!canNavigate(element)) {
    return null;
  }
  if (element instanceof PomTargetPsiElement) {
    return ((PomTargetPsiElement)element).getTarget();
  }
  final PsiElement navigationElement = element.getNavigationElement();
  if (navigationElement instanceof PomTargetPsiElement) {
    return ((PomTargetPsiElement)navigationElement).getTarget();
  }
  final int offset = navigationElement instanceof PsiFile ? -1 : navigationElement.getTextOffset();
  final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(navigationElement);
  if (virtualFile == null || !virtualFile.isValid()) {
    return null;
  }
  OpenFileDescriptor desc = new OpenFileDescriptor(navigationElement.getProject(), virtualFile, offset);
  desc.setUseCurrentWindow(FileEditorManager.USE_CURRENT_WINDOW.isIn(navigationElement));
  return desc;
}
项目:intellij-ce-playground    文件:CoverageListNode.java   
public boolean contains(VirtualFile file) {
  final Object value = getValue();
  if (value instanceof PsiElement) {
    final boolean equalContainingFile = Comparing.equal(PsiUtilCore.getVirtualFile((PsiElement)value), file);
    if (equalContainingFile) return true;
  }
  if (value instanceof PsiDirectory) {
    return contains(file, (PsiDirectory)value);
  }
  else if (value instanceof PsiDirectoryContainer) {
    final PsiDirectory[] directories = ((PsiDirectoryContainer)value).getDirectories();
    for (PsiDirectory directory : directories) {
      if (contains(file, directory)) return true;
    }
  }
  return false;
}
项目:intellij-ce-playground    文件:JavaCompletionUtil.java   
public static void shortenReference(final PsiFile file, final int offset) throws IncorrectOperationException {
  Project project = file.getProject();
  final PsiDocumentManager manager = PsiDocumentManager.getInstance(project);
  Document document = manager.getDocument(file);
  if (document == null) {
    PsiUtilCore.ensureValid(file);
    LOG.error("No document for " + file);
    return;
  }

  manager.commitDocument(document);
  final PsiReference ref = file.findReferenceAt(offset);
  if (ref != null) {
    PsiElement element = ref.getElement();
    if (element != null) {
      JavaCodeStyleManager.getInstance(project).shortenClassReferences(element);
      PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
    }
  }
}
项目:intellij-ce-playground    文件:JavaPsiClassReferenceElement.java   
private static String getName(final PsiClass psiClass, final LookupElement item, boolean diamond, @NotNull PsiSubstitutor substitutor) {
  if (item instanceof JavaPsiClassReferenceElement) {
    String forced = ((JavaPsiClassReferenceElement)item).getForcedPresentableName();
    if (forced != null) {
      return forced;
    }
  }

  String name = PsiUtilCore.getName(psiClass);
  if (diamond) {
    return name + "<>";
  }

  if (substitutor != PsiSubstitutor.EMPTY) {
    final PsiTypeParameter[] params = psiClass.getTypeParameters();
    if (params.length > 0) {
      return name + formatTypeParameters(substitutor, params);
    }
  }

  return StringUtil.notNullize(name);
}
项目:intellij-ce-playground    文件:TestClassFilter.java   
public boolean isAccepted(final PsiClass aClass) {
  return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
    @Override
    public Boolean compute() {
      if (aClass.getQualifiedName() != null && ConfigurationUtil.PUBLIC_INSTANTIATABLE_CLASS.value(aClass) &&
          (aClass.isInheritor(myBase, true) || JUnitUtil.isTestClass(aClass))) {
        final CompilerConfiguration compilerConfiguration = CompilerConfiguration.getInstance(getProject());
        final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(aClass);
        if (virtualFile == null) return false;
        return !compilerConfiguration.isExcludedFromCompilation(virtualFile) &&
               !ProjectRootManager.getInstance(myProject).getFileIndex().isUnderSourceRootOfType(virtualFile, JavaModuleSourceRootTypes.RESOURCES);
      }
      return false;
    }
  });
}
项目:intellij-ce-playground    文件:InspectionResultsViewComparator.java   
private static int compareEntity(final RefEntity entity, final PsiElement element) {
  if (entity instanceof RefElement) {
    final PsiElement psiElement = ((RefElement)entity).getElement();
    if (psiElement != null && element != null) {
      return PsiUtilCore.compareElementsByPosition(psiElement, element);
    }
    if (element == null) return psiElement == null ? 0 : 1;
  }
  if (element instanceof PsiQualifiedNamedElement) {
    return StringUtil.compare(entity.getQualifiedName(), ((PsiQualifiedNamedElement)element).getQualifiedName(), true);
  }
  if (element instanceof PsiNamedElement) {
    return StringUtil.compare(entity.getName(), ((PsiNamedElement)element).getName(), true);
  }
  return -1;
}
项目:intellij-ce-playground    文件:CodeInsightUtilCore.java   
public static <T extends PsiElement> T forcePsiPostprocessAndRestoreElement(@NotNull T element,
                                                                            boolean useFileLanguage) {
  final PsiFile psiFile = element.getContainingFile();
  final Document document = psiFile.getViewProvider().getDocument();
  //if (document == null) return element;
  final Language language = useFileLanguage ? psiFile.getLanguage() : PsiUtilCore.getDialect(element);
  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(psiFile.getProject());
  final RangeMarker rangeMarker = document.createRangeMarker(element.getTextRange());
  documentManager.doPostponedOperationsAndUnblockDocument(document);
  documentManager.commitDocument(document);

  T elementInRange = findElementInRange(psiFile, rangeMarker.getStartOffset(), rangeMarker.getEndOffset(),
                                        (Class<? extends T>)element.getClass(),
                                        language);
  rangeMarker.dispose();
  return elementInRange;
}
项目:intellij-ce-playground    文件:ExternalAnnotationsLineMarkerProvider.java   
@Override
public void navigate(MouseEvent e, PsiElement nameIdentifier) {
  final PsiElement listOwner = nameIdentifier.getParent();
  final PsiFile containingFile = listOwner.getContainingFile();
  final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(listOwner);

  if (virtualFile != null && containingFile != null) {
    final Project project = listOwner.getProject();
    final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();

    if (editor != null) {
      editor.getCaretModel().moveToOffset(nameIdentifier.getTextOffset());
      final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());

      if (file != null && virtualFile.equals(file.getVirtualFile())) {
        final JBPopup popup = createActionGroupPopup(containingFile, project, editor);
        if (popup != null) {
          popup.show(new RelativePoint(e));
        }
      }
    }
  }
}
项目:intellij-ce-playground    文件:SPIAnnotator.java   
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
  final VirtualFile file = PsiUtilCore.getVirtualFile(element);
  if (file != null && file.getFileType() instanceof SPIFileType) {
    final String serviceProviderName = file.getName();
    final PsiClass psiClass =
      ClassUtil.findPsiClass(element.getManager(), serviceProviderName, null, true, element.getContainingFile().getResolveScope());
    if (element instanceof PsiFile) {
      if (psiClass == null) {
        holder.createErrorAnnotation(element, "No service provider \"" + serviceProviderName + "\' found").setFileLevelAnnotation(true);
      }
    } else if (element instanceof SPIClassProviderReferenceElement) {
      final PsiElement resolve = ((SPIClassProviderReferenceElement)element).resolve();
      if (resolve == null) {
        holder.createErrorAnnotation(element, "Cannot resolve symbol " + element.getText());
      } else if (resolve instanceof PsiClass && psiClass != null) {
        if (!((PsiClass)resolve).isInheritor(psiClass, true)) {
          holder.createErrorAnnotation(element, "Registered extension should implement " + serviceProviderName);
        }
      }
    }
  }
}
项目:intellij-ce-playground    文件:JavaLangClassMemberReference.java   
@Override
public void handleInsert(InsertionContext context, LookupElement item) {
  final Object object = item.getObject();
  if (object instanceof PsiMethod) {
    final PsiElement newElement = PsiUtilCore.getElementAtOffset(context.getFile(), context.getStartOffset());
    final int start = newElement.getTextRange().getEndOffset();
    final PsiElement params = newElement.getParent().getParent();
    final int end = params.getTextRange().getEndOffset() - 1;
    final String types = getMethodTypes((PsiMethod)object);
    context.getDocument().replaceString(start, end, types);
    context.commitDocument();
    final PsiElement firstParam = PsiUtilCore.getElementAtOffset(context.getFile(), context.getStartOffset());
    final PsiMethodCallExpression methodCall = PsiTreeUtil.getParentOfType(firstParam, PsiMethodCallExpression.class);
    if (methodCall != null) {
      JavaCodeStyleManager.getInstance(context.getProject()).shortenClassReferences(methodCall);
    }
  }
}
项目:intellij-ce-playground    文件:JavaFindUsagesHandler.java   
@NotNull
private static PsiElement[] getParameterElementsToSearch(@NotNull PsiParameter parameter, @NotNull PsiMethod method) {
  PsiMethod[] overrides = OverridingMethodsSearch.search(method, true).toArray(PsiMethod.EMPTY_ARRAY);
  for (int i = 0; i < overrides.length; i++) {
    final PsiElement navigationElement = overrides[i].getNavigationElement();
    if (navigationElement instanceof PsiMethod) {
      overrides[i] = (PsiMethod)navigationElement;
    }
  }
  List<PsiElement> elementsToSearch = new ArrayList<PsiElement>(overrides.length + 1);
  elementsToSearch.add(parameter);
  int idx = method.getParameterList().getParameterIndex(parameter);
  for (PsiMethod override : overrides) {
    final PsiParameter[] parameters = override.getParameterList().getParameters();
    if (idx < parameters.length) {
      elementsToSearch.add(parameters[idx]);
    }
  }
  return PsiUtilCore.toPsiElementArray(elementsToSearch);
}
项目:intellij-ce-playground    文件:PackageViewPane.java   
@Override
public void deleteElement(@NotNull DataContext dataContext) {
  List<PsiDirectory> allElements = Arrays.asList(getSelectedDirectories());
  List<PsiElement> validElements = new ArrayList<PsiElement>();
  for (PsiElement psiElement : allElements) {
    if (psiElement != null && psiElement.isValid()) validElements.add(psiElement);
  }
  final PsiElement[] elements = PsiUtilCore.toPsiElementArray(validElements);

  LocalHistoryAction a = LocalHistory.getInstance().startAction(IdeBundle.message("progress.deleting"));
  try {
    DeleteHandler.deletePsiElement(elements, myProject);
  }
  finally {
    a.finish();
  }
}
项目:intellij-ce-playground    文件:RenameJavaClassProcessor.java   
public void findExistingNameConflicts(final PsiElement element, final String newName, final MultiMap<PsiElement,String> conflicts) {
  if (element instanceof PsiCompiledElement) return;
  final PsiClass aClass = (PsiClass)element;
  if (newName.equals(aClass.getName())) return;
  final PsiClass containingClass = aClass.getContainingClass();
  if (containingClass != null) { // innerClass
    PsiClass[] innerClasses = containingClass.getInnerClasses();
    for (PsiClass innerClass : innerClasses) {
      if (newName.equals(innerClass.getName())) {
        conflicts.putValue(innerClass, RefactoringBundle.message("inner.class.0.is.already.defined.in.class.1", newName, containingClass.getQualifiedName()));
        break;
      }
    }
  }
  else if (!(aClass instanceof PsiTypeParameter)) {
    final String qualifiedNameAfterRename = PsiUtilCore.getQualifiedNameAfterRename(aClass.getQualifiedName(), newName);
    Project project = element.getProject();
    final PsiClass conflictingClass =
      JavaPsiFacade.getInstance(project).findClass(qualifiedNameAfterRename, GlobalSearchScope.allScope(project));
    if (conflictingClass != null) {
      conflicts.putValue(conflictingClass, RefactoringBundle.message("class.0.already.exists", qualifiedNameAfterRename));
    }
  }
}
项目:intellij-ce-playground    文件:CodeDocumentationUtil.java   
/**
 * Analyzes position at the given offset at the given text and returns information about comments presence and kind there if any.
 * 
 * @param file              target file being edited (necessary for language recognition at target offset. Language is necessary
 *                          to get information about specific comment syntax)
 * @param chars             target text
 * @param offset            target offset at the given text
 * @param lineStartOffset   start offset of the line that contains given offset
 * @return                  object that encapsulates information about comments at the given offset at the given text
 */
@NotNull
public static CommentContext tryParseCommentContext(@NotNull PsiFile file, @NotNull CharSequence chars, int offset, int lineStartOffset) {
  Commenter langCommenter = LanguageCommenters.INSTANCE.forLanguage(PsiUtilCore.getLanguageAtOffset(file, offset));
  final boolean isInsideCommentLikeCode = langCommenter instanceof CodeDocumentationAwareCommenter;
  if (!isInsideCommentLikeCode) {
    return new CommentContext();
  }
  final CodeDocumentationAwareCommenter commenter = (CodeDocumentationAwareCommenter)langCommenter;
  int commentStartOffset = CharArrayUtil.shiftForward(chars, lineStartOffset, " \t");

  boolean docStart = commenter.getDocumentationCommentPrefix() != null
                     && CharArrayUtil.regionMatches(chars, commentStartOffset, commenter.getDocumentationCommentPrefix());
  boolean cStyleStart = commenter.getBlockCommentPrefix() != null
                        && CharArrayUtil.regionMatches(chars, commentStartOffset, commenter.getBlockCommentPrefix());
  boolean docAsterisk = commenter.getDocumentationCommentLinePrefix() != null
                        && CharArrayUtil.regionMatches(chars, commentStartOffset, commenter.getDocumentationCommentLinePrefix());
  final int firstNonSpaceInLine = CharArrayUtil.shiftForward(chars, offset, " \t");
  boolean slashSlash = commenter.getLineCommentPrefix() != null
                       && CharArrayUtil.regionMatches(chars, commentStartOffset, commenter.getLineCommentPrefix())
                       && firstNonSpaceInLine < chars.length() && chars.charAt(firstNonSpaceInLine) != '\n';
  return new CommentContext(commenter, docStart, cStyleStart, docAsterisk, slashSlash, commentStartOffset);
}
项目:intellij-ce-playground    文件:UsageScopeGroupingRule.java   
@Override
public UsageGroup groupUsage(@NotNull Usage usage) {
  if (!(usage instanceof PsiElementUsage)) {
    return null;
  }
  PsiElementUsage elementUsage = (PsiElementUsage)usage;

  PsiElement element = elementUsage.getElement();
  VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element);

  if (virtualFile == null) {
    return null;
  }
  ProjectFileIndex fileIndex = ProjectRootManager.getInstance(element.getProject()).getFileIndex();
  boolean isInLib = fileIndex.isInLibraryClasses(virtualFile) || fileIndex.isInLibrarySource(virtualFile);
  if (isInLib) return LIBRARY;
  boolean isInTest = fileIndex.isInTestSourceContent(virtualFile);
  return isInTest ? TEST : PRODUCTION;
}
项目:intellij-ce-playground    文件:CommanderPanel.java   
@Override
public void selectElement(final PsiElement element) {
  final boolean isDirectory = element instanceof PsiDirectory;
  if (!isDirectory) {
    EditorHelper.openInEditor(element);
  }
  ApplicationManager.getApplication().invokeLater(new Runnable() {
    @Override
    public void run() {
      myBuilder.selectElement(element, PsiUtilCore.getVirtualFile(element));
      if (!isDirectory) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
          @Override
          public void run() {
            if (myMoveFocus) {
              ToolWindowManager.getInstance(myProject).activateEditorComponent();
            }
          }
        });
      }
    }
  }, ModalityState.NON_MODAL);
}
项目:intellij-ce-playground    文件:CodeCompletionHandlerBase.java   
private static boolean shouldSkipAutoPopup(Editor editor, PsiFile psiFile) {
  int offset = editor.getCaretModel().getOffset();
  int psiOffset = Math.max(0, offset - 1);

  PsiElement elementAt = InjectedLanguageUtil.findInjectedElementNoCommit(psiFile, psiOffset);
  if (elementAt == null) {
    elementAt = psiFile.findElementAt(psiOffset);
  }
  if (elementAt == null) return true;

  Language language = PsiUtilCore.findLanguageFromElement(elementAt);

  for (CompletionConfidence confidence : CompletionConfidenceEP.forLanguage(language)) {
    final ThreeState result = confidence.shouldSkipAutopopup(elementAt, psiFile, offset);
    if (result != ThreeState.UNSURE) {
      LOG.debug(confidence + " has returned shouldSkipAutopopup=" + result);
      return result == ThreeState.YES;
    }
  }
  return false;
}
项目:intellij-ce-playground    文件:FileAssociationsManagerImpl.java   
public PsiFile[] getAssociationsFor(PsiFile file, FileType... fileTypes) {
  final VirtualFile virtualFile = file.getVirtualFile();
  if (virtualFile == null) return PsiFile.EMPTY_ARRAY;

  for (VirtualFilePointer pointer : myAssociations.keySet()) {
    if (pointer.isValid() && pointer.getUrl().equals(virtualFile.getUrl())) {
      final VirtualFilePointerContainer container = myAssociations.get(pointer);
      if (container != null) {
        final VirtualFile[] files = container.getFiles();
        final Set<PsiFile> list = new HashSet<PsiFile>();
        final PsiManager psiManager = PsiManager.getInstance(myProject);
        for (VirtualFile assoc : files) {
          final PsiFile psiFile = psiManager.findFile(assoc);
          if (psiFile != null && (fileTypes.length == 0 || matchesFileType(psiFile, fileTypes))) {
            list.add(psiFile);
          }
        }
        return PsiUtilCore.toPsiFileArray(list);
      }
      else {
        return PsiFile.EMPTY_ARRAY;
      }
    }
  }
  return PsiFile.EMPTY_ARRAY;
}
项目:intellij-ce-playground    文件:DefaultNavBarExtension.java   
private static boolean processChildren(final PsiDirectory object, final Object rootElement, final Processor<Object> processor) {
  return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
    @Override
    public Boolean compute() {
      final ModuleFileIndex moduleFileIndex =
        rootElement instanceof Module ? ModuleRootManager.getInstance((Module)rootElement).getFileIndex() : null;
      final PsiElement[] children = object.getChildren();
      for (PsiElement child : children) {
        if (child != null && child.isValid()) {
          if (moduleFileIndex != null) {
            final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(child);
            if (virtualFile != null && !moduleFileIndex.isInContent(virtualFile)) continue;
          }
          if (!processor.process(child)) return false;
        }
      }
      return true;
    }
  });
}
项目:intellij-ce-playground    文件:TypeOrElementOrAttributeReference.java   
@Override
@Nullable
public PsiElement resolve() {
  final PsiElement psiElement = ResolveCache
    .getInstance(getElement().getProject()).resolveWithCaching(this, MyResolver.INSTANCE, false, false);

  return psiElement != PsiUtilCore.NULL_PSI_ELEMENT ? psiElement:null;
}
项目:intellij-ce-playground    文件:JavaFileManagerImpl.java   
@NotNull
@Override
public PsiClass[] findClasses(@NotNull String qName, @NotNull final GlobalSearchScope scope) {
  final Collection<PsiClass> classes = JavaFullClassNameIndex.getInstance().get(qName.hashCode(), myManager.getProject(), scope);
  if (classes.isEmpty()) return PsiClass.EMPTY_ARRAY;
  List<PsiClass> result = new ArrayList<PsiClass>(classes.size());
  for (PsiClass aClass : classes) {
    final String qualifiedName = aClass.getQualifiedName();
    if (qualifiedName == null || !qualifiedName.equals(qName)) continue;

    PsiUtilCore.ensureValid(aClass);
    PsiFile file = aClass.getContainingFile();
    if (file == null) {
      throw new AssertionError("No file for class: " + aClass + " of " + aClass.getClass());
    }

    VirtualFile vFile = file.getVirtualFile();
    if (!hasAcceptablePackage(vFile)) continue;

    result.add(aClass);
  }

  int count = result.size();
  if (count == 0) return PsiClass.EMPTY_ARRAY;
  if (count == 1) return new PsiClass[] {result.get(0)};

  ContainerUtil.quickSort(result, new Comparator<PsiClass>() {
    @Override
    public int compare(PsiClass o1, PsiClass o2) {
      return scope.compare(o2.getContainingFile().getVirtualFile(), o1.getContainingFile().getVirtualFile());
    }
  });

  return result.toArray(new PsiClass[count]);
}
项目:intellij-ce-playground    文件:BraceHighlightingHandler.java   
private void showScopeHint(final int lbraceStart, final int lbraceEnd) {
  LogicalPosition bracePosition = myEditor.offsetToLogicalPosition(lbraceStart);
  Point braceLocation = myEditor.logicalPositionToXY(bracePosition);
  final int y = braceLocation.y;
  myAlarm.addRequest(
      new Runnable() {
        @Override
        public void run() {
          if (!myEditor.getComponent().isShowing()) return;
          Rectangle viewRect = myEditor.getScrollingModel().getVisibleArea();
          if (y < viewRect.y) {
            int start = lbraceStart;
            if (!(myPsiFile instanceof PsiPlainTextFile) && myPsiFile.isValid()) {
              PsiDocumentManager.getInstance(myProject).commitAllDocuments();
              start = BraceMatchingUtil.getBraceMatcher(getFileTypeByOffset(lbraceStart), PsiUtilCore
                .getLanguageAtOffset(myPsiFile, lbraceStart)).getCodeConstructStart(myPsiFile, lbraceStart);
            }
            TextRange range = new TextRange(start, lbraceEnd);
            int line1 = myDocument.getLineNumber(range.getStartOffset());
            int line2 = myDocument.getLineNumber(range.getEndOffset());
            line1 = Math.max(line1, line2 - 5);
            range = new TextRange(myDocument.getLineStartOffset(line1), range.getEndOffset());
            LightweightHint hint = EditorFragmentComponent.showEditorFragmentHint(myEditor, range, true, true);
            myEditor.putUserData(HINT_IN_EDITOR_KEY, hint);
          }
        }
      },
      300, ModalityState.stateForComponent(myEditor.getComponent()));
}
项目:intellij-ce-playground    文件:PsiElementFinderImpl.java   
@Override
@NotNull
public PsiClass[] getClasses(@Nullable String shortName, @NotNull PsiPackage psiPackage, @NotNull final GlobalSearchScope scope) {
  List<PsiClass> list = null;
  String packageName = psiPackage.getQualifiedName();
  for (PsiDirectory dir : psiPackage.getDirectories(scope)) {
    PsiClass[] classes = JavaDirectoryService.getInstance().getClasses(dir);
    if (classes.length == 0) continue;
    if (list == null) list = new ArrayList<PsiClass>();
    for (PsiClass aClass : classes) {
      // class file can be located in wrong place inside file system
      String qualifiedName = aClass.getQualifiedName();
      if (qualifiedName != null) qualifiedName = StringUtil.getPackageName(qualifiedName);
      if (Comparing.strEqual(qualifiedName, packageName)) {
        if (shortName == null || shortName.equals(aClass.getName())) list.add(aClass);
      }
    }
  }
  if (list == null) {
    return PsiClass.EMPTY_ARRAY;
  }

  if (list.size() > 1) {
    ContainerUtil.quickSort(list, new Comparator<PsiClass>() {
      @Override
      public int compare(PsiClass o1, PsiClass o2) {
        VirtualFile file1 = PsiUtilCore.getVirtualFile(o1);
        VirtualFile file2 = PsiUtilCore.getVirtualFile(o2);
        return file1 == null ? file2 == null ? 0 : -1 : file2 == null ? 1 : scope.compare(file2, file1);
      }
    });
  }

  return list.toArray(new PsiClass[list.size()]);
}
项目:intellij-ce-playground    文件:ShowImplementationsAction.java   
@NotNull
private static PsiElement[] filterElements(@NotNull final PsiElement[] targetElements) {
  final Set<PsiElement> unique = new LinkedHashSet<PsiElement>(Arrays.asList(targetElements));
  for (final PsiElement elt : targetElements) {
    ApplicationManager.getApplication().runReadAction(new Runnable() {
      @Override
      public void run() {
        final PsiFile containingFile = elt.getContainingFile();
        LOG.assertTrue(containingFile != null, elt);
        PsiFile psiFile = containingFile.getOriginalFile();
        if (psiFile.getVirtualFile() == null) unique.remove(elt);
      }
    });
  }
  // special case for Python (PY-237)
  // if the definition is the tree parent of the target element, filter out the target element
  for (int i = 1; i < targetElements.length; i++) {
    final PsiElement targetElement = targetElements[i];
    if (ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
      @Override
      public Boolean compute() {
        return PsiTreeUtil.isAncestor(targetElement, targetElements[0], true);
      }
    })) {
      unique.remove(targetElements[0]);
      break;
    }
  }
  return PsiUtilCore.toPsiElementArray(unique);
}
项目:intellij-ce-playground    文件:ClsClassImpl.java   
@Override
@NotNull
public PsiElement[] getChildren() {
  List<PsiElement> children = ContainerUtil.newArrayList();
  ContainerUtil.addAll(children, getChildren(getDocComment(), getModifierList(), getNameIdentifier(), getExtendsList(), getImplementsList()));
  ContainerUtil.addAll(children, getOwnFields());
  ContainerUtil.addAll(children, getOwnMethods());
  ContainerUtil.addAll(children, getOwnInnerClasses());
  return PsiUtilCore.toPsiElementArray(children);
}
项目:intellij-ce-playground    文件:CompletionData.java   
public static LookupElement objectToLookupItem(final @NotNull Object object) {
  if (object instanceof LookupElement) return (LookupElement)object;

  String s = null;
  TailType tailType = TailType.NONE;
  if (object instanceof PsiElement){
    s = PsiUtilCore.getName((PsiElement)object);
  }
  else if (object instanceof PsiMetaData) {
    s = ((PsiMetaData)object).getName();
  }
  else if (object instanceof String) {
    s = (String)object;
  }
  else if (object instanceof Template) {
    s = ((Template) object).getKey();
  }
  else if (object instanceof PresentableLookupValue) {
    s = ((PresentableLookupValue)object).getPresentation();
  }
  if (s == null) {
    throw new AssertionError("Null string for object: " + object + " of class " + object.getClass());
  }

  LookupItem item = new LookupItem(object, s);

  if (object instanceof LookupValueWithUIHint && ((LookupValueWithUIHint) object).isBold()) {
    item.setBold();
  }
  item.setAttribute(LookupItem.TAIL_TYPE_ATTR, tailType);
  return item;
}
项目:intellij-ce-playground    文件:PsiImportStatementBaseImpl.java   
@Override
public PsiJavaCodeReferenceElement getImportReference() {
  PsiUtilCore.ensureValid(this);
  final PsiImportStatementStub stub = getStub();
  if (stub != null) {
    return stub.getReference();
  }
  return (PsiJavaCodeReferenceElement)calcTreeElement().findChildByRoleAsPsiElement(ChildRole.IMPORT_REFERENCE);
}
项目:intellij-ce-playground    文件:ThumbnailViewUI.java   
@NotNull
private PsiElement[] getSelectedElements() {
    VirtualFile[] selectedFiles = getSelectedFiles();
    Set<PsiElement> psiElements = new HashSet<PsiElement>(selectedFiles.length);
    PsiManager psiManager = PsiManager.getInstance(thumbnailView.getProject());
    for (VirtualFile file : selectedFiles) {
        PsiFile psiFile = psiManager.findFile(file);
        PsiElement element = psiFile != null ? psiFile : psiManager.findDirectory(file);
        if (element != null) {
            psiElements.add(element);
        }
    }
  return PsiUtilCore.toPsiElementArray(psiElements);
}
项目:intellij-ce-playground    文件:XmlCopyPastePreProcessor.java   
@Override
@NotNull
public String preprocessOnPaste(Project project, PsiFile file, Editor editor, String text, RawText rawText) {
  final Document document = editor.getDocument();
  PsiDocumentManager.getInstance(project).commitDocument(document);
  int caretOffset = editor.getCaretModel().getOffset();
  PsiElement element = PsiUtilCore.getElementAtOffset(file, caretOffset);

  ASTNode node = element.getNode();
  if (node != null) {
    boolean hasMarkup = text.indexOf('>') >= 0 || text.indexOf('<') >= 0;
    if (element.getTextOffset() == caretOffset &&
        node.getElementType() == XmlTokenType.XML_END_TAG_START &&
        node.getTreePrev().getElementType() == XmlTokenType.XML_TAG_END) {

       return hasMarkup ? text : encode(text, element);
    } else {
      XmlElement parent = PsiTreeUtil.getParentOfType(element, XmlText.class, XmlAttributeValue.class);
      if (parent != null) {
        if (parent instanceof XmlText && hasMarkup) {
          return text;
        }

        if (TreeUtil.findParent(node, XmlElementType.XML_CDATA) == null &&
            TreeUtil.findParent(node, XmlElementType.XML_COMMENT) == null) {
          return encode(text, element);
        }
      }
    }
  }
  return text;
}
项目:intellij-ce-playground    文件:MethodReferencesSearch.java   
public SearchParameters(@NotNull PsiMethod method, @NotNull SearchScope scope, boolean strictSignatureSearch, @Nullable SearchRequestCollector optimizer) {
  myMethod = method;
  myScope = scope;
  myStrictSignatureSearch = strictSignatureSearch;
  isSharedOptimizer = optimizer != null;
  myOptimizer = optimizer != null ? optimizer : new SearchRequestCollector(new SearchSession());
  myProject = PsiUtilCore.getProjectInReadAction(method);
}
项目:intellij-ce-playground    文件:InspectionResultsViewComparator.java   
private static int compareEntities(final RefEntity entity1, final RefEntity entity2) {
  if (entity1 instanceof RefElement && entity2 instanceof RefElement) {
    return PsiUtilCore.compareElementsByPosition(((RefElement)entity1).getElement(), ((RefElement)entity2).getElement());
  }
  if (entity1 != null && entity2 != null) {
    return entity1.getName().compareToIgnoreCase(entity2.getName());
  }
  if (entity1 != null) return -1;
  return entity2 != null ? 1 : 0;
}
项目:intellij-ce-playground    文件:PsiDocumentManagerBase.java   
@Nullable
@Override
public Document getDocument(@NotNull PsiFile file) {
  if (file instanceof PsiBinaryFile) return null;

  Document document = getCachedDocument(file);
  if (document != null) {
    if (!file.getViewProvider().isPhysical() && document.getUserData(HARD_REF_TO_PSI) == null) {
      PsiUtilCore.ensureValid(file);
      cachePsi(document, file);
    }
    return document;
  }

  FileViewProvider viewProvider = file.getViewProvider();
  if (!viewProvider.isEventSystemEnabled()) return null;

  document = FileDocumentManager.getInstance().getDocument(viewProvider.getVirtualFile());
  if (document != null) {
    if (document.getTextLength() != file.getTextLength()) {
      String message = "Document/PSI mismatch: " + file + " (" + file.getClass() + "); physical=" + viewProvider.isPhysical();
      if (document.getTextLength() + file.getTextLength() < 8096) {
        message += "\n=== document ===\n" + document.getText() + "\n=== PSI ===\n" + file.getText();
      }
      throw new AssertionError(message);
    }

    if (!viewProvider.isPhysical()) {
      PsiUtilCore.ensureValid(file);
      cachePsi(document, file);
      file.putUserData(HARD_REF_TO_DOCUMENT, document);
    }
  }

  return document;
}
项目:intellij-ce-playground    文件:TestDataLineMarkerProvider.java   
public Info getInfo(@NotNull PsiElement e) {

    PsiElement element = e.getParent();
    if (!(e instanceof PsiIdentifier) ||
        !(element instanceof PsiMethod) &&
        !(element instanceof PsiClass)) {
      return null;
    }

    if (DumbService.isDumb(element.getProject()) || !PsiUtil.isPluginProject(element.getProject())) {
      return null;
    }

    final VirtualFile file = PsiUtilCore.getVirtualFile(element);
    if (file == null || !ProjectFileIndex.SERVICE.getInstance(element.getProject()).isInTestSourceContent(file)) {
      return null;
    }
    if (element instanceof PsiMethod) {
      return new Info(ActionManager.getInstance().getAction("TestData.Navigate"));
    } else {
      final PsiClass psiClass = (PsiClass)element;
      final String basePath = getTestDataBasePath(psiClass);
      if (basePath != null) {
        return new Info(new GotoTestDataAction(basePath, psiClass.getProject(), AllIcons.Nodes.Folder));
      }
    }
    return null;
  }