/**
  * Subclasses may override/extend this method to create custom filters, perhaps based on the
  * default filter create by the superclass. <b>Note</b> that this method is invoked by the
  * superclass constructor, so subclasses must not attempt to access their own state.
  *
  * @return my notification filter
  */
 protected NotificationFilter createFilter() {
   return NotificationFilter.createNotifierTypeFilter(ResourceSet.class)
       .or(NotificationFilter.createNotifierTypeFilter(Resource.class));
 }
/**
 * Listens for removed Ensembles and closes their editors
 *
 * @author Marco Jacobasch
 */
public class EnsembleRemoveListener extends DemultiplexingListener {

  /** NotificationFilter to select only remove notifications and Ensembles or EnsembleRepository */
  private static final NotificationFilter REMOVE_FILTER =
      NotificationFilter.createEventTypeFilter(Notification.REMOVE)
          .and(
              NotificationFilter.createNotifierTypeFilter(
                      DatamodelPackage.Literals.CONCRETE_ENSEMBLE)
                  .or(
                      NotificationFilter.createNotifierTypeFilter(
                          DatamodelPackage.Literals.ENSEMBLE_REPOSITORY)));

  /** Creates Listener with a NotificationFilter */
  public EnsembleRemoveListener() {
    super(REMOVE_FILTER);
  }

  /**
   * Checks only if removed object was an Ensemble, if true, closes all open Ensemble Editors.
   *
   * <p>Checking remove event and correct classes is done by the NotificationFilter
   */
  @Override
  protected void handleNotification(TransactionalEditingDomain domain, Notification notification) {

    if (notification.getOldValue() instanceof Ensemble) {
      final Ensemble oldEnsemble = (Ensemble) notification.getOldValue();

      Display.getDefault()
          .asyncExec(
              new Runnable() {
                @Override
                public void run() {
                  IWorkbenchPage page = getActivePage();
                  Ensemble ens = oldEnsemble;

                  if (page != null) {
                    IEditorReference[] editors =
                        page.findEditors(
                            new EnsembleEditorInput(ens),
                            EnsembleEditor.ID,
                            IWorkbenchPage.MATCH_ID | IWorkbenchPage.MATCH_INPUT);

                    page.closeEditors(editors, false);
                  }
                }
              });
    }
  }

  /**
   * Get the current active page to close all editors
   *
   * @return
   */
  private IWorkbenchPage getActivePage() {
    IWorkbenchPage result = null;

    IWorkbench bench = PlatformUI.getWorkbench();
    if (bench != null) {
      IWorkbenchWindow window = bench.getActiveWorkbenchWindow();

      if (window != null) {
        result = window.getActivePage();
      }
    }

    return result;
  }
}