@Nullable private PsiClass getScriptClass() { final VirtualFile scriptFile = getScriptFile(); if (scriptFile == null) return null; final PsiFile file = PsiManager.getInstance(getProject()).findFile(scriptFile); return GroovyRunnerUtil.getRunningClass(file); }
@NotNull private static String findMainClass(VirtualFile gradleHome, VirtualFile script, Project project) { final String userDefined = System.getProperty("gradle.launcher.class"); if (StringUtil.isNotEmpty(userDefined)) { return userDefined; } VirtualFile launcher = gradleHome.findFileByRelativePath("bin/gradle"); if (launcher == null) { launcher = gradleHome.findFileByRelativePath("bin/gradle.bat"); } if (launcher != null) { try { final String text = StringUtil.convertLineSeparators(VfsUtilCore.loadText(launcher)); final Matcher matcher = MAIN_CLASS_NAME_PATTERN.matcher(text); if (matcher.find()) { String candidate = matcher.group(1); if (StringUtil.isNotEmpty(candidate)) { return candidate; } } } catch (IOException ignored) { } } final PsiFile grFile = PsiManager.getInstance(project).findFile(script); if (grFile != null && JavaPsiFacade.getInstance(project) .findClass("org.gradle.BootstrapMain", grFile.getResolveScope()) != null) { return "org.gradle.BootstrapMain"; } return "org.gradle.launcher.GradleMain"; }
@Nullable public static PsiFile virtualFileToPsiFile(Project project, VirtualFile virtualFile) { if (virtualFile == null) { return null; } return PsiManager.getInstance(project).findFile(virtualFile); }
@Nullable public static PsiDirectory findPossiblePackageDirectoryInModule( Module module, String packageName) { PsiDirectory psiDirectory = null; if (!"".equals(packageName)) { PsiPackage rootPackage = findLongestExistingPackage(module.getProject(), packageName); if (rootPackage != null) { final PsiDirectory[] psiDirectories = getPackageDirectoriesInModule(rootPackage, module); if (psiDirectories.length > 0) { psiDirectory = psiDirectories[0]; } } } if (psiDirectory == null) { if (checkSourceRootsConfigured(module)) { final List<VirtualFile> sourceRoots = ModuleRootManager.getInstance(module).getSourceRoots(JavaModuleSourceRootTypes.SOURCES); for (VirtualFile sourceRoot : sourceRoots) { final PsiDirectory directory = PsiManager.getInstance(module.getProject()).findDirectory(sourceRoot); if (directory != null) { psiDirectory = directory; break; } } } } return psiDirectory; }
public static void addLibraryChildren( final LibraryOrSdkOrderEntry entry, final List<AbstractTreeNode> children, Project project, ProjectViewNode node) { final PsiManager psiManager = PsiManager.getInstance(project); VirtualFile[] files = entry instanceof LibraryOrderEntry ? getLibraryRoots((LibraryOrderEntry) entry) : entry.getRootFiles(OrderRootType.CLASSES); for (final VirtualFile file : files) { if (!file.isValid()) continue; if (file.isDirectory()) { final PsiDirectory psiDir = psiManager.findDirectory(file); if (psiDir == null) { continue; } children.add(new PsiDirectoryNode(project, psiDir, node.getSettings())); } else { final PsiFile psiFile = psiManager.findFile(file); if (psiFile == null) continue; children.add(new PsiFileNode(project, psiFile, node.getSettings())); } } }
@Nullable private static PsiElement getElementToCopy( @Nullable final Editor editor, final DataContext dataContext) { PsiElement element = null; if (editor != null) { PsiReference reference = TargetElementUtilBase.findReference(editor); if (reference != null) { element = reference.getElement(); } } if (element == null) { element = LangDataKeys.PSI_ELEMENT.getData(dataContext); } if (element == null && editor == null) { VirtualFile virtualFile = PlatformDataKeys.VIRTUAL_FILE.getData(dataContext); Project project = PlatformDataKeys.PROJECT.getData(dataContext); if (virtualFile != null && project != null) { element = PsiManager.getInstance(project).findFile(virtualFile); } } if (element instanceof PsiFile && !((PsiFile) element).getViewProvider().isPhysical()) { return null; } for (QualifiedNameProvider provider : Extensions.getExtensions(QualifiedNameProvider.EP_NAME)) { PsiElement adjustedElement = provider.adjustElementToCopy(element); if (adjustedElement != null) return adjustedElement; } return element; }
@Nullable public static PsiClass[] getAllTestClasses(final TestClassFilter filter, boolean sync) { final PsiClass[][] holder = new PsiClass[1][]; final Runnable process = () -> { final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); final Collection<PsiClass> set = new LinkedHashSet<>(); final PsiManager manager = PsiManager.getInstance(filter.getProject()); final GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject()); final GlobalSearchScope scope = projectScope.intersectWith(filter.getScope()); for (final PsiClass psiClass : AllClassesSearch.search(scope, manager.getProject())) { if (filter.isAccepted(psiClass)) { if (indicator != null) { indicator.setText2( "Found test class " + ReadAction.compute(psiClass::getQualifiedName)); } set.add(psiClass); } } holder[0] = set.toArray(new PsiClass[set.size()]); }; if (sync) { ProgressManager.getInstance() .runProcessWithProgressSynchronously( process, "Searching For Tests...", true, filter.getProject()); } else { process.run(); } return holder[0]; }
public static void generateProject( @NotNull final Project project, @NotNull final VirtualFile baseDir, @NotNull final String name, @NotNull final String[] authors, @NotNull final String description) { final Course course = getCourse(project, name, authors, description); final PsiDirectory projectDir = PsiManager.getInstance(project).findDirectory(baseDir); if (projectDir == null) return; new WriteCommandAction.Simple(project) { @Override protected void run() throws Throwable { createTestHelper(project, projectDir); PsiDirectory lessonDir = new CCCreateLesson().createItem(null, project, projectDir, course); if (lessonDir == null) { LOG.error("Failed to create lesson"); return; } new CCCreateTask().createItem(null, project, lessonDir, course); } }.execute(); }
private void createTreeModel() { final PsiManager psiManager = PsiManager.getInstance(myProject); final FileIndex fileIndex = myModule != null ? ModuleRootManager.getInstance(myModule).getFileIndex() : ProjectRootManager.getInstance(myProject).getFileIndex(); fileIndex.iterateContent( new ContentIterator() { public boolean processFile(VirtualFile fileOrDir) { if (fileOrDir.isDirectory() && fileIndex.isInSourceContent(fileOrDir)) { final PsiDirectory psiDirectory = psiManager.findDirectory(fileOrDir); LOG.assertTrue(psiDirectory != null); PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(psiDirectory); if (aPackage != null) { addPackage(aPackage); } } return true; } }); TreeUtil.sort( myModel, new Comparator() { public int compare(Object o1, Object o2) { DefaultMutableTreeNode n1 = (DefaultMutableTreeNode) o1; DefaultMutableTreeNode n2 = (DefaultMutableTreeNode) o2; PsiNamedElement element1 = (PsiNamedElement) n1.getUserObject(); PsiNamedElement element2 = (PsiNamedElement) n2.getUserObject(); return element1.getName().compareToIgnoreCase(element2.getName()); } }); }
@Nullable private static PsiElement getSelectedPsiElement( final DataContext dataContext, final Project project) { PsiElement element = null; final Editor editor = CommonDataKeys.EDITOR.getData(dataContext); if (editor != null) { final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (psiFile != null) { final int offset = editor.getCaretModel().getOffset(); element = psiFile.findElementAt(offset); if (element == null && offset > 0 && offset == psiFile.getTextLength()) { element = psiFile.findElementAt(offset - 1); } } } if (element == null) { final PsiElement[] elements = LangDataKeys.PSI_ELEMENT_ARRAY.getData(dataContext); element = elements != null && elements.length > 0 ? elements[0] : null; } if (element == null) { final VirtualFile[] files = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext); if (files != null && files.length > 0) { element = PsiManager.getInstance(project).findFile(files[0]); } } return element; }
@Nullable @Override public PsiPackage resolvePackage( @NotNull PsiPackageManager packageManager, @NotNull VirtualFile virtualFile, @NotNull Class<? extends ModuleExtension> extensionClass, String qualifiedName) { ProjectFileIndex fileIndexFacade = ProjectFileIndex.SERVICE.getInstance(packageManager.getProject()); PsiManager psiManager = PsiManager.getInstance(packageManager.getProject()); if (fileIndexFacade.isInLibraryClasses(virtualFile)) { List<OrderEntry> orderEntriesForFile = fileIndexFacade.getOrderEntriesForFile(virtualFile); for (OrderEntry orderEntry : orderEntriesForFile) { Module ownerModule = orderEntry.getOwnerModule(); ModuleExtension extension = ModuleUtilCore.getExtension(ownerModule, extensionClass); if (extension != null) { for (PsiPackageSupportProvider p : PsiPackageSupportProvider.EP_NAME.getExtensions()) { if (p.isSupported(extension)) { return p.createPackage(psiManager, packageManager, extensionClass, qualifiedName); } } } } } return null; }
private PsiElement[] getElementsToDelete() { ArrayList<PsiElement> result = new ArrayList<PsiElement>(); Object[] elements = getSelectedNodeElements(); for (int idx = 0; elements != null && idx < elements.length; idx++) { if (elements[idx] instanceof PsiElement) { final PsiElement element = (PsiElement) elements[idx]; result.add(element); if (element instanceof PsiDirectory) { final VirtualFile virtualFile = ((PsiDirectory) element).getVirtualFile(); final String path = virtualFile.getPath(); if (path.endsWith(JarFileSystem.JAR_SEPARATOR)) { // if is jar-file root final VirtualFile vFile = LocalFileSystem.getInstance() .findFileByPath( path.substring(0, path.length() - JarFileSystem.JAR_SEPARATOR.length())); if (vFile != null) { final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(vFile); if (psiFile != null) { elements[idx] = psiFile; } } } } } } return result.toArray(new PsiElement[result.size()]); }
@Nullable @Override public RefEntity getReference(final String type, final String fqName) { for (RefManagerExtension extension : myExtensions.values()) { final RefEntity refEntity = extension.getReference(type, fqName); if (refEntity != null) return refEntity; } if (SmartRefElementPointer.FILE.equals(type)) { return RefFileImpl.fileFromExternalName(this, fqName); } if (SmartRefElementPointer.MODULE.equals(type)) { return RefModuleImpl.moduleFromName(this, fqName); } if (SmartRefElementPointer.PROJECT.equals(type)) { return getRefProject(); } if (SmartRefElementPointer.DIR.equals(type)) { String url = VfsUtilCore.pathToUrl(PathMacroManager.getInstance(getProject()).expandPath(fqName)); VirtualFile vFile = VirtualFileManager.getInstance().findFileByUrl(url); if (vFile != null) { final PsiDirectory dir = PsiManager.getInstance(getProject()).findDirectory(vFile); return getReference(dir); } } return null; }
static void subscribeTo(NavBarPanel panel) { if (panel.getClientProperty(LISTENER) != null) { unsubscribeFrom(panel); } final NavBarListener listener = new NavBarListener(panel); final Project project = panel.getProject(); panel.putClientProperty(LISTENER, listener); KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(listener); FileStatusManager.getInstance(project).addFileStatusListener(listener); PsiManager.getInstance(project).addPsiTreeChangeListener(listener); WolfTheProblemSolver.getInstance(project).addProblemListener(listener); ActionManager.getInstance().addAnActionListener(listener); final MessageBusConnection connection = project.getMessageBus().connect(); connection.subscribe(ProjectTopics.PROJECT_ROOTS, listener); connection.subscribe(NavBarModelListener.NAV_BAR, listener); connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, listener); panel.putClientProperty(BUS, connection); panel.addKeyListener(listener); if (panel.isInFloatingMode()) { final Window window = SwingUtilities.windowForComponent(panel); if (window != null) { window.addWindowFocusListener(listener); } } }
@Override @NotNull public Collection<PsiFileSystemItem> getRoots(@NotNull final Module module) { return ContainerUtil.mapNotNull( ModuleRootManager.getInstance(module).getContentRoots(), virtualFile -> PsiManager.getInstance(module.getProject()).findDirectory(virtualFile)); }
@Nullable public static PsiDirectory selectFolderDir( final Project project, VirtualFile res, ResourceFolderType folderType) { final PsiDirectory directory = PsiManager.getInstance(project).findDirectory(res); if (directory == null) { return null; } if (ApplicationManager.getApplication().isUnitTestMode() && ourTargetFolderName != null) { PsiDirectory subDirectory = directory.findSubdirectory(ourTargetFolderName); if (subDirectory != null) { return subDirectory; } return directory.createSubdirectory(ourTargetFolderName); } final CreateResourceDirectoryDialog dialog = new CreateResourceDirectoryDialog(project, folderType, directory, null) { @Override protected InputValidator createValidator() { return new ResourceDirectorySelector(project, directory); } }; dialog.setTitle("Select Resource Directory"); dialog.show(); final InputValidator validator = dialog.getValidator(); if (validator != null) { PsiElement[] createdElements = ((ResourceDirectorySelector) validator).getCreatedElements(); if (createdElements != null && createdElements.length > 0) { return (PsiDirectory) createdElements[0]; } } return null; }
@Override public void navigate(Project project) { VirtualFile currentVirtualFile = null; AccessToken accessToken = ReadAction.start(); try { if (!myVirtualFile.isValid()) return; PsiFile psiFile = PsiManager.getInstance(project).findFile(myVirtualFile); if (psiFile != null) { PsiElement navigationElement = psiFile.getNavigationElement(); // Sources may be downloaded. if (navigationElement instanceof PsiFile) { currentVirtualFile = ((PsiFile) navigationElement).getVirtualFile(); } } if (currentVirtualFile == null) { currentVirtualFile = myVirtualFile; } } finally { accessToken.finish(); } new OpenFileHyperlinkInfo(myProject, currentVirtualFile, myLineNumber - 1).navigate(project); }
@Nullable public static PropertiesFile getPropertiesFile( @NotNull Project project, @NotNull VirtualFile file) { PsiFile psiFile = PsiManager.getInstance(project).findFile(file); if (!(psiFile instanceof PropertiesFile)) return null; return (PropertiesFile) psiFile; }
@Nullable public Object getData(String dataId) { if (CommonDataKeys.PROJECT.is(dataId)) { return editor != null ? editor.getProject() : null; } else if (CommonDataKeys.VIRTUAL_FILE.is(dataId)) { return editor != null ? editor.getFile() : null; } else if (CommonDataKeys.VIRTUAL_FILE_ARRAY.is(dataId)) { return editor != null ? new VirtualFile[] {editor.getFile()} : new VirtualFile[] {}; } else if (CommonDataKeys.PSI_FILE.is(dataId)) { return getData(CommonDataKeys.PSI_ELEMENT.getName()); } else if (CommonDataKeys.PSI_ELEMENT.is(dataId)) { VirtualFile file = editor != null ? editor.getFile() : null; return file != null && file.isValid() ? PsiManager.getInstance(editor.getProject()).findFile(file) : null; } else if (LangDataKeys.PSI_ELEMENT_ARRAY.is(dataId)) { return editor != null ? new PsiElement[] {(PsiElement) getData(CommonDataKeys.PSI_ELEMENT.getName())} : new PsiElement[] {}; } else if (PlatformDataKeys.COPY_PROVIDER.is(dataId) && copyPasteSupport != null) { return this; } else if (PlatformDataKeys.CUT_PROVIDER.is(dataId) && copyPasteSupport != null) { return copyPasteSupport.getCutProvider(); } else if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER.is(dataId)) { return deleteProvider; } else if (ImageComponentDecorator.DATA_KEY.is(dataId)) { return editor != null ? editor : this; } return null; }
@Override public void hyperlinkUpdate(@NotNull HyperlinkEvent e) { if (e.getEventType() != HyperlinkEvent.EventType.ACTIVATED) { return; } String description = e.getDescription(); if (StringUtil.isEmpty(description) || !description.startsWith(DocumentationManager.PSI_ELEMENT_PROTOCOL)) { return; } String elementName = e.getDescription().substring(DocumentationManager.PSI_ELEMENT_PROTOCOL.length()); final PsiElement targetElement = myProvider.getDocumentationElementForLink( PsiManager.getInstance(myProject), elementName, myContext); if (targetElement != null) { LightweightHint hint = myHint; if (hint != null) { hint.hide(true); } myDocumentationManager.showJavaDocInfo(targetElement, myContext, true, null); } }
public Object[] createPath(final Project project) { final VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(url); if (file == null || !file.isValid()) { return null; } return new Object[] {PsiManager.getInstance(project).findFile(file)}; }
@Nullable static HighlightInfo checkFileDuplicates(@NotNull PsiJavaModule element, @NotNull PsiFile file) { Module module = ModuleUtilCore.findModuleForPsiElement(element); if (module != null) { Project project = file.getProject(); Collection<VirtualFile> others = FilenameIndex.getVirtualFilesByName(project, MODULE_INFO_FILE, new ModulesScope(module)); if (others.size() > 1) { String message = JavaErrorMessages.message("module.file.duplicate"); HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR) .range(range(element)) .description(message) .create(); others .stream() .map(f -> PsiManager.getInstance(project).findFile(f)) .filter(f -> f != file) .findFirst() .ifPresent( duplicate -> QuickFixAction.registerQuickFixAction( info, new GoToSymbolFix( duplicate, JavaErrorMessages.message("module.open.duplicate.text")))); return info; } } return null; }
public void merge(final Binding b, final boolean removeObject) { for (final PsiTypeVariable var : b.getBoundVariables()) { final int index = var.getIndex(); if (myBindings.get(index) != null) { LOG.error("Oops... Binding conflict..."); } else { final PsiType type = b.apply(var); final PsiClassType javaLangObject = PsiType.getJavaLangObject( PsiManager.getInstance(myProject), GlobalSearchScope.allScope(myProject)); if (removeObject && javaLangObject.equals(type)) { final HashSet<PsiTypeVariable> cluster = myFactory.getClusterOf(var.getIndex()); if (cluster != null) { for (final PsiTypeVariable war : cluster) { final PsiType wtype = b.apply(war); if (!javaLangObject.equals(wtype)) { myBindings.put(index, type); break; } } } } else { myBindings.put(index, type); } } } }
public PsiType apply(final PsiType type) { if (type instanceof PsiTypeVariable) { final PsiType t = myBindings.get(((PsiTypeVariable) type).getIndex()); return t == null ? type : t; } else if (type instanceof PsiArrayType) { return apply(((PsiArrayType) type).getComponentType()).createArrayType(); } else if (type instanceof PsiClassType) { final PsiClassType.ClassResolveResult result = Util.resolveType(type); final PsiClass theClass = result.getElement(); final PsiSubstitutor aSubst = result.getSubstitutor(); PsiSubstitutor theSubst = PsiSubstitutor.EMPTY; if (theClass != null) { for (final PsiTypeParameter aParm : aSubst.getSubstitutionMap().keySet()) { final PsiType aType = aSubst.substitute(aParm); theSubst = theSubst.put(aParm, apply(aType)); } return JavaPsiFacade.getInstance(theClass.getProject()) .getElementFactory() .createType(theClass, theSubst); } else { return type; } } else if (type instanceof PsiWildcardType) { final PsiWildcardType wcType = (PsiWildcardType) type; final PsiType bound = wcType.getBound(); if (bound != null) { final PsiType abound = apply(bound); if (abound instanceof PsiWildcardType) { return null; } return wcType.isExtends() ? PsiWildcardType.createExtends(PsiManager.getInstance(myProject), abound) : PsiWildcardType.createSuper(PsiManager.getInstance(myProject), abound); } return type; } else { return type; } }
public KotlinPsiElementFinderImpl(Project project) { this.javaFileManager = findJavaFileManager(project); this.psiPackageManager = PsiPackageManager.getInstance(project); this.isCliFileManager = javaFileManager instanceof KotlinCliJavaFileManager; this.packageIndex = DirectoryIndex.getInstance(project); this.psiManager = PsiManager.getInstance(project); }
@Nullable public static <T extends MavenDomElement> T getMavenDomModel( @NotNull Project project, @NotNull VirtualFile file, @NotNull Class<T> clazz) { if (!file.isValid()) return null; PsiFile psiFile = PsiManager.getInstance(project).findFile(file); if (psiFile == null) return null; return getMavenDomModel(psiFile, clazz); }
private static boolean isSuitable(@NotNull Project project, @NotNull VirtualFile file) { if (file instanceof HttpVirtualFile) { return false; } final FileViewProvider provider = PsiManager.getInstance(project).findViewProvider(file); return provider != null && BreadcrumbsXmlWrapper.findInfoProvider(provider) != null; }
@Nullable private PsiDirectory getPsiDirectory() { if (myDirectory == null) { if (myVDirectory.isValid() && !myProject.isDisposed()) { myDirectory = PsiManager.getInstance(myProject).findDirectory(myVDirectory); } } return myDirectory; }
@NotNull @Override public PsiType getForcedType() { final PsiType selectedType = mySettings.getSelectedType(); if (selectedType != null) return selectedType; final PsiManager manager = PsiManager.getInstance(myProject); final GlobalSearchScope resolveScope = mySettings.getToReplaceIn().getResolveScope(); return PsiType.getJavaLangObject(manager, resolveScope); }
@Override public PsiFileSystemItem findRoot(final Project project, @NotNull final VirtualFile file) { final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); VirtualFile contentRootForFile = index.getContentRootForFile(file); return contentRootForFile != null ? PsiManager.getInstance(project).findDirectory(contentRootForFile) : null; }