Java Code Examples for com.intellij.psi.util.PsiUtilCore#getVirtualFile()

The following examples show how to use com.intellij.psi.util.PsiUtilCore#getVirtualFile() . 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: Evaluator.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Nullable
@RequiredReadAction
public static DotNetTypeProxy findTypeMirror(@Nonnull CSharpEvaluateContext context, @Nullable PsiElement element)
{
	if(element instanceof CSharpTypeDeclaration)
	{
		DotNetDebugContext debuggerContext = context.getDebuggerContext();

		VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element);
		if(virtualFile == null)
		{
			return null;
		}
		return debuggerContext.getVirtualMachine().findType(element.getProject(), ((CSharpTypeDeclaration) element).getVmQName(), virtualFile);
	}
	return null;
}
 
Example 2
Source File: EditSourceUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static Navigatable getDescriptor(final PsiElement element) {
  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;
}
 
Example 3
Source File: IdeHelper.java    From yiistorm with MIT License 6 votes vote down vote up
public static void navigateToPsiElement(PsiElement psiElement) {
    Project project = psiElement.getProject();
    PsiElement navElement = psiElement.getNavigationElement();
    navElement = TargetElementUtilBase.getInstance().getGotoDeclarationTarget(psiElement, navElement);
    if (navElement instanceof Navigatable) {
        if (((Navigatable) navElement).canNavigate()) {
            ((Navigatable) navElement).navigate(true);
        }
    } else if (navElement != null) {
        int navOffset = navElement.getTextOffset();
        VirtualFile virtualFile = PsiUtilCore.getVirtualFile(navElement);
        if (virtualFile != null) {
            new OpenFileDescriptor(project, virtualFile, navOffset).navigate(true);
        }
    }
}
 
Example 4
Source File: QuickEditHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void commitToOriginal(final DocumentEvent e) {
  VirtualFile origVirtualFile = PsiUtilCore.getVirtualFile(myNewFile.getContext());
  myCommittingToOriginal = true;
  try {
    if (origVirtualFile == null || !ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(origVirtualFile).hasReadonlyFiles()) {
      PostprocessReformattingAspect.getInstance(myProject).disablePostprocessFormattingInside(new Runnable() {
        @Override
        public void run() {
          if (myAltFullRange != null) {
            altCommitToOriginal(e);
            return;
          }
          commitToOriginalInner();
        }
      });
      PsiDocumentManager.getInstance(myProject).doPostponedOperationsAndUnblockDocument(myOrigDocument);
    }
  }
  finally {
    myCommittingToOriginal = false;
  }
}
 
Example 5
Source File: PsiElementRenameHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void invoke(PsiElement element, Project project, PsiElement nameSuggestionContext, @Nullable Editor editor) {
  if (element != null && !canRename(project, editor, element)) {
    return;
  }

  VirtualFile contextFile = PsiUtilCore.getVirtualFile(nameSuggestionContext);

  if (nameSuggestionContext != null &&
      nameSuggestionContext.isPhysical() &&
      (contextFile == null || !ScratchUtil.isScratch(contextFile) && !PsiManager.getInstance(project).isInProject(nameSuggestionContext))) {
    final String message = "Selected element is used from non-project files. These usages won't be renamed. Proceed anyway?";
    if (ApplicationManager.getApplication().isUnitTestMode()) throw new CommonRefactoringUtil.RefactoringErrorHintException(message);
    if (Messages.showYesNoDialog(project, message, RefactoringBundle.getCannotRefactorMessage(null), Messages.getWarningIcon()) != Messages.YES) {
      return;
    }
  }

  FeatureUsageTracker.getInstance().triggerFeatureUsed("refactoring.rename");

  rename(element, project, nameSuggestionContext, editor);
}
 
Example 6
Source File: FavoritesViewSelectInTarget.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void select(PsiElement element, boolean requestFocus) {
  PsiElement toSelect = findElementToSelect(element, null);
  if (toSelect != null) {
    VirtualFile virtualFile = PsiUtilCore.getVirtualFile(toSelect);
    select(toSelect, virtualFile, requestFocus);
  }
}
 
Example 7
Source File: DocumentationManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static String generateFileDoc(@Nonnull PsiFile psiFile, boolean withUrl) {
  VirtualFile file = PsiUtilCore.getVirtualFile(psiFile);
  File ioFile = file == null || !file.isInLocalFileSystem() ? null : VfsUtilCore.virtualToIoFile(file);
  BasicFileAttributes attr = null;
  try {
    attr = ioFile == null ? null : Files.readAttributes(Paths.get(ioFile.toURI()), BasicFileAttributes.class);
  }
  catch (Exception ignored) {
  }
  if (attr == null) return null;
  FileType type = file.getFileType();
  String typeName = type == UnknownFileType.INSTANCE ? "Unknown" : type == PlainTextFileType.INSTANCE ? "Text" : type instanceof ArchiveFileType ? "Archive" : type.getId();
  String languageName = type.isBinary() ? "" : psiFile.getLanguage().getDisplayName();
  return (withUrl ? DocumentationMarkup.DEFINITION_START + file.getPresentableUrl() + DocumentationMarkup.DEFINITION_END + DocumentationMarkup.CONTENT_START : "") +
         getVcsStatus(psiFile.getProject(), file) +
         getScope(psiFile.getProject(), file) +
         "<p><span class='grayed'>Size:</span> " +
         StringUtil.formatFileSize(attr.size()) +
         "<p><span class='grayed'>Type:</span> " +
         typeName +
         (type.isBinary() || typeName.equals(languageName) ? "" : " (" + languageName + ")") +
         "<p><span class='grayed'>Modified:</span> " +
         DateFormatUtil.formatDateTime(attr.lastModifiedTime().toMillis()) +
         "<p><span class='grayed'>Created:</span> " +
         DateFormatUtil.formatDateTime(attr.creationTime().toMillis()) +
         (withUrl ? DocumentationMarkup.CONTENT_END : "");
}
 
Example 8
Source File: ScratchFileServiceImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public UsageType getUsageType(PsiElement element) {
  VirtualFile file = PsiUtilCore.getVirtualFile(element);
  RootType rootType = ScratchFileService.getInstance().getRootType(file);
  return rootType == null ? null : ourUsageTypes.get(rootType);
}
 
Example 9
Source File: ClassSearchEverywhereContributor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
protected Navigatable createExtendedNavigatable(PsiElement psi, String searchText, int modifiers) {
  Navigatable res = super.createExtendedNavigatable(psi, searchText, modifiers);
  if (res != null) {
    return res;
  }

  VirtualFile file = PsiUtilCore.getVirtualFile(psi);
  String memberName = getMemberName(searchText);
  if (file != null && memberName != null) {
    Navigatable delegate = GotoClassAction.findMember(memberName, searchText, psi, file);
    if (delegate != null) {
      return new Navigatable() {
        @Override
        public void navigate(boolean requestFocus) {
          NavigationUtil.activateFileWithPsiElement(psi, openInCurrentWindow(modifiers));
          delegate.navigate(true);

        }

        @Override
        public boolean canNavigate() {
          return delegate.canNavigate();
        }

        @Override
        public boolean canNavigateToSource() {
          return delegate.canNavigateToSource();
        }
      };
    }
  }

  return null;
}
 
Example 10
Source File: LockedIconDescriptorUpdater.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Override
public void updateIcon(@Nonnull IconDescriptor iconDescriptor, @Nonnull PsiElement element, int flags) {
  if (BitUtil.isSet(flags, Iconable.ICON_FLAG_READ_STATUS)) {
    VirtualFile file = PsiUtilCore.getVirtualFile(element);
    final boolean isLocked = !element.isWritable() || !WritingAccessProvider.isPotentiallyWritable(file, element.getProject());

    if (isLocked) {
      iconDescriptor.addLayerIcon(AllIcons.Nodes.Locked);
    }
  }
}
 
Example 11
Source File: AbstractPsiBasedNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private VirtualFile getVirtualFileForValue() {
  PsiElement psiElement = extractPsiFromValue();
  if (psiElement == null) {
    return null;
  }
  return PsiUtilCore.getVirtualFile(psiElement);
}
 
Example 12
Source File: TodoTreeBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static TodoNodeVisitor getVisitorFor(Object obj) {
  if (obj instanceof TodoItemNode) {
    SmartTodoItemPointer value = ((TodoItemNode)obj).getValue();
    if (value != null) {
      return new TodoNodeVisitor(value::getTodoItem, value.getTodoItem().getFile().getVirtualFile());
    }
  }
  else {
    Object o = obj instanceof AbstractTreeNode ? ((AbstractTreeNode)obj).getValue() : null;
    return new TodoNodeVisitor(() -> obj instanceof AbstractTreeNode ? ((AbstractTreeNode)obj).getValue() : obj, o instanceof PsiElement ? PsiUtilCore.getVirtualFile((PsiElement)o) : null);
  }
  return null;
}
 
Example 13
Source File: DaemonCodeAnalyzerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void setHighlightingEnabled(@Nonnull PsiFile file, boolean value) {
  VirtualFile virtualFile = PsiUtilCore.getVirtualFile(file);
  if (value) {
    myDisabledHighlightingFiles.remove(virtualFile);
  }
  else {
    myDisabledHighlightingFiles.add(virtualFile);
  }
}
 
Example 14
Source File: CSharpCopyClassHandlerDelegate.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
private static void doCopy(@Nonnull CSharpTypeDeclaration typeDeclaration, @Nullable PsiDirectory defaultTargetDirectory, Project project)
{
	PsiDirectory targetDirectory;
	String newName;
	boolean openInEditor;
	VirtualFile virtualFile = PsiUtilCore.getVirtualFile(typeDeclaration);
	CopyFilesOrDirectoriesDialog dialog = new CopyFilesOrDirectoriesDialog(new PsiElement[]{typeDeclaration.getContainingFile()}, defaultTargetDirectory, project, false);
	if(dialog.showAndGet())
	{
		newName = dialog.getNewName();
		targetDirectory = dialog.getTargetDirectory();
		openInEditor = dialog.openInEditor();
	}
	else
	{
		return;
	}

	if(targetDirectory != null)
	{
		PsiManager manager = PsiManager.getInstance(project);
		try
		{
			if(virtualFile.isDirectory())
			{
				PsiFileSystemItem psiElement = manager.findDirectory(virtualFile);
				MoveFilesOrDirectoriesUtil.checkIfMoveIntoSelf(psiElement, targetDirectory);
			}
		}
		catch(IncorrectOperationException e)
		{
			CommonRefactoringUtil.showErrorHint(project, null, e.getMessage(), CommonBundle.getErrorTitle(), null);
			return;
		}

		CommandProcessor.getInstance().executeCommand(project, () -> doCopy(typeDeclaration, newName, targetDirectory, false, openInEditor), RefactoringBundle.message("copy.handler.copy.files" +
				".directories"), null);
	}
}
 
Example 15
Source File: PartialTypeCollector.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
protected String getContainerText(PsiElement element, String name)
{
	VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element);
	if(virtualFile == null)
	{
		return SymbolPresentationUtil.getSymbolContainerText(element);
	}
	else
	{
		return "(" + virtualFile.getPath() + ")";
	}
}
 
Example 16
Source File: RefManagerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void visitElement(PsiElement element) {
  ProgressManager.checkCanceled();
  final RefManagerExtension extension = getExtension(element.getLanguage());
  if (extension != null) {
    extension.visitElement(element);
  }
  else if (processExternalElements) {
    PsiFile file = element.getContainingFile();
    if (file != null) {
      RefManagerExtension externalFileManagerExtension = myExtensions.values().stream().filter(ex -> ex.shouldProcessExternalFile(file)).findFirst().orElse(null);
      if (externalFileManagerExtension == null) {
        if (element instanceof PsiFile) {
          VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element);
          if (virtualFile instanceof VirtualFileWithId) {
            registerUnprocessed((VirtualFileWithId)virtualFile);
          }
        }
      }
      else {
        RefElement refFile = getReference(file);
        LOG.assertTrue(refFile != null, file);
        for (PsiReference reference : element.getReferences()) {
          PsiElement resolve = reference.resolve();
          if (resolve != null) {
            fireNodeMarkedReferenced(resolve, file);
            RefElement refWhat = getReference(resolve);
            if (refWhat == null) {
              PsiFile targetContainingFile = resolve.getContainingFile();
              //no logic to distinguish different elements in the file anyway
              if (file == targetContainingFile) continue;
              refWhat = getReference(targetContainingFile);
            }

            if (refWhat != null) {
              ((RefElementImpl)refWhat).addInReference(refFile);
              ((RefElementImpl)refFile).addOutReference(refWhat);
            }
          }
        }

        Stream<? extends PsiElement> implicitRefs = externalFileManagerExtension.extractExternalFileImplicitReferences(file);
        implicitRefs.forEach(e -> {
          RefElement superClassReference = getReference(e);
          if (superClassReference != null) {
            //in case of implicit inheritance, e.g. GroovyObject
            //= no explicit reference is provided, dependency on groovy library could be treated as redundant though it is not
            //inReference is not important in this case
            ((RefElementImpl)refFile).addOutReference(superClassReference);
          }
        });

        if (element instanceof PsiFile) {
          externalFileManagerExtension.markExternalReferencesProcessed(refFile);
        }
      }
    }
  }
  for (PsiElement aChildren : element.getChildren()) {
    aChildren.accept(this);
  }
}
 
Example 17
Source File: CSharpAbstractElementTreeNode.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@Override
public boolean contains(@Nonnull VirtualFile file)
{
	T value = getValue();
	return value != null && value.isValid() && PsiUtilCore.getVirtualFile(value) == file;
}
 
Example 18
Source File: HardElementInfo.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
VirtualFile getVirtualFile() {
  return PsiUtilCore.getVirtualFile(myElement);
}
 
Example 19
Source File: PartialTypeCollector.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@Override
public String getElementText(PsiElement element)
{
	VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element);
	return virtualFile == null ? SymbolPresentationUtil.getSymbolPresentableText(element) : virtualFile.getName();
}
 
Example 20
Source File: BasePsiNode.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected BasePsiNode(Project project, @Nonnull T value, ViewSettings viewSettings) {
  super(project, value, viewSettings);
  myVirtualFile = PsiUtilCore.getVirtualFile(value);
}