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;
    }
  }
  @Override
  public void writeExternal(Element parentNode) throws WriteExternalException {
    if (myDefaultProject != null) {
      myDefaultProject.save();
    }

    if (myDefaultProjectRootElement
        == null) { // read external isn't called if config folder is absent
      myDefaultProjectRootElement = new Element(ELEMENT_DEFAULT_PROJECT);
    }

    myDefaultProjectRootElement.detach();
    parentNode.addContent(myDefaultProjectRootElement);
  }
  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);
                            }
                          }
                        });
              }
            });
  }