fix "IDEA-221944 Deadlock on opening second project" and support preloading for proje...
[idea/community.git] / java / java-impl / src / com / intellij / psi / impl / file / PsiJavaDirectoryFactory.java
1 // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
2 package com.intellij.psi.impl.file;
3
4 import com.intellij.openapi.project.Project;
5 import com.intellij.openapi.roots.ProjectFileIndex;
6 import com.intellij.openapi.roots.ProjectRootManager;
7 import com.intellij.openapi.util.io.FileUtil;
8 import com.intellij.openapi.util.text.StringUtil;
9 import com.intellij.openapi.vfs.VirtualFile;
10 import com.intellij.psi.*;
11 import com.intellij.psi.impl.PsiManagerImpl;
12 import org.jetbrains.annotations.NotNull;
13 import org.jetbrains.annotations.Nullable;
14 import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes;
15
16 /**
17  * @author yole
18  */
19 public final class PsiJavaDirectoryFactory extends PsiDirectoryFactory {
20   private final PsiManagerImpl myManager;
21
22   public PsiJavaDirectoryFactory(@NotNull Project project) {
23     myManager = (PsiManagerImpl)PsiManager.getInstance(project);
24   }
25
26   @NotNull
27   @Override
28   public PsiDirectory createDirectory(@NotNull final VirtualFile file) {
29     return new PsiJavaDirectoryImpl(myManager, file);
30   }
31
32   @Override
33   @NotNull
34   public String getQualifiedName(@NotNull final PsiDirectory directory, final boolean presentable) {
35     final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(directory);
36     if (aPackage != null) {
37       final String qualifiedName = aPackage.getQualifiedName();
38       if (!qualifiedName.isEmpty()) return qualifiedName;
39       if (presentable) {
40         return PsiBundle.message("default.package.presentation") + " (" + directory.getVirtualFile().getPresentableUrl() + ")";
41       }
42       return "";
43     }
44     return presentable ? StringUtil.notNullize(FileUtil.getLocationRelativeToUserHome(directory.getVirtualFile().getPresentableUrl())) : "";
45   }
46
47   @Nullable
48   @Override
49   public PsiDirectoryContainer getDirectoryContainer(@NotNull PsiDirectory directory) {
50     return JavaDirectoryService.getInstance().getPackage(directory);
51   }
52
53   @Override
54   public boolean isPackage(@NotNull PsiDirectory directory) {
55     ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myManager.getProject()).getFileIndex();
56     VirtualFile virtualFile = directory.getVirtualFile();
57     return fileIndex.isUnderSourceRootOfType(virtualFile, JavaModuleSourceRootTypes.SOURCES) && fileIndex.getPackageNameByDirectory(virtualFile) != null;
58   }
59
60   @Override
61   public boolean isValidPackageName(String name) {
62     return PsiNameHelper.getInstance(myManager.getProject()).isQualifiedName(name);
63   }
64 }