@Override
  public void runWhenProjectIsInitialized(@NotNull final Runnable action) {
    final Application application = ApplicationManager.getApplication();
    if (application == null) return;

    //noinspection SynchronizeOnThis
    synchronized (this) {
      // in tests which simulate project opening, post-startup activities could have been run
      // already.
      // Then we should act as if the project was initialized
      boolean initialized =
          myProject.isInitialized()
              || application.isUnitTestMode() && myPostStartupActivitiesPassed;
      if (!initialized) {
        registerPostStartupActivity(action);
        return;
      }
    }

    Runnable runnable =
        new Runnable() {
          @Override
          public void run() {
            if (!myProject.isDisposed()) {
              action.run();
            }
          }
        };
    if (application.isDispatchThread() && ModalityState.current() == ModalityState.NON_MODAL) {
      runnable.run();
    } else {
      application.invokeLater(runnable, ModalityState.NON_MODAL);
    }
  }
  public void reloadProjectImpl(@NotNull final Project p, final boolean clearCopyToRestore) {
    if (clearCopyToRestore) {
      mySavedCopies.clear();
      mySavedTimestamps.clear();
    }

    final Project[] project = {p};

    ProjectReloadState.getInstance(project[0]).onBeforeAutomaticProjectReload();
    final Application application = ApplicationManager.getApplication();

    application.invokeLater(
        new Runnable() {
          @Override
          public void run() {
            LOG.debug("Reloading project.");
            ProjectImpl projectImpl = (ProjectImpl) project[0];
            if (projectImpl.isDisposed()) return;
            IProjectStore projectStore = projectImpl.getStateStore();
            final String location = projectImpl.getPresentableUrl();

            final List<IFile> original;
            try {
              final IComponentStore.SaveSession saveSession = projectStore.startSave();
              original = saveSession.getAllStorageFiles(true);
              saveSession.finishSave();
            } catch (IOException e) {
              LOG.error(e);
              return;
            }

            if (project[0].isDisposed() || ProjectUtil.closeAndDispose(project[0])) {
              application.runWriteAction(
                  new Runnable() {
                    @Override
                    public void run() {
                      for (final IFile originalFile : original) {
                        restoreCopy(
                            LocalFileSystem.getInstance().refreshAndFindFileByIoFile(originalFile));
                      }
                    }
                  });

              project[0] = null; // Let it go.

              ProjectUtil.openProject(location, null, true);
            }
          }
        },
        ModalityState.NON_MODAL);
  }