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

The following examples show how to use com.intellij.openapi.vfs.VirtualFile#getFileSystem() . 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: VfsEventGenerationHelper.java    From consulo with Apache License 2.0 6 votes vote down vote up
void scheduleCreation(@Nonnull VirtualFile parent,
                      @Nonnull String childName,
                      @Nonnull FileAttributes attributes,
                      @Nullable String symlinkTarget,
                      @Nonnull ThrowableRunnable<RefreshWorker.RefreshCancelledException> checkCanceled) throws RefreshWorker.RefreshCancelledException {
  if (LOG.isTraceEnabled()) LOG.trace("create parent=" + parent + " name=" + childName + " attr=" + attributes);
  ChildInfo[] children = null;
  if (attributes.isDirectory() && parent.getFileSystem() instanceof LocalFileSystem && !attributes.isSymLink()) {
    try {
      Path child = Paths.get(parent.getPath(), childName);
      if (shouldScanDirectory(parent, child, childName)) {
        Path[] relevantExcluded = ContainerUtil.mapNotNull(ProjectManagerEx.getInstanceEx().getAllExcludedUrls(), url -> {
          Path path = Paths.get(VirtualFileManager.extractPath(url));
          return path.startsWith(child) ? path : null;
        }, new Path[0]);
        children = scanChildren(child, relevantExcluded, checkCanceled);
      }
    }
    catch (InvalidPathException ignored) {
      // Paths.get() throws sometimes
    }
  }
  VFileCreateEvent event = new VFileCreateEvent(null, parent, childName, attributes.isDirectory(), attributes, symlinkTarget, true, children);
  myEvents.add(event);
}
 
Example 2
Source File: PsiCopyPasteManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static List<File> asFileList(final PsiElement[] elements) {
  final List<File> result = new ArrayList<>();
  for (PsiElement element : elements) {
    final PsiFileSystemItem psiFile;
    if (element instanceof PsiFileSystemItem) {
      psiFile = (PsiFileSystemItem)element;
    }
    else if (element instanceof PsiDirectoryContainer) {
      final PsiDirectory[] directories = ((PsiDirectoryContainer)element).getDirectories();
      psiFile = directories[0];
    }
    else {
      psiFile = element.getContainingFile();
    }
    if (psiFile != null) {
      VirtualFile vFile = psiFile.getVirtualFile();
      if (vFile != null && vFile.getFileSystem() instanceof LocalFileSystem) {
        result.add(new File(vFile.getPath()));
      }
    }
  }
  return result.isEmpty() ? null : result;
}
 
Example 3
Source File: FileAppearanceServiceImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public CellAppearanceEx forVirtualFile(@Nonnull final VirtualFile file) {
  if (!file.isValid()) {
    return forInvalidUrl(file.getPresentableUrl());
  }

  final VirtualFileSystem fileSystem = file.getFileSystem();
  if (fileSystem instanceof ArchiveFileSystem) {
    return new JarSubfileCellAppearance(file);
  }
  if (fileSystem instanceof HttpFileSystem) {
    return new HttpUrlCellAppearance(file);
  }
  if (file.isDirectory()) {
    return SimpleTextCellAppearance.regular(file.getPresentableUrl(), AllIcons.Nodes.Folder);
  }
  return new ValidFileCellAppearance(file);
}
 
Example 4
Source File: FileSystemTreeImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static FileElement getFileElementFor(@Nonnull VirtualFile file) {
  VirtualFile selectFile;

  if ((file.getFileSystem() instanceof ArchiveFileSystem) && file.getParent() == null) {
    selectFile = ArchiveVfsUtil.getVirtualFileForJar(file);
    if (selectFile == null) {
      return null;
    }
  }
  else {
    selectFile = file;
  }

  return new FileElement(selectFile, selectFile.getName());
}
 
Example 5
Source File: PlatformDocumentationUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static List<String> getHttpRoots(final String[] roots, String relPath) {
  final ArrayList<String> result = new ArrayList<String>();
  for (String root : roots) {
    final VirtualFile virtualFile = VirtualFileManager.getInstance().findFileByUrl(root);
    if (virtualFile != null) {
      if (virtualFile.getFileSystem() instanceof HttpFileSystem) {
        String url = virtualFile.getUrl();
        if (!url.endsWith("/")) url += "/";
        result.add(url + relPath);
      }
      else {
        VirtualFile file = virtualFile.findFileByRelativePath(relPath);
        if (file != null) result.add(file.getUrl());
      }
    }
  }

  return result.isEmpty() ? null : result;
}
 
Example 6
Source File: PsiDirectoryNode.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean contains(@Nonnull VirtualFile file) {
  final PsiDirectory value = getValue();
  if (value == null) {
    return false;
  }

  VirtualFile directory = value.getVirtualFile();
  if (directory.getFileSystem() instanceof LocalFileSystem) {
    file = PathUtil.getLocalFile(file);
  }

  if (!VfsUtilCore.isAncestor(directory, file, false)) {
    return false;
  }

  return !FileTypeRegistry.getInstance().isFileIgnored(file);
}
 
Example 7
Source File: ArchiveVfsUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Return original file from local system, when file is mirror in archive file system
 */
@Nullable
public static VirtualFile getVirtualFileForArchive(@Nullable VirtualFile virtualFile) {
  if (virtualFile == null || !virtualFile.isValid()) {
    return null;
  }

  if (virtualFile.getFileSystem() instanceof ArchiveFileSystem) {
    return ((ArchiveFileSystem)virtualFile.getFileSystem()).getLocalVirtualFileFor(virtualFile);
  }
  return null;
}
 
Example 8
Source File: PathUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static VirtualFile getLocalFile(@Nonnull VirtualFile file) {
  if (!file.isValid()) {
    return file;
  }
  if (file.getFileSystem() instanceof LocalFileProvider) {
    final VirtualFile localFile = ((LocalFileProvider)file.getFileSystem()).getLocalVirtualFileFor(file);
    if (localFile != null) {
      return localFile;
    }
  }
  return file;
}
 
Example 9
Source File: ProjectUtilCore.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static String displayUrlRelativeToProject(@Nonnull VirtualFile file,
                                                 @Nonnull String url,
                                                 @Nonnull Project project,
                                                 boolean includeFilePath,
                                                 boolean keepModuleAlwaysOnTheLeft) {
  final VirtualFile baseDir = project.getBaseDir();
  if (baseDir != null && includeFilePath) {
    //noinspection ConstantConditions
    final String projectHomeUrl = baseDir.getPresentableUrl();
    if (url.startsWith(projectHomeUrl)) {
      url = "..." + url.substring(projectHomeUrl.length());
    }
  }

  if (SystemInfo.isMac && file.getFileSystem() instanceof LocalFileProvider) {
    final VirtualFile fileForJar = ((LocalFileProvider)file.getFileSystem()).getLocalVirtualFileFor(file);
    if (fileForJar != null) {
      final OrderEntry libraryEntry = LibraryUtil.findLibraryEntry(file, project);
      if (libraryEntry != null) {
        if (libraryEntry instanceof ModuleExtensionWithSdkOrderEntry) {
          url = url + " - [" + ((ModuleExtensionWithSdkOrderEntry)libraryEntry).getSdkName() + "]";
        }
        else {
          url = url + " - [" + libraryEntry.getPresentableName() + "]";
        }
      }
      else {
        url = url + " - [" + fileForJar.getName() + "]";
      }
    }
  }

  final Module module = ModuleUtilCore.findModuleForFile(file, project);
  if (module == null) return url;
  return !keepModuleAlwaysOnTheLeft && SystemInfo.isMac ?
         url + " - [" + module.getName() + "]" :
         "[" + module.getName() + "] - " + url;
}
 
Example 10
Source File: ItemElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static Image getIconForUrl(final String url, final boolean isValid, final boolean isJarDirectory) {
  final Image icon;
  if (isValid) {
    VirtualFile presentableFile;
    if (isArchiveFileRoot(url)) {
      presentableFile = LocalFileSystem.getInstance().findFileByPath(getPresentablePath(url));
    }
    else {
      presentableFile = VirtualFileManager.getInstance().findFileByUrl(url);
    }
    if (presentableFile != null && presentableFile.isValid()) {
      if (presentableFile.getFileSystem() instanceof HttpFileSystem) {
        icon = AllIcons.Nodes.PpWeb;
      }
      else {
        if (presentableFile.isDirectory()) {
          if (isJarDirectory) {
            icon = AllIcons.Nodes.JarDirectory;
          }
          else {
            icon = AllIcons.Nodes.TreeClosed;
          }
        }
        else {
          icon = IconUtilEx.getIcon(presentableFile, 0, null);
        }
      }
    }
    else {
      icon = AllIcons.Nodes.PpInvalid;
    }
  }
  else {
    icon = AllIcons.Nodes.PpInvalid;
  }
  return icon;
}
 
Example 11
Source File: AbstractFileViewProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected AbstractFileViewProvider(@Nonnull PsiManager manager, @Nonnull VirtualFile virtualFile, boolean eventSystemEnabled) {
  myManager = (PsiManagerEx)manager;
  myVirtualFile = virtualFile;
  myEventSystemEnabled = eventSystemEnabled;
  setContent(new VirtualFileContent());
  myPhysical = isEventSystemEnabled() && !(virtualFile instanceof LightVirtualFile) && !(virtualFile.getFileSystem() instanceof NonPhysicalFileSystem);
  virtualFile.putUserData(FREE_THREADED, isFreeThreaded(this));
  if (virtualFile instanceof VirtualFileWindow && !(this instanceof FreeThreadedFileViewProvider) && !isFreeThreaded(this)) {
    throw new IllegalArgumentException("Must not create " + getClass() + " for injected file " + virtualFile + "; InjectedFileViewProvider must be used instead");
  }
}
 
Example 12
Source File: FileStatusManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public FileStatus getStatus(@Nonnull final VirtualFile file) {
  if (file.getFileSystem() instanceof NonPhysicalFileSystem) {
    return FileStatus.SUPPRESSED;  // do not leak light files via cache
  }

  FileStatus status = getCachedStatus(file);
  if (status == null || status == FileStatusNull.INSTANCE) {
    status = calcStatus(file);
    cacheChangedFileStatus(file, status);
  }

  return status;
}
 
Example 13
Source File: FileRefresher.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Starts watching the specified file, which was added before.
 *
 * @param file      a file to watch
 * @param recursive {@code true} if a file should be considered as root
 * @return an object that allows to stop watching the specified file
 */
protected Object watch(VirtualFile file, boolean recursive) {
  VirtualFileSystem fs = file.getFileSystem();
  if (fs instanceof LocalFileSystem) {
    return LocalFileSystem.getInstance().addRootToWatch(file.getPath(), recursive);
  }
  return null;
}
 
Example 14
Source File: BashPsiFileUtils.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
@Nullable
public static String findRelativeFilePath(PsiFile base, PsiFile targetFile) {
    PsiFile currentFile = BashPsiUtils.findFileContext(base);
    VirtualFile baseVirtualFile = currentFile.getVirtualFile();
    if (!(baseVirtualFile.getFileSystem() instanceof LocalFileSystem)) {
        throw new IncorrectOperationException("Can not rename file refeferences in non-local files");
    }

    VirtualFile targetVirtualFile = BashPsiUtils.findFileContext(targetFile).getVirtualFile();
    if (!(targetVirtualFile.getFileSystem() instanceof LocalFileSystem)) {
        throw new IncorrectOperationException("Can not bind to non-local files");
    }

    VirtualFile baseParent = baseVirtualFile.getParent();
    VirtualFile targetParent = targetVirtualFile.getParent();
    if (baseParent == null || targetParent == null) {
        throw new IllegalStateException("parent directories not found");
    }

    char separator = '/';

    String baseDirPath = ensureEnds(baseParent.getPath(), separator);
    String targetDirPath = ensureEnds(targetParent.getPath(), separator);

    String targetRelativePath = FileUtilRt.getRelativePath(baseDirPath, targetDirPath, separator, true);
    if (targetRelativePath == null) {
        return null;
    }

    if (".".equals(targetRelativePath)) {
        //same parent dir
        return targetVirtualFile.getName();
    }

    return ensureEnds(targetRelativePath, separator) + targetVirtualFile.getName();
}
 
Example 15
Source File: PsiDirectoryImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public PsiFile copyFileFrom(@Nonnull String newName, @Nonnull PsiFile originalFile) throws IncorrectOperationException {
  checkCreateFile(newName);

  final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(originalFile);
  if (document != null) {
    FileDocumentManager.getInstance().saveDocument(document);
  }

  final VirtualFile parent = getVirtualFile();
  try {
    final VirtualFile vFile = originalFile.getVirtualFile();
    if (vFile == null) throw new IncorrectOperationException("Cannot copy nonphysical file");
    VirtualFile copyVFile;
    if (parent.getFileSystem() == vFile.getFileSystem()) {
      copyVFile = vFile.copy(this, parent, newName);
    }
    else if (vFile instanceof LightVirtualFile) {
      copyVFile = parent.createChildData(this, newName);
      copyVFile.setBinaryContent(originalFile.getText().getBytes(copyVFile.getCharset()));
    }
    else {
      copyVFile = VfsUtilCore.copyFile(this, vFile, parent, newName);
    }
    LOG.assertTrue(copyVFile != null, "File was not copied: " + vFile);
    DumbService.getInstance(getProject()).completeJustSubmittedTasks();
    final PsiFile copyPsi = myManager.findFile(copyVFile);
    if (copyPsi == null) {
      LOG.error("Could not find file '" + copyVFile + "' after copying '" + vFile + "'");
    }
    updateAddedFile(copyPsi);
    return copyPsi;
  }
  catch (IOException e) {
    throw new IncorrectOperationException(e);
  }
}
 
Example 16
Source File: ShowImageDuplicatesAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
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 17
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void fileChanged(@NotNull final Project project, @NotNull final VirtualFile file) {
  if (!BUILD_FILE_NAME.equals(file.getName())) {
    return;
  }
  if (LocalFileSystem.getInstance() != file.getFileSystem() && !ApplicationManager.getApplication().isUnitTestMode()) {
    return;
  }
  if (!VfsUtilCore.isAncestor(project.getBaseDir(), file, true)) {
    return;
  }
  getInstance(project).scheduleUpdate();
}
 
Example 18
Source File: FileElement.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static boolean isArchiveFileSystem(VirtualFile file) {
  return file.getFileSystem() instanceof ArchiveFileSystem;
}
 
Example 19
Source File: ArchiveFileDiffElement.java    From consulo with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"ConstantConditions"})
public ArchiveFileDiffElement(@Nonnull VirtualFile file) {
  super(file.getFileSystem() instanceof ArchiveFileSystem ? file : ArchiveVfsUtil.getArchiveRootForLocalFile(file));
}
 
Example 20
Source File: ProjectUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static String calcRelativeToProjectPath(@Nonnull final VirtualFile file,
                                               @Nullable final Project project,
                                               final boolean includeFilePath,
                                               final boolean includeUniqueFilePath,
                                               final boolean keepModuleAlwaysOnTheLeft) {
  if (file instanceof VirtualFilePathWrapper) {
    return includeFilePath ? ((VirtualFilePathWrapper)file).getPresentablePath() : file.getName();
  }
  String url;
  if (includeFilePath) {
    url = file.getPresentableUrl();
  }
  else if (includeUniqueFilePath) {
    url = UniqueVFilePathBuilder.getInstance().getUniqueVirtualFilePath(project, file);
  }
  else {
    url = file.getName();
  }
  if (project == null) {
    return url;
  }
  else {
    final VirtualFile baseDir = project.getBaseDir();
    if (baseDir != null && includeFilePath) {
      //noinspection ConstantConditions
      final String projectHomeUrl = baseDir.getPresentableUrl();
      if (url.startsWith(projectHomeUrl)) {
        url = "..." + url.substring(projectHomeUrl.length());
      }
    }

    if (SystemInfo.isMac && file.getFileSystem() instanceof ArchiveFileSystem) {
      final VirtualFile fileForJar = ((ArchiveFileSystem)file.getFileSystem()).getLocalVirtualFileFor(file);
      if (fileForJar != null) {
        final OrderEntry libraryEntry = LibraryUtil.findLibraryEntry(file, project);
        if (libraryEntry != null) {
          if (libraryEntry instanceof ModuleExtensionWithSdkOrderEntry) {
            url = url + " - [" + ((ModuleExtensionWithSdkOrderEntry)libraryEntry).getSdkName() + "]";
          }
          else {
            url = url + " - [" + libraryEntry.getPresentableName() + "]";
          }
        }
        else {
          url = url + " - [" + fileForJar.getName() + "]";
        }
      }
    }

    final Module module = ModuleUtil.findModuleForFile(file, project);
    if (module == null) return url;
    return !keepModuleAlwaysOnTheLeft && SystemInfo.isMac ? url + " - [" + module.getName() + "]" : "[" + module.getName() + "] - " + url;
  }
}