Java Code Examples for com.intellij.psi.PsiFile#isPhysical()

The following examples show how to use com.intellij.psi.PsiFile#isPhysical() . These examples are extracted from open source projects. 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 Project: consulo   File: PsiCacheKey.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets modification count from tracker based on {@link #myModifyCause}
 *
 * @param tracker track to get modification count from
 * @return modification count
 * @throws AssertionError if {@link #myModifyCause} is junk
 */
private long getModificationCount(@Nonnull PsiElement element) {
  PsiFile file = element.getContainingFile();
  long fileStamp = file == null || file.isPhysical() ? 0 : file.getModificationStamp();
  PsiModificationTracker tracker = file == null ? element.getManager().getModificationTracker() : file.getManager().getModificationTracker();

  if (myModifyCause.equals(PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT)) {
    return fileStamp + tracker.getJavaStructureModificationCount();
  }
  if (myModifyCause.equals(PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT)) {
    return fileStamp + tracker.getOutOfCodeBlockModificationCount();
  }
  if (myModifyCause.equals(PsiModificationTracker.MODIFICATION_COUNT)) {
    return fileStamp + tracker.getModificationCount();
  }
  throw new AssertionError("No modification tracker found for key " + myModifyCause);
}
 
Example 2
Source Project: consulo   File: LossyEncodingInspection.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public ProblemDescriptor[] checkFile(@Nonnull PsiFile file, @Nonnull InspectionManager manager, boolean isOnTheFly) {
  if (InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file)) return null;
  if (!file.isPhysical()) return null;
  FileViewProvider viewProvider = file.getViewProvider();
  if (viewProvider.getBaseLanguage() != file.getLanguage()) return null;
  VirtualFile virtualFile = file.getVirtualFile();
  if (virtualFile == null) return null;
  if (!virtualFile.isInLocalFileSystem()) return null;
  CharSequence text = viewProvider.getContents();
  Charset charset = LoadTextUtil.extractCharsetFromFileContent(file.getProject(), virtualFile, text);

  // no sense in checking transparently decoded file: all characters there are already safely encoded
  if (charset instanceof Native2AsciiCharset) return null;

  List<ProblemDescriptor> descriptors = new SmartList<ProblemDescriptor>();
  boolean ok = checkFileLoadedInWrongEncoding(file, manager, isOnTheFly, virtualFile, charset, descriptors);
  if (ok) {
    checkIfCharactersWillBeLostAfterSave(file, manager, isOnTheFly, text, charset, descriptors);
  }

  return descriptors.toArray(new ProblemDescriptor[descriptors.size()]);
}
 
Example 3
Source Project: consulo   File: CodeInsightUtilBase.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean preparePsiElementsForWrite(@Nonnull Collection<? extends PsiElement> elements) {
  if (elements.isEmpty()) return true;
  Set<VirtualFile> files = new THashSet<VirtualFile>();
  Project project = null;
  for (PsiElement element : elements) {
    if (element == null) continue;
    PsiFile file = element.getContainingFile();
    if (file == null || !file.isPhysical()) continue;
    project = file.getProject();
    VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile == null) continue;
    files.add(virtualFile);
  }
  if (!files.isEmpty()) {
    VirtualFile[] virtualFiles = VfsUtilCore.toVirtualFileArray(files);
    ReadonlyStatusHandler.OperationStatus status = ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(virtualFiles);
    return !status.hasReadonlyFiles();
  }
  return true;
}
 
Example 4
Source Project: intellij-haxe   File: HaxeDebugUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String elementLocation(PsiElement element) {
  if (null == element) {
    return "(unknown file) : 0";
  }

  final PsiFile file = element.getContainingFile();
  final String contents = null != file ? file.getText() : null;
  final int line = null != contents ? StringUtil.offsetToLineNumber(contents, element.getTextOffset()) : 0;

  StringBuilder builder = new StringBuilder(null != file && file.isPhysical() ? file.getName() : "(virtual file)");
  builder.append(" : ");
  builder.append(line);

  return builder.toString();
}
 
Example 5
Source Project: intellij-xquery   File: XQueryUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static PsiFile getFileByRelativePath(Project project, String filename, PsiFile containingFile) {
    if (!containingFile.isPhysical()) return null;
    VirtualFile containingDirectory = containingFile.getParent().getVirtualFile();
    VirtualFile foundByRelativePath = containingDirectory.findFileByRelativePath(filename);
    if (foundByRelativePath != null) {
        PsiFile found = PsiManager.getInstance(project).findFile(foundByRelativePath);
        if (found != null) {
            return found;
        }
    }
    return null;
}
 
Example 6
Source Project: consulo   File: ExcludedFiles.java    License: Apache License 2.0 5 votes vote down vote up
public boolean contains(@Nonnull PsiFile file) {
  if (file.isPhysical()) {
    for (FileSetDescriptor descriptor : myDescriptors) {
      if (descriptor.matches(file)) return true;
    }
  }
  return false;
}
 
Example 7
Source Project: consulo   File: PsiCachedValue.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isVeryPhysical(@Nonnull PsiElement dependency) {
  if (!dependency.isValid()) {
    return false;
  }
  if (!dependency.isPhysical()) {
    return false;
  }
  // injected files are physical but can sometimes (look at you, completion)
  // be inexplicably injected into non-physical element, in which case PSI_MODIFICATION_COUNT doesn't change and thus can't be relied upon
  InjectedLanguageManager manager = InjectedLanguageManager.getInstance(myManager.getProject());
  PsiFile topLevelFile = manager.getTopLevelFile(dependency);
  return topLevelFile != null && topLevelFile.isPhysical();
}
 
Example 8
Source Project: consulo   File: PsiEventWrapperAspect.java    License: Apache License 2.0 5 votes vote down vote up
private static void sendAfterEvents(TreeChangeEvent changeSet) {
  ASTNode rootElement = changeSet.getRootElement();
  PsiFile file = (PsiFile)rootElement.getPsi();
  if (!file.isPhysical()) {
    promoteNonPhysicalChangesToDocument(rootElement, file);
    ((PsiManagerImpl)file.getManager()).afterChange(false);
    return;
  }

  ((TreeChangeEventImpl)changeSet).fireEvents();
}
 
Example 9
@NotNull
public static Set<PsiFile> findIncludedFiles(@NotNull PsiFile sourceFile, boolean diveDeep, boolean bashOnly) {
    if (!(sourceFile instanceof BashFile)) {
        return Collections.emptySet();
    }

    if (!sourceFile.isPhysical()) {
        return Collections.emptySet();
    }

    if (DumbService.isDumb(sourceFile.getProject())) {
        return Collections.emptySet();
    }

    Project project = sourceFile.getProject();

    Set<PsiFile> includersTodo = Sets.newLinkedHashSet(Collections.singletonList(sourceFile));
    Set<PsiFile> includersDone = Sets.newLinkedHashSet();

    Set<PsiFile> allIncludedFiles = Sets.newHashSet();

    while (!includersTodo.isEmpty()) {
        Iterator<PsiFile> iterator = includersTodo.iterator();

        PsiFile file = iterator.next();
        iterator.remove();

        includersDone.add(file);

        VirtualFile virtualFile = file.getVirtualFile();
        if (virtualFile == null) {
            continue;
        }

        String filePath = virtualFile.getPath();

        Collection<BashIncludeCommand> commands = StubIndex.getElements(BashIncludeCommandIndex.KEY, filePath, project, BashSearchScopes.bashOnly(BashSearchScopes.moduleScope(file)), BashIncludeCommand.class);
        if (commands.isEmpty()) {
            continue;
        }

        for (BashIncludeCommand command : commands) {
            BashFileReference fileReference = command.getFileReference();
            if (fileReference != null && fileReference.isStatic()) {
                PsiFile referencedFile = fileReference.findReferencedFile();
                if (bashOnly && !(referencedFile instanceof BashFile)) {
                    continue;
                }

                if (referencedFile != null) {
                    allIncludedFiles.add(referencedFile);

                    if (!includersDone.contains(referencedFile)) {
                        //the include commands of this command have to be collected, too
                        includersTodo.add(referencedFile);
                    }
                }
            }
        }

        if (!diveDeep) {
            //the first iteration is the original source
            break;
        }
    }

    return allIncludedFiles;
}
 
Example 10
Source Project: consulo   File: CoverageDataManagerImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void editorCreated(@Nonnull EditorFactoryEvent event) {
  synchronized (myLock) {
    if (myIsProjectClosing) return;
  }

  final Editor editor = event.getEditor();
  if (editor.getProject() != myProject) return;
  final PsiFile psiFile = ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() {
    @Nullable
    @Override
    public PsiFile compute() {
      if (myProject.isDisposed()) return null;
      final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
      final Document document = editor.getDocument();
      return documentManager.getPsiFile(document);
    }
  });

  if (psiFile != null && myCurrentSuitesBundle != null && psiFile.isPhysical()) {
    final CoverageEngine engine = myCurrentSuitesBundle.getCoverageEngine();
    if (!engine.coverageEditorHighlightingApplicableTo(psiFile)) {
      return;
    }

    SrcFileAnnotator annotator = getAnnotator(editor);
    if (annotator == null) {
      annotator = new SrcFileAnnotator(psiFile, editor);
    }

    final SrcFileAnnotator finalAnnotator = annotator;

    synchronized (ANNOTATORS_LOCK) {
      myAnnotators.put(editor, finalAnnotator);
    }

    final Runnable request = new Runnable() {
      @Override
      public void run() {
        if (myProject.isDisposed()) return;
        if (myCurrentSuitesBundle != null) {
          if (engine.acceptedByFilters(psiFile, myCurrentSuitesBundle)) {
            finalAnnotator.showCoverageInformation(myCurrentSuitesBundle);
          }
        }
      }
    };
    myCurrentEditors.put(editor, request);
    myAlarm.addRequest(request, 100);
  }
}
 
Example 11
Source Project: consulo   File: CompositeElement.java    License: Apache License 2.0 4 votes vote down vote up
private static String getThreadingDiagnostics(@Nonnull PsiFile psiFile) {
  return "psiFile: " + psiFile +
         "; psiFile.getViewProvider(): " + psiFile.getViewProvider() +
         "; psiFile.isPhysical(): " + psiFile.isPhysical() +
         "; nonPhysicalOrInjected: " + isNonPhysicalOrInjected(psiFile);
}
 
Example 12
Source Project: consulo   File: CompositeElement.java    License: Apache License 2.0 4 votes vote down vote up
private static boolean isNonPhysicalOrInjected(@Nonnull PsiFile psiFile) {
  return psiFile instanceof DummyHolder || psiFile.getViewProvider() instanceof FreeThreadedFileViewProvider || !psiFile.isPhysical();
}
 
Example 13
Source Project: consulo   File: CompletionAssertions.java    License: Apache License 2.0 4 votes vote down vote up
static void assertCommitSuccessful(Editor editor, PsiFile psiFile) {
  Document document = editor.getDocument();
  int docLength = document.getTextLength();
  int psiLength = psiFile.getTextLength();
  PsiDocumentManager manager = PsiDocumentManager.getInstance(psiFile.getProject());
  boolean committed = !manager.isUncommited(document);
  if (docLength == psiLength && committed) {
    return;
  }

  FileViewProvider viewProvider = psiFile.getViewProvider();

  String message = "unsuccessful commit:";
  message += "\nmatching=" + (psiFile == manager.getPsiFile(document));
  message += "\ninjectedEditor=" + (editor instanceof EditorWindow);
  message += "\ninjectedFile=" + InjectedLanguageManager.getInstance(psiFile.getProject()).isInjectedFragment(psiFile);
  message += "\ncommitted=" + committed;
  message += "\nfile=" + psiFile.getName();
  message += "\nfile class=" + psiFile.getClass();
  message += "\nfile.valid=" + psiFile.isValid();
  message += "\nfile.physical=" + psiFile.isPhysical();
  message += "\nfile.eventSystemEnabled=" + viewProvider.isEventSystemEnabled();
  message += "\nlanguage=" + psiFile.getLanguage();
  message += "\ndoc.length=" + docLength;
  message += "\npsiFile.length=" + psiLength;
  String fileText = psiFile.getText();
  if (fileText != null) {
    message += "\npsiFile.text.length=" + fileText.length();
  }
  FileASTNode node = psiFile.getNode();
  if (node != null) {
    message += "\nnode.length=" + node.getTextLength();
    String nodeText = node.getText();
    message += "\nnode.text.length=" + nodeText.length();
  }
  VirtualFile virtualFile = viewProvider.getVirtualFile();
  message += "\nvirtualFile=" + virtualFile;
  message += "\nvirtualFile.class=" + virtualFile.getClass();
  message += "\n" + DebugUtil.currentStackTrace();

  throw new RuntimeExceptionWithAttachments("Commit unsuccessful", message, new Attachment(virtualFile.getPath() + "_file.txt", StringUtil.notNullize(fileText)), createAstAttachment(psiFile, psiFile),
                                            new Attachment("docText.txt", document.getText()));
}
 
Example 14
Source Project: consulo   File: CompletionAssertions.java    License: Apache License 2.0 4 votes vote down vote up
private static String fileInfo(PsiFile file) {
  return file + " of " + file.getClass() + " in " + file.getViewProvider() + ", languages=" + file.getViewProvider().getLanguages() + ", physical=" + file.isPhysical();
}