com.intellij.psi.SmartPsiElementPointer Java Examples

The following examples show how to use com.intellij.psi.SmartPsiElementPointer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: QueryToXMLConverter.java    From dbunit-extractor with MIT License 6 votes vote down vote up
@Override
public boolean isAvailable(@NotNull final Project project,
                           final Editor editor,
                           @NotNull final PsiElement psiElement) {
    final boolean isDataSetFile;
    if (editor instanceof EditorWindow) {
        isDataSetFile = ((EditorWindow) editor).getDelegate()
                                               .getDocument()
                                               .getText()
                                               .startsWith("<dataset>");
    } else {
        isDataSetFile = editor.getDocument().getText().startsWith("<dataset>");
    }
    SmartPsiElementPointer<SqlSelectStatement> pointer = getNearestPointer(project, psiElement);
    final String selectedText = editor.getSelectionModel().getSelectedText();
    final boolean hasSelectedQuery = editor.getSelectionModel().hasSelection() && selectedText.trim().toUpperCase().startsWith("SELECT");
    return isDataSetFile && (hasSelectedQuery || pointer != null);
}
 
Example #2
Source File: ElementCreator.java    From consulo with Apache License 2.0 6 votes vote down vote up
public PsiElement[] tryCreate(@Nonnull final String inputString) {
  if (inputString.length() == 0) {
    Messages.showMessageDialog(myProject, IdeBundle.message("error.name.should.be.specified"), CommonBundle.getErrorTitle(), Messages.getErrorIcon());
    return PsiElement.EMPTY_ARRAY;
  }

  Ref<List<SmartPsiElementPointer>> createdElements = Ref.create();
  Exception exception = executeCommand(getActionName(inputString), () -> {
    PsiElement[] psiElements = create(inputString);
    SmartPointerManager manager = SmartPointerManager.getInstance(myProject);
    createdElements.set(ContainerUtil.map(psiElements, manager::createSmartPsiElementPointer));
  });
  if (exception != null) {
    handleException(exception);
    return PsiElement.EMPTY_ARRAY;
  }

  return ContainerUtil.mapNotNull(createdElements.get(), SmartPsiElementPointer::getElement).toArray(PsiElement.EMPTY_ARRAY);
}
 
Example #3
Source File: LookupElement.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * @return a PSI element associated with this lookup element. It's used for navigation, showing quick documentation and sorting by proximity to the current location.
 * The default implementation tries to extract PSI element from {@link #getObject()} result.
 */
@Nullable
public PsiElement getPsiElement() {
  Object o = getObject();
  if (o instanceof PsiElement) {
    return (PsiElement)o;
  }
  if (o instanceof ResolveResult) {
    return ((ResolveResult)o).getElement();
  }
  if (o instanceof PsiElementNavigationItem) {
    return ((PsiElementNavigationItem)o).getTargetElement();
  }
  if (o instanceof SmartPsiElementPointer) {
    return ((SmartPsiElementPointer)o).getElement();
  }
  return null;
}
 
Example #4
Source File: UsageInfoToUsageConverter.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public List<SmartPsiElementPointer<PsiElement>> getAllElementPointers() {
  List<SmartPsiElementPointer<PsiElement>> result = new ArrayList<SmartPsiElementPointer<PsiElement>>(myPrimarySearchedElements.size() + myAdditionalSearchedElements.size());
  result.addAll(myPrimarySearchedElements);
  result.addAll(myAdditionalSearchedElements);
  return result;
}
 
Example #5
Source File: NavigationGutterIconBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
public MyNavigationGutterIconRenderer(@Nonnull NavigationGutterIconBuilder builder,
                                      final Alignment alignment,
                                      final Image icon,
                                      @Nullable final String tooltipText,
                                      @Nonnull NotNullLazyValue<List<SmartPsiElementPointer>> pointers,
                                      Computable<PsiElementListCellRenderer> cellRenderer,
                                      boolean empty) {
  super(builder.myPopupTitle, builder.myEmptyText, cellRenderer, pointers);
  myAlignment = alignment;
  myIcon = icon;
  myTooltipText = tooltipText;
  myEmpty = empty;
}
 
Example #6
Source File: NavigationGutterIconRenderer.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected NavigationGutterIconRenderer(final String popupTitle, final String emptyText, @Nonnull Computable<PsiElementListCellRenderer> cellRenderer,
  @Nonnull NotNullLazyValue<List<SmartPsiElementPointer>> pointers) {
  myPopupTitle = popupTitle;
  myEmptyText = emptyText;
  myCellRenderer = cellRenderer;
  myPointers = pointers;
}
 
Example #7
Source File: DocumentationComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
Context(SmartPsiElementPointer<PsiElement> element, String text, String externalUrl, DocumentationProvider provider, Rectangle viewRect, int highlightedLink) {
  this.element = element;
  this.text = text;
  this.externalUrl = externalUrl;
  this.provider = provider;
  this.viewRect = viewRect;
  this.highlightedLink = highlightedLink;
}
 
Example #8
Source File: DocumentationComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
protected Navigatable[] getNavigatables(DataContext dataContext) {
  SmartPsiElementPointer<PsiElement> element = myElement;
  if (element != null) {
    PsiElement psiElement = element.getElement();
    return psiElement instanceof Navigatable ? new Navigatable[]{(Navigatable)psiElement} : null;
  }
  return null;
}
 
Example #9
Source File: DocumentationComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void setDataInternal(@Nullable SmartPsiElementPointer<PsiElement> element, @Nonnull String text, @Nonnull Rectangle viewRect, @Nullable String ref) {
  myIsEmpty = false;
  if (myManager == null) return;

  myText = text;
  setElement(element);
  myDecoratedText = decorate(text);

  showHint(viewRect, ref);
}
 
Example #10
Source File: DocumentationComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void setData(@Nullable PsiElement element, @Nonnull String text, @Nullable String effectiveExternalUrl, @Nullable String ref, @Nullable DocumentationProvider provider) {
  pushHistory();
  myExternalUrl = effectiveExternalUrl;
  myProvider = provider;

  SmartPsiElementPointer<PsiElement> pointer = null;
  if (element != null && element.isValid()) {
    pointer = SmartPointerManager.getInstance(element.getProject()).createSmartPsiElementPointer(element);
  }
  setDataInternal(pointer, text, new Rectangle(0, 0), ref);
}
 
Example #11
Source File: NavigationGutterIconRenderer.java    From consulo with Apache License 2.0 5 votes vote down vote up
public List<PsiElement> getTargetElements() {
  return ContainerUtil.mapNotNull(myPointers.getValue(), new NullableFunction<SmartPsiElementPointer, PsiElement>() {
    public PsiElement fun(final SmartPsiElementPointer smartPsiElementPointer) {
      return smartPsiElementPointer.getElement();
    }
  });
}
 
Example #12
Source File: ExtractMethodPanel.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
/**
 * Opens definition of method and highlights statements, which should be extracted.
 *
 * @param sourceMethod method from which code is proposed to be extracted into separate method.
 * @param scope        scope of the current project.
 * @param slice        computation slice.
 */
private static void openDefinition(@Nullable PsiMethod sourceMethod, AnalysisScope scope, ASTSlice slice) {
    new Task.Backgroundable(scope.getProject(), "Search Definition") {
        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            indicator.setIndeterminate(true);
        }

        @Override
        public void onSuccess() {
            if (sourceMethod != null) {
                Set<SmartPsiElementPointer<PsiElement>> statements = slice.getSliceStatements();
                PsiStatement psiStatement = (PsiStatement) statements.iterator().next().getElement();
                if (psiStatement != null && psiStatement.isValid()) {
                    EditorHelper.openInEditor(psiStatement);
                    Editor editor = FileEditorManager.getInstance(sourceMethod.getProject()).getSelectedTextEditor();
                    if (editor != null) {
                        TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
                        editor.getMarkupModel().removeAllHighlighters();
                        statements.stream()
                                .filter(statement -> statement.getElement() != null)
                                .forEach(statement ->
                                        editor.getMarkupModel().addRangeHighlighter(statement.getElement().getTextRange().getStartOffset(),
                                                statement.getElement().getTextRange().getEndOffset(), HighlighterLayer.SELECTION,
                                                attributes, HighlighterTargetArea.EXACT_RANGE));
                    }
                }
            }
        }
    }.queue();
}
 
Example #13
Source File: SmartRefElementPointerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private String getContainingFileName(RefElement ref) {
  SmartPsiElementPointer pointer = ref.getPointer();
  if (pointer == null) return null;
  PsiFile file = pointer.getContainingFile();
  if (file == null) return null;
  return file.getName();
}
 
Example #14
Source File: EditorFoldingInfo.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public PsiElement getPsiElement(@Nonnull FoldRegion region) {
  final SmartPsiElementPointer<?> pointer = myFoldRegionToSmartPointerMap.get(region);
  if (pointer == null) {
    return null;
  }
  PsiElement element = pointer.getElement();
  return element != null && element.isValid() ? element : null;
}
 
Example #15
Source File: UsageInfoToUsageConverter.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static List<SmartPsiElementPointer<PsiElement>> convertToSmartPointers(@Nonnull PsiElement[] primaryElements) {
  if (primaryElements.length == 0) return Collections.emptyList();

  final SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(primaryElements[0].getProject());
  return ContainerUtil.mapNotNull(primaryElements, new Function<PsiElement, SmartPsiElementPointer<PsiElement>>() {
    @Override
    public SmartPsiElementPointer<PsiElement> fun(final PsiElement s) {
      return smartPointerManager.createSmartPsiElementPointer(s);
    }
  });
}
 
Example #16
Source File: FavoritesTreeNodeDescriptor.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static String getLocation(final AbstractTreeNode element, final Project project) {
  Object nodeElement = element.getValue();
  if (nodeElement instanceof SmartPsiElementPointer) {
    nodeElement = ((SmartPsiElementPointer)nodeElement).getElement();
  }
  if (nodeElement instanceof PsiElement) {
    if (nodeElement instanceof PsiDirectory) {
      return ((PsiDirectory)nodeElement).getVirtualFile().getPresentableUrl();
    }
    if (nodeElement instanceof PsiFile) {
      final PsiFile containingFile = (PsiFile)nodeElement;
      final VirtualFile virtualFile = containingFile.getVirtualFile();
      return virtualFile != null ? virtualFile.getPresentableUrl() : "";
    }
  }

  if (nodeElement instanceof LibraryGroupElement) {
    return ((LibraryGroupElement)nodeElement).getModule().getName();
  }
  if (nodeElement instanceof NamedLibraryElement) {
    final NamedLibraryElement namedLibraryElement = ((NamedLibraryElement)nodeElement);
    final Module module = namedLibraryElement.getModule();
    return (module != null ? module.getName() : "") + ":" + namedLibraryElement.getOrderEntry().getPresentableName();
  }

  final FavoriteNodeProvider[] nodeProviders = Extensions.getExtensions(FavoriteNodeProvider.EP_NAME, project);
  for (FavoriteNodeProvider provider : nodeProviders) {
    String location = provider.getElementLocation(nodeElement);
    if (location != null) return location;
  }
  return null;
}
 
Example #17
Source File: QueryToXMLConverter.java    From dbunit-extractor with MIT License 5 votes vote down vote up
@Nullable
private SmartPsiElementPointer<SqlSelectStatement> getStatementPointer(final @NotNull Project project,
                                                                       final @NotNull PsiElement psiElement) {
    final SqlSelectStatement sqlSelectStatement =
            PsiTreeUtil.getParentOfType(psiElement.getContainingFile().findElementAt(psiElement.getTextOffset()),
                                        SqlSelectStatement.class);
    SmartPsiElementPointer<SqlSelectStatement> pointer = null;
    if (sqlSelectStatement != null) {
        pointer = SmartPointerManager.getInstance(project)
                                     .createSmartPsiElementPointer(sqlSelectStatement);
    }
    return pointer;
}
 
Example #18
Source File: QueryToXMLConverter.java    From dbunit-extractor with MIT License 5 votes vote down vote up
private SmartPsiElementPointer<SqlSelectStatement> getNearestPointer(final @NotNull Project project,
                                                                     final @NotNull PsiElement psiElement) {
    SmartPsiElementPointer<SqlSelectStatement> pointer = getStatementPointer(project, psiElement);
    if (pointer == null && psiElement.getPrevSibling() != null) {
        pointer = getStatementPointer(project, psiElement.getPrevSibling());
    }
    if (pointer == null && psiElement.getPrevSibling() != null) {
        final String prevText = psiElement.getPrevSibling().getText();
        if ((prevText.equals(";") || prevText.isEmpty()) && psiElement.getPrevSibling().getPrevSibling() != null) {
            pointer = getStatementPointer(project, psiElement.getPrevSibling().getPrevSibling());
        }
    }
    return pointer;
}
 
Example #19
Source File: PsiTreeAnchorizer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public Object retrieveElement(@Nonnull final Object pointer) {
  if (pointer instanceof SmartPsiElementPointer) {
    return ReadAction.compute(() -> ((SmartPsiElementPointer)pointer).getElement());
  }

  return super.retrieveElement(pointer);
}
 
Example #20
Source File: BlazeCoverageProjectViewClassDecorator.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
private static PsiElement getPsiElement(@SuppressWarnings("rawtypes") AbstractTreeNode node) {
  Object value = node.getValue();
  if (value instanceof PsiElement) {
    return (PsiElement) value;
  }
  if (value instanceof SmartPsiElementPointer) {
    return ((SmartPsiElementPointer) value).getElement();
  }
  return null;
}
 
Example #21
Source File: PsiTreeAnchorizer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void freeAnchor(final Object element) {
  if (element instanceof SmartPsiElementPointer) {
    ApplicationManager.getApplication().runReadAction(() -> {
      SmartPsiElementPointer pointer = (SmartPsiElementPointer)element;
      Project project = pointer.getProject();
      if (!project.isDisposed()) {
        SmartPointerManager.getInstance(project).removePointer(pointer);
      }
    });
  }
}
 
Example #22
Source File: FileContextUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
public static PsiElement getFileContext(@Nonnull PsiFile file) {
  SmartPsiElementPointer pointer = file.getUserData(INJECTED_IN_ELEMENT);
  return pointer == null ? null : pointer.getElement();
}
 
Example #23
Source File: EditorFoldingInfo.java    From consulo with Apache License 2.0 4 votes vote down vote up
void addRegion(@Nonnull FoldRegion region, @Nonnull SmartPsiElementPointer<?> pointer){
  myFoldRegionToSmartPointerMap.put(region, pointer);
}
 
Example #24
Source File: Place.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public SmartPsiElementPointer<PsiLanguageInjectionHost> getHostPointer() {
  return ((ShredImpl)get(0)).getSmartPointer();
}
 
Example #25
Source File: FavoritesTreeStructure.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public Object[] getChildElements(Object element) {
  if (!(element instanceof AbstractTreeNode)) {
    return ArrayUtil.EMPTY_OBJECT_ARRAY;
  }

  final AbstractTreeNode favTreeElement = (AbstractTreeNode)element;
  try {
    if (!(element instanceof FavoritesListNode)) {
      return super.getChildElements(favTreeElement);
    }

    final List<AbstractTreeNode> result = new ArrayList<AbstractTreeNode>();
    final FavoritesListNode listNode = (FavoritesListNode)element;
    if (listNode.getProvider() != null) {
      return ArrayUtil.toObjectArray(listNode.getChildren());
    }
    final Collection<AbstractTreeNode> roots = FavoritesListNode.getFavoritesRoots(myProject, listNode.getName(), listNode);
    for (AbstractTreeNode<?> abstractTreeNode : roots) {
      final Object value = abstractTreeNode.getValue();

      if (value == null) continue;
      if (value instanceof PsiElement && !((PsiElement)value).isValid()) continue;
      if (value instanceof SmartPsiElementPointer && ((SmartPsiElementPointer)value).getElement() == null) continue;

      boolean invalid = false;
      for (FavoriteNodeProvider nodeProvider : Extensions.getExtensions(FavoriteNodeProvider.EP_NAME, myProject)) {
        if (nodeProvider.isInvalidElement(value)) {
          invalid = true;
          break;
        }
      }
      if (invalid) continue;

      result.add(abstractTreeNode);
    }
    //myFavoritesRoots = result;
    //if (result.isEmpty()) {
    //  result.add(getEmptyScreen());
    //}
    return ArrayUtil.toObjectArray(result);
  }
  catch (Exception e) {
  }

  return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
 
Example #26
Source File: NavigationGutterIconBuilder.java    From consulo with Apache License 2.0 4 votes vote down vote up
private MyNavigationGutterIconRenderer createGutterIconRenderer(@Nonnull Project project) {
  checkBuilt();
  final SmartPointerManager manager = SmartPointerManager.getInstance(project);

  NotNullLazyValue<List<SmartPsiElementPointer>> pointers = new NotNullLazyValue<List<SmartPsiElementPointer>>() {
    @Override
    @Nonnull
    public List<SmartPsiElementPointer> compute() {
      Set<PsiElement> elements = new THashSet<PsiElement>();
      Collection<? extends T> targets = myTargets.getValue();
      final List<SmartPsiElementPointer> list = new ArrayList<SmartPsiElementPointer>(targets.size());
      for (final T target : targets) {
        for (final PsiElement psiElement : myConverter.fun(target)) {
          if (elements.add(psiElement) && psiElement.isValid()) {
            list.add(manager.createSmartPsiElementPointer(psiElement));
          }
        }
      }
      return list;
    }
  };

  final boolean empty = isEmpty();

  if (myTooltipText == null && !myLazy) {
    final SortedSet<String> names = new TreeSet<String>();
    for (T t : myTargets.getValue()) {
      final String text = myNamer.fun(t);
      if (text != null) {
        names.add(MessageFormat.format(PATTERN, text));
      }
    }
    @NonNls StringBuilder sb = new StringBuilder("<html><body>");
    if (myTooltipTitle != null) {
      sb.append(myTooltipTitle).append("<br>");
    }
    for (String name : names) {
      sb.append(name).append("<br>");
    }
    sb.append("</body></html>");
    myTooltipText = sb.toString();
  }

  Computable<PsiElementListCellRenderer> renderer =
    myCellRenderer == null ? new Computable<PsiElementListCellRenderer>() {
      @Override
      public PsiElementListCellRenderer compute() {
        return new DefaultPsiElementCellRenderer();
      }
    } : myCellRenderer;
  return new MyNavigationGutterIconRenderer(this, myAlignment, myIcon, myTooltipText, pointers, renderer, empty);
}
 
Example #27
Source File: DocumentationComponent.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void setElement(SmartPsiElementPointer<PsiElement> element) {
  myElement = element;
  myModificationCount = getCurrentModificationCount();
}
 
Example #28
Source File: RefElementImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public SmartPsiElementPointer getPointer() {
  return myID;
}
 
Example #29
Source File: UsageInfoToUsageConverter.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static PsiElement[] convertToPsiElements(@Nonnull List<SmartPsiElementPointer<PsiElement>> primary) {
  return ContainerUtil.map2Array(primary, PsiElement.class, SMARTPOINTER_TO_ELEMENT_MAPPER);
}
 
Example #30
Source File: UsageInfoToUsageConverter.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public PsiElement fun(final SmartPsiElementPointer<PsiElement> pointer) {
  return pointer.getElement();
}