com.intellij.openapi.vfs.encoding.EncodingManager Java Examples

The following examples show how to use com.intellij.openapi.vfs.encoding.EncodingManager. 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: TestUtils.java    From intellij with Apache License 2.0 6 votes vote down vote up
static void createMockApplication(Disposable parentDisposable) {
  final MyMockApplication instance = new MyMockApplication(parentDisposable);

  // If there was no previous application, ApplicationManager leaves the MockApplication in place,
  // which can break future tests.
  Application oldApplication = ApplicationManager.getApplication();
  if (oldApplication == null) {
    Disposer.register(
        parentDisposable,
        () ->
            new ApplicationManager() {
              {
                ourApplication = null;
              }
            });
  }

  ApplicationManager.setApplication(instance, FileTypeManager::getInstance, parentDisposable);
  instance.registerService(EncodingManager.class, EncodingManagerImpl.class);
}
 
Example #2
Source File: TestUtils.java    From intellij with Apache License 2.0 6 votes vote down vote up
public static void createMockApplication(Disposable parentDisposable) {
  final BlazeMockApplication instance = new BlazeMockApplication(parentDisposable);

  // If there was no previous application,
  // ApplicationManager leaves the MockApplication in place, which can break future tests.
  Application oldApplication = ApplicationManager.getApplication();
  if (oldApplication == null) {
    Disposer.register(
        parentDisposable,
        () -> {
          new ApplicationManager() {
            {
              ourApplication = null;
            }
          };
        });
  }

  ApplicationManager.setApplication(instance, FileTypeManager::getInstance, parentDisposable);
  instance.registerService(EncodingManager.class, EncodingManagerImpl.class);
}
 
Example #3
Source File: FilePathImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Charset getCharset(Project project) {
  // try to find existing virtual file
  VirtualFile existing = myVirtualFile != null && myVirtualFile.isValid() ? myVirtualFile : null;
  if (existing == null) {
    LocalFileSystem lfs = LocalFileSystem.getInstance();
    for (File f = myFile; f != null; f = f.getParentFile()) {
      existing = lfs.findFileByIoFile(f);
      if (existing != null && existing.isValid()) {
        break;
      }
    }
  }
  if (existing != null) {
    Charset rc = existing.getCharset();
    if (rc != null) {
      return rc;
    }
  }
  EncodingManager e = project != null ? EncodingProjectManager.getInstance(project) : null;
  if (e == null) {
    e = EncodingManager.getInstance();
  }
  return e.getDefaultCharset();
}
 
Example #4
Source File: LightApplicationBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void registerServices(@Nonnull InjectingContainerBuilder builder) {
  builder.bind(PsiBuilderFactory.class).to(PsiBuilderFactoryImpl.class);
  builder.bind(FileTypeRegistry.class).to(LightFileTypeRegistry.class);
  builder.bind(FileDocumentManager.class).to(LightFileDocumentManager.class);
  builder.bind(JobLauncher.class).to(LightJobLauncher.class);
  builder.bind(EncodingManager.class).to(LightEncodingManager.class);
  builder.bind(PathMacrosService.class).to(LightPathMacrosService.class);
  builder.bind(PathMacros.class).to(LightPathMacros.class);
  builder.bind(UISettings.class);
  builder.bind(ExpandableItemsHandlerFactory.class).to(LightExpandableItemsHandlerFactory.class);
  builder.bind(TreeUIHelper.class).to(LightTreeUIHelper.class);
  builder.bind(UiActivityMonitor.class).to(LightUiActivityMonitor.class);
  builder.bind(TreeAnchorizer.class).to(TreeAnchorizer.class);
  builder.bind(ProgressManager.class).to(CoreProgressManager.class);
}
 
Example #5
Source File: UsageViewTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testUsageViewDoesNotHoldPsiFilesOrDocuments() throws Exception {
  PsiFile psiFile = createFile("X.java", "public class X{} //iuggjhfg");
  Usage[] usages = new Usage[100];
  for (int i = 0; i < usages.length; i++) {
    usages[i] = createUsage(psiFile,i);
  }

  UsageView usageView = UsageViewManager.getInstance(getProject()).createUsageView(UsageTarget.EMPTY_ARRAY, usages, new UsageViewPresentation(), null);

  Disposer.register(getTestRootDisposable(), usageView);

  ((EncodingManagerImpl)EncodingManager.getInstance()).clearDocumentQueue();
  FileDocumentManager.getInstance().saveAllDocuments();
  UIUtil.dispatchAllInvocationEvents();

  LeakHunter.checkLeak(usageView, PsiFileImpl.class);
  LeakHunter.checkLeak(usageView, Document.class);
}
 
Example #6
Source File: PersistentFSImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public VirtualFile createChildFile(Object requestor, @Nonnull VirtualFile parent, @Nonnull String file) throws IOException {
  getDelegate(parent).createChildFile(requestor, parent, file);
  processEvent(new VFileCreateEvent(requestor, parent, file, false, null, null, false, null));

  final VirtualFile child = parent.findChild(file);
  if (child == null) {
    throw new IOException("Cannot create child file '" + file + "' at " + parent.getPath());
  }
  if (child.getCharset().equals(StandardCharsets.UTF_8)) {
    Project project = ProjectLocator.getInstance().guessProjectForFile(child);
    EncodingManager encodingManager = project == null ? EncodingManager.getInstance() : EncodingProjectManager.getInstance(project);
    if (encodingManager.shouldAddBOMForNewUtf8File()) {
      child.setBOM(CharsetToolkit.UTF8_BOM);
    }
  }
  return child;
}
 
Example #7
Source File: VirtualFileSystemEntry.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private Charset computeCharset() {
  Charset charset;
  if (isDirectory()) {
    Charset configured = EncodingManager.getInstance().getEncoding(this, true);
    charset = configured == null ? Charset.defaultCharset() : configured;
    setCharset(charset);
  }
  else {
    FileType fileType = getFileType();
    if (isCharsetSet()) {
      // file type detection may have cached the charset, no need to re-detect
      return super.getCharset();
    }
    try {
      final byte[] content = VfsUtilCore.loadBytes(this);
      charset = LoadTextUtil.detectCharsetAndSetBOM(this, content, fileType);
    }
    catch (IOException e) {
      return super.getCharset();
    }
  }
  return charset;
}
 
Example #8
Source File: EncodingPanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void registerCustomListeners() {
  // should update to reflect encoding-from-content
  EncodingManager.getInstance().addPropertyChangeListener(evt -> {
    if (evt.getPropertyName().equals(EncodingManagerImpl.PROP_CACHED_ENCODING_CHANGED)) {
      Document document = evt.getSource() instanceof Document ? (Document)evt.getSource() : null;
      updateForDocument(document);
    }
  }, this);
  ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(VirtualFileManager.VFS_CHANGES, new BulkVirtualFileListenerAdapter(new VirtualFileListener() {
    @Override
    public void propertyChanged(@Nonnull VirtualFilePropertyEvent event) {
      if (VirtualFile.PROP_ENCODING.equals(event.getPropertyName())) {
        updateForFile(event.getFile());
      }
    }
  }));
}
 
Example #9
Source File: ConsoleViewRunningState.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static OutputStreamWriter createOutputStreamWriter(OutputStream processInput, ProcessHandler processHandler) {
  Charset charset = null;
  if (processHandler instanceof OSProcessHandler) {
    charset = ((OSProcessHandler)processHandler).getCharset();
  }
  if (charset == null) {
    charset = EncodingManager.getInstance().getDefaultCharset();
  }

  return new OutputStreamWriter(processInput, charset);
}
 
Example #10
Source File: VcsHistoryUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static String loadRevisionContentGuessEncoding(@Nonnull final VcsFileRevision revision, @Nullable final VirtualFile file,
                                                      @javax.annotation.Nullable final Project project) throws VcsException, IOException {
  final byte[] bytes = loadRevisionContent(revision);
  if (file != null) {
    return new String(bytes, file.getCharset());
  }
  EncodingManager e = project != null ? EncodingProjectManager.getInstance(project) : null;
  if (e == null) {
    e = EncodingManager.getInstance();
  }

  return CharsetToolkit.bytesToString(bytes, e.getDefaultCharset());
}
 
Example #11
Source File: LocalFilePath.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public Charset getCharset(@Nullable Project project) {
  VirtualFile file = getVirtualFile();
  String path = myPath;
  while ((file == null || !file.isValid()) && !path.isEmpty()) {
    path = PathUtil.getParentPath(path);
    file = LocalFileSystem.getInstance().findFileByPath(path);
  }
  if (file != null) {
    return file.getCharset();
  }
  EncodingManager e = project == null ? EncodingManager.getInstance() : EncodingProjectManager.getInstance(project);
  return e.getDefaultCharset();
}
 
Example #12
Source File: CoreApplicationEnvironment.java    From consulo with Apache License 2.0 5 votes vote down vote up
public CoreApplicationEnvironment(@Nonnull Disposable parentDisposable) {
  myParentDisposable = parentDisposable;

  myFileTypeRegistry = new CoreFileTypeRegistry();

  myApplication = createApplication(myParentDisposable);
  ApplicationManager.setApplication(myApplication, myParentDisposable);
  myLocalFileSystem = createLocalFileSystem();
  myJarFileSystem = createJarFileSystem();

  final InjectingContainer appContainer = myApplication.getInjectingContainer();
  registerComponentInstance(appContainer, FileDocumentManager.class, new MockFileDocumentManagerImpl(DocumentImpl::new, null));

  VirtualFileSystem[] fs = {myLocalFileSystem, myJarFileSystem};
  VirtualFileManagerImpl virtualFileManager = new VirtualFileManagerImpl(myApplication, fs);
  registerComponentInstance(appContainer, VirtualFileManager.class, virtualFileManager);

  registerApplicationExtensionPoint(ASTLazyFactory.EP.getExtensionPointName(), ASTLazyFactory.class);
  registerApplicationExtensionPoint(ASTLeafFactory.EP.getExtensionPointName(), ASTLeafFactory.class);
  registerApplicationExtensionPoint(ASTCompositeFactory.EP.getExtensionPointName(), ASTCompositeFactory.class);

  addExtension(ASTLazyFactory.EP.getExtensionPointName(), new DefaultASTLazyFactory());
  addExtension(ASTLeafFactory.EP.getExtensionPointName(), new DefaultASTLeafFactory());
  addExtension(ASTCompositeFactory.EP.getExtensionPointName(), new DefaultASTCompositeFactory());

  registerApplicationService(EncodingManager.class, new CoreEncodingRegistry());
  registerApplicationService(VirtualFilePointerManager.class, createVirtualFilePointerManager());
  registerApplicationService(PsiBuilderFactory.class, new PsiBuilderFactoryImpl());
  registerApplicationService(ReferenceProvidersRegistry.class, new MockReferenceProvidersRegistry());
  registerApplicationService(StubTreeLoader.class, new CoreStubTreeLoader());
  registerApplicationService(PsiReferenceService.class, new PsiReferenceServiceImpl());
  registerApplicationService(MetaDataRegistrar.class, new MetaRegistry());

  registerApplicationService(ProgressManager.class, createProgressIndicatorProvider());

  registerApplicationService(JobLauncher.class, createJobLauncher());
  registerApplicationService(CodeFoldingSettings.class, new CodeFoldingSettings());
  registerApplicationService(CommandProcessor.class, new CoreCommandProcessor());
}
 
Example #13
Source File: LoadTextUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to detect text in the {@code bytes} and call the {@code fileTextProcessor} with the text (if detected) or with null if not
 */
public static String getTextFromBytesOrNull(@Nonnull byte[] bytes, int startOffset, int endOffset) {
  Charset defaultCharset = EncodingManager.getInstance().getDefaultCharset();
  DetectResult info = guessFromBytes(bytes, startOffset, endOffset, defaultCharset);
  Charset charset;
  if (info.hardCodedCharset != null) {
    charset = info.hardCodedCharset;
  }
  else {
    switch (info.guessed) {
      case SEVEN_BIT:
        charset = CharsetToolkit.US_ASCII_CHARSET;
        break;
      case VALID_UTF8:
        charset = StandardCharsets.UTF_8;
        break;
      case INVALID_UTF8:
      case BINARY:
        // the charset was not detected so the file is likely binary
        return null;
      default:
        throw new IllegalStateException(String.valueOf(info.guessed));
    }
  }
  byte[] bom = info.BOM;
  ConvertResult result = convertBytes(bytes, Math.min(startOffset + (bom == null ? 0 : bom.length), endOffset), endOffset, charset);
  return result.text.toString();
}
 
Example #14
Source File: ScriptRunnerUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static OSProcessHandler execute(@Nonnull String exePath,
                                       @Nullable String workingDirectory,
                                       @Nullable VirtualFile scriptFile,
                                       String[] parameters) throws ExecutionException {
  GeneralCommandLine commandLine = new GeneralCommandLine();
  commandLine.setExePath(exePath);
  commandLine.setPassParentEnvironment(true);
  if (scriptFile != null) {
    commandLine.addParameter(scriptFile.getPresentableUrl());
  }
  commandLine.addParameters(parameters);

  if (workingDirectory != null) {
    commandLine.setWorkDirectory(workingDirectory);
  }

  LOG.debug("Command line: " + commandLine.getCommandLineString());
  LOG.debug("Command line env: " + commandLine.getEnvironment());

  final OSProcessHandler processHandler = new ColoredProcessHandler(commandLine.createProcess(), commandLine.getCommandLineString(),
                                                                    EncodingManager.getInstance().getDefaultCharset());
  if (LOG.isDebugEnabled()) {
    processHandler.addProcessListener(new ProcessAdapter() {
      @Override
      public void onTextAvailable(ProcessEvent event, Key outputType) {
        LOG.debug(outputType + ": " + event.getText());
      }
    });
  }

  //ProcessTerminatedListener.attach(processHandler, project);
  return processHandler;
}
 
Example #15
Source File: HeavyIdeaTestFixtureImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();

  initApplication();
  setUpProject();

  EncodingManager.getInstance(); // adds listeners
  myEditorListenerTracker = new EditorListenerTracker();
  myThreadTracker = new ThreadTracker();
  InjectedLanguageManagerImpl.pushInjectors(getProject());
}
 
Example #16
Source File: UndoHandler.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
private void performUndoableAction(List<String> filesChangedList) {
    for (String fileName : filesChangedList)
        try {
            VirtualFile virtualFile = getInstance().findFileByIoFile(new File(fileName));
            if (virtualFile != null) {
                Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
                getInstance().refreshAndFindFileByIoFile(new File(fileName));
                if (document != null)
                    document.setText(StringUtils.join(FileUtils.readLines(new File(fileName), EncodingManager.getInstance().getEncoding(virtualFile, true).toString()).toArray(), "\n"));
            }
        } catch (Exception ignored) {
            LOG.debug(ignored);
        }
}
 
Example #17
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static int getPreviewCharCount(@Nonnull VirtualFile file) {
  Charset charset = EncodingManager.getInstance().getEncoding(file, false);
  float bytesPerChar = charset == null ? 2 : charset.newEncoder().averageBytesPerChar();
  return (int)(FileUtilRt.LARGE_FILE_PREVIEW_SIZE / bytesPerChar);
}
 
Example #18
Source File: OSProcessHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * {@code commandLine} must not be not empty (for correct thread attribution in the stacktrace)
 */
public OSProcessHandler(@Nonnull Process process, /*@NotNull*/ String commandLine) {
  this(process, commandLine, EncodingManager.getInstance().getDefaultCharset());
}
 
Example #19
Source File: EncodingEnvironmentUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static Charset getCharset(Project project) {
  return (project != null ? EncodingProjectManager.getInstance(project) : EncodingManager.getInstance()).getDefaultCharset();
}
 
Example #20
Source File: PlatformLiteFixture.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void initApplication() {
  //if (ApplicationManager.getApplication() instanceof MockApplicationEx) return;
  final MockApplicationEx instance = new MockApplicationEx(getTestRootDisposable());
  ApplicationManager.setApplication(instance, getTestRootDisposable());
  getApplication().registerService(EncodingManager.class, EncodingManagerImpl.class);
}
 
Example #21
Source File: EditorListenerTracker.java    From consulo with Apache License 2.0 4 votes vote down vote up
public EditorListenerTracker() {
  EncodingManager.getInstance(); //adds listeners
  EditorEventMulticasterImpl multicaster = (EditorEventMulticasterImpl)EditorFactory.getInstance().getEventMulticaster();
  before = multicaster.getListeners();
  myDefaultProjectInitialized = ((DefaultProjectFactoryImpl)DefaultProjectFactory.getInstance()).isDefaultProjectInitialized();
}
 
Example #22
Source File: LightPlatformTestCase.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void doTearDown(@Nonnull final Project project, ApplicationStarter application, boolean checkForEditors) throws Exception {
  DocumentCommitThread.getInstance().clearQueue();
  CodeStyleSettingsManager.getInstance(project).dropTemporarySettings();
  checkAllTimersAreDisposed();
  UsefulTestCase.doPostponedFormatting(project);

  LookupManager lookupManager = LookupManager.getInstance(project);
  if (lookupManager != null) {
    lookupManager.hideActiveLookup();
  }
  ((StartupManagerImpl)StartupManager.getInstance(project)).prepareForNextTest();
  InspectionProfileManager.getInstance().deleteProfile(PROFILE);
  assertNotNull("Application components damaged", ProjectManager.getInstance());

  new WriteCommandAction.Simple(project) {
    @Override
    @RequiredWriteAction
    protected void run() throws Throwable {
      if (ourSourceRoot != null) {
        try {
          final VirtualFile[] children = ourSourceRoot.getChildren();
          for (VirtualFile child : children) {
            child.delete(this);
          }
        }
        catch (IOException e) {
          //noinspection CallToPrintStackTrace
          e.printStackTrace();
        }
      }
      EncodingManager encodingManager = EncodingManager.getInstance();
      if (encodingManager instanceof EncodingManagerImpl) ((EncodingManagerImpl)encodingManager).clearDocumentQueue();

      FileDocumentManager manager = FileDocumentManager.getInstance();

      ApplicationManager.getApplication().runWriteAction(EmptyRunnable.getInstance()); // Flush postponed formatting if any.
      manager.saveAllDocuments();
      if (manager instanceof FileDocumentManagerImpl) {
        ((FileDocumentManagerImpl)manager).dropAllUnsavedDocuments();
      }
    }
  }.execute().throwException();

  assertFalse(PsiManager.getInstance(project).isDisposed());

  PsiDocumentManagerImpl documentManager = clearUncommittedDocuments(project);
  ((HintManagerImpl)HintManager.getInstance()).cleanup();
  DocumentCommitThread.getInstance().clearQueue();

  UIUtil.invokeAndWaitIfNeeded(new Runnable() {
    @Override
    public void run() {
      ((UndoManagerImpl)UndoManager.getGlobalInstance()).dropHistoryInTests();
      ((UndoManagerImpl)UndoManager.getInstance(project)).dropHistoryInTests();

      UIUtil.dispatchAllInvocationEvents();
    }
  });

  TemplateDataLanguageMappings.getInstance(project).cleanupForNextTest();

  ProjectManagerEx.getInstanceEx().closeTestProject(project);
  //application.setDataProvider(null);
  ourTestCase = null;
  ((PsiManagerImpl)PsiManager.getInstance(project)).cleanupForNextTest();

  CompletionProgressIndicator.cleanupForNextTest();

  if (checkForEditors) {
    checkEditorsReleased();
  }
  if (isLight(project)) {
    // mark temporarily as disposed so that rogue component trying to access it will fail
    ((ProjectImpl)project).setTemporarilyDisposed(true);
    documentManager.clearUncommittedDocuments();
  }
}
 
Example #23
Source File: DiffElement.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public Charset getCharset() {
  return EncodingManager.getInstance().getDefaultCharset();
}
 
Example #24
Source File: RemoteFilePath.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public Charset getCharset(@Nullable Project project) {
  EncodingManager em = project == null ? EncodingManager.getInstance() : EncodingProjectManager.getInstance(project);
  return em.getDefaultCharset();
}
 
Example #25
Source File: ContentRevisionUtil.java    From p4ic4idea with Apache License 2.0 4 votes vote down vote up
@NotNull
public static Charset getNonNullCharset(@Nullable Charset charset) {
    return charset == null
            ? EncodingManager.getInstance().getDefaultCharset()
            : charset;
}