Java Code Examples for com.intellij.openapi.vfs.VirtualFile#getLength()

The following examples show how to use com.intellij.openapi.vfs.VirtualFile#getLength() . 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
@RequiredReadAction
@Nullable
@Override
public EditorNotificationPanel createNotificationPanel(@Nonnull VirtualFile file, @Nonnull FileEditor fileEditor) {
  if (!myProject.isDisposed() && !GeneralSettings.getInstance().isSyncOnFrameActivation()) {
    VirtualFileSystem fs = file.getFileSystem();
    if (fs instanceof LocalFileSystem) {
      FileAttributes attributes = ((LocalFileSystem)fs).getAttributes(file);
      if (attributes == null || file.getTimeStamp() != attributes.lastModified || file.getLength() != attributes.length) {
        LogUtil.debug(LOG, "%s: (%s,%s) -> %s", file, file.getTimeStamp(), file.getLength(), attributes);
        return createPanel(file);
      }
    }
  }

  return null;
}
 
Example 2
Source Project: consulo   File: MatchPatchPaths.java    License: Apache License 2.0 6 votes vote down vote up
private static int getMatchingLines(final AbstractFilePatchInProgress<TextFilePatch> patch) {
  final VirtualFile base = patch.getCurrentBase();
  if (base == null) return -1;
  String text;
  try {
    if (base.getLength() > BIG_FILE_BOUND) {
      // partially
      text = VfsUtilCore.loadText(base, BIG_FILE_BOUND);
    }
    else {
      text = VfsUtilCore.loadText(base);
    }
  }
  catch (IOException e) {
    return 0;
  }
  return new GenericPatchApplier(text, patch.getPatch().getHunks()).weightContextMatch(100, 5);
}
 
Example 3
Source Project: consulo   File: StubTreeLoaderImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void diagnoseLengthMismatch(VirtualFile vFile, boolean wasIndexedAlready, @Nullable Document document, boolean saved, @Nullable PsiFile cachedPsi) {
  String message = "Outdated stub in index: " +
                   vFile +
                   " " +
                   getIndexingStampInfo(vFile) +
                   ", doc=" +
                   document +
                   ", docSaved=" +
                   saved +
                   ", wasIndexedAlready=" +
                   wasIndexedAlready +
                   ", queried at " +
                   vFile.getTimeStamp();
  message += "\ndoc length=" + (document == null ? -1 : document.getTextLength()) + "\nfile length=" + vFile.getLength();
  if (cachedPsi != null) {
    message += "\ncached PSI " + cachedPsi.getClass();
    if (cachedPsi instanceof PsiFileImpl && ((PsiFileImpl)cachedPsi).isContentsLoaded()) {
      message += "\nPSI length=" + cachedPsi.getTextLength();
    }
    List<Project> projects = ContainerUtil.findAll(ProjectManager.getInstance().getOpenProjects(), p -> PsiManagerEx.getInstanceEx(p).getFileManager().findCachedViewProvider(vFile) != null);
    message += "\nprojects with file: " + (LOG.isDebugEnabled() ? projects.toString() : projects.size());
  }

  processError(vFile, message, new Exception());
}
 
Example 4
Source Project: saros   File: IntellijFile.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public long getSize() throws IOException {
  VirtualFile virtualFile = getVirtualFile();

  if (!existsInternal(virtualFile)) {
    throw new FileNotFoundException(
        "Could not obtain the size for " + this + " as it does not exist or is not valid");
  }

  return virtualFile.getLength();
}
 
Example 5
Source Project: consulo   File: FileTypeManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isDetectable(@Nonnull final VirtualFile file) {
  if (file.isDirectory() || !file.isValid() || file.is(VFileProperty.SPECIAL) || file.getLength() == 0) {
    // for empty file there is still hope its type will change
    return false;
  }
  return file.getFileSystem() instanceof FileSystemInterface;
}
 
Example 6
Source Project: consulo   File: FileTypeManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
private FileType detectFromContent(@Nonnull VirtualFile file, @Nullable byte[] content, @Nonnull Iterable<? extends FileTypeDetector> detectors) throws IOException {
  FileType fileType;
  if (content != null) {
    fileType = detect(file, content, content.length, detectors);
  }
  else {
    try (InputStream inputStream = ((FileSystemInterface)file.getFileSystem()).getInputStream(file)) {
      if (toLog()) {
        log("F: detectFromContentAndCache(" + file.getName() + "):" + " inputStream=" + streamInfo(inputStream));
      }

      int fileLength = (int)file.getLength();

      int bufferLength = StreamSupport.stream(detectors.spliterator(), false).map(FileTypeDetector::getDesiredContentPrefixLength).max(Comparator.naturalOrder()).orElse(FileUtilRt.getUserContentLoadLimit());
      byte[] buffer = fileLength <= FileUtilRt.THREAD_LOCAL_BUFFER_LENGTH ? FileUtilRt.getThreadLocalBuffer() : new byte[Math.min(fileLength, bufferLength)];

      int n = readSafely(inputStream, buffer, 0, buffer.length);
      fileType = detect(file, buffer, n, detectors);

      if (toLog()) {
        try (InputStream newStream = ((FileSystemInterface)file.getFileSystem()).getInputStream(file)) {
          byte[] buffer2 = new byte[50];
          int n2 = newStream.read(buffer2, 0, buffer2.length);
          log("F: detectFromContentAndCache(" + file.getName() + "): result: " + fileType.getName() +
              "; stream: " + streamInfo(inputStream) +
              "; newStream: " + streamInfo(newStream) +
              "; read: " + n2 +
              "; buffer: " + Arrays.toString(buffer2));
        }
      }
    }
  }

  if (LOG.isDebugEnabled()) {
    LOG.debug(file + "; type=" + fileType.getDescription() + "; " + counterAutoDetect);
  }
  return fileType;
}
 
Example 7
public static boolean fileSizeIsGreaterThan(@Nonnull VirtualFile vFile, final long maxBytes) {
  if (vFile instanceof LightVirtualFile) {
    // This is optimization in order to avoid conversion of [large] file contents to bytes
    final int lengthInChars = ((LightVirtualFile)vFile).getContent().length();
    if (lengthInChars < maxBytes / 2) return false;
    if (lengthInChars > maxBytes) return true;
  }

  return vFile.getLength() > maxBytes;
}
 
Example 8
Source Project: consulo   File: ImagePreviewComponent.java    License: Apache License 2.0 5 votes vote down vote up
public static JComponent getPreviewComponent(@Nullable final PsiElement parent) {
  if (parent == null) {
    return null;
  }
  final PsiReference[] references = parent.getReferences();
  for (final PsiReference reference : references) {
    final PsiElement fileItem = reference.resolve();
    if (fileItem instanceof PsiFileSystemItem) {
      final PsiFileSystemItem item = (PsiFileSystemItem)fileItem;
      if (!item.isDirectory()) {
        final VirtualFile file = item.getVirtualFile();
        if (file != null && supportedExtensions.contains(file.getExtension())) {
          try {
            refresh(file);
            SoftReference<BufferedImage> imageRef = file.getUserData(BUFFERED_IMAGE_REF_KEY);
            final BufferedImage image = SoftReference.dereference(imageRef);
            if (image != null) {
              return new ImagePreviewComponent(image, file.getLength());
            }
          }
          catch (IOException ignored) {
            // nothing
          }
        }
      }
    }
  }

  return null;
}
 
Example 9
private static void collectAndShowDuplicates(final Project project) {
  final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
  if (indicator != null && !indicator.isCanceled()) {
    indicator.setText("Collecting project images...");
    indicator.setIndeterminate(false);
    final List<VirtualFile> images = new ArrayList<VirtualFile>();
    for (String ext : IMAGE_EXTENSIONS) {
      images.addAll(FilenameIndex.getAllFilesByExt(project, ext));
    }

    final Map<Long, Set<VirtualFile>> duplicates = new HashMap<Long, Set<VirtualFile>>();
    final Map<Long, VirtualFile> all = new HashMap<Long, VirtualFile>();
    for (int i = 0; i < images.size(); i++) {
      indicator.setFraction((double)(i + 1) / (double)images.size());
      final VirtualFile file = images.get(i);
      if (!(file.getFileSystem() instanceof LocalFileSystem)) continue;
      final long length = file.getLength();
      if (all.containsKey(length)) {
        if (!duplicates.containsKey(length)) {
          final HashSet<VirtualFile> files = new HashSet<VirtualFile>();
          files.add(all.get(length));
          duplicates.put(length, files);
        }
        duplicates.get(length).add(file);
      } else {
        all.put(length, file);
      }
      indicator.checkCanceled();
    }
    showResults(project, images, duplicates, all);
  }
}
 
Example 10
@Nullable
private FileEditor createTempFileEditor(@Nonnull VirtualFile file) {
  if (file.getLength() > PersistentFSConstants.getMaxIntellisenseFileSize()) return null;

  FileEditorProviderManager editorProviderManager = FileEditorProviderManager.getInstance();
  final FileEditorProvider[] providers = editorProviderManager.getProviders(myProject, file);
  return providers.length == 0 ? null : providers[0].createEditor(myProject, file);
}
 
Example 11
Source Project: consulo   File: StubTreeLoader.java    License: Apache License 2.0 4 votes vote down vote up
@Nonnull
public RuntimeException stubTreeAndIndexDoNotMatch(@Nullable ObjectStubTree stubTree, @Nonnull PsiFileWithStubSupport psiFile, @Nullable Throwable cause) {
  VirtualFile file = psiFile.getViewProvider().getVirtualFile();
  StubTree stubTreeFromIndex = (StubTree)readFromVFile(psiFile.getProject(), file);
  boolean compiled = psiFile instanceof PsiCompiledElement;
  Document document = compiled ? null : FileDocumentManager.getInstance().getDocument(file);
  IndexingStampInfo indexingStampInfo = getIndexingStampInfo(file);
  boolean upToDate = indexingStampInfo != null && indexingStampInfo.isUpToDate(document, file, psiFile);

  boolean canBePrebuilt = isPrebuilt(psiFile.getVirtualFile());

  String msg = "PSI and index do not match.\nPlease report the problem to JetBrains with the files attached\n";

  if (canBePrebuilt) {
    msg += "This stub can have pre-built origin\n";
  }

  if (upToDate) {
    msg += "INDEXED VERSION IS THE CURRENT ONE";
  }

  msg += " file=" + psiFile;
  msg += ", file.class=" + psiFile.getClass();
  msg += ", file.lang=" + psiFile.getLanguage();
  msg += ", modStamp=" + psiFile.getModificationStamp();

  if (!compiled) {
    String text = psiFile.getText();
    PsiFile fromText = PsiFileFactory.getInstance(psiFile.getProject()).createFileFromText(psiFile.getName(), psiFile.getFileType(), text);
    if (fromText.getLanguage().equals(psiFile.getLanguage())) {
      boolean consistent = DebugUtil.psiToString(psiFile, true).equals(DebugUtil.psiToString(fromText, true));
      if (consistent) {
        msg += "\n tree consistent";
      }
      else {
        msg += "\n AST INCONSISTENT, perhaps after incremental reparse; " + fromText;
      }
    }
  }

  if (stubTree != null) {
    msg += "\n stub debugInfo=" + stubTree.getDebugInfo();
  }

  msg += "\nlatestIndexedStub=" + stubTreeFromIndex;
  if (stubTreeFromIndex != null) {
    if (stubTree != null) {
      msg += "\n   same size=" + (stubTree.getPlainList().size() == stubTreeFromIndex.getPlainList().size());
    }
    msg += "\n   debugInfo=" + stubTreeFromIndex.getDebugInfo();
  }

  FileViewProvider viewProvider = psiFile.getViewProvider();
  msg += "\n viewProvider=" + viewProvider;
  msg += "\n viewProvider stamp: " + viewProvider.getModificationStamp();

  msg += "; file stamp: " + file.getModificationStamp();
  msg += "; file modCount: " + file.getModificationCount();
  msg += "; file length: " + file.getLength();

  if (document != null) {
    msg += "\n doc saved: " + !FileDocumentManager.getInstance().isDocumentUnsaved(document);
    msg += "; doc stamp: " + document.getModificationStamp();
    msg += "; doc size: " + document.getTextLength();
    msg += "; committed: " + PsiDocumentManager.getInstance(psiFile.getProject()).isCommitted(document);
  }

  msg += "\nindexing info: " + indexingStampInfo;

  Attachment[] attachments = createAttachments(stubTree, psiFile, file, stubTreeFromIndex);

  // separate methods and separate exception classes for EA to treat these situations differently
  return hasPsiInManyProjects(file)
         ? handleManyProjectsMismatch(msg, attachments, cause)
         : upToDate ? handleUpToDateMismatch(msg, attachments, cause) : new RuntimeExceptionWithAttachments(msg, cause, attachments);
}
 
Example 12
private static boolean isBig(@Nonnull VirtualFile virtualFile) {
  return virtualFile.getLength() > VcsConfiguration.ourMaximumFileForBaseRevisionSize;
}