Java Code Examples for com.intellij.psi.PsiElement#isValid()

The following examples show how to use com.intellij.psi.PsiElement#isValid() . 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: CleanupInspectionIntention.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected final void applyFix(Project project, CommonProblemDescriptor descriptor) {
  final QuickFix[] fixes = descriptor.getFixes();
  if (fixes != null && fixes.length > 0) {
    for (final QuickFix fix : fixes) {
      if (fix != null && (myQuickfixClass == null || fix.getClass().isAssignableFrom(myQuickfixClass))) {
        final ProblemDescriptor problemDescriptor = (ProblemDescriptor)descriptor;
        final PsiElement element = problemDescriptor.getPsiElement();
        if (element != null && element.isValid()) {
          collectFix(fix, problemDescriptor, project);
          myApplicableFixFound = true;
        }
        break;
      }
    }
  }
}
 
Example 2
Source File: ChangeSignaturePassFactory.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void doApplyInformationToEditor() {
  HighlightInfo info = null;
  final InplaceChangeSignature currentRefactoring = InplaceChangeSignature.getCurrentRefactoring(myEditor);
  if (currentRefactoring != null) {
    final ChangeInfo changeInfo = currentRefactoring.getStableChange();
    final PsiElement element = changeInfo.getMethod();
    int offset = myEditor.getCaretModel().getOffset();
    if (element == null || !element.isValid()) return;
    final TextRange elementTextRange = element.getTextRange();
    if (elementTextRange == null || !elementTextRange.contains(offset)) return;
    final LanguageChangeSignatureDetector<ChangeInfo> detector = LanguageChangeSignatureDetectors.INSTANCE.forLanguage(changeInfo.getLanguage());
    TextRange range = detector.getHighlightingRange(changeInfo);
    TextAttributes attributes = new TextAttributes(null, null,
                                                   myEditor.getColorsScheme().getAttributes(CodeInsightColors.WEAK_WARNING_ATTRIBUTES)
                                                           .getEffectColor(),
                                                   null, Font.PLAIN);
    HighlightInfo.Builder builder = HighlightInfo.newHighlightInfo(HighlightInfoType.INFORMATION).range(range);
    builder.textAttributes(attributes);
    builder.descriptionAndTooltip(SIGNATURE_SHOULD_BE_POSSIBLY_CHANGED);
    info = builder.createUnconditionally();
    QuickFixAction.registerQuickFixAction(info, new ApplyChangeSignatureAction(currentRefactoring.getInitialName()));
  }
  Collection<HighlightInfo> infos = info != null ? Collections.singletonList(info) : Collections.emptyList();
  UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument, 0, myFile.getTextLength(), infos, getColorsScheme(), getId());
}
 
Example 3
Source File: UsageContextCallHierarchyPanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isAvailableFor(@Nonnull UsageView usageView) {
  UsageTarget[] targets = ((UsageViewImpl)usageView).getTargets();
  if (targets.length == 0) return false;
  UsageTarget target = targets[0];
  if (!(target instanceof PsiElementUsageTarget)) return false;
  PsiElement element = ((PsiElementUsageTarget)target).getElement();
  if (element == null || !element.isValid()) return false;

  Project project = element.getProject();
  DataContext context = SimpleDataContext.getSimpleContext(CommonDataKeys.PSI_ELEMENT, element, SimpleDataContext.getProjectContext(project));
  HierarchyProvider provider = BrowseHierarchyActionBase.findBestHierarchyProvider(LanguageCallHierarchy.INSTANCE, element, context);
  if (provider == null) return false;
  PsiElement providerTarget = provider.getTarget(context);
  return providerTarget != null;
}
 
Example 4
Source File: PackageViewPane.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void deleteElement(@Nonnull 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();
  }
}
 
Example 5
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 6
Source File: ProblemDescriptionNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid() {
  if (myElement instanceof RefElement && !myElement.isValid()) return false;
  final CommonProblemDescriptor descriptor = getDescriptor();
  if (descriptor instanceof ProblemDescriptor) {
    final PsiElement psiElement = ((ProblemDescriptor)descriptor).getPsiElement();
    return psiElement != null && psiElement.isValid();
  }
  return true;
}
 
Example 7
Source File: SubstrateRef.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isValid() {
  StubElement parent = myStub.getParentStub();
  if (parent == null) {
    LOG.error("No parent for stub " + myStub + " of class " + myStub.getClass());
    return false;
  }
  PsiElement psi = parent.getPsi();
  return psi != null && psi.isValid();
}
 
Example 8
Source File: DependenciesPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Object getData(@Nonnull Key<?> dataId) {
  PackageDependenciesNode node = getSelectedNode();
  if (PlatformDataKeys.NAVIGATABLE == dataId) {
    return node;
  }
  if (LangDataKeys.PSI_ELEMENT == dataId && node != null)  {
    final PsiElement element = node.getPsiElement();
    return element != null && element.isValid() ? element : null;
  }
  return null;
}
 
Example 9
Source File: MoveFilesOrDirectoriesProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void retargetUsages(UsageInfo[] usages, Map<PsiElement, PsiElement> oldToNewMap) {
  final List<NonCodeUsageInfo> nonCodeUsages = new ArrayList<>();
  for (UsageInfo usageInfo : usages) {
    if (usageInfo instanceof MyUsageInfo) {
      final MyUsageInfo info = (MyUsageInfo)usageInfo;
      final PsiElement element = myElementsToMove[info.myIndex];

      if (info.getReference() instanceof FileReference || info.getReference() instanceof PsiDynaReference) {
        final PsiElement usageElement = info.getElement();
        if (usageElement != null) {
          final PsiFile usageFile = usageElement.getContainingFile();
          final PsiFile psiFile = usageFile.getViewProvider().getPsi(usageFile.getViewProvider().getBaseLanguage());
          if (psiFile != null && psiFile.equals(element)) {
            continue;  // already processed in MoveFilesOrDirectoriesUtil.doMoveFile
          }
        }
      }
      final PsiElement refElement = info.myReference.getElement();
      if (refElement != null && refElement.isValid()) {
        info.myReference.bindToElement(element);
      }
    } else if (usageInfo instanceof NonCodeUsageInfo) {
      nonCodeUsages.add((NonCodeUsageInfo)usageInfo);
    }
  }

  for (PsiFile movedFile : myFoundUsages.keySet()) {
    MoveFileHandler.forElement(movedFile).retargetUsages(myFoundUsages.get(movedFile), oldToNewMap);
  }

  myNonCodeUsages = nonCodeUsages.toArray(new NonCodeUsageInfo[nonCodeUsages.size()]);
}
 
Example 10
Source File: PsiScopesUtilCore.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean treeWalkUp(@Nonnull final PsiScopeProcessor processor,
                                 @Nonnull final PsiElement entrance,
                                 @Nullable final PsiElement maxScope,
                                 @Nonnull final ResolveState state) {
  if (!entrance.isValid()) {
    LOGGER.error(new PsiInvalidElementAccessException(entrance));
  }
  PsiElement prevParent = entrance;
  PsiElement scope = entrance;

  while (scope != null) {
    ProgressIndicatorProvider.checkCanceled();

    if (!scope.processDeclarations(processor, state, prevParent, entrance)) {
      return false; // resolved
    }


    if (scope == maxScope) break;
    prevParent = scope;
    scope = prevParent.getContext();
    if (scope != null && scope != prevParent.getParent() && !scope.isValid()) {
      break;
    }

  }

  return true;
}
 
Example 11
Source File: NavigationUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean activatePsiElementIfOpen(@Nonnull PsiElement elt, boolean searchForOpen, boolean requestFocus) {
  if (!elt.isValid()) return false;
  elt = elt.getNavigationElement();
  final PsiFile file = elt.getContainingFile();
  if (file == null || !file.isValid()) return false;

  VirtualFile vFile = file.getVirtualFile();
  if (vFile == null) return false;

  if (!EditorHistoryManager.getInstance(elt.getProject()).hasBeenOpen(vFile)) return false;

  final FileEditorManager fem = FileEditorManager.getInstance(elt.getProject());
  if (!fem.isFileOpen(vFile)) {
    fem.openFile(vFile, requestFocus, searchForOpen);
  }

  final TextRange range = elt.getTextRange();
  if (range == null) return false;

  final FileEditor[] editors = fem.getEditors(vFile);
  for (FileEditor editor : editors) {
    if (editor instanceof TextEditor) {
      final Editor text = ((TextEditor)editor).getEditor();
      final int offset = text.getCaretModel().getOffset();

      if (range.containsOffset(offset)) {
        // select the file
        fem.openFile(vFile, requestFocus, searchForOpen);
        return true;
      }
    }
  }

  return false;
}
 
Example 12
Source File: CompletionUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static PsiElement getTargetElement(LookupElement lookupElement) {
  PsiElement psiElement = lookupElement.getPsiElement();
  if (psiElement != null && psiElement.isValid()) {
    return getOriginalElement(psiElement);
  }

  Object object = lookupElement.getObject();
  if (object instanceof LookupValueWithPsiElement) {
    final PsiElement element = ((LookupValueWithPsiElement)object).getElement();
    if (element != null && element.isValid()) return getOriginalElement(element);
  }

  return null;
}
 
Example 13
Source File: QuickFixAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void refreshViews(@Nonnull Project project, @Nonnull RefEntity[] refElements, @Nonnull InspectionToolWrapper toolWrapper) {
  final Set<PsiElement> ignoredElements = new HashSet<PsiElement>();
  for (RefEntity element : refElements) {
    final PsiElement psiElement = element instanceof RefElement ? ((RefElement)element).getElement() : null;
    if (psiElement != null && psiElement.isValid()) {
      ignoredElements.add(psiElement);
    }
  }
  refreshViews(project, ignoredElements, toolWrapper);
}
 
Example 14
Source File: NavBarModelBuilderImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static PsiElement getOriginalElement(@Nullable PsiElement e) {
  if (e == null || !e.isValid()) return null;

  PsiFile containingFile = e.getContainingFile();
  if (containingFile != null && containingFile.getVirtualFile() == null) return null;

  PsiElement orig = e.getOriginalElement();
  return !(e instanceof PsiCompiledElement) && orig instanceof PsiCompiledElement ? e : orig;
}
 
Example 15
Source File: GroovyDslUtil.java    From ok-gradle with Apache License 2.0 5 votes vote down vote up
@Nullable
static GradleDslElement getNextValidParent(@NotNull GradleDslElement element) {
  PsiElement psi = element.getPsiElement();
  while (element != null && (psi == null || !psi.isValid())) {
    element = element.getParent();
    if (element != null) {
      psi = element.getPsiElement();
    }
  }

  return element;
}
 
Example 16
Source File: InspectionResultsView.java    From consulo with Apache License 2.0 5 votes vote down vote up
private PsiElement[] collectPsiElements() {
  RefEntity[] refElements = myTree.getSelectedElements();
  List<PsiElement> psiElements = new ArrayList<PsiElement>();
  for (RefEntity refElement : refElements) {
    PsiElement psiElement = refElement instanceof RefElement ? ((RefElement)refElement).getElement() : null;
    if (psiElement != null && psiElement.isValid()) {
      psiElements.add(psiElement);
    }
  }

  return PsiUtilCore.toPsiElementArray(psiElements);
}
 
Example 17
Source File: CommanderPanel.java    From consulo with Apache License 2.0 4 votes vote down vote up
public final Object getDataImpl(final Key<?> dataId) {
  if (myBuilder == null) return null;
  final Object selectedValue = getSelectedValue();
  if (LangDataKeys.PSI_ELEMENT == dataId) {
    final PsiElement selectedElement = getSelectedElement();
    return selectedElement != null && selectedElement.isValid() ? selectedElement : null;
  }
  if (LangDataKeys.PSI_ELEMENT_ARRAY == dataId) {
    return filterInvalidElements(getSelectedElements());
  }
  if (LangDataKeys.PASTE_TARGET_PSI_ELEMENT == dataId) {
    final AbstractTreeNode parentNode = myBuilder.getParentNode();
    final Object element = parentNode != null ? parentNode.getValue() : null;
    return element instanceof PsiElement && ((PsiElement)element).isValid() ? element : null;
  }
  if (PlatformDataKeys.NAVIGATABLE_ARRAY == dataId) {
    return getNavigatables();
  }
  if (PlatformDataKeys.COPY_PROVIDER == dataId) {
    return myCopyPasteDelegator != null ? myCopyPasteDelegator.getCopyProvider() : null;
  }
  if (PlatformDataKeys.CUT_PROVIDER == dataId) {
    return myCopyPasteDelegator != null ? myCopyPasteDelegator.getCutProvider() : null;
  }
  if (PlatformDataKeys.PASTE_PROVIDER == dataId) {
    return myCopyPasteDelegator != null ? myCopyPasteDelegator.getPasteProvider() : null;
  }
  if (LangDataKeys.IDE_VIEW == dataId) {
    return myIdeView;
  }
  if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER == dataId) {
    return myDeleteElementProvider;
  }
  if (LangDataKeys.MODULE == dataId) {
    return selectedValue instanceof Module ? selectedValue : null;
  }
  if (ModuleGroup.ARRAY_DATA_KEY == dataId) {
    return selectedValue instanceof ModuleGroup ? new ModuleGroup[]{(ModuleGroup)selectedValue} : null;
  }
  if (LibraryGroupElement.ARRAY_DATA_KEY == dataId) {
    return selectedValue instanceof LibraryGroupElement ? new LibraryGroupElement[]{(LibraryGroupElement)selectedValue} : null;
  }
  if (NamedLibraryElement.ARRAY_DATA_KEY == dataId) {
    return selectedValue instanceof NamedLibraryElement ? new NamedLibraryElement[]{(NamedLibraryElement)selectedValue} : null;
  }

  if (myProjectTreeStructure != null) {
    return myProjectTreeStructure.getDataFromProviders(getSelectedNodes(), dataId);
  }

  return null;
}
 
Example 18
Source File: BashRunConfigProducer.java    From BashSupport with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean setupConfigurationFromContext(BashRunConfiguration configuration, ConfigurationContext context, Ref<PsiElement> sourceElement) {
    Location location = context.getLocation();
    if (location == null) {
        return false;
    }

    PsiElement psiElement = location.getPsiElement();
    if (!psiElement.isValid()) {
        return false;
    }

    PsiFile psiFile = psiElement.getContainingFile();
    if (!(psiFile instanceof BashFile)) {
        return false;
    }
    sourceElement.set(psiFile);

    VirtualFile file = location.getVirtualFile();
    if (file == null) {
        return false;
    }

    configuration.setName(file.getPresentableName());
    configuration.setScriptName(VfsUtilCore.virtualToIoFile(file).getAbsolutePath());

    if (file.getParent() != null) {
        configuration.setWorkingDirectory(VfsUtilCore.virtualToIoFile(file.getParent()).getAbsolutePath());
    }

    Module module = context.getModule();
    if (module != null) {
        configuration.setModule(module);
    }

    // check the location given by the shebang line
    // do this only if the project interpreter isn't used because we don't want to add the options
    // because it would mess up the execution when the project interpreter was used.
    // options might be added by a shebang like "/usr/bin/env bash".
    // also, we don't want to override the defaults of the template run configuration
    if (!configuration.isUseProjectInterpreter() && configuration.getInterpreterPath().isEmpty()) {
        BashFile bashFile = (BashFile) psiFile;
        BashShebang shebang = bashFile.findShebang();
        if (shebang != null) {
            String shebandShell = shebang.shellCommand(false);

            if ((BashInterpreterDetection.instance().isSuitable(shebandShell))) {
                configuration.setInterpreterPath(shebandShell);
                configuration.setInterpreterOptions(shebang.shellCommandParams());
            }
        }
    }

    return true;
}
 
Example 19
Source File: PropertySuppressableInspectionBase.java    From eslint-plugin with MIT License 4 votes vote down vote up
public boolean isAvailable(@NotNull final Project project, final Editor editor, @NotNull final PsiElement element) {
    return element.isValid() && element.getContainingFile() instanceof JSFile;
}
 
Example 20
Source File: ReferenceCache.java    From Intellij-Plugin with Apache License 2.0 4 votes vote down vote up
private boolean isValidPsiElement(PsiElement psiElement) {
    return psiElement != null && psiElement.isValid();
}