@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;
VirtualFile[] sourceRoots = rootManager.getContentSourceRoots();
VirtualFile[] contentRoots = rootManager.getContentRoots();
final VirtualFile virtualRoot = existingFileRoot != null ? existingFileRoot :
hasPackage && fileIndex.isInSource(sourceFile) ? fileIndex.getSourceRootForFile(sourceFile) :
fileIndex.isInContent(sourceFile) ? fileIndex.getContentRootForFile(sourceFile) :
getFirstElement(hasPackage && sourceRoots.length > 0? sourceRoots : contentRoots);
if (virtualRoot == null) {