private static PsiDirectory[] suggestMostAppropriateDirectories(PsiPackage psiPackage) {
    final Project project = psiPackage.getProject();
    PsiDirectory[] directories = null;
    final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
    if (editor != null) {
      final Document document = editor.getDocument();
      final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
      if (psiFile != null) {
        final Module module = ModuleUtil.findModuleForPsiElement(psiFile);
        if (module != null) {
          directories =
              psiPackage.getDirectories(GlobalSearchScope.moduleWithDependenciesScope(module));
        } else {
          directories =
              psiPackage.getDirectories(
                  GlobalSearchScope.notScope(GlobalSearchScope.projectScope(project)));
        }
      }
    }

    if (directories == null || directories.length == 0) {
      directories = psiPackage.getDirectories();
    }
    return directories;
  }
  public static void doTearDown() throws Exception {
    UsefulTestCase.doPostponedFormatting(ourProject);

    LookupManager.getInstance(ourProject).hideActiveLookup();

    InspectionProfileManager.getInstance().deleteProfile(PROFILE);
    assertNotNull("Application components damaged", ProjectManager.getInstance());

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                try {
                  final VirtualFile[] children = ourSourceRoot.getChildren();
                  for (VirtualFile child : children) {
                    child.delete(this);
                  }
                } catch (IOException e) {
                  //noinspection CallToPrintStackTrace
                  e.printStackTrace();
                }
                FileDocumentManager manager = FileDocumentManager.getInstance();
                if (manager instanceof FileDocumentManagerImpl) {
                  ((FileDocumentManagerImpl) manager).dropAllUnsavedDocuments();
                }
              }
            });
    //    final Project[] openProjects = ProjectManagerEx.getInstanceEx().getOpenProjects();
    //    assertTrue(Arrays.asList(openProjects).contains(ourProject));
    assertFalse(PsiManager.getInstance(getProject()).isDisposed());
    if (!ourAssertionsInTestDetected) {
      if (IdeaLogger.ourErrorsOccurred != null) {
        throw IdeaLogger.ourErrorsOccurred;
      }
      // assertTrue("Logger errors occurred. ", IdeaLogger.ourErrorsOccurred == null);
    }
    ((PsiDocumentManagerImpl) PsiDocumentManager.getInstance(getProject()))
        .clearUncommitedDocuments();

    ((UndoManagerImpl) UndoManager.getGlobalInstance()).dropHistoryInTests();

    ProjectManagerEx.getInstanceEx().setCurrentTestProject(null);
    ourApplication.setDataProvider(null);
    ourTestCase = null;
    ((PsiManagerImpl) ourPsiManager).cleanupForNextTest();

    final Editor[] allEditors = EditorFactory.getInstance().getAllEditors();
    if (allEditors.length > 0) {
      for (Editor allEditor : allEditors) {
        EditorFactory.getInstance().releaseEditor(allEditor);
      }
      fail("Unreleased editors: " + allEditors.length);
    }
  }
  @NotNull
  private TextChunk[] initChunks() {
    PsiFile psiFile = getPsiFile();
    Document document =
        psiFile == null ? null : PsiDocumentManager.getInstance(getProject()).getDocument(psiFile);
    TextChunk[] chunks;
    if (document == null) {
      // element over light virtual file
      PsiElement element = getElement();
      chunks = new TextChunk[] {new TextChunk(new TextAttributes(), element.getText())};
    } else {
      chunks = ChunkExtractor.extractChunks(psiFile, this);
    }

    myTextChunks = new SoftReference<TextChunk[]>(chunks);
    return chunks;
  }
 private void commitChanges(XmlFile xmlFile) {
   Document doc = PsiDocumentManager.getInstance(myPsiManager.getProject()).getDocument(xmlFile);
   assert doc != null;
   FileDocumentManager.getInstance().saveDocument(doc);
 }
  @Override
  @NotNull
  public AnnotationPlace chooseAnnotationsPlace(@NotNull final PsiElement element) {
    if (!element.isPhysical()) return AnnotationPlace.IN_CODE; // element just created
    if (!element.getManager().isInProject(element)) return AnnotationPlace.EXTERNAL;
    final Project project = myPsiManager.getProject();
    final PsiFile containingFile = element.getContainingFile();
    final VirtualFile virtualFile = containingFile.getVirtualFile();
    LOG.assertTrue(virtualFile != null);
    final List<OrderEntry> entries =
        ProjectRootManager.getInstance(project).getFileIndex().getOrderEntriesForFile(virtualFile);
    if (!entries.isEmpty()) {
      for (OrderEntry entry : entries) {
        if (!(entry instanceof ModuleOrderEntry)) {
          if (AnnotationOrderRootType.getUrls(entry).length > 0) {
            return AnnotationPlace.EXTERNAL;
          }
          break;
        }
      }
    }
    final MyExternalPromptDialog dialog =
        ApplicationManager.getApplication().isUnitTestMode()
                || ApplicationManager.getApplication().isHeadlessEnvironment()
            ? null
            : new MyExternalPromptDialog(project);
    if (dialog != null && dialog.isToBeShown()) {
      final PsiElement highlightElement =
          element instanceof PsiNameIdentifierOwner
              ? ((PsiNameIdentifierOwner) element).getNameIdentifier()
              : element.getNavigationElement();
      LOG.assertTrue(highlightElement != null);
      final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
      final List<RangeHighlighter> highlighters = new ArrayList<RangeHighlighter>();
      final boolean highlight =
          editor != null
              && editor.getDocument()
                  == PsiDocumentManager.getInstance(project).getDocument(containingFile);
      try {
        if (highlight) { // do not highlight for batch inspections
          final EditorColorsManager colorsManager = EditorColorsManager.getInstance();
          final TextAttributes attributes =
              colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
          final TextRange textRange = highlightElement.getTextRange();
          HighlightManager.getInstance(project)
              .addRangeHighlight(
                  editor,
                  textRange.getStartOffset(),
                  textRange.getEndOffset(),
                  attributes,
                  true,
                  highlighters);
          final LogicalPosition logicalPosition =
              editor.offsetToLogicalPosition(textRange.getStartOffset());
          editor.getScrollingModel().scrollTo(logicalPosition, ScrollType.CENTER);
        }

        dialog.show();
        if (dialog.getExitCode() == 2) {
          return AnnotationPlace.EXTERNAL;
        } else if (dialog.getExitCode() == 1) {
          return AnnotationPlace.NOWHERE;
        }

      } finally {
        if (highlight) {
          HighlightManager.getInstance(project)
              .removeSegmentHighlighter(editor, highlighters.get(0));
        }
      }
    } else if (dialog != null) {
      dialog.close(DialogWrapper.OK_EXIT_CODE);
    }
    return AnnotationPlace.IN_CODE;
  }
 protected static Document getDocument(final PsiFile file) {
   return PsiDocumentManager.getInstance(getProject()).getDocument(file);
 }
 protected static void commitAllDocuments() {
   PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
 }
 protected static void commitDocument(final Document document) {
   PsiDocumentManager.getInstance(getProject()).commitDocument(document);
 }
  public static void doSetup(
      final LightProjectDescriptor descriptor,
      final LocalInspectionTool[] localInspectionTools,
      final Map<String, InspectionTool> availableInspectionTools)
      throws Exception {
    assertNull(
        "Previous test "
            + ourTestCase
            + " hasn't called tearDown(). Probably overriden without super call.",
        ourTestCase);
    IdeaLogger.ourErrorsOccurred = null;

    if (ourProject == null || !ourProjectDescriptor.equals(descriptor)) {
      initProject(descriptor);
    }

    ProjectManagerEx.getInstanceEx().setCurrentTestProject(ourProject);

    ((PsiDocumentManagerImpl) PsiDocumentManager.getInstance(getProject()))
        .clearUncommitedDocuments();

    for (LocalInspectionTool tool : localInspectionTools) {
      enableInspectionTool(availableInspectionTools, new LocalInspectionToolWrapper(tool));
    }

    final InspectionProfileImpl profile =
        new InspectionProfileImpl("Configurable") {
          @NotNull
          public InspectionProfileEntry[] getInspectionTools(PsiElement element) {
            if (availableInspectionTools != null) {
              final Collection<InspectionTool> tools = availableInspectionTools.values();
              return tools.toArray(new InspectionTool[tools.size()]);
            }
            return new InspectionTool[0];
          }

          @Override
          public List<ToolsImpl> getAllEnabledInspectionTools() {
            List<ToolsImpl> result = new ArrayList<ToolsImpl>();
            for (InspectionProfileEntry entry : getInspectionTools(null)) {
              result.add(new ToolsImpl(entry, entry.getDefaultLevel(), true));
            }
            return result;
          }

          public boolean isToolEnabled(HighlightDisplayKey key, PsiElement element) {
            return key != null && availableInspectionTools.containsKey(key.toString());
          }

          public HighlightDisplayLevel getErrorLevel(
              @NotNull HighlightDisplayKey key, PsiElement element) {
            InspectionTool localInspectionTool = availableInspectionTools.get(key.toString());
            return localInspectionTool != null
                ? localInspectionTool.getDefaultLevel()
                : HighlightDisplayLevel.WARNING;
          }

          public InspectionTool getInspectionTool(
              @NotNull String shortName, @NotNull PsiElement element) {
            if (availableInspectionTools.containsKey(shortName)) {
              return availableInspectionTools.get(shortName);
            }
            return null;
          }
        };
    final InspectionProfileManager inspectionProfileManager =
        InspectionProfileManager.getInstance();
    inspectionProfileManager.addProfile(profile);
    inspectionProfileManager.setRootProfile(profile.getName());
    InspectionProjectProfileManager.getInstance(getProject()).updateProfile(profile);
    InspectionProjectProfileManager.getInstance(getProject()).setProjectProfile(profile.getName());

    assertFalse(getPsiManager().isDisposed());

    CodeStyleSettingsManager.getInstance(getProject())
        .setTemporarySettings(new CodeStyleSettings());
  }
 public Document getDocument() {
   PsiFile file = getUsageInfo().getFile();
   if (file == null) return null;
   return PsiDocumentManager.getInstance(getProject()).getDocument(file);
 }