/*
    VLDocking Framework 2.1
    Copyright VLSOLUTIONS, 2004-2006

    email : info@vlsolutions.com
------------------------------------------------------------------------
This software is distributed under the CeCILL license, a GNU GPL-compatible
license adapted to french law.
French and English license headers are provided at the begining of
the source files of this software application.
------------------------------------------------------------------------
LICENCE CeCILL (FRENCH VERSION).
------------------------------------------------------------------------
Ce logiciel est un programme informatique servant à améliorer les interfaces
homme-machine d'applications Java basées sur Swing, en leur apportant un
ensemble de fonctions relatives au dockage des composants.

Ce logiciel est régi par la licence CeCILL soumise au droit français et
respectant les principes de diffusion des logiciels libres. Vous pouvez
utiliser, modifier et/ou redistribuer ce programme sous les conditions
de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
sur le site "http://www.cecill.info".

En contrepartie de l'accessibilité au code source et des droits de copie,
de modification et de redistribution accordés par cette licence, il n'est
offert aux utilisateurs qu'une garantie limitée.  Pour les mêmes raisons,
seule une responsabilité restreinte pèse sur l'auteur du programme,  le
titulaire des droits patrimoniaux et les concédants successifs.

A cet égard  l'attention de l'utilisateur est attirée sur les risques
associés au chargement,  à l'utilisation,  à la modification et/ou au
développement et à la reproduction du logiciel par l'utilisateur étant
donné sa spécificité de logiciel libre, qui peut le rendre complexe à
manipuler et qui le réserve donc à des développeurs et des professionnels
avertis possédant  des  connaissances  informatiques approfondies.  Les
utilisateurs sont donc invités à charger  et  tester  l'adéquation  du
logiciel à leurs besoins dans des conditions permettant d'assurer la
sécurité de leurs systèmes et ou de leurs données et, plus généralement,
à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.

Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
pris connaissance de la licence CeCILL, et que vous en avez accepté les
termes.

------------------------------------------------------------------------
CeCILL License (ENGLISH VERSION)
------------------------------------------------------------------------

This software is a computer program whose purpose is to enhance Human-Computer
Interfaces written in Java with the Swing framework, providing them a set of
functions related to component docking.

This software is governed by the CeCILL  license under French law and
abiding by the rules of distribution of free software.  You can  use,
modify and/ or redistribute the software under the terms of the CeCILL
license as circulated by CEA, CNRS and INRIA at the following URL
"http://www.cecill.info".

As a counterpart to the access to the source code and  rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty  and the software's author,  the holder of the
economic rights,  and the successive licensors  have only  limited
liability.

In this respect, the user's attention is drawn to the risks associated
with loading,  using,  modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean  that it is complicated to manipulate,  and  that  also
therefore means  that it is reserved for developers  and  experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or
data to be ensured and,  more generally, to use and operate it in the
same conditions as regards security.

The fact that you are presently reading this means that you have had
knowledge of the CeCILL license and that you accept its terms.

*/


package com.vlsolutions.swing.docking.animation;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;


/** Utility class used to perform move/resize animation for awt/swing components.
 * <p>
 * This class moves/resizes a Component given a start and end Rectangle and
 * a duration.
 * <p>
 * Movements and listeners notifications are processed in the Swing Event Thread.
 *
 * @author Lilian Chamontin, vlsolutions.
 * @version 1.0
 * */
public class ComponentAnimator {
  /** The animated component */
  protected Component comp;

  /** the component's start bounds */
  protected Rectangle startBounds;

  /** the component's end bounds */
  protected Rectangle endBounds;

  /** the animation duration in seconds */
  protected float duration;

  /** animation start time System.currentTimeMillis() */
  private long start;

  /** time elapsed since the beginnig of animation */
  protected float elapsed = 0;

  private Timer timer;

  private ArrayList listeners = new ArrayList(3);


  /** Single-shot animator (use another ComponentAnimator for a new animation).
   *
   *
   * @param comp     the component to animate
   * @param startBounds  initial bounds of the component
   * @param endBounds    end bounds of the component
   * @param duration     duration of animation, expressed in seconds
   * @param listener     single listener used for animation notification
   */
  public ComponentAnimator(Component comp, Rectangle startBounds,
      Rectangle endBounds, float duration, AnimationListener listener) {
    this.comp = comp;
    this.startBounds = startBounds;
    this.endBounds = endBounds;
    this.duration = duration;
    addAnimationListener(listener);
    start();

  }

  /** Reusable component animator.
   * To start an animation, don't forget to call the {@link #start() start() }method.
   * */
  public ComponentAnimator(Component comp, Rectangle startBounds,
      Rectangle endBounds, float duration) {
    this.comp = comp;
    this.startBounds = startBounds;
    this.endBounds = endBounds;
    this.duration = duration;
  }


  /** Starts the animation.
   * <P> The component is <code>setBounds</code>ed to startBounds and made visible,
   * than a Swing timer is started to process the animation (refresh rate is 100 ms).
   * <P> the ANIMATION_START event is then fired to all listeners.
   */
  public void start(){
      if (duration == 0 ){ // heavy weight == no animation
        fireAnimationEvent(new AnimationEvent(comp, AnimationEvent.ANIMATION_START));
        // already the end
        comp.setBounds(endBounds.x, endBounds.y, endBounds.width, endBounds.height);
        comp.invalidate();
        comp.validate();
        comp.repaint();
        fireAnimationEvent(new AnimationEvent(comp, AnimationEvent.ANIMATION_END));          
      } else {
        comp.setBounds(startBounds.x, startBounds.y,
            startBounds.width,
            startBounds.height);
        comp.validate();
        comp.setVisible(true);
        timer = new Timer(100, new AnimationActionListener());
        start = System.currentTimeMillis();
        timer.start();
        fireAnimationEvent(new AnimationEvent(comp, AnimationEvent.ANIMATION_START));
      }
    }

  /** Cancels the animation (the component is not reset to its initial location/size) */
  public void cancel(){
     timer.stop();
  }


  /** Adds a new listener to the animator
   * @param listener  the listener  */
  public void addAnimationListener(AnimationListener listener) {
    if (listener != null && ! listeners.contains(listener)){
      listeners.add(listener);
    }
  }

  /** loops over the listeners to fire animation event */
  private void fireAnimationEvent(AnimationEvent e){
    for (int i = 0; i < listeners.size(); i++) {
      ((AnimationListener) listeners.get(i)).animation(e);
    }
  }

  /** Returns the duration of the animation
   *
   * @return the duration of the animation, in seconds
   */
  public float getDuration() {
    return duration;
  }

  /** Sets the duration of the animation.
   * <P> Warning : do not change this value during an animation
   *
   * @param duration the new duration in seconds
   */
  public void setDuration(float duration) {
    this.duration = duration;
  }

  /** Returns the end bounds of the components.
   *
   * @return the end bounds of the components.
   */
  public Rectangle getEndBounds() {
    return endBounds;
  }

  /** Sets the end bounds of the component.
   * <P>Warning : do not change end bounds during an animation.
   *
   * @param endBounds
   */
  public void setEndBounds(Rectangle endBounds) {
    this.endBounds = endBounds;
  }

  /** Returns the start bounds of the component.
   *
   * @return the start bounds of the component (those of when animation starts).
   */
  public Rectangle getStartBounds() {
    return startBounds;
  }

  /** Sets the start bounds of the component for animation.
   * <P> Warning :do not change start bounds during an animation
   * @param startBounds the start bounds of the component.
   */
  public void setStartBounds(Rectangle startBounds) {
    this.startBounds = startBounds;
  }

  /** Inner action listener to hide actionPerformed from the public API. */
  private class AnimationActionListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      long time = System.currentTimeMillis();
      elapsed = (time - start) / 1000f;
      if (elapsed < duration) {
        float f1 = (duration - elapsed) / duration;
        float f2 = elapsed / duration;
        Rectangle newBounds = new Rectangle();
        newBounds.x = (int) (startBounds.x * f1 + endBounds.x * f2);
        newBounds.y = (int) (startBounds.y * f1 + endBounds.y * f2);
        newBounds.width = (int) (startBounds.width * f1 + endBounds.width * f2);
        newBounds.height = (int) (startBounds.height * f1 +
            endBounds.height * f2);
        comp.setBounds(newBounds.x, newBounds.y,
            newBounds.width,
            newBounds.height);
        comp.validate();
        fireAnimationEvent(new AnimationEvent(comp,
            AnimationEvent.ANIMATION_FRAME));
      } else {

        // the end
        comp.setBounds(endBounds.x, endBounds.y,
            endBounds.width,
            endBounds.height);
        comp.validate();
        timer.stop();
        fireAnimationEvent(new AnimationEvent(comp,
            AnimationEvent.ANIMATION_END));

      }

    }
  }

}
