com.intellij.openapi.project.ex.ProjectManagerEx Java Examples

The following examples show how to use com.intellij.openapi.project.ex.ProjectManagerEx. 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: DesktopApplicationImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
private boolean disposeSelf(final boolean checkCanCloseProject) {
  final ProjectManagerImpl manager = (ProjectManagerImpl)ProjectManagerEx.getInstanceEx();
  if (manager != null) {
    final boolean[] canClose = {true};
    for (final Project project : manager.getOpenProjects()) {
      try {
        CommandProcessor.getInstance().executeCommand(project, () -> {
          if (!manager.closeProject(project, true, true, checkCanCloseProject)) {
            canClose[0] = false;
          }
        }, ApplicationBundle.message("command.exit"), null);
      }
      catch (Throwable e) {
        LOG.error(e);
      }
      if (!canClose[0]) {
        return false;
      }
    }
  }
  runWriteAction(() -> consulo.disposer.Disposer.dispose(DesktopApplicationImpl.this));

  consulo.disposer.Disposer.assertIsEmpty();
  return true;
}
 
Example #2
Source File: AsyncHelper.java    From r2m-plugin-android with Apache License 2.0 6 votes vote down vote up
private void performFileOperation() {
    project.save();
    FileDocumentManager.getInstance().saveAllDocuments();
    ProjectManagerEx.getInstanceEx().blockReloadingProjectOnExternalChanges();
    ProgressManager.getInstance().run(new Task.Backgroundable(project, MESSAGE_GENERATING_SERVICE, false) {
        public void run(@NotNull ProgressIndicator progressIndicator) {
            getGenerator().makeFilePerformance(progressIndicator);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    onActionSuccess(GenerateActions.FILE_OPERATION_SUCCESS);
                }
            });
        }
    });
}
 
Example #3
Source File: AddControllerForm.java    From r2m-plugin-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onGenerateFinished(boolean result, File file) {
    SaveAndSyncHandlerImpl.refreshOpenFiles();
    VirtualFileManager.getInstance().refreshWithoutFileWatcher(false);
    ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
    project.getBaseDir().refresh(false, true);

    if (null == JavaPsiFacade.getInstance(project).findPackage("com.magnet.android.mms.async")) {
        showMissingDependencies();
    }

    if (!result) {
        showCloseDialog(file);
    } else {
        getThis().setVisible(true);
    }
}
 
Example #4
Source File: FileTemplateUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static String mergeTemplate(String templateContent, final VelocityContext context, boolean useSystemLineSeparators) throws IOException {
  final StringWriter stringWriter = new StringWriter();
  try {
    VelocityWrapper.evaluate(null, context, stringWriter, templateContent);
  }
  catch (final VelocityException e) {
    LOG.error("Error evaluating template:\n" + templateContent, e);
    ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(IdeBundle.message("error.parsing.file.template", e.getMessage()), IdeBundle.message("title.velocity.error")));
  }
  final String result = stringWriter.toString();

  if (useSystemLineSeparators) {
    final String newSeparator = CodeStyleSettingsManager.getSettings(ProjectManagerEx.getInstanceEx().getDefaultProject()).getLineSeparator();
    if (!"\n".equals(newSeparator)) {
      return StringUtil.convertLineSeparators(result, newSeparator);
    }
  }

  return result;
}
 
Example #5
Source File: HeavyIdeaTestFixtureImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void setUpProject() throws Exception {
  new WriteCommandAction.Simple(null) {
    @Override
    protected void run() throws Throwable {
      File projectDir = FileUtil.createTempDirectory(myName + "_", "project");
      FileUtil.delete(projectDir);
      myFilesToDelete.add(projectDir);

      LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectDir);
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      new Throwable(projectDir.getPath()).printStackTrace(new PrintStream(buffer));
      myProject = PlatformTestCase.createProject(projectDir, buffer.toString());

      for (ModuleFixtureBuilder moduleFixtureBuilder : myModuleFixtureBuilders) {
        moduleFixtureBuilder.getFixture().setUp();
      }

      StartupManagerImpl sm = (StartupManagerImpl)StartupManager.getInstance(myProject);
      sm.runStartupActivities(UIAccess.get());
      sm.runPostStartupActivities(UIAccess.get());

      ProjectManagerEx.getInstanceEx().openTestProject(myProject);
      LightPlatformTestCase.clearUncommittedDocuments(myProject);
    }
  }.execute().throwException();
}
 
Example #6
Source File: RunContentManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private CloseListener(@Nonnull final Content content, @Nonnull Executor executor) {
  myContent = content;
  content.getManager().addContentManagerListener(this);
  ProjectManager projectManager = ProjectManager.getInstance();
  myExecutor = executor;

  projectManager.addProjectManagerListener(this);
  myCloseRegisterVetoRemover = ((ProjectManagerEx)projectManager).registerCloseProjectVeto(project -> {
    if (project != myProject) return true;

    if (myContent == null) return true;

    final boolean canClose = closeQuery(true);
    if (canClose) {
      myContent.getManager().removeContent(myContent, true);
      myContent = null;
    }
    return canClose;
  });
}
 
Example #7
Source File: VfsEventGenerationHelper.java    From consulo with Apache License 2.0 6 votes vote down vote up
void scheduleCreation(@Nonnull VirtualFile parent,
                      @Nonnull String childName,
                      @Nonnull FileAttributes attributes,
                      @Nullable String symlinkTarget,
                      @Nonnull ThrowableRunnable<RefreshWorker.RefreshCancelledException> checkCanceled) throws RefreshWorker.RefreshCancelledException {
  if (LOG.isTraceEnabled()) LOG.trace("create parent=" + parent + " name=" + childName + " attr=" + attributes);
  ChildInfo[] children = null;
  if (attributes.isDirectory() && parent.getFileSystem() instanceof LocalFileSystem && !attributes.isSymLink()) {
    try {
      Path child = Paths.get(parent.getPath(), childName);
      if (shouldScanDirectory(parent, child, childName)) {
        Path[] relevantExcluded = ContainerUtil.mapNotNull(ProjectManagerEx.getInstanceEx().getAllExcludedUrls(), url -> {
          Path path = Paths.get(VirtualFileManager.extractPath(url));
          return path.startsWith(child) ? path : null;
        }, new Path[0]);
        children = scanChildren(child, relevantExcluded, checkCanceled);
      }
    }
    catch (InvalidPathException ignored) {
      // Paths.get() throws sometimes
    }
  }
  VFileCreateEvent event = new VFileCreateEvent(null, parent, childName, attributes.isDirectory(), attributes, symlinkTarget, true, children);
  myEvents.add(event);
}
 
Example #8
Source File: MergeVersion.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void reportProjectFileChangeIfNeeded(Project project, VirtualFile file) {
  if (file != null && ! file.isDirectory()) {
    if (ProjectCoreUtil.isProjectOrWorkspaceFile(file) || isProjectFile(file)) {
      ProjectManagerEx.getInstanceEx().saveChangedProjectFile(file, project);
    }
  }
}
 
Example #9
Source File: NewOrImportModuleUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@RequiredUIAccess
public static <T extends ModuleImportContext> AsyncResult<Project> importProject(@Nonnull T context, @Nonnull ModuleImportProvider<T> importProvider) {
  final ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx();
  final String projectFilePath = context.getPath();
  String projectName = context.getName();

  try {
    File projectDir = new File(projectFilePath);
    FileUtil.ensureExists(projectDir);
    File projectConfigDir = new File(projectDir, Project.DIRECTORY_STORE_FOLDER);
    FileUtil.ensureExists(projectConfigDir);

    final Project newProject = projectManager.createProject(projectName, projectFilePath);

    if (newProject == null) return AsyncResult.rejected();

    newProject.save();

    ModifiableModuleModel modifiableModel = ModuleManager.getInstance(newProject).getModifiableModel();

    importProvider.process(context, newProject, modifiableModel, module -> {
    });

    WriteAction.runAndWait(modifiableModel::commit);

    newProject.save();

    context.dispose();

    return AsyncResult.resolved(newProject);
  }
  catch (Exception e) {
    context.dispose();

    return AsyncResult.<Project>undefined().rejectWithThrowable(e);
  }
}
 
Example #10
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Inject
public FileDocumentManagerImpl(Application application, ProjectManager projectManager) {
  ((ProjectManagerEx)projectManager).registerCloseProjectVeto(new MyProjectCloseHandler());

  myBus = application.getMessageBus();
  InvocationHandler handler = (proxy, method, args) -> {
    multiCast(method, args);
    return null;
  };

  ClassLoader loader = FileDocumentManagerListener.class.getClassLoader();
  myMultiCaster = (FileDocumentManagerListener)Proxy.newProxyInstance(loader, new Class[]{FileDocumentManagerListener.class}, handler);
}
 
Example #11
Source File: BaseApplication.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected boolean canExit() {
  ProjectManagerEx projectManager = (ProjectManagerEx)ProjectManager.getInstance();
  Project[] projects = projectManager.getOpenProjects();
  for (Project project : projects) {
    if (!projectManager.canClose(project)) {
      return false;
    }
  }

  return true;
}
 
Example #12
Source File: PlatformTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();
  if (ourTestCase != null) {
    String message = "Previous test " + ourTestCase + " hasn't called tearDown(). Probably overridden without super call.";
    ourTestCase = null;
    fail(message);
  }

  LOGGER.info(getClass().getName() + ".setUp()");

  initApplication();

  myEditorListenerTracker = new EditorListenerTracker();
  myThreadTracker = new ThreadTracker();

  setUpProject();

  storeSettings();
  ourTestCase = this;
  if (myProject != null) {
    ProjectManagerEx.getInstanceEx().openTestProject(myProject);
    CodeStyleSettingsManager.getInstance(myProject).setTemporarySettings(new CodeStyleSettings());
    InjectedLanguageManagerImpl.pushInjectors(getProject());
  }

  DocumentCommitThread.getInstance().clearQueue();
  UIUtil.dispatchAllInvocationEvents();
}
 
Example #13
Source File: OneFileAtProjectTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@RequiredUIAccess
protected void tearDown() throws Exception {
  super.tearDown();
  myFile = null;
  ProjectManagerEx.getInstanceEx().closeTestProject(myProject);
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      Disposer.dispose(myProject);
    }
  });
  myProject = null;
  myPsiManager = null;
}
 
Example #14
Source File: PantsOpenProjectProvider.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
private Project createProject(VirtualFile file, AddModuleWizard dialog) {
  Project project = PantsUtil.findBuildRoot(file)
    .map(root -> Paths.get(root.getPath()))
    .map(root -> ProjectManagerEx.getInstanceEx().newProject(root, dialog.getProjectName(), new OpenProjectTask()))
    .orElse(null);
  if (project != null) {
    project.putUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT, true);
  }
  return project;
}
 
Example #15
Source File: ProjectImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isOpen() {
  return ProjectManagerEx.getInstanceEx().isProjectOpened(this);
}
 
Example #16
Source File: PlatformTestCase.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected void setUpProject() throws Exception {
  myProjectManager = ProjectManagerEx.getInstanceEx();
  assertNotNull("Cannot instantiate ProjectManager component", myProjectManager);

  File tempProjectDir = getTempProjectDir();

  myProject = doCreateProject(tempProjectDir);
  myProjectManager.openTestProject(myProject);
  LocalFileSystem.getInstance().refreshIoFiles(myFilesToDelete);

  setUpModule();

  LightPlatformTestCase.clearUncommittedDocuments(getProject());

  runStartupActivities();
}
 
Example #17
Source File: BaseSdkCompat.java    From intellij with Apache License 2.0 4 votes vote down vote up
/** #api193: project opening requirements changed in 2020.1. */
public static void openProject(Project project, Path projectFile) {
  ProjectManagerEx.getInstanceEx().openProject(project);
}
 
Example #18
Source File: TemplateProjectPropertiesAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void actionPerformed(AnActionEvent e) {
  Project defaultProject = ProjectManagerEx.getInstanceEx().getDefaultProject();
  ShowSettingsUtil.getInstance().showSettingsDialog(defaultProject);
}
 
Example #19
Source File: ProjectUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * @param project cannot be null
 */
@RequiredUIAccess
public static boolean closeAndDispose(@Nonnull final Project project) {
  return ProjectManagerEx.getInstanceEx().closeAndDispose(project);
}
 
Example #20
Source File: ProjectUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public static AsyncResult<Project> openAsync(@Nonnull String path, @Nullable final Project projectToCloseFinal, boolean forceOpenInNewFrame, @Nonnull UIAccess uiAccess) {
  final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path);

  if (virtualFile == null) return AsyncResult.rejected("file path not find");

  return PooledAsyncResult.create((result) -> {
    ProjectOpenProcessor provider = ProjectOpenProcessors.getInstance().findProcessor(VfsUtilCore.virtualToIoFile(virtualFile));
    if (provider != null) {
      result.doWhenDone((project) -> {
        uiAccess.give(() -> {
          if (project.isDisposed()) return;

          final ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.PROJECT_VIEW);

          if (toolWindow != null && toolWindow.getType() != ToolWindowType.SLIDING) {
            toolWindow.activate(null);
          }
        });
      });

      result.doWhenRejected(() -> WelcomeFrameManager.getInstance().showIfNoProjectOpened());

      AsyncResult<Void> reopenAsync = AsyncResult.undefined();

      Project projectToClose = projectToCloseFinal;
      Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
      if (!forceOpenInNewFrame && openProjects.length > 0) {
        if (projectToClose == null) {
          projectToClose = openProjects[openProjects.length - 1];
        }

        final Project finalProjectToClose = projectToClose;
        confirmOpenNewProjectAsync(uiAccess, false).doWhenDone(exitCode -> {
          if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
            AsyncResult<Void> closeResult = ProjectManagerEx.getInstanceEx().closeAndDisposeAsync(finalProjectToClose, uiAccess);
            closeResult.doWhenDone((Runnable)reopenAsync::setDone);
            closeResult.doWhenRejected(() -> result.reject("not closed project"));
          }
          else if (exitCode != GeneralSettings.OPEN_PROJECT_NEW_WINDOW) { // not in a new window
            result.reject("not open in new window");
          }
          else {
            reopenAsync.setDone();
          }
        });
      }
      else {
        reopenAsync.setDone();
      }

      // we need reexecute it due after dialog - it will be executed in ui thread
      reopenAsync.doWhenDone(() -> PooledAsyncResult.create(() -> provider.doOpenProjectAsync(virtualFile, uiAccess)).notify(result));
    }
    else {
      result.reject("provider for file path is not find");
    }
  });
}
 
Example #21
Source File: BlockReloadingUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void block() {
  ProjectManagerEx.getInstanceEx().blockReloadingProjectOnExternalChanges();
}
 
Example #22
Source File: BlockReloadingUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void unblock() {
  ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
}
 
Example #23
Source File: AbstractCommonUpdateAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void runImpl() {
  ProjectManagerEx.getInstanceEx().blockReloadingProjectOnExternalChanges();
  myProjectLevelVcsManager.startBackgroundVcsOperation();

  myBefore = LocalHistory.getInstance().putSystemLabel(myProject, "Before update");
  myLocalHistoryAction = LocalHistory.getInstance().startAction(LOCAL_HISTORY_ACTION);
  ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();

  try {
    int toBeProcessed = myVcsToVirtualFiles.size();
    int processed = 0;
    for (AbstractVcs vcs : myVcsToVirtualFiles.keySet()) {
      final UpdateEnvironment updateEnvironment = myActionInfo.getEnvironment(vcs);
      updateEnvironment.fillGroups(myUpdatedFiles);
      Collection<FilePath> files = myVcsToVirtualFiles.get(vcs);

      final SequentialUpdatesContext context = myContextInfo.get(vcs);
      final Ref<SequentialUpdatesContext> refContext = new Ref<>(context);

      // actual update
      UpdateSession updateSession =
              updateEnvironment.updateDirectories(files.toArray(new FilePath[files.size()]), myUpdatedFiles, progressIndicator, refContext);

      myContextInfo.put(vcs, refContext.get());
      processed++;
      if (progressIndicator != null) {
        progressIndicator.setFraction((double)processed / (double)toBeProcessed);
        progressIndicator.setText2("");
      }
      final List<VcsException> exceptionList = updateSession.getExceptions();
      gatherExceptions(vcs, exceptionList);
      myUpdateSessions.add(updateSession);
    }
  } finally {
    try {
      ProgressManager.progress(VcsBundle.message("progress.text.synchronizing.files"));
      doVfsRefresh();
    } finally {
      myProjectLevelVcsManager.stopBackgroundVcsOperation();
      if (!myProject.isDisposed()) {
        myProject.getMessageBus().syncPublisher(UpdatedFilesListener.UPDATED_FILES).
                consume(UpdatedFilesReverseSide.getPathsFromUpdatedFiles(myUpdatedFiles));
      }
    }
  }
}
 
Example #24
Source File: AbstractCommonUpdateAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void onSuccessImpl(final boolean wasCanceled) {
  if (!myProject.isOpen() || myProject.isDisposed()) {
    ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
    LocalHistory.getInstance().putSystemLabel(myProject, LOCAL_HISTORY_ACTION); // TODO check why this label is needed
    return;
  }
  boolean continueChain = false;
  for (SequentialUpdatesContext context : myContextInfo.values()) {
    continueChain |= (context != null) && (context.shouldFail());
  }
  final boolean continueChainFinal = continueChain;

  final boolean someSessionWasCancelled = wasCanceled || someSessionWasCanceled(myUpdateSessions);
  // here text conflicts might be interactively resolved
  for (final UpdateSession updateSession : myUpdateSessions) {
    updateSession.onRefreshFilesCompleted();
  }
  // only after conflicts are resolved, put a label
  if (myLocalHistoryAction != null) {
    myLocalHistoryAction.finish();
  }
  myAfter = LocalHistory.getInstance().putSystemLabel(myProject, "After update");

  if (myActionInfo.canChangeFileStatus()) {
    final List<VirtualFile> files = new ArrayList<>();
    final RemoteRevisionsCache revisionsCache = RemoteRevisionsCache.getInstance(myProject);
    revisionsCache.invalidate(myUpdatedFiles);
    UpdateFilesHelper.iterateFileGroupFiles(myUpdatedFiles, new UpdateFilesHelper.Callback() {
      @Override
      public void onFile(final String filePath, final String groupId) {
        @NonNls final String path = VfsUtilCore.pathToUrl(filePath.replace(File.separatorChar, '/'));
        final VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(path);
        if (file != null) {
          files.add(file);
        }
      }
    });
    myDirtyScopeManager.filesDirty(files, null);
  }

  final boolean updateSuccess = !someSessionWasCancelled && myGroupedExceptions.isEmpty();

  WaitForProgressToShow.runOrInvokeLaterAboveProgress(() -> {
    if (myProject.isDisposed()) {
      ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
      return;
    }

    if (!myGroupedExceptions.isEmpty()) {
      if (continueChainFinal) {
        gatherContextInterruptedMessages();
      }
      AbstractVcsHelper.getInstance(myProject).showErrors(myGroupedExceptions, VcsBundle.message("message.title.vcs.update.errors",
                                                                                                 getTemplatePresentation().getText()));
    }
    else if (someSessionWasCancelled) {
      ProgressManager.progress(VcsBundle.message("progress.text.updating.canceled"));
    }
    else {
      ProgressManager.progress(VcsBundle.message("progress.text.updating.done"));
    }

    final boolean noMerged = myUpdatedFiles.getGroupById(FileGroup.MERGED_WITH_CONFLICT_ID).isEmpty();
    if (myUpdatedFiles.isEmpty() && myGroupedExceptions.isEmpty()) {
      NotificationType type;
      String content;
      if (someSessionWasCancelled) {
        content = VcsBundle.message("progress.text.updating.canceled");
        type = NotificationType.WARNING;
      }
      else {
        content = getAllFilesAreUpToDateMessage(myRoots);
        type = NotificationType.INFORMATION;
      }
      VcsNotifier.getInstance(myProject).notify(STANDARD_NOTIFICATION.createNotification(content, type));
    }
    else if (!myUpdatedFiles.isEmpty()) {
      final UpdateInfoTree tree = showUpdateTree(continueChainFinal && updateSuccess && noMerged, someSessionWasCancelled);
      final CommittedChangesCache cache = CommittedChangesCache.getInstance(myProject);
      cache.processUpdatedFiles(myUpdatedFiles, incomingChangeLists -> tree.setChangeLists(incomingChangeLists));

      Notification notification = prepareNotification(tree, someSessionWasCancelled);
      notification.addAction(new ViewUpdateInfoNotification(myProject, tree, "View", notification));
      VcsNotifier.getInstance(myProject).notify(notification);
    }

    ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();

    if (continueChainFinal && updateSuccess) {
      if (!noMerged) {
        showContextInterruptedError();
      }
      else {
        // trigger next update; for CVS when updating from several branches simultaneously
        reset();
        ProgressManager.getInstance().run(this);
      }
    }
  }, null, myProject);
}
 
Example #25
Source File: TemplateProjectStructureAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
@RequiredUIAccess
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  Project defaultProject = ProjectManagerEx.getInstanceEx().getDefaultProject();
  ShowSettingsUtil.getInstance().showProjectStructureDialog(defaultProject);
}
 
Example #26
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();
  }
}