public static void setApplication(@NotNull Application instance, @NotNull Getter<FileTypeRegistry> fileTypeRegistryGetter, @NotNull Disposable parent) { final Application old = ourApplication; final Getter<FileTypeRegistry> oldFileTypeRegistry = FileTypeRegistry.ourInstanceGetter; Disposer.register(parent, new Disposable() { @Override public void dispose() { if (old != null) { // to prevent NPEs in threads still running setApplication(old); //noinspection AssignmentToStaticFieldFromInstanceMethod FileTypeRegistry.ourInstanceGetter = oldFileTypeRegistry; } } }); setApplication(instance); FileTypeRegistry.ourInstanceGetter = fileTypeRegistryGetter; }
public void testNonPhysicalFile() throws Exception { String fileName = "Test.java"; FileType fileType = FileTypeRegistry.getInstance().getFileTypeByFileName(fileName); PsiFile psiFile = PsiFileFactory.getInstance(getProject()).createFileFromText(fileName, fileType, "class Test {}", 0, false); VirtualFile virtualFile = psiFile.getViewProvider().getVirtualFile(); Document document = FileDocumentManager.getInstance().getDocument(virtualFile); assertNotNull(document); EditorFactory editorFactory = EditorFactory.getInstance(); Editor editor = editorFactory.createViewer(document, getProject()); try { editor.getSelectionModel().setSelection(0, document.getTextLength()); String syntaxInfo = getSyntaxInfo(editor, psiFile); assertEquals("foreground=java.awt.Color[r=0,g=0,b=128],fontStyle=1,text=class \n" + "foreground=java.awt.Color[r=0,g=0,b=0],fontStyle=0,text=Test {}\n", syntaxInfo); } finally { editorFactory.releaseEditor(editor); } }
public static int getCumulativeVersion() { int version = VERSION; for (final FileType fileType : FileTypeRegistry.getInstance().getRegisteredFileTypes()) { if (fileType instanceof LanguageFileType) { Language l = ((LanguageFileType)fileType).getLanguage(); ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(l); if (parserDefinition != null) { final IFileElementType type = parserDefinition.getFileNodeType(); if (type instanceof IStubFileElementType) { version += ((IStubFileElementType)type).getStubVersion(); } } } BinaryFileStubBuilder builder = BinaryFileStubBuilders.INSTANCE.forFileType(fileType); if (builder != null) { version += builder.getStubVersion(); } } return version; }
public static PsiFile setName(@NotNull PsiFile file, @NotNull String newName) throws IncorrectOperationException { VirtualFile vFile = file.getViewProvider().getVirtualFile(); PsiManagerImpl manager = (PsiManagerImpl)file.getManager(); try{ final FileType newFileType = FileTypeRegistry.getInstance().getFileTypeByFileName(newName); if (UnknownFileType.INSTANCE.equals(newFileType) || newFileType.isBinary()) { // before the file becomes unknown or a binary (thus, not openable in the editor), save it to prevent data loss final FileDocumentManager fdm = FileDocumentManager.getInstance(); final Document doc = fdm.getCachedDocument(vFile); if (doc != null) { fdm.saveDocumentAsIs(doc); } } vFile.rename(manager, newName); } catch(IOException e){ throw new IncorrectOperationException(e); } return file.getViewProvider().isPhysical() ? manager.findFile(vFile) : file; }
@NotNull @Override public PsiElement createFromTemplate(final Project project, final PsiDirectory directory, String fileName, final FileTemplate template, final String templateText, @NotNull final Map<String, Object> props) throws IncorrectOperationException { fileName = checkAppendExtension(fileName, template); if (FileTypeManager.getInstance().isFileIgnored(fileName)) { throw new IncorrectOperationException("This filename is ignored (Settings | Editor | File Types | Ignore files and folders)"); } directory.checkCreateFile(fileName); FileType type = FileTypeRegistry.getInstance().getFileTypeByFileName(fileName); PsiFile file = PsiFileFactory.getInstance(project).createFileFromText(fileName, type, templateText); if (template.isReformatCode()) { CodeStyleManager.getInstance(project).reformat(file); } file = (PsiFile)directory.add(file); return file; }
@Override public boolean contains(@NotNull VirtualFile file) { final PsiDirectory value = getValue(); if (value == null) { return false; } VirtualFile directory = value.getVirtualFile(); if (directory.getFileSystem() instanceof LocalFileSystem) { file = PathUtil.getLocalFile(file); } if (!VfsUtilCore.isAncestor(directory, file, false)) { return false; } if (Registry.is("ide.hide.excluded.files")) { final Project project = value.getProject(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); return !fileIndex.isExcluded(file); } else { return !FileTypeRegistry.getInstance().isFileIgnored(file); } }
public void persistAttribute(@NotNull Project project, @NotNull VirtualFile fileOrDir, @NotNull LanguageLevel level) throws IOException { final DataInputStream iStream = PERSISTENCE.readAttribute(fileOrDir); if (iStream != null) { try { final int oldLevelOrdinal = DataInputOutputUtil.readINT(iStream); if (oldLevelOrdinal == level.ordinal()) return; } finally { iStream.close(); } } final DataOutputStream oStream = PERSISTENCE.writeAttribute(fileOrDir); DataInputOutputUtil.writeINT(oStream, level.ordinal()); oStream.close(); for (VirtualFile child : fileOrDir.getChildren()) { final FileType fileType = FileTypeRegistry.getInstance().getFileTypeByFileName(child.getName()); if (!child.isDirectory() && PythonFileType.INSTANCE.equals(fileType)) { clearSdkPathCache(child); PushedFilePropertiesUpdater.getInstance(project).filePropertiesChanged(child); } } }
@NotNull @Override public DiffContent[] getContents() { try { ContentRevision beforeRevision = selectedChange.getBeforeRevision(); ContentRevision afterRevision = selectedChange.getAfterRevision(); FileType srcFileType = FileTypeRegistry.getInstance() .getFileTypeByFileName(beforeRevision.getFile().getName()); FileType dstFileType = FileTypeRegistry.getInstance() .getFileTypeByFileName(afterRevision.getFile().getName()); return new DiffContent[]{ new SimpleContent(defaultString(beforeRevision.getContent()), srcFileType), new SimpleContent(defaultString(afterRevision.getContent()), dstFileType) }; } catch (Exception e1) { throw new RuntimeException(e1); } }
/** * For every #createMockApplication there needs to be a corresponding call to * #disposeMockApplication when the test is complete. */ public static Disposable createMockApplication() { Disposable parentDisposable = getParentDisposableForCleanup(); final PluginMockApplication instance = new PluginMockApplication(parentDisposable); ApplicationManager.setApplication( instance, new Getter<FileTypeRegistry>() { @Override public FileTypeRegistry get() { return FileTypeManager.getInstance(); } }, parentDisposable); instance.registerService(EncodingManager.class, EncodingManagerImpl.class); return parentDisposable; }
public static void setApplication(@NotNull Application instance, @NotNull Getter<FileTypeRegistry> fileTypeRegistryGetter, @NotNull Getter<EncodingRegistry> encodingRegistryGetter, @NotNull Disposable parent) { final Application old = ourApplication; final Getter<FileTypeRegistry> oldFileTypeRegistry = FileTypeRegistry.ourInstanceGetter; final Getter<EncodingRegistry> oldEncodingRegistry = EncodingRegistry.ourInstanceGetter; Disposer.register(parent, new Disposable() { @Override public void dispose() { if (old != null) { // to prevent NPEs in threads still running setApplication(old); //noinspection AssignmentToStaticFieldFromInstanceMethod FileTypeRegistry.ourInstanceGetter = oldFileTypeRegistry; //noinspection AssignmentToStaticFieldFromInstanceMethod EncodingRegistry.ourInstanceGetter = oldEncodingRegistry; } } }); setApplication(instance); FileTypeRegistry.ourInstanceGetter = fileTypeRegistryGetter; EncodingRegistry.ourInstanceGetter = encodingRegistryGetter; }
public void initApplication() { //if (ApplicationManager.getApplication() instanceof MockApplicationEx) return; final MockApplicationEx instance = new MockApplicationEx(getTestRootDisposable()); ApplicationManager.setApplication(instance, new Getter<FileTypeRegistry>() { @Override public FileTypeRegistry get() { return FileTypeManager.getInstance(); } }, new Getter<EncodingRegistry>() { @Override public EncodingRegistry get() { return EncodingManager.getInstance(); } }, getTestRootDisposable()); getApplication().registerService(EncodingManager.class, EncodingManagerImpl.class); }
@NotNull public static List<VirtualFile> getVirtualFileListFromAttachedObject(Object attached) { List<VirtualFile> result; List<File> fileList = getFileListFromAttachedObject(attached); if (fileList.isEmpty()) { result = Collections.emptyList(); } else { result = new ArrayList<VirtualFile>(fileList.size()); for (File file : fileList) { VirtualFile virtualFile = VfsUtil.findFileByIoFile(file, true); if (virtualFile == null) continue; result.add(virtualFile); // detect and store file type for Finder-2-IDEA drag-n-drop if (!virtualFile.isDirectory() && virtualFile.getFileType() == UnknownFileType.INSTANCE) { FileTypeRegistry.getInstance().detectFileTypeFromContent(virtualFile); } } } return result; }
public static PsiFile setName(final PsiFile file, String newName) throws IncorrectOperationException { VirtualFile vFile = file.getViewProvider().getVirtualFile(); PsiManagerImpl manager = (PsiManagerImpl)file.getManager(); try{ final FileType newFileType = FileTypeRegistry.getInstance().getFileTypeByFileName(newName); if (UnknownFileType.INSTANCE.equals(newFileType) || newFileType.isBinary()) { // before the file becomes unknown or a binary (thus, not openable in the editor), save it to prevent data loss final FileDocumentManager fdm = FileDocumentManager.getInstance(); final Document doc = fdm.getCachedDocument(vFile); if (doc != null) { fdm.saveDocumentAsIs(doc); } } vFile.rename(manager, newName); } catch(IOException e){ throw new IncorrectOperationException(e.toString(),e); } return file.getViewProvider().isPhysical() ? manager.findFile(vFile) : file; }
@Override public PsiElement createFromTemplate(final Project project, final PsiDirectory directory, String fileName, final FileTemplate template, final String templateText, final Map<String, Object> props) throws IncorrectOperationException { fileName = checkAppendExtension(fileName, template); if (FileTypeManager.getInstance().isFileIgnored(fileName)) { throw new IncorrectOperationException("This filename is ignored (Settings | File Types | Ignore files and folders)"); } directory.checkCreateFile(fileName); FileType type = FileTypeRegistry.getInstance().getFileTypeByFileName(fileName); PsiFile file = PsiFileFactory.getInstance(project).createFileFromText(fileName, type, templateText); if (template.isReformatCode()) { CodeStyleManager.getInstance(project).reformat(file); } file = (PsiFile)directory.add(file); return file; }
@Nonnull public static List<VirtualFile> getVirtualFileListFromAttachedObject(Object attached) { List<VirtualFile> result; List<File> fileList = getFileListFromAttachedObject(attached); if (fileList.isEmpty()) { result = Collections.emptyList(); } else { result = new ArrayList<VirtualFile>(fileList.size()); for (File file : fileList) { VirtualFile virtualFile = VfsUtil.findFileByIoFile(file, true); if (virtualFile == null) continue; result.add(virtualFile); // detect and store file type for Finder-2-IDEA drag-n-drop if (!virtualFile.isDirectory() && virtualFile.getFileType() == UnknownFileType.INSTANCE) { FileTypeRegistry.getInstance().detectFileTypeFromContent(virtualFile); } } } return result; }
@RequiredDispatchThread public static PsiFile setName(final PsiFile file, String newName) throws IncorrectOperationException { VirtualFile vFile = file.getViewProvider().getVirtualFile(); PsiManagerImpl manager = (PsiManagerImpl)file.getManager(); try{ final FileType newFileType = FileTypeRegistry.getInstance().getFileTypeByFileName(newName); if (UnknownFileType.INSTANCE.equals(newFileType) || newFileType.isBinary()) { // before the file becomes unknown or a binary (thus, not openable in the editor), save it to prevent data loss final FileDocumentManager fdm = FileDocumentManager.getInstance(); final Document doc = fdm.getCachedDocument(vFile); if (doc != null) { fdm.saveDocumentAsIs(doc); } } vFile.rename(manager, newName); } catch(IOException e){ throw new IncorrectOperationException(e); } return file.getViewProvider().isPhysical() ? manager.findFile(vFile) : file; }
/** * FIXME [VISTALL] find way found regexp plugin */ @RequiredReadAction private static List<PsiElement> getTopLevelRegExpChars(String regExpText, Project project) { FileType regexpFileType = FileTypeRegistry.getInstance().getFileTypeByExtension("regexp"); if (regexpFileType == UnknownFileType.INSTANCE) { return Collections.emptyList(); } PsiFile file = PsiFileFactory.getInstance(project).createFileFromText("A.regexp", regexpFileType, regExpText); List<PsiElement> result = null; final PsiElement[] children = file.getChildren(); for (PsiElement child : children) { PsiElement[] grandChildren = child.getChildren(); if (grandChildren.length != 1) return Collections.emptyList(); // a | b, more than one branch, can not predict in current way for (PsiElement grandGrandChild : grandChildren[0].getChildren()) { if (result == null) result = new ArrayList<>(); result.add(grandGrandChild); } } return result != null ? result : Collections.emptyList(); }
@Override public boolean contains(@Nonnull VirtualFile file) { final PsiDirectory value = getValue(); if (value == null) { return false; } VirtualFile directory = value.getVirtualFile(); if (directory.getFileSystem() instanceof LocalFileSystem) { file = PathUtil.getLocalFile(file); } if (!VfsUtilCore.isAncestor(directory, file, false)) { return false; } return !FileTypeRegistry.getInstance().isFileIgnored(file); }
@Override public boolean isMyFileType(@NotNull VirtualFile file) { VirtualFile parent = file.getParent(); if (parent != null && Comparing.equal("services", parent.getNameSequence())) { final VirtualFile gParent = parent.getParent(); if (gParent != null && Comparing.equal("META-INF", gParent.getNameSequence())) { final String fileName = file.getName(); for (Object condition : Extensions.getExtensions("com.intellij.vetoSPICondition")) { if (((Condition<String>)condition).value(fileName)) return false; } return FileTypeRegistry.getInstance().getFileTypeByFileName(fileName) == FileTypes.UNKNOWN; } } return false; }
public TodoIndex(MessageBus messageBus, FileTypeRegistry manager) { myFileTypeManager = manager; messageBus.connect().subscribe(IndexPatternProvider.INDEX_PATTERNS_CHANGED, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { FileBasedIndex.getInstance().requestRebuild(NAME); } }); }
public static boolean shouldProcess(@NotNull VirtualFile file, @NotNull Project project) { if (file.isDirectory() || !file.isWritable() || FileTypeRegistry.getInstance().isFileIgnored(file) || file.getFileType().isBinary() || file.equals(project.getProjectFile()) || file.equals(project.getWorkspaceFile())) { return false; } Module module = FileIndexFacade.getInstance(project).getModuleForFile(file); return module == null || !ModuleUtilCore.isModuleFile(module, file); }
@Nullable public String getNewFileTemplateName() { FileType fileType = FileTypeRegistry.getInstance().getFileTypeByFileName(myText); if (fileType != UnknownFileType.INSTANCE) { return fileType.getName() + " File." + fileType.getDefaultExtension(); } return null; }
public void setLanguage(@NotNull Language language) { myLanguage = language; FileType type = language.getAssociatedFileType(); if (type == null) { type = FileTypeRegistry.getInstance().getFileTypeByFileName(getName()); } setFileType(type); }
/** * Tries to find PSI file for a virtual file and throws assertion error with debug info if it is null. */ @NotNull public static PsiFile getPsiFile(@NotNull Project project, @NotNull VirtualFile file) { PsiManager psiManager = PsiManager.getInstance(project); PsiFile psi = psiManager.findFile(file); if (psi != null) return psi; FileType fileType = file.getFileType(); FileViewProvider viewProvider = psiManager.findViewProvider(file); Document document = FileDocumentManager.getInstance().getDocument(file); boolean ignored = !(file instanceof LightVirtualFile) && FileTypeRegistry.getInstance().isFileIgnored(file); VirtualFile vDir = file.getParent(); PsiDirectory psiDir = vDir == null ? null : PsiManager.getInstance(project).findDirectory(vDir); FileIndexFacade indexFacade = FileIndexFacade.getInstance(project); StringBuilder sb = new StringBuilder(); sb.append("valid=").append(file.isValid()). append(" isDirectory=").append(file.isDirectory()). append(" hasDocument=").append(document != null). append(" length=").append(file.getLength()); sb.append("\nproject=").append(project.getName()). append(" default=").append(project.isDefault()). append(" open=").append(project.isOpen());; sb.append("\nfileType=").append(fileType.getName()).append("/").append(fileType.getClass().getName()); sb.append("\nisIgnored=").append(ignored); sb.append(" underIgnored=").append(indexFacade.isUnderIgnored(file)); sb.append(" inLibrary=").append(indexFacade.isInLibrarySource(file) || indexFacade.isInLibraryClasses(file)); sb.append(" parentDir=").append(vDir == null ? "no-vfs" : vDir.isDirectory() ? "has-vfs-dir" : "has-vfs-file"). append("/").append(psiDir == null ? "no-psi" : "has-psi"); sb.append("\nviewProvider=").append(viewProvider == null ? "null" : viewProvider.getClass().getName()); if (viewProvider != null) { List<PsiFile> files = viewProvider.getAllFiles(); sb.append(" language=").append(viewProvider.getBaseLanguage().getID()); sb.append(" physical=").append(viewProvider.isPhysical()); sb.append(" rootCount=").append(files.size()); for (PsiFile o : files) { sb.append("\n root=").append(o.getLanguage().getID()).append("/").append(o.getClass().getName()); } } LOG.error("no PSI for file '" + file.getName() + "'", new Attachment(file.getPresentableUrl(), sb.toString())); throw new AssertionError(); }
@Override public VirtualFile fun(String s) { final FileType fileType = FileTypeRegistry.getInstance().getFileTypeByFileName(s); final VirtualFile localFile = PATH_TO_LOCAL_VFILE.fun(s); if (localFile == null) return null; if (ArchiveFileType.INSTANCE.equals(fileType) && !localFile.isDirectory()) { return StandardFileSystems.getJarRootForLocalFile(localFile); } return localFile; }
@Override public int getVersion() { FileType[] types = myFileTypeManager.getRegisteredFileTypes(); int version = 1; for (FileType type : types) { version += type.getName().hashCode(); } version *= 31; for (FileTypeRegistry.FileTypeDetector detector : Extensions.getExtensions(FileTypeRegistry.FileTypeDetector.EP_NAME)) { version += detector.getVersion(); } return version; }
@Nullable private static String readContent(@NotNull JsonReader reader, @NotNull List<DiffContent> contents, @NotNull List<String> titles, @Nullable String defaultFileTypeName) throws IOException { FileTypeRegistry fileTypeRegistry = FileTypeRegistry.getInstance(); FileType defaultFileType = defaultFileTypeName == null ? null : fileTypeRegistry.findFileTypeByName(defaultFileTypeName); reader.beginArray(); while (reader.hasNext()) { String title = null; String fileType = null; String content = null; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("title")) { title = reader.nextString(); } else if (name.equals("fileType")) { fileType = reader.nextString(); } else if (name.equals("content")) { content = reader.nextString(); } else { reader.skipValue(); } } reader.endObject(); if (content == null) { return "content is not specified"; } FileType type = fileType == null ? defaultFileType : fileTypeRegistry.findFileTypeByName(fileType); contents.add(DiffContentFactory.getInstance().create(content, type)); titles.add(StringUtil.isEmptyOrSpaces(title) ? "" : title); } reader.endArray(); return null; }
public void initApplication() { //if (ApplicationManager.getApplication() instanceof MockApplicationEx) return; final MockApplicationEx instance = new MockApplicationEx(getTestRootDisposable()); ApplicationManager.setApplication(instance, new Getter<FileTypeRegistry>() { @Override public FileTypeRegistry get() { return FileTypeManager.getInstance(); } }, getTestRootDisposable()); getApplication().registerService(EncodingManager.class, EncodingManagerImpl.class); }
@Override @NotNull public PsiFile createFileFromText(@NotNull String name, @NotNull String text){ FileType type = FileTypeRegistry.getInstance().getFileTypeByFileName(name); if (type.isBinary()) { throw new RuntimeException("Cannot create binary files from text: name " + name + ", file type " + type); } return createFileFromText(name, type, text); }
@Override public boolean contains(@NotNull VirtualFile file) { PsiFileSystemItem value = getValue(); if (!(value instanceof PsiDirectory)) return super.contains(file); PsiDirectory dir = (PsiDirectory)value; return VfsUtilCore.isAncestor(dir.getVirtualFile(), file, false) && !FileTypeRegistry.getInstance().isFileIgnored(file); }
public Collection<AbstractTreeNode> getDirectoryChildren(final PsiDirectory psiDirectory, final ViewSettings settings, final boolean withSubDirectories) { final List<AbstractTreeNode> children = new ArrayList<AbstractTreeNode>(); final Project project = psiDirectory.getProject(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); final Module module = fileIndex.getModuleForFile(psiDirectory.getVirtualFile()); final ModuleFileIndex moduleFileIndex = module == null ? null : ModuleRootManager.getInstance(module).getFileIndex(); if (!settings.isFlattenPackages() || skipDirectory(psiDirectory)) { processPsiDirectoryChildren(psiDirectory, directoryChildrenInProject(psiDirectory, settings), children, fileIndex, null, settings, withSubDirectories); } else { // source directory in "flatten packages" mode final PsiDirectory parentDir = psiDirectory.getParentDirectory(); if (parentDir == null || skipDirectory(parentDir) && withSubDirectories) { addAllSubpackages(children, psiDirectory, moduleFileIndex, settings); } if (withSubDirectories) { PsiDirectory[] subdirs = psiDirectory.getSubdirectories(); for (PsiDirectory subdir : subdirs) { if (!skipDirectory(subdir)) { continue; } VirtualFile directoryFile = subdir.getVirtualFile(); if (Registry.is("ide.hide.excluded.files")) { if (fileIndex.isExcluded(directoryFile)) continue; } else { if (FileTypeRegistry.getInstance().isFileIgnored(directoryFile)) continue; } children.add(new PsiDirectoryNode(project, subdir, settings)); } } processPsiDirectoryChildren(psiDirectory, psiDirectory.getFiles(), children, fileIndex, moduleFileIndex, settings, withSubDirectories); } return children; }
@Override @NotNull public FileType getFileType() { if (myType == null) { myType = getLanguage().getAssociatedFileType(); if (myType == null) { VirtualFile virtualFile = getOriginalFile().getVirtualFile(); myType = virtualFile == null ? FileTypeRegistry.getInstance().getFileTypeByFileName(getName()) : virtualFile.getFileType(); } } return myType; }
public ProjectFileIndexImpl(@NotNull Project project, @NotNull DirectoryIndex directoryIndex, @NotNull FileTypeRegistry fileTypeManager) { myProject = project; myDirectoryIndex = directoryIndex; myFileTypeRegistry = fileTypeManager; myContentFilter = new ContentFilter(); myFileExclusionManager = ProjectFileExclusionManager.SERVICE.getInstance(project); }
public ModuleFileIndexImpl(Module module, DirectoryIndex directoryIndex) { myModule = module; myDirectoryIndex = directoryIndex; myFileTypeRegistry = FileTypeRegistry.getInstance(); myContentFilter = new ContentFilter(); myExclusionManager = ProjectFileExclusionManager.SERVICE.getInstance(module.getProject()); }
public void setLanguage(final Language language) { myLanguage = language; myFileType = language.getAssociatedFileType(); if (myFileType == null) { myFileType = FileTypeRegistry.getInstance().getFileTypeByFileName(myName); } }
private static void detectFileType(VirtualFile virtualFile) { if (virtualFile == null || !virtualFile.isValid() || virtualFile.isDirectory()) return; FileType fileType = virtualFile.getFileType(); if (fileType == UnknownFileType.INSTANCE) { FileTypeRegistry.getInstance().detectFileTypeFromContent(virtualFile); } }