/**
 * GUI Commands
 * Copyright 2004 Andrew Pietsch
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * $Id: UndoContext.java,v 1.4 2004/12/12 05:29:33 pietschy Exp $
 */
package org.pietschy.command.undo;

import javax.swing.event.*;
import javax.swing.undo.UndoManager;
import javax.swing.undo.UndoableEdit;

/**
 * UndoContext extends {@link UndoManager} to provide state change notifications to listners.
 * @version $Revision: 1.4 $
 * @author andrewp
 */
public class
UndoContext
extends UndoManager
implements UndoableEditListener

{
   private EventListenerList listenerList = new EventListenerList();

   public UndoContext()
   {
   }


   public boolean
   addEdit(UndoableEdit anEdit)
   {
      boolean result = super.addEdit(anEdit);
      fireStateChaged();
      return result;
   }

   public void
   undoableEditHappened(UndoableEditEvent e)
   {
      super.undoableEditHappened(e);
      fireStateChaged();
   }


   public void
   undo()
   {
      super.undo();
      fireStateChaged();
   }

   public void
   redo()
   {
      super.redo();
      fireStateChaged();
   }


   public boolean
   canUndo()
   {
      return super.canUndo();
   }

   public boolean
   canRedo()
   {
      return super.canRedo();
   }

   public void
   fireStateChaged()
   {
      ChangeEvent event = null;
      // Guaranteed to return a non-null array
      Object[] listeners = listenerList.getListenerList();
      // Process the listeners last to first, notifying
      // those that are interested in this event
      for (int i = listeners.length - 2; i >= 0; i -= 2)
      {
         if (listeners[i] == ChangeListener.class)
         {
            // Lazily create the event:
            if (event == null)
               event = new ChangeEvent(this);
            ((ChangeListener) listeners[i + 1]).stateChanged(event);
         }
      }
   }

   public void
   addChangeListener(ChangeListener l)
   {
      listenerList.add(ChangeListener.class, l);
   }

   public void
   removeChangeListener(ChangeListener l)
   {
      listenerList.add(ChangeListener.class, l);
   }
}
