Exemplo n.º 1
0
  @NotNull
  private static List<VirtualFile> findClasses(File file, boolean isJre) {
    List<VirtualFile> result = ContainerUtil.newArrayList();
    VirtualFileManager fileManager = VirtualFileManager.getInstance();

    String path = file.getPath();
    if (JrtFileSystem.isModularJdk(path)) {
      String url =
          VirtualFileManager.constructUrl(
              JrtFileSystem.PROTOCOL,
              FileUtil.toSystemIndependentName(path) + JrtFileSystem.SEPARATOR);
      for (String module : JrtFileSystem.listModules(path)) {
        ContainerUtil.addIfNotNull(result, fileManager.findFileByUrl(url + module));
      }
    }

    for (File root : JavaSdkUtil.getJdkClassesRoots(file, isJre)) {
      String url = VfsUtil.getUrlForLibraryRoot(root);
      ContainerUtil.addIfNotNull(result, fileManager.findFileByUrl(url));
    }

    Collections.sort(result, (o1, o2) -> o1.getPath().compareTo(o2.getPath()));

    return result;
  }
  @NotNull
  private VirtualFilePointer create(
      @Nullable("null means the pointer will be created from the (not null) url") VirtualFile file,
      @Nullable("null means url has to be computed from the (not-null) file path") String url,
      @NotNull Disposable parentDisposable,
      @Nullable VirtualFilePointerListener listener) {
    VirtualFileSystem fileSystem;
    String protocol;
    String path;
    if (file == null) {
      int protocolEnd = url.indexOf(URLUtil.SCHEME_SEPARATOR);
      if (protocolEnd == -1) {
        protocol = null;
        fileSystem = null;
      } else {
        protocol = url.substring(0, protocolEnd);
        fileSystem = myVirtualFileManager.getFileSystem(protocol);
      }
      path = url.substring(protocolEnd + URLUtil.SCHEME_SEPARATOR.length());
    } else {
      fileSystem = file.getFileSystem();
      protocol = fileSystem.getProtocol();
      path = file.getPath();
      url = VirtualFileManager.constructUrl(protocol, path);
    }

    if (fileSystem == TEMP_FILE_SYSTEM) {
      // for tests, recreate always
      VirtualFile found = file == null ? VirtualFileManager.getInstance().findFileByUrl(url) : file;
      return new IdentityVirtualFilePointer(found, url);
    }

    boolean isJar = fileSystem == JAR_FILE_SYSTEM;
    if (fileSystem != LOCAL_FILE_SYSTEM && !isJar) {
      // we are unable to track alien file systems for now
      VirtualFile found =
          fileSystem == null
              ? null
              : file != null ? file : VirtualFileManager.getInstance().findFileByUrl(url);
      // if file is null, this pointer will never be alive
      return getOrCreateIdentity(url, found);
    }

    if (file == null) {
      String cleanPath = cleanupPath(path, isJar);
      // if newly created path is the same as substringed from url one then the url did not change,
      // we can reuse it
      //noinspection StringEquality
      if (cleanPath != path) {
        url = VirtualFileManager.constructUrl(protocol, cleanPath);
        path = cleanPath;
      }
    }
    // else url has come from VirtualFile.getPath() and is good enough

    VirtualFilePointerImpl pointer =
        getOrCreate(parentDisposable, listener, path, Pair.create(file, url));
    DelegatingDisposable.registerDisposable(parentDisposable, pointer);
    return pointer;
  }
 private String dubImportPath(String rootPath) {
   String pathUrl = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, rootPath);
   VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(pathUrl);
   if (file == null) {
     return null;
   }
   final List<String> sourcesDir = new ArrayList<>();
   VfsUtilCore.visitChildrenRecursively(
       file,
       new VirtualFileVisitor() {
         @Override
         public boolean visitFile(@NotNull VirtualFile file) {
           if (file.isDirectory()) {
             if (file.getName().equals("source")) {
               sourcesDir.add("source");
             }
             if (file.getName().equals("src")) {
               sourcesDir.add("src");
             }
           }
           return true;
         }
       });
   return sourcesDir.isEmpty() ? null : rootPath + File.separator + sourcesDir.get(0);
 }
  @NotNull
  private VirtualFilePointer create(
      @Nullable VirtualFile file,
      @NotNull String url,
      @NotNull final Disposable parentDisposable,
      @Nullable VirtualFilePointerListener listener) {
    String protocol;
    VirtualFileSystem fileSystem;
    if (file == null) {
      protocol = VirtualFileManager.extractProtocol(url);
      fileSystem = myVirtualFileManager.getFileSystem(protocol);
    } else {
      protocol = null;
      fileSystem = file.getFileSystem();
    }
    if (fileSystem == TempFileSystem.getInstance()) {
      // for tests, recreate always since
      VirtualFile found =
          fileSystem == null
              ? null
              : file != null ? file : VirtualFileManager.getInstance().findFileByUrl(url);
      return new IdentityVirtualFilePointer(found, url);
    }
    if (fileSystem != LocalFileSystem.getInstance() && fileSystem != JarFileSystem.getInstance()) {
      // we are unable to track alien file systems for now
      VirtualFile found =
          fileSystem == null
              ? null
              : file != null ? file : VirtualFileManager.getInstance().findFileByUrl(url);
      // if file is null, this pointer will never be alive
      return getOrCreateIdentity(url, found);
    }

    String path;
    if (file == null) {
      path = VirtualFileManager.extractPath(url);
      path = cleanupPath(path, protocol);
      url = VirtualFileManager.constructUrl(protocol, path);
    } else {
      path = file.getPath();
      // url has come from VirtualFile.getUrl() and is good enough
    }

    VirtualFilePointerImpl pointer = getOrCreate(file, url, parentDisposable, listener, path);

    int newCount = pointer.incrementUsageCount();

    if (newCount == 1) {
      Disposer.register(parentDisposable, pointer);
    } else {
      // already registered
      register(parentDisposable, pointer);
    }

    return pointer;
  }
Exemplo n.º 5
0
 private void disposeListeners() {
   FileStatusManager.getInstance(myProject).removeFileStatusListener(myFileStatusListener);
   VirtualFileManager.getInstance().removeVirtualFileListener(myFileListener);
   VirtualFileManager.getInstance().removeVirtualFileManagerListener(myVirtualFileManagerListener);
   myProject
       .getComponent(ProjectLevelVcsManager.class)
       .removeVcsListener(myDirectoryMappingListener);
   ChangeListManager.getInstance(myProject).removeChangeListListener(myChangeListListener);
   myMessageBusConnection.disconnect();
 }
 public static String getUrlForLibraryRoot(@NotNull File libraryRoot) {
   String path = FileUtil.toSystemIndependentName(libraryRoot.getAbsolutePath());
   if (FileTypeManager.getInstance().getFileTypeByFileName(libraryRoot.getName())
       == FileTypes.ARCHIVE) {
     return VirtualFileManager.constructUrl(
         JarFileSystem.getInstance().getProtocol(), path + JarFileSystem.JAR_SEPARATOR);
   } else {
     return VirtualFileManager.constructUrl(LocalFileSystem.getInstance().getProtocol(), path);
   }
 }
  @SuppressWarnings({"HardCodedStringLiteral"})
  @Nullable
  public static VirtualFile findRelativeFile(@NotNull String uri, @Nullable VirtualFile base) {
    if (base != null) {
      if (!base.isValid()) {
        LOG.error("Invalid file name: " + base.getName() + ", url: " + uri);
      }
    }

    uri = uri.replace('\\', '/');

    if (uri.startsWith("file:///")) {
      uri = uri.substring("file:///".length());
      if (!SystemInfo.isWindows) uri = "/" + uri;
    } else if (uri.startsWith("file:/")) {
      uri = uri.substring("file:/".length());
      if (!SystemInfo.isWindows) uri = "/" + uri;
    } else if (uri.startsWith("file:")) {
      uri = uri.substring("file:".length());
    }

    VirtualFile file = null;

    if (uri.startsWith("jar:file:/")) {
      uri = uri.substring("jar:file:/".length());
      if (!SystemInfo.isWindows) uri = "/" + uri;
      file = VirtualFileManager.getInstance().findFileByUrl(JarFileSystem.PROTOCOL_PREFIX + uri);
    } else {
      if (!SystemInfo.isWindows && StringUtil.startsWithChar(uri, '/')) {
        file = LocalFileSystem.getInstance().findFileByPath(uri);
      } else if (SystemInfo.isWindows
          && uri.length() >= 2
          && Character.isLetter(uri.charAt(0))
          && uri.charAt(1) == ':') {
        file = LocalFileSystem.getInstance().findFileByPath(uri);
      }
    }

    if (file == null && uri.contains(JarFileSystem.JAR_SEPARATOR)) {
      file = JarFileSystem.getInstance().findFileByPath(uri);
      if (file == null && base == null) {
        file = VirtualFileManager.getInstance().findFileByUrl(uri);
      }
    }

    if (file == null) {
      if (base == null) return LocalFileSystem.getInstance().findFileByPath(uri);
      if (!base.isDirectory()) base = base.getParent();
      if (base == null) return LocalFileSystem.getInstance().findFileByPath(uri);
      file = VirtualFileManager.getInstance().findFileByUrl(base.getUrl() + "/" + uri);
      if (file == null) return null;
    }

    return file;
  }
  @Nullable
  private static VirtualFile getHelpFile(final PsiElement element) {
    final XmlTag xmlTag = PsiTreeUtil.getParentOfType(element, XmlTag.class);
    if (xmlTag == null) {
      return null;
    }
    final AntDomElement antElement = AntSupport.getAntDomElement(xmlTag);
    if (antElement == null) {
      return null;
    }
    final AntDomProject antProject = antElement.getAntProject();
    if (antProject == null) {
      return null;
    }
    final AntInstallation installation = antProject.getAntInstallation();
    if (installation == null) {
      return null; // not configured properly and bundled installation missing
    }
    final String antHomeDir = AntInstallation.HOME_DIR.get(installation.getProperties());

    if (antHomeDir == null) {
      return null;
    }

    @NonNls String path = antHomeDir + "/docs/manual";
    String url;
    if (new File(path).exists()) {
      url =
          VirtualFileManager.constructUrl(
              LocalFileSystem.PROTOCOL, FileUtil.toSystemIndependentName(path));
    } else {
      path = antHomeDir + "/docs.zip";
      if (new File(path).exists()) {
        url =
            VirtualFileManager.constructUrl(
                JarFileSystem.PROTOCOL,
                FileUtil.toSystemIndependentName(path)
                    + JarFileSystem.JAR_SEPARATOR
                    + "docs/manual");
      } else {
        return null;
      }
    }

    final VirtualFile documentationRoot = VirtualFileManager.getInstance().findFileByUrl(url);
    if (documentationRoot == null) {
      return null;
    }

    return getHelpFile(antElement, documentationRoot);
  }
  public void testFindRoot() throws IOException {
    VirtualFile root = LocalFileSystem.getInstance().findFileByPath("wrong_path");
    assertNull(root);

    VirtualFile root2;
    if (SystemInfo.isWindows) {
      root = LocalFileSystem.getInstance().findFileByPath("\\\\unit-133");
      assertNotNull(root);
      root2 = LocalFileSystem.getInstance().findFileByPath("//UNIT-133");
      assertNotNull(root2);
      assertEquals(String.valueOf(root2), root, root2);
      RefreshQueue.getInstance().processSingleEvent(new VFileDeleteEvent(this, root, false));

      root = LocalFileSystem.getInstance().findFileByIoFile(new File("\\\\unit-133"));
      assertNotNull(root);
      RefreshQueue.getInstance().processSingleEvent(new VFileDeleteEvent(this, root, false));

      if (new File("c:").exists()) {
        root = LocalFileSystem.getInstance().findFileByPath("c:");
        assertNotNull(root);
        assertEquals("C:/", root.getPath());

        root2 = LocalFileSystem.getInstance().findFileByPath("C:\\");
        assertEquals(String.valueOf(root2), root, root2);
      }
    } else if (SystemInfo.isUnix) {
      root = LocalFileSystem.getInstance().findFileByPath("/");
      assertNotNull(root);
      assertEquals(root.getPath(), "/");
    }

    root = LocalFileSystem.getInstance().findFileByPath("");
    assertNotNull(root);

    File jarFile = IoTestUtil.createTestJar();
    root = VirtualFileManager.getInstance().findFileByUrl("jar://" + jarFile.getPath() + "!/");
    assertNotNull(root);

    root2 =
        VirtualFileManager.getInstance()
            .findFileByUrl("jar://" + jarFile.getPath().replace(File.separator, "//") + "!/");
    assertEquals(String.valueOf(root2), root, root2);

    if (!SystemInfo.isFileSystemCaseSensitive) {
      root2 =
          VirtualFileManager.getInstance()
              .findFileByUrl("jar://" + jarFile.getPath().toUpperCase(Locale.US) + "!/");
      assertEquals(String.valueOf(root2), root, root2);
    }
  }
  @Nullable
  public static VirtualFile getDirectory(@NotNull final FindModel findModel) {
    String directoryName = findModel.getDirectoryName();
    if (findModel.isProjectScope() || StringUtil.isEmpty(directoryName)) {
      return null;
    }

    String path = directoryName.replace(File.separatorChar, '/');
    VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(path);
    if (virtualFile == null || !virtualFile.isDirectory()) {
      virtualFile = null;
      for (LocalFileProvider provider :
          ((VirtualFileManagerEx) VirtualFileManager.getInstance()).getLocalFileProviders()) {
        VirtualFile file = provider.findLocalVirtualFileByPath(path);
        if (file != null && file.isDirectory()) {
          if (file.getChildren().length > 0) {
            virtualFile = file;
            break;
          }
          if (virtualFile == null) {
            virtualFile = file;
          }
        }
      }
    }
    return virtualFile;
  }
  public ExternalAnnotationsManagerImpl(
      @NotNull final Project project, final PsiManager psiManager) {
    super(psiManager);
    myBus = project.getMessageBus();
    final MessageBusConnection connection = myBus.connect(project);
    connection.subscribe(
        ProjectTopics.PROJECT_ROOTS,
        new ModuleRootAdapter() {
          @Override
          public void rootsChanged(ModuleRootEvent event) {
            dropCache();
          }
        });

    final MyVirtualFileListener fileListener = new MyVirtualFileListener();
    VirtualFileManager.getInstance().addVirtualFileListener(fileListener);
    Disposer.register(
        myPsiManager.getProject(),
        new Disposable() {
          @Override
          public void dispose() {
            VirtualFileManager.getInstance().removeVirtualFileListener(fileListener);
          }
        });
  }
  @Override
  public void moduleAdded() {
    if (!myModuleInitialized) {
      myConnection.subscribe(
          ProjectTopics.PROJECT_ROOTS,
          new ModuleRootAdapter() {
            @Override
            public void rootsChanged(ModuleRootEvent event) {
              scheduleUpdate();
            }
          });
      myConnection.subscribe(GoLibrariesService.LIBRARIES_TOPIC, newRootUrls -> scheduleUpdate());

      Project project = myModule.getProject();
      StartupManager.getInstance(project)
          .runWhenProjectIsInitialized(
              () -> {
                if (!project.isDisposed() && !myModule.isDisposed()) {
                  for (PsiFileSystemItem vendor :
                      FilenameIndex.getFilesByName(
                          project, GoConstants.VENDOR, GoUtil.moduleScope(myModule), true)) {
                    if (vendor.isDirectory()) {
                      showVendoringNotification();
                      break;
                    }
                  }
                }
              });

      VirtualFileManager.getInstance().addVirtualFileListener(myFilesListener);
    }
    scheduleUpdate(0);
    myModuleInitialized = true;
  }
  public ProjectRootManagerComponent(Project project, StartupManager startupManager) {
    super(project);

    myConnection = project.getMessageBus().connect(project);
    myConnection.subscribe(
        FileTypeManager.TOPIC,
        new FileTypeListener() {
          @Override
          public void beforeFileTypesChanged(@NotNull FileTypeEvent event) {
            beforeRootsChange(true);
          }

          @Override
          public void fileTypesChanged(@NotNull FileTypeEvent event) {
            rootsChanged(true);
          }
        });

    VirtualFileManager.getInstance()
        .addVirtualFileManagerListener(
            new VirtualFileManagerAdapter() {
              @Override
              public void afterRefreshFinish(boolean asynchronous) {
                doUpdateOnRefresh();
              }
            },
            project);

    startupManager.registerStartupActivity(
        new Runnable() {
          @Override
          public void run() {
            myStartupActivityPerformed = true;
          }
        });

    myHandler =
        new BatchUpdateListener() {
          @Override
          public void onBatchUpdateStarted() {
            myRootsChanged.levelUp();
            myFileTypesChanged.levelUp();
          }

          @Override
          public void onBatchUpdateFinished() {
            myRootsChanged.levelDown();
            myFileTypesChanged.levelDown();
          }
        };

    myConnection.subscribe(VirtualFilePointerListener.TOPIC, new MyVirtualFilePointerListener());
    myDoLogCachesUpdate =
        ApplicationManager.getApplication().isInternal()
            && !ApplicationManager.getApplication().isUnitTestMode();
  }
Exemplo n.º 14
0
 @Nullable
 private static VirtualFile findInJar(File jarFile, String relativePath) {
   if (!jarFile.exists()) return null;
   String url =
       JarFileSystem.PROTOCOL_PREFIX
           + jarFile.getAbsolutePath().replace(File.separatorChar, '/')
           + JarFileSystem.JAR_SEPARATOR
           + relativePath;
   return VirtualFileManager.getInstance().findFileByUrl(url);
 }
  public void testCreationOfExcludedDirWithFilesDuringRefreshShouldNotThrowException()
      throws Exception {
    // there was a problem with the DirectoryIndex - the files that were created during the refresh
    // were not correctly excluded, thereby causing the LocalHistory to fail during addition of
    // files under the excluded dir.

    File targetDir = createTargetDir();
    FileUtil.copyDir(targetDir, new File(myRoot.getPath(), "target"));
    VirtualFileManager.getInstance().syncRefresh();

    String classesPath = myRoot.getPath() + "/target/classes";
    addExcludedDir(classesPath);
    final VirtualFile classesDir = LocalFileSystem.getInstance().findFileByPath(classesPath);
    assertNotNull(classesDir);
    delete(classesDir.getParent());

    FileUtil.copyDir(targetDir, new File(myRoot.getPath(), "target"));
    VirtualFileManager.getInstance().syncRefresh(); // shouldn't throw
  }
Exemplo n.º 16
0
  @Nullable
  public static VirtualFile getVirtualFileForJar(@Nullable VirtualFile entryVFile) {
    if (entryVFile == null) return null;
    final String path = entryVFile.getPath();
    final int separatorIndex = path.indexOf("!/");
    if (separatorIndex < 0) return null;

    String localPath = path.substring(0, separatorIndex);
    return VirtualFileManager.getInstance().findFileByUrl("file://" + localPath);
  }
  @Override
  protected void onDispose() {
    if (myFileListener != null)
      VirtualFileManager.getInstance().removeVirtualFileListener(myFileListener);

    for (Document document : getDocuments()) {
      document.removeDocumentListener(myDocumentListener);
    }
    super.onDispose();
  }
  @Override
  protected void onInit() {
    super.onInit();
    if (myFileListener != null)
      VirtualFileManager.getInstance().addVirtualFileListener(myFileListener);

    for (Document document : getDocuments()) {
      document.addDocumentListener(myDocumentListener);
    }
  }
 @Override
 public void disposeComponent() {
   Disposer.dispose(myConnection);
   Disposer.dispose(myAlarm);
   VirtualFileManager.getInstance().removeVirtualFileListener(myFilesListener);
   myLastHandledGoPathSourcesRoots.clear();
   myLastHandledExclusions.clear();
   LocalFileSystem.getInstance().removeWatchedRoots(myWatchedRequests);
   myWatchedRequests.clear();
 }
Exemplo n.º 20
0
  public ModuleImpl(@NotNull String filePath, @NotNull Project project) {
    super(project, "Module " + moduleNameByFileName(PathUtil.getFileName(filePath)));

    getPicoContainer().registerComponentInstance(Module.class, this);

    myProject = project;
    myModuleScopeProvider = new ModuleScopeProviderImpl(this);

    myName = moduleNameByFileName(PathUtil.getFileName(filePath));

    VirtualFileManager.getInstance().addVirtualFileListener(new MyVirtualFileListener(), this);
  }
  private void registerExternalProjectFileListener(VirtualFileManager virtualFileManager) {
    virtualFileManager.addVirtualFileManagerListener(
        new VirtualFileManagerListener() {
          @Override
          public void beforeRefreshStart(boolean asynchronous) {}

          @Override
          public void afterRefreshFinish(boolean asynchronous) {
            scheduleReloadApplicationAndProject();
          }
        });
  }
  private static void refreshVFS(boolean async) {
    try {
      final Semaphore s = new Semaphore(1);
      s.acquire();

      VirtualFileManager fm = VirtualFileManager.getInstance();
      if (async) {
        fm.asyncRefresh(s::release);
      } else {
        try {
          fm.syncRefresh();
        } finally {
          s.release();
        }
      }

      assertTrue(s.tryAcquire(1, TimeUnit.MINUTES));
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 23
0
  private void installListeners() {
    FileStatusManager.getInstance(myProject)
        .addFileStatusListener(myFileStatusListener = new FileStatusChangeListener());
    VirtualFileManager.getInstance()
        .addVirtualFileListener(myFileListener = new FileChangesListener());
    VirtualFileManager.getInstance()
        .addVirtualFileManagerListener(myVirtualFileManagerListener = new RefreshListener());
    myDirectoryMappingListener =
        new VcsListener() {
          public void directoryMappingChanged() {
            rebuildTreeLater();
          }
        };
    myProject.getComponent(ProjectLevelVcsManager.class).addVcsListener(myDirectoryMappingListener);
    ChangeListManager.getInstance(myProject)
        .addChangeListListener(myChangeListListener = new ChangeListUpdateListener());
    myMessageBusConnection = myBus.connect();
    myMessageBusConnection.subscribe(
        FileEditorManagerListener.FILE_EDITOR_MANAGER,
        new FileEditorManagerAdapter() {
          @Override
          public void fileOpened(FileEditorManager source, VirtualFile file) {
            if (myProjectView.isAutoscrollFromSource(getId())) {
              selectNode(file, false);
            }
          }

          @Override
          public void selectionChanged(FileEditorManagerEvent event) {
            if (myProjectView.isAutoscrollFromSource(getId())) {
              VirtualFile newFile = event.getNewFile();
              if (newFile != null) {
                selectNode(newFile, false);
              }
            }
          }
        });
  }
  @Override
  public void dispose() {
    if (mySelectedEditor != null) {
      for (final Map.Entry<PropertiesFile, Editor> entry : myEditors.entrySet()) {
        if (mySelectedEditor.equals(entry.getValue())) {
          writeEditorPropertyValue(mySelectedEditor, entry.getKey(), null);
        }
      }
    }

    VirtualFileManager.getInstance().removeVirtualFileListener(myVfsListener);
    myDisposed = true;
    Disposer.dispose(myStructureViewComponent);
    releaseAllEditors();
  }
 private static void addRootsToTrack(
     final String[] urls, final Collection<String> recursive, final Collection<String> flat) {
   for (String url : urls) {
     if (url != null) {
       final String protocol = VirtualFileManager.extractProtocol(url);
       if (protocol == null || LocalFileSystem.PROTOCOL.equals(protocol)) {
         recursive.add(extractLocalPath(url));
       } else if (JarFileSystem.PROTOCOL.equals(protocol)) {
         flat.add(extractLocalPath(url));
       } else if (StandardFileSystems.JRT_PROTOCOL.equals(protocol)) {
         recursive.add(extractLocalPath(url));
       }
     }
   }
 }
Exemplo n.º 26
0
 public static void addLibrary(
     Module module, String libName, String libDir, String[] classRoots, String[] sourceRoots) {
   String proto =
       (classRoots.length > 0 ? classRoots[0] : sourceRoots[0]).endsWith(".jar!/")
           ? JarFileSystem.PROTOCOL
           : LocalFileSystem.PROTOCOL;
   String parentUrl = VirtualFileManager.constructUrl(proto, libDir);
   List<String> classesUrls = new ArrayList<>();
   List<String> sourceUrls = new ArrayList<>();
   for (String classRoot : classRoots) {
     classesUrls.add(parentUrl + classRoot);
   }
   for (String sourceRoot : sourceRoots) {
     sourceUrls.add(parentUrl + sourceRoot);
   }
   ModuleRootModificationUtil.addModuleLibrary(module, libName, classesUrls, sourceUrls);
 }
Exemplo n.º 27
0
  public static void attachJdkAnnotations(@NotNull SdkModificator modificator) {
    LocalFileSystem lfs = LocalFileSystem.getInstance();
    List<String> pathsChecked = new ArrayList<>();
    // community idea under idea
    String path =
        FileUtil.toSystemIndependentName(PathManager.getHomePath()) + "/java/jdkAnnotations";
    VirtualFile root = lfs.findFileByPath(path);
    pathsChecked.add(path);

    if (root == null) { // idea under idea
      path =
          FileUtil.toSystemIndependentName(PathManager.getHomePath())
              + "/community/java/jdkAnnotations";
      root = lfs.findFileByPath(path);
      pathsChecked.add(path);
    }
    if (root == null) { // build
      String url =
          "jar://"
              + FileUtil.toSystemIndependentName(PathManager.getHomePath())
              + "/lib/jdkAnnotations.jar!/";
      root = VirtualFileManager.getInstance().findFileByUrl(url);
      pathsChecked.add(
          FileUtil.toSystemIndependentName(PathManager.getHomePath()) + "/lib/jdkAnnotations.jar");
    }
    if (root == null) {
      String msg = "Paths checked:\n";
      for (String p : pathsChecked) {
        File file = new File(p);
        msg +=
            "Path: '"
                + p
                + "' "
                + (file.exists() ? "Found" : "Not found")
                + "; directory children: "
                + Arrays.toString(file.getParentFile().listFiles())
                + "\n";
      }
      LOG.error("JDK annotations not found", msg);
      return;
    }

    OrderRootType annoType = AnnotationOrderRootType.getInstance();
    modificator.removeRoot(root, annoType);
    modificator.addRoot(root, annoType);
  }
  @NotNull
  private static String getPresentableFile(
      @NotNull String url, @Nullable Map<VirtualFile, VirtualFile> presentableFilesMap) {
    final VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url);
    if (file == null) {
      return url;
    }

    if (presentableFilesMap == null) {
      return url;
    }

    for (Map.Entry<VirtualFile, VirtualFile> entry : presentableFilesMap.entrySet()) {
      if (file == entry.getValue()) {
        return entry.getKey().getUrl();
      }
    }
    return url;
  }
  public FileTreeBuilder(
      JTree tree,
      DefaultTreeModel treeModel,
      AbstractTreeStructure treeStructure,
      Comparator<NodeDescriptor> comparator,
      FileChooserDescriptor chooserDescriptor,
      @SuppressWarnings("UnusedParameters") Runnable onInitialized) {
    super(tree, treeModel, treeStructure, comparator, false);
    myChooserDescriptor = chooserDescriptor;

    initRootNode();

    VirtualFileAdapter listener =
        new VirtualFileAdapter() {
          @Override
          public void propertyChanged(@NotNull VirtualFilePropertyEvent event) {
            doUpdate();
          }

          @Override
          public void fileCreated(@NotNull VirtualFileEvent event) {
            doUpdate();
          }

          @Override
          public void fileDeleted(@NotNull VirtualFileEvent event) {
            doUpdate();
          }

          @Override
          public void fileMoved(@NotNull VirtualFileMoveEvent event) {
            doUpdate();
          }

          private void doUpdate() {
            queueUpdateFrom(getRootNode(), false);
          }
        };
    VirtualFileManager.getInstance().addVirtualFileListener(listener, this);
  }
  @NotNull
  private VirtualFilePointer create(
      @Nullable VirtualFile file,
      @NotNull String url,
      @NotNull final Disposable parentDisposable,
      @Nullable VirtualFilePointerListener listener) {
    String protocol;
    IVirtualFileSystem fileSystem;
    if (file == null) {
      protocol = VirtualFileManager.extractProtocol(url);
      fileSystem = myVirtualFileManager.getFileSystem(protocol);
    } else {
      protocol = null;
      fileSystem = file.getFileSystem();
    }
    if (fileSystem == myTempFileSystem) {
      // for tests, recreate always
      VirtualFile found = file == null ? VirtualFileManager.getInstance().findFileByUrl(url) : file;
      return new IdentityVirtualFilePointer(found, url);
    }
    if (fileSystem != myLocalFileSystem && !(fileSystem instanceof ArchiveFileSystem)) {
      // we are unable to track alien file systems for now
      VirtualFile found =
          fileSystem == null
              ? null
              : file != null ? file : VirtualFileManager.getInstance().findFileByUrl(url);
      // if file is null, this pointer will never be alive
      return getOrCreateIdentity(url, found);
    }

    String path;
    if (file == null) {
      path = VirtualFileManager.extractPath(url);
      path = cleanupPath(path, protocol, fileSystem);
      url = VirtualFileManager.constructUrl(protocol, path);
    } else {
      path = file.getPath();
      // url has come from VirtualFile.getUrl() and is good enough
    }

    VirtualFilePointerImpl pointer =
        getOrCreate(parentDisposable, listener, path, Pair.create(file, url));

    DelegatingDisposable.registerDisposable(parentDisposable, pointer);

    return pointer;
  }