public static boolean isRoot(PsiFileSystemItem directory) { if (directory == null) return true; VirtualFile vFile = directory.getVirtualFile(); if (vFile == null) return true; ProjectFileIndex fileIndex = ProjectFileIndex.SERVICE.getInstance(directory.getProject()); return Comparing.equal(fileIndex.getClassRootForFile(vFile), vFile) || Comparing.equal(fileIndex.getContentRootForFile(vFile), vFile) || Comparing.equal(fileIndex.getSourceRootForFile(vFile), vFile); }
public boolean isContentOrSourceRoot() { if (myVDirectory != null) { final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); final VirtualFile contentRoot = fileIndex.getContentRootForFile(myVDirectory); final VirtualFile sourceRoot = fileIndex.getSourceRootForFile(myVDirectory); if (myVDirectory.equals(contentRoot) || myVDirectory.equals(sourceRoot)) { return true; } } return false; }
public void markModuleDirtyIfInSourceRoot(final VirtualFile file) { if (myCache.isEmpty()) return; final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); final Module module = fileIndex.getModuleForFile(file); if (module != null && fileIndex.getSourceRootForFile(file) != null && !fileIndex.isInTestSourceContent(file)) { markModuleDirty(module); } }
public static void removeDuplicatingClasses( final Module module, @NotNull final String packageName, @NotNull String className, @Nullable File classFile, String sourceRootPath) { if (sourceRootPath == null) { return; } VirtualFile sourceRoot = LocalFileSystem.getInstance().findFileByPath(sourceRootPath); if (sourceRoot == null) { return; } final Project project = module.getProject(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final String interfaceQualifiedName = packageName + '.' + className; PsiClass[] classes = facade.findClasses(interfaceQualifiedName, GlobalSearchScope.moduleScope(module)); final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (PsiClass c : classes) { PsiFile psiFile = c.getContainingFile(); if (className.equals(FileUtil.getNameWithoutExtension(psiFile.getName()))) { VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile != null && projectFileIndex.getSourceRootForFile(virtualFile) == sourceRoot) { final String path = virtualFile.getPath(); File f = new File(path); try { f = f.getCanonicalFile(); classFile = classFile != null ? classFile.getCanonicalFile() : null; if (f != null && !f.equals(classFile) && f.exists()) { if (f.delete()) { virtualFile.refresh(true, false); } else { ApplicationManager.getApplication() .invokeLater( new Runnable() { public void run() { Messages.showErrorDialog( project, "Can't delete file " + path, CommonBundle.getErrorTitle()); } }, project.getDisposed()); } } } catch (IOException e) { LOG.info(e); } } } } }
@Nullable private VirtualFile getFileRoot(VirtualFile file) { if (myIndex.isLibraryClassFile(file)) { return myIndex.getClassRootForFile(file); } if (myIndex.isInContent(file)) { return myIndex.getSourceRootForFile(file); } if (myIndex.isInLibraryClasses(file)) { return myIndex.getClassRootForFile(file); } return null; }
private static void collectSourceRoots( PsiElement[] psiElements, ProjectFileIndex fileIndex, Set<VirtualFile> initialRoots) { for (PsiElement element : psiElements) { final VirtualFile file = PsiUtilCore.getVirtualFile(element); if (file != null) { final VirtualFile sourceRootForFile = fileIndex.getSourceRootForFile(file); if (sourceRootForFile != null) { initialRoots.add(sourceRootForFile); } } else if (element instanceof PsiDirectoryContainer) { collectSourceRoots( ((PsiDirectoryContainer) element).getDirectories(), fileIndex, initialRoots); } } }
public static String getRootDirectoryForPackage(PsiDirectory directory) { PsiManager manager = directory.getManager(); final VirtualFile virtualFile = directory.getVirtualFile(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(manager.getProject()).getFileIndex(); VirtualFile root = fileIndex.getSourceRootForFile(virtualFile); if (root == null) { root = fileIndex.getClassRootForFile(virtualFile); } if (root != null) { return root.getPresentableUrl(); } return null; }
public DirectoryNode( VirtualFile aDirectory, Project project, boolean compactPackages, boolean showFQName, VirtualFile baseDir, final VirtualFile[] contentRoots) { super(project); myVDirectory = aDirectory; final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(project); final ProjectFileIndex index = projectRootManager.getFileIndex(); String dirName = aDirectory.getName(); if (showFQName) { final VirtualFile contentRoot = index.getContentRootForFile(myVDirectory); if (contentRoot != null) { if (Comparing.equal(myVDirectory, contentRoot)) { myFQName = dirName; } else { final VirtualFile sourceRoot = index.getSourceRootForFile(myVDirectory); if (Comparing.equal(myVDirectory, sourceRoot)) { myFQName = VfsUtilCore.getRelativePath(myVDirectory, contentRoot, '/'); } else if (sourceRoot != null) { myFQName = VfsUtilCore.getRelativePath(myVDirectory, sourceRoot, '/'); } else { myFQName = VfsUtilCore.getRelativePath(myVDirectory, contentRoot, '/'); } } if (contentRoots.length > 1 && ProjectRootsUtil.isModuleContentRoot(myVDirectory, project)) { myFQName = getContentRootName(baseDir, myFQName); } } else { myFQName = FilePatternPackageSet.getLibRelativePath(myVDirectory, index); } dirName = myFQName; } else { if (contentRoots.length > 1 && ProjectRootsUtil.isModuleContentRoot(myVDirectory, project)) { dirName = getContentRootName(baseDir, dirName); } } myDirName = dirName; myCompactPackages = compactPackages; }
public static String getReferencePath(Project project, VirtualFile file) { final LogicalRoot logicalRoot = LogicalRootsManager.getLogicalRootsManager(project).findLogicalRoot(file); if (logicalRoot != null) { return getRelativePath(file, logicalRoot.getVirtualFile()); } ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); VirtualFile sourceRoot = fileIndex.getSourceRootForFile(file); if (sourceRoot != null) { return getRelativePath(file, sourceRoot); } VirtualFile root = fileIndex.getContentRootForFile(file); if (root != null) { return getRelativePath(file, root); } return file.getPath(); }
@Nullable static String getDependencyFolder( @NotNull final Project project, @NotNull final VirtualFile sourceFile, @NotNull final VirtualFile genFolder) { final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); final VirtualFile sourceRoot = index.getSourceRootForFile(sourceFile); if (sourceRoot == null) { return null; } final VirtualFile parent = sourceFile.getParent(); if (parent == sourceRoot) { return genFolder.getPath(); } final String relativePath = VfsUtilCore.getRelativePath(sourceFile.getParent(), sourceRoot, '/'); assert relativePath != null; return genFolder.getPath() + '/' + relativePath; }
@Override public String toString() { if (myText == null) { Module module = ModuleUtilCore.findModuleForPsiElement(myClass); if (module != null) { myText = module.getName(); } else { VirtualFile virtualFile = myClass.getContainingFile().getVirtualFile(); final ProjectFileIndex index = ProjectRootManager.getInstance(myClass.getProject()).getFileIndex(); VirtualFile root = index.getSourceRootForFile(virtualFile); if (root == null) { root = index.getClassRootForFile(virtualFile); } if (root != null) { myText = root.getName(); } else { myText = virtualFile.getPath(); } } } return myText; }
@NotNull private static PsiClass createBeanClass(final WizardData wizardData) throws MyException { final PsiManager psiManager = PsiManager.getInstance(wizardData.myProject); final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(wizardData.myProject); final ProjectFileIndex fileIndex = projectRootManager.getFileIndex(); final VirtualFile sourceRoot = fileIndex.getSourceRootForFile(wizardData.myFormFile); if (sourceRoot == null) { throw new MyException(UIDesignerBundle.message("error.form.file.is.not.in.source.root")); } final PsiDirectory rootDirectory = psiManager.findDirectory(sourceRoot); LOG.assertTrue(rootDirectory != null); final PsiPackage aPackage = JavaPsiFacade.getInstance(psiManager.getProject()).findPackage(wizardData.myPackageName); if (aPackage == null) { throw new MyException( UIDesignerBundle.message("error.package.does.not.exist", wizardData.myPackageName)); } PsiDirectory targetDir = null; final PsiDirectory[] directories = aPackage.getDirectories(); for (final PsiDirectory psiDirectory : directories) { if (PsiTreeUtil.isAncestor(rootDirectory, psiDirectory, false)) { targetDir = psiDirectory; break; } } if (targetDir == null) { // todo throw new MyException( UIDesignerBundle.message("error.cannot.find.package", wizardData.myPackageName)); } //noinspection HardCodedStringLiteral final String body = "public class " + wizardData.myShortClassName + "{\n" + "public " + wizardData.myShortClassName + "(){}\n" + "}"; try { PsiFile sourceFile = PsiFileFactory.getInstance(psiManager.getProject()) .createFileFromText(wizardData.myShortClassName + ".java", body); sourceFile = (PsiFile) targetDir.add(sourceFile); final PsiClass beanClass = ((PsiJavaFile) sourceFile).getClasses()[0]; final ArrayList<String> properties = new ArrayList<String>(); final HashMap<String, String> property2fqClassName = new HashMap<String, String>(); final FormProperty2BeanProperty[] bindings = wizardData.myBindings; for (final FormProperty2BeanProperty binding : bindings) { if (binding == null || binding.myBeanProperty == null) { continue; } properties.add(binding.myBeanProperty.myName); // todo: handle "casts" ? final String propertyClassName = binding.myFormProperty.getComponentPropertyClassName(); property2fqClassName.put(binding.myBeanProperty.myName, propertyClassName); } generateBean(beanClass, ArrayUtil.toStringArray(properties), property2fqClassName); return beanClass; } catch (IncorrectOperationException e) { throw new MyException(e.getMessage()); } }
@NotNull public static VirtualFile getTargetDirectoryFor( @NotNull Project project, @NotNull VirtualFile sourceFile, @Nullable String targetFile, @Nullable String targetPackage, boolean returnRoot) { boolean hasPackage = StringUtil.isNotEmpty(targetPackage); ProjectRootManager rootManager = ProjectRootManager.getInstance(project); ProjectFileIndex fileIndex = ProjectFileIndex.SERVICE.getInstance(project); Collection<VirtualFile> files = targetFile == null ? Collections.<VirtualFile>emptyList() : FilenameIndex.getVirtualFilesByName( project, targetFile, ProjectScope.getAllScope(project)); VirtualFile existingFile = null; for (VirtualFile file : files) { String existingFilePackage = fileIndex.getPackageNameByDirectory(file.getParent()); if (!hasPackage || existingFilePackage == null || targetPackage.equals(existingFilePackage)) { existingFile = file; break; } } VirtualFile existingFileRoot = existingFile == null ? null : fileIndex.isInSourceContent(existingFile) ? fileIndex.getSourceRootForFile(existingFile) : fileIndex.isInContent(existingFile) ? fileIndex.getContentRootForFile(existingFile) : null; boolean preferGenRoot = sourceFile.getFileType() == BnfFileType.INSTANCE || sourceFile.getFileType() == JFlexFileType.INSTANCE; boolean preferSourceRoot = hasPackage && !preferGenRoot; VirtualFile[] sourceRoots = rootManager.getContentSourceRoots(); VirtualFile[] contentRoots = rootManager.getContentRoots(); final VirtualFile virtualRoot = existingFileRoot != null ? existingFileRoot : preferSourceRoot && fileIndex.isInSource(sourceFile) ? fileIndex.getSourceRootForFile(sourceFile) : fileIndex.isInContent(sourceFile) ? fileIndex.getContentRootForFile(sourceFile) : getFirstElement( preferSourceRoot && sourceRoots.length > 0 ? sourceRoots : contentRoots); if (virtualRoot == null) { fail(project, sourceFile, "Unable to guess target source root"); throw new ProcessCanceledException(); } try { String genDirName = Options.GEN_DIR.get(); boolean newGenRoot = !fileIndex.isInSourceContent(virtualRoot); final String relativePath = (hasPackage && newGenRoot ? genDirName + "/" + targetPackage : hasPackage ? targetPackage : newGenRoot ? genDirName : "") .replace('.', '/'); if (relativePath.isEmpty()) { return virtualRoot; } else { VirtualFile result = new WriteAction<VirtualFile>() { @Override protected void run(@NotNull Result<VirtualFile> result) throws Throwable { result.setResult(VfsUtil.createDirectoryIfMissing(virtualRoot, relativePath)); } }.execute().throwException().getResultObject(); VfsUtil.markDirtyAndRefresh(false, true, true, result); return returnRoot && newGenRoot ? ObjectUtils.assertNotNull(virtualRoot.findChild(genDirName)) : returnRoot ? virtualRoot : result; } } catch (ProcessCanceledException ex) { throw ex; } catch (Exception ex) { fail(project, sourceFile, ex.getMessage()); throw new ProcessCanceledException(); } }
public MoveClassesOrPackagesToNewDirectoryDialog( @NotNull final PsiDirectory directory, PsiElement[] elementsToMove, boolean canShowPreserveSourceRoots, final MoveCallback moveCallback) { super(false); setTitle(MoveHandler.REFACTORING_NAME); myDirectory = directory; myElementsToMove = elementsToMove; myMoveCallback = moveCallback; myDestDirectoryField.setText( FileUtil.toSystemDependentName(directory.getVirtualFile().getPath())); final FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false); myDestDirectoryField .getButton() .addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { final VirtualFile[] files = FileChooser.chooseFiles( myDirectory.getProject(), descriptor, directory.getVirtualFile()); if (files.length == 1) { myDestDirectoryField.setText(FileUtil.toSystemDependentName(files[0].getPath())); } } }); if (elementsToMove.length == 1) { PsiElement firstElement = elementsToMove[0]; myNameLabel.setText( RefactoringBundle.message( "move.single.class.or.package.name.label", UsageViewUtil.getType(firstElement), UsageViewUtil.getLongName(firstElement))); } else if (elementsToMove.length > 1) { myNameLabel.setText( elementsToMove[0] instanceof PsiClass ? RefactoringBundle.message("move.specified.classes") : RefactoringBundle.message("move.specified.packages")); } final JavaRefactoringSettings refactoringSettings = JavaRefactoringSettings.getInstance(); mySearchInCommentsAndStringsCheckBox.setSelected(refactoringSettings.MOVE_SEARCH_IN_COMMENTS); mySearchForTextOccurrencesCheckBox.setSelected(refactoringSettings.MOVE_SEARCH_FOR_TEXT); myDestDirectoryField .getTextField() .getDocument() .addDocumentListener( new DocumentAdapter() { public void textChanged(DocumentEvent event) { setOKActionEnabled(myDestDirectoryField.getText().length() > 0); } }); if (canShowPreserveSourceRoots) { final Set<VirtualFile> sourceRoots = new HashSet<VirtualFile>(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(directory.getProject()).getFileIndex(); for (PsiElement element : elementsToMove) { if (element instanceof PsiPackage) { for (PsiDirectory psiDirectory : ((PsiPackage) element).getDirectories()) { sourceRoots.add(fileIndex.getSourceRootForFile(psiDirectory.getVirtualFile())); } } else if (element instanceof PsiClass) { final PsiDirectory psiDirectory = element.getContainingFile().getContainingDirectory(); LOG.assertTrue(psiDirectory != null); if (psiDirectory != null) { sourceRoots.add(psiDirectory.getVirtualFile()); } } } myPreserveSourceRoot.setVisible(sourceRoots.size() > 1); } init(); }
public void setData( final Project project, final PsiDirectory initialTargetDirectory, final Pass<String> errorMessageUpdater, final EditorComboBox editorComboBox) { myInitialTargetDirectory = initialTargetDirectory; mySourceRoots = ProjectRootManager.getInstance(project).getContentSourceRoots(); new ComboboxSpeedSearch(getComboBox()) { @Override protected String getElementText(Object element) { if (element == NULL_WRAPPER) return LEAVE_IN_SAME_SOURCE_ROOT; if (element instanceof DirectoryChooser.ItemWrapper) { final VirtualFile virtualFile = ((DirectoryChooser.ItemWrapper) element).getDirectory().getVirtualFile(); final Module module = ModuleUtil.findModuleForFile(virtualFile, project); if (module != null) { return module.getName(); } } return super.getElementText(element); } }; final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); getComboBox() .setRenderer( new ListCellRendererWrapper<DirectoryChooser.ItemWrapper>(getComboBox().getRenderer()) { @Override public void customize( JList list, DirectoryChooser.ItemWrapper itemWrapper, int index, boolean selected, boolean hasFocus) { if (itemWrapper != NULL_WRAPPER && itemWrapper != null) { setIcon(itemWrapper.getIcon(fileIndex)); setText(itemWrapper.getRelativeToProjectPath()); } else { setText(LEAVE_IN_SAME_SOURCE_ROOT); } } }); final VirtualFile initialSourceRoot = initialTargetDirectory != null ? fileIndex.getSourceRootForFile(initialTargetDirectory.getVirtualFile()) : null; final VirtualFile[] selection = new VirtualFile[] {initialSourceRoot}; addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { VirtualFile root = MoveClassesOrPackagesUtil.chooseSourceRoot( new PackageWrapper(PsiManager.getInstance(project), getTargetPackage()), mySourceRoots, initialTargetDirectory); if (root == null) return; final ComboBoxModel model = getComboBox().getModel(); for (int i = 0; i < model.getSize(); i++) { DirectoryChooser.ItemWrapper item = (DirectoryChooser.ItemWrapper) model.getElementAt(i); if (item != NULL_WRAPPER && fileIndex.getSourceRootForFile(item.getDirectory().getVirtualFile()) == root) { getComboBox().setSelectedItem(item); getComboBox().repaint(); return; } } setComboboxModel( getComboBox(), root, root, fileIndex, mySourceRoots, project, true, errorMessageUpdater); } }); editorComboBox.addDocumentListener( new DocumentAdapter() { @Override public void documentChanged(DocumentEvent e) { JComboBox comboBox = getComboBox(); DirectoryChooser.ItemWrapper selectedItem = (DirectoryChooser.ItemWrapper) comboBox.getSelectedItem(); setComboboxModel( comboBox, selectedItem != null && selectedItem != NULL_WRAPPER ? fileIndex.getSourceRootForFile(selectedItem.getDirectory().getVirtualFile()) : initialSourceRoot, selection[0], fileIndex, mySourceRoots, project, false, errorMessageUpdater); } }); setComboboxModel( getComboBox(), initialSourceRoot, selection[0], fileIndex, mySourceRoots, project, false, errorMessageUpdater); getComboBox() .addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object selectedItem = getComboBox().getSelectedItem(); updateErrorMessage(errorMessageUpdater, fileIndex, selectedItem); if (selectedItem instanceof DirectoryChooser.ItemWrapper && selectedItem != NULL_WRAPPER) { PsiDirectory directory = ((DirectoryChooser.ItemWrapper) selectedItem).getDirectory(); if (directory != null) { selection[0] = fileIndex.getSourceRootForFile(directory.getVirtualFile()); } } } }); }
private void setComboboxModel( final JComboBox comboBox, final VirtualFile initialTargetDirectorySourceRoot, final VirtualFile oldSelection, final ProjectFileIndex fileIndex, final VirtualFile[] sourceRoots, final Project project, final boolean forceIncludeAll, final Pass<String> updateErrorMessage) { final LinkedHashSet<PsiDirectory> targetDirectories = new LinkedHashSet<PsiDirectory>(); final HashMap<PsiDirectory, String> pathsToCreate = new HashMap<PsiDirectory, String>(); MoveClassesOrPackagesUtil.buildDirectoryList( new PackageWrapper(PsiManager.getInstance(project), getTargetPackage()), sourceRoots, targetDirectories, pathsToCreate); if (!forceIncludeAll && targetDirectories.size() > pathsToCreate.size()) { targetDirectories.removeAll(pathsToCreate.keySet()); } final ArrayList<DirectoryChooser.ItemWrapper> items = new ArrayList<DirectoryChooser.ItemWrapper>(); DirectoryChooser.ItemWrapper initial = null; DirectoryChooser.ItemWrapper oldOne = null; for (PsiDirectory targetDirectory : targetDirectories) { DirectoryChooser.ItemWrapper itemWrapper = new DirectoryChooser.ItemWrapper(targetDirectory, pathsToCreate.get(targetDirectory)); items.add(itemWrapper); final VirtualFile sourceRootForFile = fileIndex.getSourceRootForFile(targetDirectory.getVirtualFile()); if (sourceRootForFile == initialTargetDirectorySourceRoot) { initial = itemWrapper; } else if (sourceRootForFile == oldSelection) { oldOne = itemWrapper; } } items.add(NULL_WRAPPER); final DirectoryChooser.ItemWrapper selection = chooseSelection(initialTargetDirectorySourceRoot, fileIndex, items, initial, oldOne); final ComboBoxModel model = comboBox.getModel(); if (model instanceof CollectionComboBoxModel) { boolean sameModel = model.getSize() == items.size(); if (sameModel) { for (int i = 0; i < items.size(); i++) { final DirectoryChooser.ItemWrapper oldItem = (DirectoryChooser.ItemWrapper) model.getElementAt(i); final DirectoryChooser.ItemWrapper itemWrapper = items.get(i); if (!areItemsEquivalent(oldItem, itemWrapper)) { sameModel = false; break; } } } if (sameModel) { if (areItemsEquivalent( (DirectoryChooser.ItemWrapper) comboBox.getSelectedItem(), selection)) { return; } } } updateErrorMessage(updateErrorMessage, fileIndex, selection); Collections.sort( items, new Comparator<DirectoryChooser.ItemWrapper>() { @Override public int compare(DirectoryChooser.ItemWrapper o1, DirectoryChooser.ItemWrapper o2) { if (o1 == NULL_WRAPPER) return -1; if (o2 == NULL_WRAPPER) return 1; return o1.getRelativeToProjectPath().compareToIgnoreCase(o2.getRelativeToProjectPath()); } }); comboBox.setModel(new CollectionComboBoxModel(items, selection)); }