Java 类com.intellij.psi.impl.source.PostprocessReformattingAspect 实例源码

项目:intellij-ce-playground    文件:JavaCompletionUtil.java   
public static boolean promptTypeArgs(InsertionContext context, int offset) {
  if (offset < 0) {
    return false;
  }

  OffsetKey key = context.trackOffset(offset, false);
  PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting();
  offset = context.getOffset(key);
  if (offset < 0) {
    return false;
  }

  String open = escapeXmlIfNeeded(context, "<");
  context.getDocument().insertString(offset, open);
  context.getEditor().getCaretModel().moveToOffset(offset + open.length());
  context.getDocument().insertString(offset + open.length(), escapeXmlIfNeeded(context, ">"));
  context.setAddCompletionChar(false);
  return true;
}
项目:intellij-ce-playground    文件:PsiTypeLookupItem.java   
public static void addImportForItem(InsertionContext context, PsiClass aClass) {
  if (aClass.getQualifiedName() == null) return;
  PsiFile file = context.getFile();

  int startOffset = context.getStartOffset();
  int tail = context.getTailOffset();
  int newTail = JavaCompletionUtil.insertClassReference(aClass, file, startOffset, tail);
  if (newTail > context.getDocument().getTextLength() || newTail < 0) {
    LOG.error(LogMessageEx.createEvent("Invalid offset after insertion ",
                                       "offset=" + newTail + "\n" +
                                       "start=" + startOffset + "\n" +
                                       "tail=" + tail + "\n" +
                                       "file.length=" + file.getTextLength() + "\n" +
                                       "document=" + context.getDocument() + "\n" +
                                       DebugUtil.currentStackTrace(),
                                       AttachmentFactory.createAttachment(context.getDocument())));
    return;

  }
  context.setTailOffset(newTail);
  JavaCompletionUtil.shortenReference(file, context.getStartOffset());
  PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting();
}
项目:intellij-ce-playground    文件:ExtractMethodHandler.java   
public static void run(@NotNull final Project project, final Editor editor, final ExtractMethodProcessor processor) {
  CommandProcessor.getInstance().executeCommand(project, new Runnable() {
    public void run() {
      PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Runnable() {
        public void run() {
          try {
            final RefactoringEventData beforeData = new RefactoringEventData();
            beforeData.addElements(processor.myElements);
            project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted("refactoring.extract.method", beforeData);

            processor.doRefactoring();

            final RefactoringEventData data = new RefactoringEventData();
            data.addElement(processor.getExtractedMethod());
            project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone("refactoring.extract.method", data);
          }
          catch (IncorrectOperationException e) {
            LOG.error(e);
          }
        }
      });
    }
  }, REFACTORING_NAME, null);
}
项目:intellij-ce-playground    文件:ShortenClassReferencesTest.java   
private void doTest() {
  myFixture.configureByFile(getTestName(false) + ".java");
  CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
    @Override
    public void run() {
      WriteCommandAction.runWriteCommandAction(null, new Runnable() {
        @Override
        public void run() {
          JavaCodeStyleManager.getInstance(getProject()).shortenClassReferences(myFixture.getFile());
          PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting();
          PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
        }
      });
    }
  }, "", "");
  myFixture.checkResultByFile(getTestName(false) + "_after.java");
}
项目:intellij-ce-playground    文件:InlineToAnonymousClassMultifileTest.java   
private void doTest(String className) throws Exception {
  String rootBefore = getRoot() + "/before";
  PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17());
  final VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete);
  PsiClass classToInline = myJavaFacade.findClass(className, ProjectScope.getAllScope(myProject));
  assertEquals(null, InlineToAnonymousClassHandler.getCannotInlineMessage(classToInline));
  InlineToAnonymousClassProcessor processor = new InlineToAnonymousClassProcessor(myProject, 
                                                                                  classToInline,
                                                                                  null, false, false, false);
  UsageInfo[] usages = processor.findUsages();
  MultiMap<PsiElement,String> conflicts = processor.getConflicts(usages);
  assertEquals(0, conflicts.size());
  processor.run();

  String rootAfter = getRoot() + "/after";
  VirtualFile rootDir2 = LocalFileSystem.getInstance().findFileByPath(rootAfter.replace(File.separatorChar, '/'));
  myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
  PlatformTestUtil.assertDirectoriesEqual(rootDir2, rootDir);
}
项目:intellij-ce-playground    文件:InlineMethodMultifileTest.java   
private void doTest(String className, String methodName) throws Exception {
  String rootBefore = getRoot() + "/before";
  PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17());
  final VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete);
  PsiClass aClass = myJavaFacade.findClass(className, ProjectScope.getAllScope(myProject));
  assertTrue(aClass != null);
  PsiElement element = aClass.findMethodsByName(methodName, false)[0];
  assertTrue(element instanceof PsiMethod);
  PsiMethod method = (PsiMethod)element;
  final boolean condition = InlineMethodProcessor.checkBadReturns(method) && !InlineUtil.allUsagesAreTailCalls(method);
  assertFalse("Bad returns found", condition);

  InlineOptions options = new MockInlineMethodOptions();
  final InlineMethodProcessor processor = new InlineMethodProcessor(getProject(), method, null, myEditor, options.isInlineThisOnly());
  processor.run();

  String rootAfter = getRoot() + "/after";
  VirtualFile rootDir2 = LocalFileSystem.getInstance().findFileByPath(rootAfter.replace(File.separatorChar, '/'));
  myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
  PlatformTestUtil.assertDirectoriesEqual(rootDir2, rootDir);
}
项目:intellij-ce-playground    文件:CopyClassTest.java   
private void doMultifileTest() throws Exception {
  String root = JavaTestUtil.getJavaTestDataPath() + "/refactoring/copyClass/multifile/" + getTestName(true);
  String rootBefore = root + "/before";
  PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17());
  VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete);

  final HashMap<PsiFile, PsiClass[]> map = new HashMap<>();
  final VirtualFile sourceDir = rootDir.findChild("p1");
  for (VirtualFile file : sourceDir.getChildren()) {
    final PsiFile psiFile = myPsiManager.findFile(file);
    if (psiFile instanceof PsiJavaFile) {
      map.put(psiFile, ((PsiJavaFile)psiFile).getClasses());
    }
  }

  final VirtualFile targetVDir = rootDir.findChild("p2");
  CopyClassesHandler.doCopyClasses(map, null, myPsiManager.findDirectory(targetVDir), myProject);

  String rootAfter = root + "/after";
  VirtualFile rootDir2 = LocalFileSystem.getInstance().findFileByPath(rootAfter.replace(File.separatorChar, '/'));
  myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
  PlatformTestUtil.assertDirectoriesEqual(rootDir2, rootDir);
}
项目:intellij-ce-playground    文件:CopyClassTest.java   
private void doPackageCopy() throws Exception {
  String root = JavaTestUtil.getJavaTestDataPath() + "/refactoring/copyClass/multifile/" + getTestName(true);
  String rootBefore = root + "/before";
  PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17());
  VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete);

  final VirtualFile targetVDir = rootDir.findChild("p2");
  final PsiDirectory sourceP1Dir = myPsiManager.findDirectory(rootDir.findChild("p1"));
  final PsiDirectory targetP2Dir = myPsiManager.findDirectory(targetVDir);
  new CopyClassesHandler().doCopy(new PsiElement[]{sourceP1Dir}, targetP2Dir);

  String rootAfter = root + "/after";
  VirtualFile rootDir2 = LocalFileSystem.getInstance().findFileByPath(rootAfter.replace(File.separatorChar, '/'));
  myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
  PlatformTestUtil.assertDirectoriesEqual(rootDir2, rootDir);
}
项目:intellij-ce-playground    文件:LightPlatformCodeInsightTestCase.java   
@NotNull
private static Document setupFileEditorAndDocument(@NotNull String fileName, @NotNull String fileText) throws IOException {
  EncodingProjectManager.getInstance(getProject()).setEncoding(null, CharsetToolkit.UTF8_CHARSET);
  EncodingProjectManager.getInstance(ProjectManager.getInstance().getDefaultProject()).setEncoding(null, CharsetToolkit.UTF8_CHARSET);
  PostprocessReformattingAspect.getInstance(ourProject).doPostponedFormatting();
  deleteVFile();
  myVFile = getSourceRoot().createChildData(null, fileName);
  VfsUtil.saveText(myVFile, fileText);
  final FileDocumentManager manager = FileDocumentManager.getInstance();
  final Document document = manager.getDocument(myVFile);
  assertNotNull("Can't create document for '" + fileName + "'", document);
  manager.reloadFromDisk(document);
  document.insertString(0, " ");
  document.deleteString(0, 1);
  myFile = getPsiManager().findFile(myVFile);
  assertNotNull("Can't create PsiFile for '" + fileName + "'. Unknown file type most probably.", myFile);
  assertTrue(myFile.isPhysical());
  myEditor = createEditor(myVFile);
  myVFile.setCharset(CharsetToolkit.UTF8_CHARSET);

  PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
  return document;
}
项目:intellij-ce-playground    文件:LightPlatformCodeInsightTestCase.java   
/**
 * Validates that content of the editor as well as caret and selection matches one specified in data file that
 * should be formed with the same format as one used in configureByFile
 * @param message - this check specific message. Added to text, caret position, selection checking. May be null
 * @param filePath - relative path from %IDEA_INSTALLATION_HOME%/testData/
 * @param ignoreTrailingSpaces - whether trailing spaces in editor in data file should be stripped prior to comparing.
 */
protected void checkResultByFile(@Nullable String message, @TestDataFile @NotNull String filePath, final boolean ignoreTrailingSpaces) {
  bringRealEditorBack();

  getProject().getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
  if (ignoreTrailingSpaces) {
    final Editor editor = myEditor;
    TrailingSpacesStripper.stripIfNotCurrentLine(editor.getDocument(), false);
    EditorUtil.fillVirtualSpaceUntilCaret(editor);
  }

  PsiDocumentManager.getInstance(getProject()).commitAllDocuments();

  String fullPath = getTestDataPath() + filePath;

  File ioFile = new File(fullPath);

  assertTrue(getMessage("Cannot find file " + fullPath, message), ioFile.exists());
  String fileText = null;
  try {
    fileText = FileUtil.loadFile(ioFile, CharsetToolkit.UTF8_CHARSET);
  } catch (IOException e) {
    LOG.error(e);
  }
  checkResultByText(message, StringUtil.convertLineSeparators(fileText), ignoreTrailingSpaces, getTestDataPath() + "/" + filePath);
}
项目:intellij-ce-playground    文件:TailTypeDecorator.java   
@Override
public void handleInsert(InsertionContext context) {
  final LookupElement delegate = getDelegate();
  final TailType tailType = computeTailType(context);

  final LookupItem lookupItem = delegate.as(LookupItem.CLASS_CONDITION_KEY);
  if (lookupItem != null && tailType != null) {
    lookupItem.setTailType(TailType.UNKNOWN);
  }
  delegate.handleInsert(context);
  if (tailType != null && tailType.isApplicable(context)) {
    PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting();
    int tailOffset = context.getTailOffset();
    if (tailOffset < 0) {
      throw new AssertionError("tailOffset < 0: delegate=" + getDelegate() + "; this=" + this + "; tail=" + tailType);
    }
    tailType.processTail(context.getEditor(), tailOffset);
  }
}
项目:intellij-ce-playground    文件:QuickEditHandler.java   
private void commitToOriginal(final DocumentEvent e) {
  VirtualFile origVirtualFile = PsiUtilCore.getVirtualFile(myNewFile.getContext());
  myCommittingToOriginal = true;
  try {
    if (origVirtualFile == null || !ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(origVirtualFile).hasReadonlyFiles()) {
      PostprocessReformattingAspect.getInstance(myProject).disablePostprocessFormattingInside(new Runnable() {
        @Override
        public void run() {
          if (myAltFullRange != null) {
            altCommitToOriginal(e);
            return;
          }
          commitToOriginalInner();
        }
      });
      PsiDocumentManager.getInstance(myProject).doPostponedOperationsAndUnblockDocument(myOrigDocument);
    }
  }
  finally {
    myCommittingToOriginal = false;
  }
}
项目:intellij-ce-playground    文件:FlipCommaIntention.java   
@Override
public void invoke(@NotNull Project project, @NotNull final Editor editor, @NotNull PsiFile file) throws IncorrectOperationException {
  final PsiElement element = currentCommaElement(editor, file);
  if (element != null) {
    new WriteCommandAction(project, file) {
      protected void run(@NotNull Result result) throws Throwable {
        PostprocessReformattingAspect.getInstance(getProject()).disablePostprocessFormattingInside(new Runnable() {
          @Override
          public void run() {
            swapAtComma(editor, element);
          }
        });
      }
    }.execute();
  }
}
项目:intellij-ce-playground    文件:GroovyRangeTypeCheckTest.java   
public void doTest() {
  myFixture.configureByFile(getTestName(false) + ".groovy");

  final int offset = myFixture.getEditor().getCaretModel().getOffset();
  final PsiElement atCaret = myFixture.getFile().findElementAt(offset);
  final GrRangeExpression range = PsiTreeUtil.getParentOfType(atCaret, GrRangeExpression.class);
  final GroovyRangeTypeCheckInspection inspection = new GroovyRangeTypeCheckInspection();

  final GroovyFix fix = inspection.buildFix(range);

  LocalQuickFix[] fixes = {fix};
  final ProblemDescriptor descriptor = InspectionManager.getInstance(getProject()).createProblemDescriptor(range, "bla-bla", false, fixes, ProblemHighlightType.WEAK_WARNING);
  WriteCommandAction.runWriteCommandAction(null, new Runnable() {
    @Override
    public void run() {
      fix.applyFix(myFixture.getProject(), descriptor);
      PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting();
    }
  });


  myFixture.checkResultByFile(getTestName(false) + "_after.groovy");
}
项目:intellij-ce-playground    文件:ParameterToMapEntryTest.java   
private void doTestImpl(String filePath) {
    myFixture.configureByFile(filePath);
    int offset = myFixture.getEditor().getCaretModel().getOffset();
    final PsiFile file = myFixture.getFile();


    final ConvertParameterToMapEntryIntention intention = new ConvertParameterToMapEntryIntention();
    PsiElement element = file.findElementAt(offset);
    while (element != null && !(element instanceof GrReferenceExpression || element instanceof GrParameter)) {
      element = element.getParent();
    }
    Assert.assertNotNull(element);

    final PsiElementPredicate condition = intention.getElementPredicate();
    Assert.assertTrue(condition.satisfiedBy(element));

    // Launch it!
    intention.processIntention(element, myFixture.getProject(), myFixture.getEditor());
    PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting();
    final String result = file.getText();
    //System.out.println(result);
    myFixture.checkResultByFile(filePath.replace(".groovy", ".test"), true);
//    String expected = getExpectedResult(filePath);
//    Assert.assertEquals(expected, result);
  }
项目:intellij-ce-playground    文件:GroovyMoveScriptTest.java   
private void doTest(String[] fileNames, String newDirName) {
  String testName = getTestName(true);
  final VirtualFile actualRoot = myFixture.copyDirectoryToProject(testName + "/before", "");

  performAction(fileNames, newDirName, VfsUtilCore.getRelativePath(actualRoot, myFixture.getTempDirFixture().getFile(""), '/'));

  final VirtualFile expectedRoot = LocalFileSystem.getInstance().findFileByPath(getTestDataPath() + getTestName(true) + "/after");
  //File expectedRoot = new File(getTestDataPath() + testName + "/after");
  getProject().getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();

  VirtualFileManager.getInstance().syncRefresh();
  try {
    PlatformTestUtil.assertDirectoriesEqual(expectedRoot, actualRoot);
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
}
项目:intellij-ce-playground    文件:JavaFxPsiUtil.java   
public static void insertImportWhenNeeded(XmlFile xmlFile,
                                          String shortName,
                                          String qualifiedName) {
  if (shortName != null && findPsiClass(shortName, xmlFile.getRootTag()) == null) {
    final XmlDocument document = xmlFile.getDocument();
    if (document != null) {
      final XmlProcessingInstruction processingInstruction = createSingleImportInstruction(qualifiedName, xmlFile.getProject());
      final XmlProlog prolog = document.getProlog();
      if (prolog != null) {
        prolog.add(processingInstruction);
      } else {
        document.addBefore(processingInstruction, document.getRootTag());
      }
      PostprocessReformattingAspect.getInstance(xmlFile.getProject()).doPostponedFormatting(xmlFile.getViewProvider());
    }
  }
}
项目:tools-idea    文件:MultiFileTestCase.java   
protected void doTest(final PerformAction performAction, final String testName) throws Exception {
  String path = getTestDataPath() + getTestRoot() + testName;

  String pathBefore = path + "/before";
  final VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, pathBefore, myFilesToDelete, false);
  prepareProject(rootDir);
  PsiDocumentManager.getInstance(myProject).commitAllDocuments();

  String pathAfter = path + "/after";
  final VirtualFile rootAfter = LocalFileSystem.getInstance().findFileByPath(pathAfter.replace(File.separatorChar, '/'));

  performAction.performAction(rootDir, rootAfter);
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    public void run() {
      myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
    }
  });

  FileDocumentManager.getInstance().saveAllDocuments();

  if (myDoCompare) {
    PlatformTestUtil.assertDirectoriesEqual(rootAfter, rootDir);
  }
}
项目:tools-idea    文件:JavaCompletionUtil.java   
public static boolean promptTypeArgs(InsertionContext context, int offset) {
  if (offset < 0) {
    return false;
  }

  OffsetKey key = context.trackOffset(offset, false);
  PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting();
  offset = context.getOffset(key);
  if (offset < 0) {
    return false;
  }

  String open = escapeXmlIfNeeded(context, "<");
  context.getDocument().insertString(offset, open);
  context.getEditor().getCaretModel().moveToOffset(offset + open.length());
  context.getDocument().insertString(offset + open.length(), escapeXmlIfNeeded(context, ">"));
  context.setAddCompletionChar(false);
  return true;
}
项目:tools-idea    文件:PsiTypeLookupItem.java   
public static void addImportForItem(InsertionContext context, PsiClass aClass) {
  if (aClass.getQualifiedName() == null) return;
  PsiFile file = context.getFile();

  int startOffset = context.getStartOffset();
  int tail = context.getTailOffset();
  int newTail = JavaCompletionUtil.insertClassReference(aClass, file, startOffset, tail);
  if (newTail > context.getDocument().getTextLength() || newTail < 0) {
    LOG.error(LogMessageEx.createEvent("Invalid offset after insertion ",
                                       "offset=" + newTail + "\n" +
                                       "start=" + startOffset + "\n" +
                                       "tail=" + tail + "\n" +
                                       "file.length=" + file.getTextLength() + "\n" +
                                       "document=" + context.getDocument() + "\n" +
                                       DebugUtil.currentStackTrace(),
                                       AttachmentFactory.createAttachment(context.getDocument())));
    return;

  }
  context.setTailOffset(newTail);
  JavaCompletionUtil.shortenReference(file, context.getStartOffset());
  PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting();
}
项目:tools-idea    文件:ExtractMethodHandler.java   
public static void run(@NotNull final Project project, final Editor editor, final ExtractMethodProcessor processor) {
  CommandProcessor.getInstance().executeCommand(project, new Runnable() {
    public void run() {
      PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Runnable() {
        public void run() {
          try {
            processor.doRefactoring();
          }
          catch (IncorrectOperationException e) {
            LOG.error(e);
          }
        }
      });
    }
  }, REFACTORING_NAME, null);
}
项目:tools-idea    文件:ShortenClassReferencesTest.java   
private void doTest() {
  myFixture.configureByFile(getTestName(false) + ".java");
  CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
    @Override
    public void run() {
      ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
          JavaCodeStyleManager.getInstance(getProject()).shortenClassReferences(myFixture.getFile());
          PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting();
          PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
        }
      });
    }
  }, "", "");
  myFixture.checkResultByFile(getTestName(false) + "_after.java");
}
项目:tools-idea    文件:InlineToAnonymousClassMultifileTest.java   
private void doTest(String className) throws Exception {
  String rootBefore = getRoot() + "/before";
  PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17());
  final VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete);
  PsiClass classToInline = myJavaFacade.findClass(className, ProjectScope.getAllScope(myProject));
  assertEquals(null, InlineToAnonymousClassHandler.getCannotInlineMessage(classToInline));
  InlineToAnonymousClassProcessor processor = new InlineToAnonymousClassProcessor(myProject, 
                                                                                  classToInline,
                                                                                  null, false, false, false);
  UsageInfo[] usages = processor.findUsages();
  MultiMap<PsiElement,String> conflicts = processor.getConflicts(usages);
  assertEquals(0, conflicts.size());
  processor.run();

  String rootAfter = getRoot() + "/after";
  VirtualFile rootDir2 = LocalFileSystem.getInstance().findFileByPath(rootAfter.replace(File.separatorChar, '/'));
  myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
  PlatformTestUtil.assertDirectoriesEqual(rootDir2, rootDir);
}
项目:tools-idea    文件:InlineMethodMultifileTest.java   
private void doTest(String className, String methodName) throws Exception {
  String rootBefore = getRoot() + "/before";
  PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17());
  final VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete);
  PsiClass aClass = myJavaFacade.findClass(className, ProjectScope.getAllScope(myProject));
  assertTrue(aClass != null);
  PsiElement element = aClass.findMethodsByName(methodName, false)[0];
  assertTrue(element instanceof PsiMethod);
  PsiMethod method = (PsiMethod)element;
  final boolean condition = InlineMethodProcessor.checkBadReturns(method) && !InlineUtil.allUsagesAreTailCalls(method);
  assertFalse("Bad returns found", condition);

  InlineOptions options = new MockInlineMethodOptions();
  final InlineMethodProcessor processor = new InlineMethodProcessor(getProject(), method, null, myEditor, options.isInlineThisOnly());
  processor.run();

  String rootAfter = getRoot() + "/after";
  VirtualFile rootDir2 = LocalFileSystem.getInstance().findFileByPath(rootAfter.replace(File.separatorChar, '/'));
  myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
  PlatformTestUtil.assertDirectoriesEqual(rootDir2, rootDir);
}
项目:tools-idea    文件:CopyClassTest.java   
private void doMultifileTest() throws Exception {
  String root = JavaTestUtil.getJavaTestDataPath() + "/refactoring/copyClass/multifile/" + getTestName(true);
  String rootBefore = root + "/before";
  PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17());
  VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete);

  final HashMap<PsiFile, PsiClass[]> map = new HashMap<PsiFile, PsiClass[]>();
  final VirtualFile sourceDir = rootDir.findChild("p1");
  for (VirtualFile file : sourceDir.getChildren()) {
    final PsiFile psiFile = myPsiManager.findFile(file);
    if (psiFile instanceof PsiJavaFile) {
      map.put(psiFile, ((PsiJavaFile)psiFile).getClasses());
    }
  }

  final VirtualFile targetVDir = rootDir.findChild("p2");
  CopyClassesHandler.doCopyClasses(map, null, myPsiManager.findDirectory(targetVDir), myProject);

  String rootAfter = root + "/after";
  VirtualFile rootDir2 = LocalFileSystem.getInstance().findFileByPath(rootAfter.replace(File.separatorChar, '/'));
  myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
  PlatformTestUtil.assertDirectoriesEqual(rootDir2, rootDir);
}
项目:tools-idea    文件:CopyClassTest.java   
private void doPackageCopy() throws Exception {
  String root = JavaTestUtil.getJavaTestDataPath() + "/refactoring/copyClass/multifile/" + getTestName(true);
  String rootBefore = root + "/before";
  PsiTestUtil.removeAllRoots(myModule, IdeaTestUtil.getMockJdk17());
  VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootBefore, myFilesToDelete);

  final VirtualFile targetVDir = rootDir.findChild("p2");
  final PsiDirectory sourceP1Dir = myPsiManager.findDirectory(rootDir.findChild("p1"));
  final PsiDirectory targetP2Dir = myPsiManager.findDirectory(targetVDir);
  new CopyClassesHandler().doCopy(new PsiElement[]{sourceP1Dir}, targetP2Dir);

  String rootAfter = root + "/after";
  VirtualFile rootDir2 = LocalFileSystem.getInstance().findFileByPath(rootAfter.replace(File.separatorChar, '/'));
  myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
  PlatformTestUtil.assertDirectoriesEqual(rootDir2, rootDir);
}
项目:tools-idea    文件:LightPlatformCodeInsightTestCase.java   
@NotNull
private static Document setupFileEditorAndDocument(@NotNull String fileName, @NotNull String fileText) throws IOException {
  EncodingProjectManager.getInstance(getProject()).setEncoding(null, CharsetToolkit.UTF8_CHARSET);
  EncodingProjectManager.getInstance(ProjectManager.getInstance().getDefaultProject()).setEncoding(null, CharsetToolkit.UTF8_CHARSET);
  PostprocessReformattingAspect.getInstance(ourProject).doPostponedFormatting();
  deleteVFile();
  myVFile = getSourceRoot().createChildData(null, fileName);
  VfsUtil.saveText(myVFile, fileText);
  final FileDocumentManager manager = FileDocumentManager.getInstance();
  final Document document = manager.getDocument(myVFile);
  assertNotNull("Can't create document for '" + fileName + "'", document);
  manager.reloadFromDisk(document);
  document.insertString(0, " ");
  document.deleteString(0, 1);
  myFile = getPsiManager().findFile(myVFile);
  assertNotNull("Can't create PsiFile for '" + fileName + "'. Unknown file type most probably.", myFile);
  assertTrue(myFile.isPhysical());
  myEditor = createEditor(myVFile);
  myVFile.setCharset(CharsetToolkit.UTF8_CHARSET);

  PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
  return document;
}
项目:tools-idea    文件:LightPlatformCodeInsightTestCase.java   
/**
 * Validates that content of the editor as well as caret and selection matches one specified in data file that
 * should be formed with the same format as one used in configureByFile
 * @param message - this check specific message. Added to text, caret position, selection checking. May be null
 * @param filePath - relative path from %IDEA_INSTALLATION_HOME%/testData/
 * @param ignoreTrailingSpaces - whether trailing spaces in editor in data file should be stripped prior to comparing.
 * @throws Exception
 */
protected void checkResultByFile(@Nullable String message, @NotNull String filePath, final boolean ignoreTrailingSpaces) {
  bringRealEditorBack();

  getProject().getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
  if (ignoreTrailingSpaces) {
    final Editor editor = myEditor;
    TrailingSpacesStripper.stripIfNotCurrentLine(editor.getDocument(), false);
    EditorUtil.fillVirtualSpaceUntilCaret(editor);
  }

  PsiDocumentManager.getInstance(getProject()).commitAllDocuments();

  String fullPath = getTestDataPath() + filePath;

  File ioFile = new File(fullPath);

  assertTrue(getMessage("Cannot find file " + fullPath, message), ioFile.exists());
  String fileText = null;
  try {
    fileText = FileUtil.loadFile(ioFile, CharsetToolkit.UTF8);
  } catch (IOException e) {
    LOG.error(e);
  }
  checkResultByText(message, StringUtil.convertLineSeparators(fileText), ignoreTrailingSpaces, getTestDataPath() + "/" + filePath);
}
项目:tools-idea    文件:TailTypeDecorator.java   
@Override
public void handleInsert(InsertionContext context) {
  final LookupElement delegate = getDelegate();
  final TailType tailType = computeTailType(context);

  final LookupItem lookupItem = delegate.as(LookupItem.CLASS_CONDITION_KEY);
  if (lookupItem != null && tailType != null) {
    lookupItem.setTailType(TailType.UNKNOWN);
  }
  delegate.handleInsert(context);
  if (tailType != null && tailType.isApplicable(context)) {
    PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting();
    int tailOffset = context.getTailOffset();
    if (tailOffset < 0) {
      throw new AssertionError("tailOffset < 0: delegate=" + getDelegate() + "; this=" + this + "; tail=" + tailType);
    }
    tailType.processTail(context.getEditor(), tailOffset);
  }
}
项目:tools-idea    文件:QuickEditHandler.java   
private void commitToOriginal() {
  if (!isValid()) return;
  final PsiFile origFile = (PsiFile)myNewFile.getUserData(FileContextUtil.INJECTED_IN_ELEMENT).getElement();
  VirtualFile origFileVirtualFile = origFile != null? origFile.getVirtualFile() : null;
  myCommittingToOriginal = true;
  try {
    if (origFileVirtualFile == null || !ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(origFileVirtualFile).hasReadonlyFiles()) {
      PostprocessReformattingAspect.getInstance(myProject).disablePostprocessFormattingInside(new Runnable() {
        @Override
        public void run() {
          if (myAltFullRange != null) {
            altCommitToOriginal();
            return;
          }
          commitToOriginalInner();
        }
      });
    }
  }
  finally {
    myCommittingToOriginal = false;
  }
}
项目:tools-idea    文件:GroovyRangeTypeCheckTest.java   
public void doTest() {
  myFixture.configureByFile(getTestName(false) + ".groovy");

  final int offset = myFixture.getEditor().getCaretModel().getOffset();
  final PsiElement atCaret = myFixture.getFile().findElementAt(offset);
  final GrRangeExpression range = PsiTreeUtil.getParentOfType(atCaret, GrRangeExpression.class);
  final GroovyRangeTypeCheckInspection inspection = new GroovyRangeTypeCheckInspection();

  final GroovyFix fix = inspection.buildFix(range);

  LocalQuickFix[] fixes = {fix};
  final ProblemDescriptor descriptor = InspectionManager.getInstance(getProject()).createProblemDescriptor(range, "bla-bla", false, fixes, ProblemHighlightType.WEAK_WARNING);
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      fix.applyFix(myFixture.getProject(), descriptor);
      PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting();
    }
  });


  myFixture.checkResultByFile(getTestName(false) + "_after.groovy");
}
项目:tools-idea    文件:ParameterToMapEntryTest.java   
private void doTestImpl(String filePath) {
    myFixture.configureByFile(filePath);
    int offset = myFixture.getEditor().getCaretModel().getOffset();
    final PsiFile file = myFixture.getFile();


    final ConvertParameterToMapEntryIntention intention = new ConvertParameterToMapEntryIntention();
    PsiElement element = file.findElementAt(offset);
    while (element != null && !(element instanceof GrReferenceExpression || element instanceof GrParameter)) {
      element = element.getParent();
    }
    Assert.assertNotNull(element);

    final PsiElementPredicate condition = intention.getElementPredicate();
    Assert.assertTrue(condition.satisfiedBy(element));

    // Launch it!
    intention.processIntention(element, myFixture.getProject(), myFixture.getEditor());
    PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting();
    final String result = file.getText();
    //System.out.println(result);
    myFixture.checkResultByFile(filePath.replace(".groovy", ".test"), true);
//    String expected = getExpectedResult(filePath);
//    Assert.assertEquals(expected, result);
  }
项目:tools-idea    文件:GroovyMoveScriptTest.java   
private void doTest(String[] fileNames, String newDirName) {
  String testName = getTestName(true);
  final VirtualFile actualRoot = myFixture.copyDirectoryToProject(testName + "/before", "");

  performAction(fileNames, newDirName, VfsUtilCore.getRelativePath(actualRoot, myFixture.getTempDirFixture().getFile(""), '/'));

  final VirtualFile expectedRoot = LocalFileSystem.getInstance().findFileByPath(getTestDataPath() + getTestName(true) + "/after");
  //File expectedRoot = new File(getTestDataPath() + testName + "/after");
  getProject().getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();

  VirtualFileManager.getInstance().syncRefresh();
  try {
    PlatformTestUtil.assertDirectoriesEqual(expectedRoot, actualRoot);
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
}
项目:tools-idea    文件:JavaFxPsiUtil.java   
public static void insertImportWhenNeeded(XmlFile xmlFile,
                                          String shortName,
                                          String qualifiedName) {
  if (shortName != null && findPsiClass(shortName, xmlFile.getRootTag()) == null) {
    final XmlDocument document = xmlFile.getDocument();
    if (document != null) {
      final XmlProcessingInstruction processingInstruction = createSingleImportInstruction(qualifiedName, xmlFile.getProject());
      final XmlProlog prolog = document.getProlog();
      if (prolog != null) {
        prolog.add(processingInstruction);
      } else {
        document.addBefore(processingInstruction, document.getRootTag());
      }
      PostprocessReformattingAspect.getInstance(xmlFile.getProject()).doPostponedFormatting(xmlFile.getViewProvider());
    }
  }
}
项目:consulo-javafx    文件:JavaFxPsiUtil.java   
public static void insertImportWhenNeeded(XmlFile xmlFile,
                                          String shortName,
                                          String qualifiedName) {
  if (shortName != null && findPsiClass(shortName, xmlFile.getRootTag()) == null) {
    final XmlDocument document = xmlFile.getDocument();
    if (document != null) {
      final XmlProcessingInstruction processingInstruction = createSingleImportInstruction(qualifiedName, xmlFile.getProject());
      final XmlProlog prolog = document.getProlog();
      if (prolog != null) {
        prolog.add(processingInstruction);
      } else {
        document.addBefore(processingInstruction, document.getRootTag());
      }
      PostprocessReformattingAspect.getInstance(xmlFile.getProject()).doPostponedFormatting(xmlFile.getViewProvider());
    }
  }
}
项目:consulo    文件:LightPlatformCodeInsightTestCase.java   
@Nonnull
private static Document setupFileEditorAndDocument(@Nonnull String fileName, @Nonnull String fileText) throws IOException {
  EncodingProjectManager.getInstance(getProject()).setEncoding(null, CharsetToolkit.UTF8_CHARSET);
  EncodingProjectManager.getInstance(ProjectManager.getInstance().getDefaultProject()).setEncoding(null, CharsetToolkit.UTF8_CHARSET);
  PostprocessReformattingAspect.getInstance(ourProject).doPostponedFormatting();
  deleteVFile();
  myVFile = getSourceRoot().createChildData(null, fileName);
  VfsUtil.saveText(myVFile, fileText);
  final FileDocumentManager manager = FileDocumentManager.getInstance();
  final Document document = manager.getDocument(myVFile);
  assertNotNull("Can't create document for '" + fileName + "'", document);
  manager.reloadFromDisk(document);
  document.insertString(0, " ");
  document.deleteString(0, 1);
  myFile = getPsiManager().findFile(myVFile);
  assertNotNull("Can't create PsiFile for '" + fileName + "'. Unknown file type most probably.", myFile);
  assertTrue(myFile.isPhysical());
  myEditor = createEditor(myVFile);
  myVFile.setCharset(CharsetToolkit.UTF8_CHARSET);

  PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
  return document;
}
项目:consulo    文件:LightPlatformCodeInsightTestCase.java   
/**
 * Validates that content of the editor as well as caret and selection matches one specified in data file that
 * should be formed with the same format as one used in configureByFile
 * @param message - this check specific message. Added to text, caret position, selection checking. May be null
 * @param filePath - relative path from %IDEA_INSTALLATION_HOME%/testData/
 * @param ignoreTrailingSpaces - whether trailing spaces in editor in data file should be stripped prior to comparing.
 * @throws Exception
 */
protected void checkResultByFile(@Nullable String message, @Nonnull String filePath, final boolean ignoreTrailingSpaces) {
  bringRealEditorBack();

  getProject().getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
  if (ignoreTrailingSpaces) {
    final Editor editor = myEditor;
    TrailingSpacesStripper.strip(editor.getDocument(), false, true);
    EditorUtil.fillVirtualSpaceUntilCaret(editor);
  }

  PsiDocumentManager.getInstance(getProject()).commitAllDocuments();

  String fullPath = getTestDataPath() + filePath;

  File ioFile = new File(fullPath);

  assertTrue(getMessage("Cannot find file " + fullPath, message), ioFile.exists());
  String fileText = null;
  try {
    fileText = FileUtil.loadFile(ioFile, CharsetToolkit.UTF8);
  } catch (IOException e) {
    LOG.error(e);
  }
  checkResultByText(message, StringUtil.convertLineSeparators(fileText), ignoreTrailingSpaces, getTestDataPath() + "/" + filePath);
}
项目:consulo    文件:TailTypeDecorator.java   
@Override
public void handleInsert(InsertionContext context) {
  final LookupElement delegate = getDelegate();
  final TailType tailType = computeTailType(context);

  final LookupItem lookupItem = delegate.as(LookupItem.CLASS_CONDITION_KEY);
  if (lookupItem != null && tailType != null) {
    lookupItem.setTailType(TailType.UNKNOWN);
  }
  delegate.handleInsert(context);
  if (tailType != null && tailType.isApplicable(context)) {
    PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting();
    int tailOffset = context.getTailOffset();
    if (tailOffset < 0) {
      throw new AssertionError("tailOffset < 0: delegate=" + getDelegate() + "; this=" + this + "; tail=" + tailType);
    }
    tailType.processTail(context.getEditor(), tailOffset);
  }
}
项目:consulo    文件:QuickEditHandler.java   
private void commitToOriginal(final DocumentEvent e) {
  VirtualFile origVirtualFile = PsiUtilCore.getVirtualFile(myNewFile.getContext());
  myCommittingToOriginal = true;
  try {
    if (origVirtualFile == null || !ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(origVirtualFile).hasReadonlyFiles()) {
      PostprocessReformattingAspect.getInstance(myProject).disablePostprocessFormattingInside(new Runnable() {
        @Override
        public void run() {
          if (myAltFullRange != null) {
            altCommitToOriginal(e);
            return;
          }
          commitToOriginalInner();
        }
      });
      PsiDocumentManager.getInstance(myProject).doPostponedOperationsAndUnblockDocument(myOrigDocument);
    }
  }
  finally {
    myCommittingToOriginal = false;
  }
}
项目:consulo-java    文件:MultiFileTestCase.java   
protected void doTest(final PerformAction performAction, final String testName) throws Exception {
  String path = getTestDataPath() + getTestRoot() + testName;

  String pathBefore = path + "/before";
  final VirtualFile rootDir = PsiTestUtil.createTestProjectStructure(myProject, myModule, pathBefore, PlatformTestCase.myFilesToDelete, false);
  prepareProject(rootDir);
  PsiDocumentManager.getInstance(myProject).commitAllDocuments();

  String pathAfter = path + "/after";
  final VirtualFile rootAfter = LocalFileSystem.getInstance().findFileByPath(pathAfter.replace(File.separatorChar, '/'));

  performAction.performAction(rootDir, rootAfter);
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    public void run() {
      myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
    }
  });

  FileDocumentManager.getInstance().saveAllDocuments();

  if (myDoCompare) {
    PlatformTestUtil.assertDirectoriesEqual(rootAfter, rootDir);
  }
}