Java Code Examples for com.intellij.openapi.fileEditor.FileDocumentManager

The following are top voted examples for showing how to use com.intellij.openapi.fileEditor.FileDocumentManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: bamboo-soy   File: SoyDocumentationProvider.java   View source code 6 votes vote down vote up
@Nullable
@Override
public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) {
  Document document =
      FileDocumentManager.getInstance().getDocument(element.getContainingFile().getVirtualFile());
  if (document == null) return "";

  int lineNum = document.getLineNumber(element.getTextOffset()) + 1 /* count starts at zero */;
  String path = element.getContainingFile().getVirtualFile().getName();
  StringBuilder navigateInfo = new StringBuilder("Defined at ");
  navigateInfo.append(path);
  navigateInfo.append(":");
  navigateInfo.append(lineNum);
  String optDoc = getDocCommentForEnclosingTag(element);
  if (optDoc != null) {
    navigateInfo.append("\n");
    navigateInfo.append(produceCommentPreview(optDoc));
  }
  return navigateInfo.toString();
}
 
Example 2
Project: AndroidSourceViewer   File: DiffSourceAction.java   View source code 6 votes vote down vote up
/**
 * 调用 Android 文件对比
 * @param project
 * @param f1
 * @param f2
 */
public static void diff(final Project project, final File f1, final File f2) {
    ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                VirtualFile v1 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f1);
                Document document1 = FileDocumentManager.getInstance().getDocument(v1);
                FileDocumentContentImpl fileDocumentContent1 = new FileDocumentContentImpl(project, document1, v1);
                VirtualFile v2 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f2);
                Document document2 = FileDocumentManager.getInstance().getDocument(v2);
                FileDocumentContentImpl fileDocumentContent2 = new FileDocumentContentImpl(project, document2, v2);
                SimpleDiffRequest simpleDiffRequest = new SimpleDiffRequest(Constant.TITLE, fileDocumentContent1, fileDocumentContent2,
                        f1.getName(), f2.getName());
                DiffManager.getInstance().showDiff(project, simpleDiffRequest);
            } catch (Exception e) {
                NotificationUtils.errorNotification("Diff Source Error:" + e.getMessage());
            }
        }
    });
}
 
Example 3
Project: quicknotes   File: AddToQuickNotes.java   View source code 6 votes vote down vote up
public void actionPerformed( AnActionEvent e ) {
    Editor editor = ( Editor ) e.getDataContext().getData( "editor" );
    SelectionModel selectionModel = editor.getSelectionModel();
    if ( selectionModel != null ) {
        String selectedText = selectionModel.getSelectedText();
        if ( selectedText != null && selectedText.trim().length() > 0 ) {
            Project project = ( Project ) e.getDataContext().getData( DataConstants.PROJECT );
            String panelid = ( String ) project.getUserData( QuickNotes.KEY_PANELID );
            QuickNotesPanel quickNotesPanel = QuickNotesManager.getInstance().getQuickNotesPanel( panelid );
            if ( quickNotesPanel != null ) {
                FileDocumentManager manager = FileDocumentManager.getInstance();
                VirtualFile virtualFile = manager.getFile( editor.getDocument() );
                quickNotesPanel.addNewNote( "[File: " + virtualFile.getPath() + "]\n" + selectedText );
            }
        }
    }
}
 
Example 4
Project: educational-plugin   File: Task.java   View source code 6 votes vote down vote up
@NotNull
public String getTestsText(@NotNull final Project project) {
  final Course course = getLesson().getCourse();
  final Language language = course.getLanguageById();
  final EduPluginConfigurator configurator = EduPluginConfigurator.INSTANCE.forLanguage(language);
  final VirtualFile taskDir = getTaskDir(project);
  if (taskDir != null) {
    final VirtualFile file = taskDir.findChild(configurator.getTestFileName());
    if (file == null) return "";
    final Document document = FileDocumentManager.getInstance().getDocument(file);
    if (document != null) {
      return document.getImmutableCharSequence().toString();
    }
  }

  return "";
}
 
Example 5
Project: educational-plugin   File: StudyWindowNavigationAction.java   View source code 6 votes vote down vote up
private void navigateToPlaceholder(@NotNull final Project project) {
  final Editor selectedEditor = StudyUtils.getSelectedEditor(project);
  if (selectedEditor != null) {
    final FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
    final VirtualFile openedFile = fileDocumentManager.getFile(selectedEditor.getDocument());
    if (openedFile != null) {
      final TaskFile selectedTaskFile = StudyUtils.getTaskFile(project, openedFile);
      if (selectedTaskFile != null) {
        final int offset = selectedEditor.getCaretModel().getOffset();
        final AnswerPlaceholder targetPlaceholder = getTargetPlaceholder(selectedTaskFile, offset);
        if (targetPlaceholder == null) {
          return;
        }
        StudyNavigator.navigateToAnswerPlaceholder(selectedEditor, targetPlaceholder);
      }
    }
  }
}
 
Example 6
Project: educational-plugin   File: StudyAnswerPlaceholderExtendWordHandler.java   View source code 6 votes vote down vote up
@Nullable
private static AnswerPlaceholder getAnswerPlaceholder(PsiElement e, int offset) {
  PsiFile file = e.getContainingFile();
  if (file == null) {
    return null;
  }
  VirtualFile virtualFile = file.getVirtualFile();
  if (virtualFile == null) {
    return null;
  }
  TaskFile taskFile = StudyUtils.getTaskFile(e.getProject(), virtualFile);
  if (taskFile == null) {
    return null;
  }
  Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
  if (document == null) {
    return null;
  }
  Editor editor = FileEditorManager.getInstance(e.getProject()).getSelectedTextEditor();
  return editor == null ? null : taskFile.getAnswerPlaceholder(offset);
}
 
Example 7
Project: educational-plugin   File: CCTestCase.java   View source code 6 votes vote down vote up
protected VirtualFile configureByTaskFile(String name) {
  Task task = StudyTaskManager.getInstance(getProject()).getCourse().getLessons().get(0).getTaskList().get(0);
  TaskFile taskFile = new TaskFile();
  taskFile.setTask(task);
  task.getTaskFiles().put(name, taskFile);
  VirtualFile file = copyFileToTask(name);

  taskFile.name = name;
  myFixture.configureFromExistingVirtualFile(file);
  Document document = FileDocumentManager.getInstance().getDocument(file);
  for (AnswerPlaceholder placeholder : getPlaceholders(document, false)) {
    taskFile.addAnswerPlaceholder(placeholder);
  }
  taskFile.sortAnswerPlaceholders();
  StudyUtils.drawAllAnswerPlaceholders(myFixture.getEditor(), taskFile);
  return file;
}
 
Example 8
Project: Gradle-External-Library-Helper   File: GradleManager.java   View source code 6 votes vote down vote up
private void initBuildGradle() {
    SelectFromListDialog.ToStringAspect toStringAspect = String::valueOf;
    VirtualFile gradleVirtualFile = null;
    if (modules.length > 1) {
        SelectFromListDialog dialog = new SelectFromListDialog(project, modules, toStringAspect, "Select Gradle Module", ListSelectionModel.SINGLE_SELECTION);
        boolean isOk = dialog.showAndGet();
        if (isOk) {
            gradleVirtualFile = project.getBaseDir()
                    .findChild(String.valueOf(dialog.getSelection()[0]))
                    .findChild("build.gradle");
        }
    } else {
        gradleVirtualFile = project.getBaseDir()
                .findChild(modules[0])
                .findChild("build.gradle");
    }

    if (gradleVirtualFile != null) {
        buildGradle = FileDocumentManager.getInstance().getDocument(gradleVirtualFile);
    }
}
 
Example 9
Project: manifold-ij   File: IjFile.java   View source code 6 votes vote down vote up
private String getTemporaryBuffer( IjFile file )
{
  final VirtualFile virtualFile = file.getVirtualFile();

  // we're getting the cached documents since getDocument() forces PSI creating which will cause deadlock !!!
  if( virtualFile != null && !virtualFile.getFileType().isBinary() )
  {
    final Document document = FileDocumentManager.getInstance().getCachedDocument( virtualFile );
    final String[] result = new String[1];
    if( document != null )
    {
      if( ApplicationManagerEx.getApplicationEx().tryRunReadAction( () -> result[0] = document.getText() ) )
      {
        return result[0];
      }
      else
      {
        return document.getCharsSequence().toString();
      }
    }
  }

  return null;
}
 
Example 10
Project: intellij-ce-playground   File: MavenProjectModelModifier.java   View source code 6 votes vote down vote up
@Override
public Promise<Void> changeLanguageLevel(@NotNull Module module, @NotNull final LanguageLevel level) {
  if (!myProjectsManager.isMavenizedModule(module)) return null;

  MavenProject mavenProject = myProjectsManager.findProject(module);
  if (mavenProject == null) return null;

  final MavenDomProjectModel model = MavenDomUtil.getMavenDomProjectModel(myProject, mavenProject.getFile());
  if (model == null) return null;

  new WriteCommandAction(myProject, "Add Maven Dependency", DomUtil.getFile(model)) {
    @Override
    protected void run(@NotNull Result result) throws Throwable {
      MavenDomConfiguration configuration = getCompilerPlugin(model).getConfiguration();
      XmlTag tag = configuration.ensureTagExists();
      setChildTagValue(tag, "source", level.getCompilerComplianceDefaultOption());
      setChildTagValue(tag, "target", level.getCompilerComplianceDefaultOption());
      Document document = PsiDocumentManager.getInstance(myProject).getDocument(DomUtil.getFile(model));
      if (document != null) {
        FileDocumentManager.getInstance().saveDocument(document);
      }
    }
  }.execute();
  return myProjectsManager.forceUpdateProjects(Collections.singleton(mavenProject));
}
 
Example 11
Project: intellij-ce-playground   File: StubTreeLoaderImpl.java   View source code 6 votes vote down vote up
private static ObjectStubTree processError(final VirtualFile vFile, String message, @Nullable Exception e) {
  LOG.error(message, e);

  ApplicationManager.getApplication().invokeLater(new Runnable() {
    @Override
    public void run() {
      final Document doc = FileDocumentManager.getInstance().getCachedDocument(vFile);
      if (doc != null) {
        FileDocumentManager.getInstance().saveDocument(doc);
      }
    }
  }, ModalityState.NON_MODAL);

  FileBasedIndex.getInstance().requestReindex(vFile);
  return null;
}
 
Example 12
Project: intellij-ce-playground   File: GithubCreateGistContentTest.java   View source code 6 votes vote down vote up
public void testCreateFromEditor() throws Throwable {
  VirtualFile file = myProjectRoot.findFileByRelativePath("file.txt");
  assertNotNull(file);

  Document document = FileDocumentManager.getInstance().getDocument(file);
  assertNotNull(document);

  myEditor = EditorFactory.getInstance().createEditor(document, myProject);
  assertNotNull(myEditor);

  List<FileContent> expected = new ArrayList<FileContent>();
  expected.add(new FileContent("file.txt", "file.txt content"));

  List<FileContent> actual = GithubCreateGistAction.collectContents(myProject, myEditor, file, null);

  checkEquals(expected, actual);
}
 
Example 13
Project: intellij-ce-playground   File: IdeaGateway.java   View source code 6 votes vote down vote up
@Nullable
private Entry doCreateEntry(@NotNull VirtualFile file, boolean forDeletion) {
  if (!file.isDirectory()) {
    if (!isVersioned(file)) return null;

    Pair<StoredContent, Long> contentAndStamps;
    if (forDeletion) {
      FileDocumentManager m = FileDocumentManager.getInstance();
      Document d = m.isFileModified(file) ? m.getCachedDocument(file) : null; // should not try to load document
      contentAndStamps = acquireAndClearCurrentContent(file, d);
    }
    else {
      contentAndStamps = getActualContentNoAcquire(file);
    }
    return new FileEntry(file.getName(), contentAndStamps.first, contentAndStamps.second, !file.isWritable());
  }
  DirectoryEntry newDir = new DirectoryEntry(file.getName());
  doCreateChildren(newDir, iterateDBChildren(file), forDeletion);
  if (!isVersioned(file) && newDir.getChildren().isEmpty()) return null;
  return newDir;
}
 
Example 14
Project: intellij-ce-playground   File: AbstractSimpleGradleEditorEntity.java   View source code 6 votes vote down vote up
@Override
public String toString() {
  final String value;
  List<GradleEditorSourceBinding> bindings = getDefinitionValueSourceBindings();
  if (bindings.isEmpty()) {
    value = "<undefined>";
  }
  else if (bindings.size() > 1) {
    value = "<ref>";
  }
  else {
    Document document = FileDocumentManager.getInstance().getDocument(bindings.get(0).getFile());
    RangeMarker rangeMarker = bindings.get(0).getRangeMarker();
    if (document == null) {
      value = "<unexpected!>";
    }
    else {
      value = '[' + document.getCharsSequence().subSequence(rangeMarker.getStartOffset(), rangeMarker.getEndOffset()).toString() + ']';
    }
  }
  return getName() + " " + value;
}
 
Example 15
Project: intellij-ce-playground   File: FindUtil.java   View source code 6 votes vote down vote up
public static boolean replace(Project project, Editor editor, int offset, FindModel model, ReplaceDelegate delegate) {
  Document document = editor.getDocument();

  if (!FileDocumentManager.getInstance().requestWriting(document, project)) {
    return false;
  }

  document.startGuardedBlockChecking();
  boolean toPrompt = model.isPromptOnReplace();

  try {
    doReplace(project, editor, model, document, offset, toPrompt, delegate);
  }
  catch (ReadOnlyFragmentModificationException e) {
    EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(document).handle(e);
  }
  finally {
    document.stopGuardedBlockChecking();
  }

  return true;
}
 
Example 16
Project: intellij-ce-playground   File: SourceInfo.java   View source code 6 votes vote down vote up
@Override
public int getOffset() {
  if (offset == -1) {
    Document document;
    AccessToken token = ReadAction.start();
    try {
      document = file.isValid() ? FileDocumentManager.getInstance().getDocument(file) : null;
    }
    finally {
      token.finish();
    }

    if (document == null) {
      return -1;
    }

    offset = line < document.getLineCount() ? document.getLineStartOffset(line) : -1;
  }
  return offset;
}
 
Example 17
Project: intellij-ce-playground   File: FileContentUtil.java   View source code 6 votes vote down vote up
/**
 * @deprecated to be removed after IDEA 15. Use {@link VfsUtil#saveText(VirtualFile, String)} instead.
 */
public static void setFileText(@Nullable Project project, final VirtualFile virtualFile, final String text) throws IOException {
  if (project == null) {
    project = ProjectUtil.guessProjectForFile(virtualFile);
  }
  if (project != null) {
    final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
    final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    final Document document = psiFile == null? null : psiDocumentManager.getDocument(psiFile);
    if (document != null) {
      document.setText(text != null ? text : "");
      psiDocumentManager.commitDocument(document);
      FileDocumentManager.getInstance().saveDocument(document);
      return;
    }
  }
  VfsUtil.saveText(virtualFile, text != null ? text : "");
  virtualFile.refresh(false, false);
}
 
Example 18
Project: intellij-ce-playground   File: ReformatBeforeCheckinHandler.java   View source code 6 votes vote down vote up
@Override
public void runCheckinHandlers(@NotNull final Runnable finishAction) {
  final VcsConfiguration configuration = VcsConfiguration.getInstance(myProject);
  final Collection<VirtualFile> files = myPanel.getVirtualFiles();

  final Runnable performCheckoutAction = new Runnable() {
    @Override
    public void run() {
      FileDocumentManager.getInstance().saveAllDocuments();
      finishAction.run();
    }
  };

  if (reformat(configuration, true)) {
    new ReformatCodeProcessor(
      myProject, CheckinHandlerUtil.getPsiFiles(myProject, files), FormatterUtil.REFORMAT_BEFORE_COMMIT_COMMAND_NAME, performCheckoutAction, true
    ).run();
  }
  else {
    performCheckoutAction.run();
  }

}
 
Example 19
Project: intellij-ce-playground   File: CompareFileWithEditor.java   View source code 6 votes vote down vote up
@Nullable
private static Document getEditingDocument(final DataContext dataContext) {
  Project project = CommonDataKeys.PROJECT.getData(dataContext);
  if (project == null) return null;
  VirtualFile[] selectedFiles = FileEditorManager.getInstance(project).getSelectedFiles();
  if (selectedFiles.length == 0) return null;
  VirtualFile selectedFile = selectedFiles[0];
  final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
  // find document for latest selected editor
  if (editor != null) {
    for (VirtualFile file : selectedFiles) {
      final Document document = FileDocumentManager.getInstance().getDocument(file);
      if (document == editor.getDocument()) {
        selectedFile = file;
      }
    }
  }
  if (!DiffContentUtil.isTextFile(selectedFile)) return null;
  return FileDocumentManager.getInstance().getDocument(selectedFile);
}
 
Example 20
Project: intellij-ce-playground   File: GithubShowCommitInBrowserFromAnnotateAction.java   View source code 6 votes vote down vote up
@Nullable
private static EventData calcData(AnActionEvent e, int lineNumber) {
  Project project = e.getData(CommonDataKeys.PROJECT);
  VirtualFile virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE);
  if (project == null || virtualFile == null) {
    return null;
  }
  Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
  if (document == null) {
    return null;
  }

  GitRepository repository = GitUtil.getRepositoryManager(project).getRepositoryForFile(virtualFile);
  if (repository == null) {
    return null;
  }

  return new EventData(project, repository, lineNumber);
}
 
Example 21
Project: intellij-ce-playground   File: StudyAnswerPlaceholderExtendWordHandler.java   View source code 6 votes vote down vote up
@Nullable
private static AnswerPlaceholder getAnswerPlaceholder(PsiElement e, int offset) {
  PsiFile file = e.getContainingFile();
  if (file == null) {
    return null;
  }
  VirtualFile virtualFile = file.getVirtualFile();
  if (virtualFile == null) {
    return null;
  }
  TaskFile taskFile = StudyUtils.getTaskFile(e.getProject(), virtualFile);
  if (taskFile == null) {
    return null;
  }
  Document document = FileDocumentManager.getInstance().getDocument(virtualFile);
  if (document == null) {
    return null;
  }
  Editor editor = FileEditorManager.getInstance(e.getProject()).getSelectedTextEditor();
  return editor == null ? null : taskFile.getAnswerPlaceholder(document,
                                        editor.offsetToLogicalPosition(offset));
}
 
Example 22
Project: intellij-ce-playground   File: bigFile.java   View source code 6 votes vote down vote up
private boolean processKeyTyped(char c) {
  // [vova] This is patch for Mac OS X. Under Mac "input methods"
  // is handled before our EventQueue consume upcoming KeyEvents.
  IdeEventQueue queue = IdeEventQueue.getInstance();
  if (queue.shouldNotTypeInEditor() || ProgressManager.getInstance().hasModalProgressIndicator()) {
    return false;
  }
  FileDocumentManager manager = FileDocumentManager.getInstance();
  final VirtualFile file = manager.getFile(myDocument);
  if (file != null && !file.isValid()) {
    return false;
  }

  ActionManagerEx actionManager = ActionManagerEx.getInstanceEx();
  DataContext dataContext = getDataContext();
  actionManager.fireBeforeEditorTyping(c, dataContext);
  MacUIUtil.hideCursor();
  EditorActionManager.getInstance().getTypedAction().actionPerformed(this, c, dataContext);

  return true;
}
 
Example 23
Project: intellij-ce-playground   File: EditorImpl.java   View source code 6 votes vote down vote up
private boolean processKeyTyped(char c) {
  // [vova] This is patch for Mac OS X. Under Mac "input methods"
  // is handled before our EventQueue consume upcoming KeyEvents.
  IdeEventQueue queue = IdeEventQueue.getInstance();
  if (queue.shouldNotTypeInEditor() || ProgressManager.getInstance().hasModalProgressIndicator()) {
    return false;
  }
  FileDocumentManager manager = FileDocumentManager.getInstance();
  final VirtualFile file = manager.getFile(myDocument);
  if (file != null && !file.isValid()) {
    return false;
  }

  ActionManagerEx actionManager = ActionManagerEx.getInstanceEx();
  DataContext dataContext = getDataContext();

  myImmediatePainter.paintCharacter(myEditorComponent.getGraphics(), c);

  actionManager.fireBeforeEditorTyping(c, dataContext);
  MacUIUtil.hideCursor();
  EditorActionManager.getInstance().getTypedAction().actionPerformed(this, c, dataContext);

  return true;
}
 
Example 24
Project: LayoutFormatter   File: LayoutFormatterAction.java   View source code 6 votes vote down vote up
private void execute(Project project, final VirtualFile file) {
    VirtualFile[] files = file.getChildren();
    if (files.length > 0) {
        for (VirtualFile _file : files) {
            if (Files.isXmlFileOrDir(_file)) {
                execute(project, _file);
            }
        }
    } else {
        System.out.println(file.getPath());
        final Document document = FileDocumentManager.getInstance().getDocument(file);
        new WriteCommandAction.Simple(project) {
            @Override protected void run() throws Throwable {
                String txt = document.getText();
                document.setText(Formatter.apply(txt));
            }
        }.execute();
    }
}
 
Example 25
Project: intellij-ce-playground   File: LineStatusTrackerManager.java   View source code 6 votes vote down vote up
private void resetTracker(@NotNull final VirtualFile virtualFile, boolean insertOnly) {
  final Document document = FileDocumentManager.getInstance().getCachedDocument(virtualFile);
  if (document == null) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("resetTracker: no cached document for " + virtualFile.getPath());
    }
    return;
  }

  synchronized (myLock) {
    if (isDisabled()) return;

    final LineStatusTracker tracker = myLineStatusTrackers.get(document);
    if (insertOnly && tracker != null) return;
    resetTracker(document, virtualFile, tracker);
  }
}
 
Example 26
Project: intellij-ce-playground   File: RollbackDialogAction.java   View source code 6 votes vote down vote up
public void actionPerformed(AnActionEvent e) {
  FileDocumentManager.getInstance().saveAllDocuments();
  Change[] changes = e.getData(VcsDataKeys.CHANGES);
  Project project = e.getData(CommonDataKeys.PROJECT);
  final ChangesBrowser browser = e.getData(ChangesBrowser.DATA_KEY);
  if (browser != null) {
    browser.setDataIsDirty(true);
  }
  RollbackChangesDialog.rollbackChanges(project, Arrays.asList(changes), true, new Runnable() {
    public void run() {
      if (browser != null) {
        browser.rebuildList();
        browser.setDataIsDirty(false);
      }
    }
  });
}
 
Example 27
Project: intellij-ce-playground   File: MiscPsiTest.java   View source code 6 votes vote down vote up
public void testCopyBinaryToTextFile() throws Exception{
  String text = "1234567890";
  VirtualFile vFile = myFixture.addFileToProject("Test.xxx", text).getVirtualFile();

  VirtualFile vDir = myFixture.getTempDirFixture().findOrCreateDir("dir");

  PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
  PsiFile file = getPsiManager().findFile(vFile);
  PsiDirectory dir = getPsiManager().findDirectory(vDir);
  PsiFile fileCopy = (PsiFile)file.copy();
  fileCopy = (PsiFile) fileCopy.setName("NewTest.txt");
  PsiFile newFile = (PsiFile)dir.add(fileCopy);
  assertInstanceOf(newFile, PsiPlainTextFile.class);

  assertEquals(text, VfsUtil.loadText(newFile.getVirtualFile()));
  assertEquals(newFile.getVirtualFile().getModificationStamp(), newFile.getViewProvider().getModificationStamp());
  assertFalse(FileDocumentManager.getInstance().isFileModified(newFile.getVirtualFile()));
}
 
Example 28
Project: intellij-ce-playground   File: OptimizeImportsBeforeCheckinHandler.java   View source code 6 votes vote down vote up
@Override
public void runCheckinHandlers(@NotNull final Runnable finishAction) {
  final VcsConfiguration configuration = VcsConfiguration.getInstance(myProject);
  final Collection<VirtualFile> files = myPanel.getVirtualFiles();

  final Runnable performCheckoutAction = new Runnable() {
    @Override
    public void run() {
      FileDocumentManager.getInstance().saveAllDocuments();
      finishAction.run();
    }
  };

  if (configuration.OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT && !DumbService.isDumb(myProject)) {
    new OptimizeImportsProcessor(myProject, CheckinHandlerUtil.getPsiFiles(myProject, files), COMMAND_NAME, performCheckoutAction).run();
  }  else {
    finishAction.run();
  }

}
 
Example 29
Project: intellij-ce-playground   File: OpenFileHyperlinkInfo.java   View source code 6 votes vote down vote up
@Override
public OpenFileDescriptor getDescriptor() {
  if (!myFile.isValid()) {
    return null;
  }

  int line = myDocumentLine;
  FileDocumentManager.getInstance().getDocument(myFile); // need to load decompiler text
  LineNumbersMapping mapping = myFile.getUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY);
  if (mapping != null) {
    line = mapping.bytecodeToSource(myDocumentLine + 1) - 1;
    if (line < 0) {
      line = myDocumentLine;
    }
  }

  int offset = calculateOffset(myFile, line, myDocumentColumn);
  if (offset != UNDEFINED_OFFSET) {
    return new OpenFileDescriptor(myProject, myFile, offset);
  }
  // although document position != logical position, it seems better than returning 'null'
  return new OpenFileDescriptor(myProject, myFile, line, myDocumentColumn);
}
 
Example 30
Project: intellij-ce-playground   File: EncodingProjectManagerImpl.java   View source code 6 votes vote down vote up
private static Processor<VirtualFile> createChangeCharsetProcessor() {
  return new Processor<VirtualFile>() {
    @Override
    public boolean process(final VirtualFile file) {
      if (!(file instanceof VirtualFileSystemEntry)) return false;
      Document cachedDocument = FileDocumentManager.getInstance().getCachedDocument(file);
      if (cachedDocument == null) return true;
      ProgressManager.progress("Reloading files...", file.getPresentableUrl());
      UIUtil.invokeLaterIfNeeded(new Runnable() {
        @Override
        public void run() {
          clearAndReload(file);
        }
      });
      return true;
    }
  };
}
 
Example 31
Project: intellij-ce-playground   File: FindClassTest.java   View source code 6 votes vote down vote up
public void testSynchronizationAfterChange() {
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    public void run() {
      FileDocumentManager.getInstance().saveAllDocuments();
      PsiClass psiClass = myJavaFacade.findClass("p.A");
      final VirtualFile vFile = psiClass.getContainingFile().getVirtualFile();
      File ioFile = VfsUtil.virtualToIoFile(vFile);
      ioFile.setLastModified(5);

      LocalFileSystem.getInstance().refresh(false);

      ModuleRootModificationUtil.setModuleSdk(myModule, null);

      psiClass = myJavaFacade.findClass("p.A");
      assertNotNull(psiClass);
    }
  });
}
 
Example 32
Project: intellij-ce-playground   File: RefreshAllExternalProjectsAction.java   View source code 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext());
  if (project == null) {
    e.getPresentation().setEnabled(false);
    return;
  }

  final List<ProjectSystemId> systemIds = getSystemIds(e);
  if (systemIds.isEmpty()) {
    e.getPresentation().setEnabled(false);
    return;
  }

  // We save all documents because there is a possible case that there is an external system config file changed inside the ide.
  FileDocumentManager.getInstance().saveAllDocuments();

  for (ProjectSystemId externalSystemId : systemIds) {
    ExternalSystemUtil.refreshProjects(project, externalSystemId, true);
  }
}
 
Example 33
Project: intellij-ce-playground   File: WrapWithCustomTemplateAction.java   View source code 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final Document document = myEditor.getDocument();
  final VirtualFile file = FileDocumentManager.getInstance().getFile(document);
  if (file != null) {
    ReadonlyStatusHandler.getInstance(myFile.getProject()).ensureFilesWritable(file);
  }

  String selection = myEditor.getSelectionModel().getSelectedText(true);

  if (selection != null) {
    selection = selection.trim();
    PsiDocumentManager.getInstance(myFile.getProject()).commitAllDocuments();
    myTemplate.wrap(selection, new CustomTemplateCallback(myEditor, myFile));
  }
}
 
Example 34
Project: intellij-ce-playground   File: WorkingWithOpenProjectTest.java   View source code 6 votes vote down vote up
public void _testSavingAllDocumentBeforeReimport() throws Exception {
  // cannot make it work die to order of document listeners

  myProjectsManager.listenForExternalChanges();
  final Document d = FileDocumentManager.getInstance().getDocument(myProjectPom);
  WriteCommandAction.runWriteCommandAction(null, new Runnable() {
    public void run() {
      d.setText(createPomXml("<groupId>test</groupId>" +
                             "<artifactId>project</artifactId>" +
                             "<version>1</version>" +

                             "<dependencies>" +
                             "  <dependency>" +
                             "    <groupId>junit</groupId>" +
                             "    <artifactId>junit</artifactId>" +
                             "    <version>4.0</version>" +
                             "  </dependency>" +
                             "</dependencies>"));
    }
  });

  resolveDependenciesAndImport();

  assertModuleLibDep("project", "Maven: junit:junit:4.0");
}
 
Example 35
Project: intellij-ce-playground   File: UpgradeAppenginePluginVersionHyperlink.java   View source code 6 votes vote down vote up
@Override
protected void execute(@NotNull Project project) {
  FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
  final Document document = fileDocumentManager.getDocument(myConfigToCorrect);
  if (document == null) {
    return;
  }
  boolean updated = GradleUtil.updateGradleDependencyVersion(project, document, APPENGINE_PLUGIN_NAME, new Computable<String>() {
    @Override
    public String compute() {
      ExternalRepository repository = ServiceManager.getService(ExternalRepository.class);
      FullRevision latest = repository.getLatest(APPENGINE_PLUGIN_GROUP_ID, APPENGINE_PLUGIN_ARTIFACT_ID);
      return latest == null ? DEFAULT_APPENGINE_PLUGIN_VERSION : latest.toString();
    }
  });
  if (updated) {
    GradleProjectImporter.getInstance().requestProjectSync(project, null);
  }
}
 
Example 36
Project: intellij-ce-playground   File: CommitHelper.java   View source code 6 votes vote down vote up
/**
 * Marks {@link Document documents} related to the given changes as "being committed".
 * @return documents which were marked that way.
 * @see #unmarkCommittingDocuments(java.util.Collection)
 * @see VetoSavingCommittingDocumentsAdapter
 */
@NotNull
public static Collection<Document> markCommittingDocuments(@NotNull Project project, @NotNull List<Change> changes) {
  Collection<Document> committingDocs = new ArrayList<Document>();
  for (Change change : changes) {
    VirtualFile virtualFile = ChangesUtil.getFilePath(change).getVirtualFile();
    if (virtualFile != null && !virtualFile.getFileType().isBinary()) {
      Document doc = FileDocumentManager.getInstance().getDocument(virtualFile);
      if (doc != null) {
        doc.putUserData(DOCUMENT_BEING_COMMITTED_KEY, project);
        committingDocs.add(doc);
      }
    }
  }
  return committingDocs;
}
 
Example 37
Project: intellij-ce-playground   File: MoveMembersTest.java   View source code 6 votes vote down vote up
private void performAction(String sourceClassName, String targetClassName, int[] memberIndices, final String visibility) throws Exception {
  PsiClass sourceClass = myJavaFacade.findClass(sourceClassName, ProjectScope.getProjectScope(myProject));
  assertNotNull("Class " + sourceClassName + " not found", sourceClass);
  PsiClass targetClass = myJavaFacade.findClass(targetClassName, ProjectScope.getProjectScope(myProject));
  assertNotNull("Class " + targetClassName + " not found", targetClass);

  PsiElement[] children = sourceClass.getChildren();
  ArrayList<PsiMember> members = new ArrayList<>();
  for (PsiElement child : children) {
    if (child instanceof PsiMember) {
      members.add(((PsiMember) child));
    }
  }

  LinkedHashSet<PsiMember> memberSet = new LinkedHashSet<>();
  for (int index : memberIndices) {
    PsiMember member = members.get(index);
    assertTrue(member.hasModifierProperty(PsiModifier.STATIC));
    memberSet.add(member);
  }

  MockMoveMembersOptions options = new MockMoveMembersOptions(targetClass.getQualifiedName(), memberSet);
  options.setMemberVisibility(visibility);
  new MoveMembersProcessor(myProject, null, options).run();
  FileDocumentManager.getInstance().saveAllDocuments();
}
 
Example 38
Project: deps-checker   File: VirtualFileHelper.java   View source code 5 votes vote down vote up
public static void save(VirtualFile file, String content)
{
    FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
    Document document = fileDocumentManager.getDocument(file);
    if (document != null)
    {
        document.setText(content);
        fileDocumentManager.saveDocument(document);
    }
}
 
Example 39
Project: intellij-bpmn-editor   File: BPMNFileEditor.java   View source code 5 votes vote down vote up
public BPMNFileEditor(@NotNull final Project project, @NotNull final VirtualFile file) {
    final VirtualFile vf = file instanceof LightVirtualFile ? ((LightVirtualFile) file).getOriginalFile() : file;
    final Module module = ModuleUtilCore.findModuleForFile(vf, project);
    if (module == null) {
        throw new IllegalArgumentException("No module for file " + file + " in project " + project);
    }
    this.myFile = file;
    this.myDocument = FileDocumentManager.getInstance().getDocument(file);
    this.myProject = project;
    this.editor = new BPMNEditorDiagramTab(this, project, module, file);
}
 
Example 40
Project: intellij-bpmn-editor   File: BPMNFileEditor.java   View source code 5 votes vote down vote up
public void saveToFile() {
    ApplicationManager.getApplication().invokeLater(() -> {
        if (myFile.isValid()) {
            ApplicationManager.getApplication().runWriteAction(() -> FileDocumentManager.getInstance().saveDocument(myDocument));
        }
    });
}