private void initProject(@NotNull ProjectImpl project, @Nullable ProjectImpl template)
      throws IOException {
    final ProgressIndicator indicator = myProgressManager.getProgressIndicator();
    if (indicator != null && !project.isDefault()) {
      indicator.setText(ProjectBundle.message("loading.components.for", project.getName()));
      indicator.setIndeterminate(true);
    }

    ApplicationManager.getApplication()
        .getMessageBus()
        .syncPublisher(ProjectLifecycleListener.TOPIC)
        .beforeProjectLoaded(project);

    try {
      if (template != null) {
        project.getStateStore().loadProjectFromTemplate(template);
      } else {
        project.getStateStore().load();
      }
      project.loadProjectComponents();
      project.init();
    } catch (IOException e) {
      scheduleDispose(project);
      throw e;
    } catch (ProcessCanceledException e) {
      scheduleDispose(project);
      throw e;
    }
  }
  private static void scheduleDispose(final ProjectImpl project) {
    if (project.isDefault()) {
      return;
    }

    ApplicationManager.getApplication()
        .invokeLater(
            new Runnable() {
              @Override
              public void run() {
                ApplicationManager.getApplication()
                    .runWriteAction(
                        new Runnable() {
                          @Override
                          public void run() {
                            if (!project.isDisposed()) {
                              Disposer.dispose(project);
                            }
                          }
                        });
              }
            });
  }