com.intellij.testFramework.LightVirtualFile Java Examples

The following examples show how to use com.intellij.testFramework.LightVirtualFile. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DiffUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static EditorHighlighter createEditorHighlighter(@Nullable Project project, @Nonnull DocumentContent content) {
  FileType type = content.getContentType();
  VirtualFile file = content.getHighlightFile();
  Language language = content.getUserData(DiffUserDataKeys.LANGUAGE);

  EditorHighlighterFactory highlighterFactory = EditorHighlighterFactory.getInstance();
  if (language != null) {
    SyntaxHighlighter syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(language, project, file);
    return highlighterFactory.createEditorHighlighter(syntaxHighlighter, EditorColorsManager.getInstance().getGlobalScheme());
  }
  if (file != null) {
    if ((type == null || type == PlainTextFileType.INSTANCE) || file.getFileType() == type || file instanceof LightVirtualFile) {
      return highlighterFactory.createEditorHighlighter(project, file);
    }
  }
  if (type != null) {
    return highlighterFactory.createEditorHighlighter(project, type);
  }
  return null;
}
 
Example #2
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void doSaveDocument(@Nonnull final Document document, boolean isExplicit) throws IOException, SaveVetoException {
  VirtualFile file = getFile(document);
  if (LOG.isTraceEnabled()) LOG.trace("saving: " + file);

  if (file == null || file instanceof LightVirtualFile || file.isValid() && !isFileModified(file)) {
    removeFromUnsaved(document);
    return;
  }

  if (file.isValid() && needsRefresh(file)) {
    LOG.trace("  refreshing...");
    file.refresh(false, false);
    if (!myUnsavedDocuments.contains(document)) return;
  }

  if (!maySaveDocument(file, document, isExplicit)) {
    throw new SaveVetoException();
  }

  LOG.trace("  writing...");
  WriteAction.run(() -> doSaveDocumentInWriteAction(document, file));
  LOG.trace("  done");
}
 
Example #3
Source File: FileTemplateConfigurable.java    From consulo with Apache License 2.0 6 votes vote down vote up
private EditorHighlighter createHighlighter() {
  if (myTemplate != null && myVelocityFileType != UnknownFileType.INSTANCE) {
    return EditorHighlighterFactory.getInstance().createEditorHighlighter(myProject, new LightVirtualFile("aaa." + myTemplate.getExtension() + ".ft"));
  }

  FileType fileType = null;
  if (myTemplate != null) {
    fileType = FileTypeManager.getInstance().getFileTypeByExtension(myTemplate.getExtension());
  }
  if (fileType == null) {
    fileType = PlainTextFileType.INSTANCE;
  }

  SyntaxHighlighter originalHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(fileType, null, null);
  if (originalHighlighter == null) {
    originalHighlighter = new PlainSyntaxHighlighter();
  }

  final EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
  LayeredLexerEditorHighlighter highlighter = new LayeredLexerEditorHighlighter(new TemplateHighlighter(), scheme);
  highlighter.registerLayer(FileTemplateTokenType.TEXT, new LayerDescriptor(originalHighlighter, ""));
  return highlighter;
}
 
Example #4
Source File: GlobFindUsagesTest.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Test
public void testInMemoryFileHandledGracefully() {
  createBuildFile(new WorkspacePath("java/com/google/BUILD"), "glob(['**/*.java'])");

  LightVirtualFile inMemoryFile =
      new LightVirtualFile("mockProjectViewFile", ProjectViewLanguage.INSTANCE, "");

  FileManager fileManager =
      ((PsiManagerEx) PsiManager.getInstance(getProject())).getFileManager();
  fileManager.setViewProvider(
      inMemoryFile, fileManager.createFileViewProvider(inMemoryFile, true));

  PsiFile psiFile = fileManager.findFile(inMemoryFile);

  FindUsages.findAllReferences(psiFile);
}
 
Example #5
Source File: LoadTextUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Loads content of given virtual file. If limit is {@value UNLIMITED} then full CharSequence will be returned. Else CharSequence
 * will be truncated by limit if it has bigger length.
 *
 * @param file  Virtual file for content loading
 * @param limit Maximum characters count or {@value UNLIMITED}
 * @return Full or truncated CharSequence with file content
 * @throws IllegalArgumentException for binary files
 */
@Nonnull
public static CharSequence loadText(@Nonnull final VirtualFile file, int limit) {
  FileType type = file.getFileType();
  if (type.isBinary()) throw new IllegalArgumentException("Attempt to load truncated text for binary file: " + file.getPresentableUrl() + ". File type: " + type.getName());

  if (file instanceof LightVirtualFile) {
    return limitCharSequence(((LightVirtualFile)file).getContent(), limit);
  }

  if (file.isDirectory()) {
    throw new AssertionError("'" + file.getPresentableUrl() + "' is a directory");
  }
  try {
    byte[] bytes = limit == UNLIMITED ? file.contentsToByteArray() : FileUtil.loadFirstAndClose(file.getInputStream(), limit);
    return getTextByBinaryPresentation(bytes, file);
  }
  catch (IOException e) {
    return ArrayUtil.EMPTY_CHAR_SEQUENCE;
  }
}
 
Example #6
Source File: AbstractFileViewProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public CharSequence getText() {
  final VirtualFile virtualFile = getVirtualFile();
  if (virtualFile instanceof LightVirtualFile) {
    Document doc = getCachedDocument();
    if (doc != null) return getLastCommittedText(doc);
    return ((LightVirtualFile)virtualFile).getContent();
  }

  final Document document = getDocument();
  if (document == null) {
    return LoadTextUtil.loadText(virtualFile);
  }
  return getLastCommittedText(document);
}
 
Example #7
Source File: CSharpFragmentFactory.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static CSharpFragmentFileImpl createExpressionFragment(Project project, String text, @Nullable final PsiElement context)
{
	LightVirtualFile virtualFile = new LightVirtualFile("dummy.cs", CSharpFileType.INSTANCE, text, System.currentTimeMillis());
	SingleRootFileViewProvider viewProvider = new SingleRootFileViewProvider(PsiManager.getInstance(project), virtualFile, true)
	{
		@Nonnull
		@Override
		public SingleRootFileViewProvider createCopy(@Nonnull final VirtualFile copy)
		{
			SingleRootFileViewProvider provider = new SingleRootFileViewProvider(getManager(), copy, false);
			CSharpFragmentFileImpl psiFile = new CSharpFragmentFileImpl(ourExpressionFileElementType, ourExpressionFileElementType, provider, context);
			provider.forceCachedPsi(psiFile);
			psiFile.getNode();
			return provider;
		}
	};
	CSharpFragmentFileImpl file = new CSharpFragmentFileImpl(ourExpressionFileElementType, ourExpressionFileElementType, viewProvider, context);
	viewProvider.forceCachedPsi(file);
	file.getNode();
	return file;
}
 
Example #8
Source File: TemplateDataElementType.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected PsiFile createPsiFileFromSource(final Language language, CharSequence sourceCode, PsiManager manager) {
  @NonNls final LightVirtualFile virtualFile = new LightVirtualFile("foo", createTemplateFakeFileType(language), sourceCode, LocalTimeCounter.currentTime());

  FileViewProvider viewProvider = new SingleRootFileViewProvider(manager, virtualFile, false) {
    @Override
    @Nonnull
    public Language getBaseLanguage() {
      return language;
    }
  };

  // Since we're already inside a template language PSI that was built regardless of the file size (for whatever reason),
  // there should also be no file size checks for template data files.
  SingleRootFileViewProvider.doNotCheckFileSizeLimit(virtualFile);

  return viewProvider.getPsi(language);
}
 
Example #9
Source File: InjectedLanguageUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static PsiLanguageInjectionHost findInjectionHost(@Nullable PsiElement psi) {
  if (psi == null) return null;
  PsiFile containingFile = psi.getContainingFile().getOriginalFile();              // * formatting
  PsiElement fileContext = containingFile.getContext();                            // * quick-edit-handler
  if (fileContext instanceof PsiLanguageInjectionHost) return (PsiLanguageInjectionHost)fileContext;
  Place shreds = getShreds(containingFile.getViewProvider()); // * injection-registrar
  if (shreds == null) {
    VirtualFile virtualFile = PsiUtilCore.getVirtualFile(containingFile);
    if (virtualFile instanceof LightVirtualFile) {
      virtualFile = ((LightVirtualFile)virtualFile).getOriginalFile();             // * dynamic files-from-text
    }
    if (virtualFile instanceof VirtualFileWindow) {
      shreds = getShreds(((VirtualFileWindow)virtualFile).getDocumentWindow());
    }
  }
  return shreds != null ? shreds.getHostPointer().getElement() : null;
}
 
Example #10
Source File: ParsingTestCase.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected void doTest(boolean checkResult) {
  String name = getTestName(false);
  try {
    String text = loadFile(name + "." + myExtension);
    myFile = createPsiFile(name, text);
    ensureParsed(myFile);
    FileViewProvider viewProvider = myFile.getViewProvider();
    VirtualFile virtualFile = viewProvider.getVirtualFile();
    if (virtualFile instanceof LightVirtualFile) {
      assertEquals("light virtual file text mismatch", text, ((LightVirtualFile)virtualFile).getContent());
    }
    assertEquals("virtual file text mismatch", text, LoadTextUtil.loadText(virtualFile));
    assertEquals("doc text mismatch", text, viewProvider.getDocument().getText());
    assertEquals("psi text mismatch", text, myFile.getText());
    if (checkResult) {
      checkResult(name, myFile);
    }
    else {
      toParseTreeText(myFile, skipSpaces(), includeRanges());
    }
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #11
Source File: FileManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void setViewProvider(@Nonnull final VirtualFile virtualFile, @Nullable final FileViewProvider fileViewProvider) {
  FileViewProvider prev = getRawCachedViewProvider(virtualFile);
  if (prev == fileViewProvider) return;
  if (prev != null) {
    DebugUtil.performPsiModification(null, () -> markInvalidated(prev));
  }

  if (fileViewProvider == null) {
    getVFileToViewProviderMap().remove(virtualFile);
  }
  else if (virtualFile instanceof LightVirtualFile) {
    virtualFile.putUserData(myPsiHardRefKey, fileViewProvider);
  }
  else {
    getVFileToViewProviderMap().put(virtualFile, fileViewProvider);
  }
}
 
Example #12
Source File: PsiFileFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public PsiFile createFileFromText(@Nonnull String name,
                                  @Nonnull Language language,
                                  @Nonnull LanguageVersion languageVersion,
                                  @Nonnull CharSequence text,
                                  boolean physical,
                                  boolean markAsCopy,
                                  boolean noSizeLimit) {
  LightVirtualFile virtualFile = new LightVirtualFile(name, language, text);
  virtualFile.putUserData(LanguageVersion.KEY, languageVersion);
  if (noSizeLimit) {
    SingleRootFileViewProvider.doNotCheckFileSizeLimit(virtualFile);
  }
  return trySetupPsiForFile(virtualFile, language, languageVersion, physical, markAsCopy);
}
 
Example #13
Source File: HaxeExpressionCodeFragmentImpl.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
public HaxeExpressionCodeFragmentImpl(Project project,
                                      @NonNls String name,
                                      CharSequence text,
                                      boolean isPhysical) {
  super(new SingleRootFileViewProvider(PsiManager.getInstance(project),
                                       new LightVirtualFile(name, FileTypeManager.getInstance().getFileTypeByFileName(name), text),
                                       isPhysical) {
    @Override
    public boolean supportsIncrementalReparse(@NotNull Language rootLanguage) {
      return false;
    }
  });

  myPhysical = isPhysical;
  ((SingleRootFileViewProvider)getViewProvider()).forceCachedPsi(this);
  final MyHaxeFileElementType type = new MyHaxeFileElementType();
  init(type, type);
}
 
Example #14
Source File: DiffContentFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static Document createPsiDocument(@Nonnull Project project,
                                          @Nonnull String content,
                                          @Nonnull FileType fileType,
                                          @Nonnull String fileName,
                                          boolean readOnly) {
  ThrowableComputable<Document,RuntimeException> action = () -> {
    LightVirtualFile file = new LightVirtualFile(fileName, fileType, content);
    file.setWritable(!readOnly);

    file.putUserData(DiffPsiFileSupport.KEY, true);

    Document document = FileDocumentManager.getInstance().getDocument(file);
    if (document == null) return null;

    PsiDocumentManager.getInstance(project).getPsiFile(document);

    return document;
  };
  return AccessRule.read(action);
}
 
Example #15
Source File: LineStatusTrackerManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
private boolean shouldBeInstalled(@javax.annotation.Nullable final VirtualFile virtualFile) {
  if (isDisabled()) return false;

  if (virtualFile == null || virtualFile instanceof LightVirtualFile) return false;
  final FileStatusManager statusManager = FileStatusManager.getInstance(myProject);
  if (statusManager == null) return false;
  if (!myStatusProvider.isSupported(virtualFile)) {
    log("shouldBeInstalled failed: no support found", virtualFile);
    return false;
  }
  final FileStatus status = statusManager.getStatus(virtualFile);
  if (status == FileStatus.NOT_CHANGED || status == FileStatus.ADDED || status == FileStatus.UNKNOWN || status == FileStatus.IGNORED) {
    log("shouldBeInstalled skipped: status=" + status, virtualFile);
    return false;
  }
  return true;
}
 
Example #16
Source File: PsiFileFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public PsiFile trySetupPsiForFile(final LightVirtualFile virtualFile,
                                  @Nonnull Language language,
                                  @Nonnull LanguageVersion languageVersion,
                                  final boolean physical,
                                  final boolean markAsCopy) {
  final FileViewProviderFactory factory = LanguageFileViewProviders.INSTANCE.forLanguage(language);
  FileViewProvider viewProvider = factory != null ? factory.createFileViewProvider(virtualFile, language, myManager, physical) : null;
  if (viewProvider == null) viewProvider = new SingleRootFileViewProvider(myManager, virtualFile, physical);

  language = viewProvider.getBaseLanguage();
  final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(language);
  if (parserDefinition != null) {
    final PsiFile psiFile = viewProvider.getPsi(language);
    if (psiFile != null) {
      psiFile.putUserData(LanguageVersion.KEY, languageVersion);
      if (markAsCopy) {
        markGenerated(psiFile);
      }
      return psiFile;
    }
  }
  return null;
}
 
Example #17
Source File: PsiFileFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nonnull
public PsiFile createFileFromText(@Nonnull String name,
                                  @Nonnull FileType fileType,
                                  @Nonnull CharSequence text,
                                  long modificationStamp,
                                  final boolean physical,
                                  boolean markAsCopy) {
  final LightVirtualFile virtualFile = new LightVirtualFile(name, fileType, text, modificationStamp);
  if (fileType instanceof LanguageFileType) {
    final Language language =
      LanguageSubstitutors.INSTANCE.substituteLanguage(((LanguageFileType)fileType).getLanguage(), virtualFile, myManager.getProject());
    final PsiFile file = trySetupPsiForFile(virtualFile, language, LanguageVersionUtil.findDefaultVersion(language), physical, markAsCopy);
    if (file != null) return file;
  }
  final SingleRootFileViewProvider singleRootFileViewProvider = new SingleRootFileViewProvider(myManager, virtualFile, physical);
  final PsiPlainTextFileImpl plainTextFile = new PsiPlainTextFileImpl(singleRootFileViewProvider);
  if (markAsCopy) CodeEditUtil.setNodeGenerated(plainTextFile.getNode(), true);
  return plainTextFile;
}
 
Example #18
Source File: CppDebugProcess.java    From CppTools with Apache License 2.0 6 votes vote down vote up
@Override
public XDebuggerEditorsProvider getEditorsProvider() {
  return new XDebuggerEditorsProvider() {
    @NotNull
    @Override
    public FileType getFileType() {
      return CppSupportLoader.CPP_FILETYPE;
    }

    @NotNull
    @Override
    public Document createDocument(@NotNull Project project, @NotNull String s, @Nullable XSourcePosition xSourcePosition, @NotNull EvaluationMode evaluationMode) {
      VirtualFile virtualFile = new LightVirtualFile("dummy.cpp", s);
      ICppCodeFragment file = new CppCodeFragment(new SingleRootFileViewProvider(PsiManager.getInstance(project), virtualFile, true));
      return PsiDocumentManager.getInstance(project).getDocument(file);
    }
  };
}
 
Example #19
Source File: PsiFileFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public PsiFile createFileFromText(@Nonnull String name,
                                  @Nonnull LanguageVersion languageVersion,
                                  @Nonnull CharSequence text,
                                  boolean physical,
                                  boolean markAsCopy,
                                  boolean noSizeLimit,
                                  @Nullable VirtualFile original) {
  LightVirtualFile virtualFile = new LightVirtualFile(name, languageVersion.getLanguage(), text);
  if (original != null) virtualFile.setOriginalFile(original);
  virtualFile.putUserData(LanguageVersion.KEY, languageVersion);
  if (noSizeLimit) {
    SingleRootFileViewProvider.doNotCheckFileSizeLimit(virtualFile);
  }
  return trySetupPsiForFile(virtualFile, languageVersion.getLanguage(), languageVersion, physical, markAsCopy);
}
 
Example #20
Source File: CSharpCreateFromTemplateHandler.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Nullable
@RequiredReadAction
public static Module findModuleByPsiDirectory(final PsiDirectory directory)
{
	LightVirtualFile l = new LightVirtualFile("test.cs", CSharpFileType.INSTANCE, "")
	{
		@Override
		public VirtualFile getParent()
		{
			return directory.getVirtualFile();
		}

		@Nonnull
		@Override
		public VirtualFileSystem getFileSystem()
		{
			return LocalFileSystem.getInstance();
		}
	};
	return CreateFileFromTemplateAction.ModuleResolver.EP_NAME.composite().resolveModule(directory, CSharpFileType.INSTANCE);
}
 
Example #21
Source File: LoadTextUtilTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void doTest(String source, String expected, String expectedSeparator) {
  final LightVirtualFile vFile = new LightVirtualFile("test.txt");
  final CharSequence real = LoadTextUtil.getTextByBinaryPresentation(source.getBytes(CharsetToolkit.US_ASCII_CHARSET), vFile);
  assertTrue("content", Comparing.equal(expected, real));
  if (expectedSeparator != null) {
    assertEquals("detected line separator", expectedSeparator, FileDocumentManager.getInstance().getLineSeparator(vFile, null));
  }
}
 
Example #22
Source File: BinaryContent.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public VirtualFile getFile() {
  if (myFileType instanceof UIBasedFileType) {
    final VirtualFile file = findVirtualFile();
    if (file != null) {
      final LightVirtualFile lightFile = new LightVirtualFile(file, new String(myBytes), 1);
      lightFile.setOriginalFile(file);
      return lightFile;
    }
  }
  return null;
}
 
Example #23
Source File: TodoTreeBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Marks specified PsiFile as dirty. It means that file is being add into "dirty" file set.
 * It presents in current file set also but the next validateCache call will validate this
 * "dirty" file. This method should be invoked when any modifications inside the file
 * have happened.
 */
private void markFileAsDirty(@Nonnull PsiFile psiFile) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  VirtualFile vFile = psiFile.getVirtualFile();
  if (vFile != null && !(vFile instanceof LightVirtualFile)) { // If PSI file isn't valid then its VirtualFile can be null
    myDirtyFileSet.add(vFile);
  }
}
 
Example #24
Source File: PsiUtilCore.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to find PSI file for a virtual file and throws assertion error with debug info if it is null.
 */
@Nonnull
public static PsiFile getPsiFile(@Nonnull Project project, @Nonnull 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();
}
 
Example #25
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static Document createDocument(@Nonnull CharSequence text, @Nonnull VirtualFile file) {
  boolean acceptSlashR = file instanceof LightVirtualFile && StringUtil.indexOf(text, '\r') >= 0;
  boolean freeThreaded = Boolean.TRUE.equals(file.getUserData(AbstractFileViewProvider.FREE_THREADED));
  DocumentImpl document = (DocumentImpl)((EditorFactoryImpl)EditorFactory.getInstance()).createDocument(text, acceptSlashR, freeThreaded);
  document.documentCreatedFrom(file);
  return document;
}
 
Example #26
Source File: AbstractFileViewProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected AbstractFileViewProvider(@Nonnull PsiManager manager, @Nonnull VirtualFile virtualFile, boolean eventSystemEnabled) {
  myManager = (PsiManagerEx)manager;
  myVirtualFile = virtualFile;
  myEventSystemEnabled = eventSystemEnabled;
  setContent(new VirtualFileContent());
  myPhysical = isEventSystemEnabled() && !(virtualFile instanceof LightVirtualFile) && !(virtualFile.getFileSystem() instanceof NonPhysicalFileSystem);
  virtualFile.putUserData(FREE_THREADED, isFreeThreaded(this));
  if (virtualFile instanceof VirtualFileWindow && !(this instanceof FreeThreadedFileViewProvider) && !isFreeThreaded(this)) {
    throw new IllegalArgumentException("Must not create " + getClass() + " for injected file " + virtualFile + "; InjectedFileViewProvider must be used instead");
  }
}
 
Example #27
Source File: BlockSupportImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static String details(FileViewProvider providerCopy, FileViewProvider viewProvider) {
  return "; languages: " + viewProvider.getLanguages() +
         "; base: " + viewProvider.getBaseLanguage() +
         "; copy: " + providerCopy +
         "; copy.base: " + providerCopy.getBaseLanguage() +
         "; vFile: " + viewProvider.getVirtualFile() +
         "; copy.vFile: " + providerCopy.getVirtualFile() +
         "; fileType: " + viewProvider.getVirtualFile().getFileType() +
         "; copy.original(): " +
         (providerCopy.getVirtualFile() instanceof LightVirtualFile ? ((LightVirtualFile)providerCopy.getVirtualFile()).getOriginalFile() : null);
}
 
Example #28
Source File: PsiDirectoryImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public PsiFile copyFileFrom(@Nonnull String newName, @Nonnull PsiFile originalFile) throws IncorrectOperationException {
  checkCreateFile(newName);

  final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(originalFile);
  if (document != null) {
    FileDocumentManager.getInstance().saveDocument(document);
  }

  final VirtualFile parent = getVirtualFile();
  try {
    final VirtualFile vFile = originalFile.getVirtualFile();
    if (vFile == null) throw new IncorrectOperationException("Cannot copy nonphysical file");
    VirtualFile copyVFile;
    if (parent.getFileSystem() == vFile.getFileSystem()) {
      copyVFile = vFile.copy(this, parent, newName);
    }
    else if (vFile instanceof LightVirtualFile) {
      copyVFile = parent.createChildData(this, newName);
      copyVFile.setBinaryContent(originalFile.getText().getBytes(copyVFile.getCharset()));
    }
    else {
      copyVFile = VfsUtilCore.copyFile(this, vFile, parent, newName);
    }
    LOG.assertTrue(copyVFile != null, "File was not copied: " + vFile);
    DumbService.getInstance(getProject()).completeJustSubmittedTasks();
    final PsiFile copyPsi = myManager.findFile(copyVFile);
    if (copyPsi == null) {
      LOG.error("Could not find file '" + copyVFile + "' after copying '" + vFile + "'");
    }
    updateAddedFile(copyPsi);
    return copyPsi;
  }
  catch (IOException e) {
    throw new IncorrectOperationException(e);
  }
}
 
Example #29
Source File: LayoutCodeDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void setUpTextRangeMode() {
  mySelectedTextRadioButton.setEnabled(myTextSelected);
  if (!myTextSelected) {
    mySelectedTextRadioButton.setToolTipText("No text selected in editor");
  }

  final boolean fileHasChanges = FormatChangedTextUtil.hasChanges(myFile);
  if (myFile.getVirtualFile() instanceof LightVirtualFile) {
    myOnlyVCSChangedTextRb.setVisible(false);
  }
  else {
    myOnlyVCSChangedTextRb.setEnabled(fileHasChanges);
    if (!fileHasChanges) {
      String hint = getChangesNotAvailableHint();
      if (hint != null) myOnlyVCSChangedTextRb.setToolTipText(hint);
    }
  }

  myWholeFileRadioButton.setEnabled(true);

  if (myTextSelected) {
    mySelectedTextRadioButton.setSelected(true);
  }
  else {
    boolean lastRunProcessedChangedText = myLastRunOptions.getLastTextRangeType() == TextRangeType.VCS_CHANGED_TEXT;
    if (lastRunProcessedChangedText && fileHasChanges) {
      myOnlyVCSChangedTextRb.setSelected(true);
    }
    else {
      myWholeFileRadioButton.setSelected(true);
    }
  }
}
 
Example #30
Source File: SingleRootFileViewProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean fileSizeIsGreaterThan(@Nonnull VirtualFile vFile, final long maxBytes) {
  if (vFile instanceof LightVirtualFile) {
    // This is optimization in order to avoid conversion of [large] file contents to bytes
    final int lengthInChars = ((LightVirtualFile)vFile).getContent().length();
    if (lengthInChars < maxBytes / 2) return false;
    if (lengthInChars > maxBytes) return true;
  }

  return vFile.getLength() > maxBytes;
}