/*
    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;

import java.beans.*;

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.*;

import com.vlsolutions.swing.docking.event.*;

/** DefaultImplementation of the SingleDockableContainer.
 *<p>
 * A Dockview is the component responsible for displaying a single user
 * component inside a DockingPanel.
 * <p>
 * The DockView contains a DockViewTitleBar, used as a header to display useful information
 * and optional controls (close/maximize/hide/float)
 * <p>
 * UI : The user component is displayed with decorations provided by a
 * {@link com.vlsolutions.swing.docking.ui.DockViewUI} delegate.
 * <p>
 * Here is an example (VLDocking 1.1 "shadow" style) :
 * <ul>
 * <li> A gadient for the title bar and a set of icons for the buttons.
 * <li> A shadowed border for enhanced visibility. <br>
 * </ul>
 * <p align="center"><img src="doc-files/dockview.gif" alt="Sample DockView" ></p>
 *
 * <p>
 * Note : multiple user-components are not displayable by the dockview :
 * the default implementation of TabbedDockableContainer is the {@link DockTabbedPane}.
 *
 * @see DockViewTitleBar
 *
 * @author Lilian Chamontin, vlsolutions.
 * @version 1.0
 * @update 2005/12/09 Lilian Chamontin : added NPE safety check around uninstallDocking as sometimes
 * uninstalling is done twice.
 * @update 2007/01/08 Lilian Chamontin : delegated the creation of the titlebar to allow easy override.
 */
public class DockView extends JPanel implements DockDropReceiver, SingleDockableContainer {
  
  private static final String uiClassID = "DockViewUI";
  
  protected DockViewTitleBar title = getTitleBar();
  
  /** the desktop managing this view  */
  protected DockingDesktop desktop;
  
  /** the dockable managed by this view  */
  protected Dockable dockable; //user component
  
  /** remember the last drop position to cache the shape used for showing the drop position */
  protected Shape lastDropShape, lastDropGeneralPath;
  
  
  /** listen to the titlebar actions */
  private PropertyChangeListener listener = new PropertyChangeListener(){
    public void propertyChange(PropertyChangeEvent e) {
      if (e.getPropertyName().equals(DockViewTitleBar.PROPERTY_AUTOHIDE)){
        if (e.getOldValue().equals(Boolean.TRUE)){
          // from autohide to dock : not possible because DockView isn't used
        } else {
          // dock to autohide
          desktop.setAutoHide(dockable, true);
        }
      } else if (e.getPropertyName().equals(DockViewTitleBar.PROPERTY_CLOSED)){
        desktop.close(dockable);
      } else if (e.getPropertyName().equals(DockViewTitleBar.PROPERTY_MAXIMIZED)){
        if (e.getNewValue().equals(Boolean.TRUE)){
          desktop.maximize(dockable);
        } else {
          desktop.restore(dockable);
        }
      } else if (e.getPropertyName().equals(DockViewTitleBar.PROPERTY_FLOAT)){
        desktop.setFloating(dockable, ((Boolean)e.getNewValue()).booleanValue());
      }
    }
  };
  
  
  
  /** Constructs an empty DockView.
   * <p>
   * A {@link #setDockable(Dockable)} call is requiered for this constructor to be usefull.
   *   */
  public DockView() {
    super(new BorderLayout());
    add(title, BorderLayout.NORTH);
  }
  
  /** Constructs a new DockView for the given dockable.
   *
   * @param dockable the dockable to show
   *  */
  public DockView(Dockable dockable){
    this();
    setDockable(dockable);
  }
  
  /** Constructs a new DockView for the given dockable.
   *
   * @param dockable the dockable to show
   *  */
  public DockView(Dockable dockable, boolean showTitle){
    super(new BorderLayout());
    add(title, BorderLayout.NORTH);
    if (!showTitle){
      title.setVisible(false);
    }
    setDockable(dockable);
  }
  
  
  
  /** Returns the contained component
   *
   * {@inheritDoc}
   * */
  public Dockable getDockable(){
    return dockable;
  }
  
  /** Adds the dockable's component to this DockView.
   *
   *
   * @param dockable the user dockable
   */
  public void setDockable(Dockable dockable){
    this.dockable = dockable;
    
    add(dockable.getComponent(), BorderLayout.CENTER);
    if (title != null){
      title.setDockable(dockable);
    }
    
    // allow resizing  of split pane beyond minimum size
    // could be replaced by adding a JScrollPane instead of panels
    setMinimumSize(new Dimension(30,30));
    
  }
  
  /** {@inheritDoc}
   */
  public String toString(){
    return "DockView of " + dockable.getDockKey();
  }
  
  /** {@inheritDoc}
   * @since 2.0
   */
  public String getUIClassID() {
    return uiClassID;
  }
  
  /** {@inheritDoc}.
   */
  public void processDockableDrag(DockDragEvent event) {
    scanDrop(event, false);
  }
  
  /**  {@inheritDoc}
   * <p>
   * Please note that a drag into a DockView can also lead to create a DockTabbedPane.
   */
  public void processDockableDrop(DockDropEvent event) {
    scanDrop(event, true);
  }
  
  
  /* common method for drag && drop gesture support */
  protected void scanDrop(DockEvent event, boolean drop){
    // reject operation if the source is an ancestor of this view.
    if (event.getDragSource().getDockableContainer().isAncestorOf(this)){
      // this is possible for compound containers (as they contain sub-dockables)
      // in that case, you cannnot drop a compound into one of its children  // 2007/01/08
      if (drop){
        ((DockDropEvent) event).rejectDrop();
      } else {
        ((DockDragEvent) event).delegateDrag();
      }
      return;
    }
    
    if (getParent() instanceof TabbedDockableContainer){
      // cannot nest DockTabbedPanes
      if (drop){
        ((DockDropEvent) event).rejectDrop();
      } else {
        ((DockDragEvent) event).delegateDrag();
      }
      return;
    }
    
    if (event.getDragSource().getDockable() == dockable) {
      // cannot drop onto itself
      if (drop){
        ((DockDropEvent) event).rejectDrop();
      } else {
        ((DockDragEvent) event).rejectDrag();
      }
      return;
    }
    
    // The dockview isn't contained inside a tabbedpane, so there are now 5 drop zones :
    // - center : create a tabbedpane
    // - top/left/bottom/right : split the view
    
    
    Rectangle bounds = getBounds();
    
    BorderSplitter splitter = new BorderSplitter(this);
    boolean accepted;
    if (drop){
      splitter.processDockableDrop((DockDropEvent)event);
      accepted = ((DockDropEvent)event).isDropAccepted();
    } else {
      splitter.processDockableDrag((DockDragEvent)event);
      accepted = ((DockDragEvent)event).isDragAccepted();
    }
    
    if (! accepted){
      // not on the borders : we should create a new tab
      if (event.getDragSource().getDockableContainer() instanceof TabbedDockableContainer) {
        // cannot drop a whole tab container
        if (drop){
          ((DockDropEvent) event).rejectDrop();
        } else {
          ((DockDragEvent) event).rejectDrag();
        }
        return;
      }
      
      // reject if key groups aren't compatible
      DockGroup thisGroup = dockable.getDockKey().getDockGroup();
      DockGroup dragGroup = event.getDragSource().getDockable().getDockKey().getDockGroup();
      if (!DockGroup.areGroupsCompatible( thisGroup, dragGroup)){
        if (drop){
          ((DockDropEvent) event).rejectDrop();
        } else {
          ((DockDragEvent) event).rejectDrag();
        }
        return;
      }
      
      Dockable d = event.getDragSource().getDockable();
      int dockableState = d.getDockKey().getDockableState();
      int viewState = dockable.getDockKey().getDockableState();
      if (drop){
        event.setDockingAction(new DockingActionCreateTabEvent(event.getDesktop(),
            d, dockableState, viewState, dockable, 0));
        
        
        /*if (dockable.getDockKey().getDockableState() == DockableState.STATE_FLOATING){
          ((DockDropEvent) event).acceptDrop(false); // don't remove a floating dockable from its hierarchy yet
        } else {*/
        ((DockDropEvent) event).acceptDrop();
        /*} */
        desktop.createTab(dockable, event.getDragSource().getDockable(), 0, true);
      } else {
        event.setDockingAction(new DockingActionCreateTabEvent(event.getDesktop(),
            d, dockableState, viewState, dockable, 0));
        
        
        Rectangle2D r2d = new Rectangle2D.Float(bounds.x, bounds.y,
            bounds.width,
            bounds.height);
        if (r2d.equals(lastDropShape)) {
          // optimized shape caching
          ( (DockDragEvent) event).acceptDrag(lastDropGeneralPath);
        } else {
          // draw a 'tabbed pane shape'
          GeneralPath path = buildPathForTab(bounds);;
          
          lastDropShape = r2d;
          lastDropGeneralPath = path;
          ( (DockDragEvent) event).acceptDrag(lastDropGeneralPath);
        }
      }
      
    }
    
  }
  
  /** Create a path used to display the drag shape of a tab container  */
  protected GeneralPath buildPathForTab(Rectangle bounds){
    GeneralPath path = new GeneralPath();
    int tabPlacement = UIManager.getInt("TabbedDockableContainer.tabPlacement");
    if (tabPlacement == SwingConstants.BOTTOM){
      Rectangle tabRect = new Rectangle(0, 0,
          bounds.width - 5, bounds.height - 5);
      path.moveTo(tabRect.x, tabRect.y);
      path.lineTo(tabRect.x + tabRect.width, tabRect.y);
      path.lineTo(tabRect.x + tabRect.width, tabRect.y + tabRect.height - 15);
      path.lineTo(tabRect.x + 30, tabRect.y + tabRect.height - 15);
      path.lineTo(tabRect.x + 25, tabRect.y + tabRect.height);
      path.lineTo(tabRect.x + 10, tabRect.y + tabRect.height);
      path.lineTo(tabRect.x + 10, tabRect.y + tabRect.height - 15);
      path.lineTo(tabRect.x, tabRect.y + tabRect.height - 15);
      path.closePath();
    } else { // TOP
      Rectangle tabRect = new Rectangle(0, 20,
          bounds.width - 5, bounds.height - 20-5);
      path.moveTo(tabRect.x, tabRect.y);
      path.lineTo(tabRect.x + 10, tabRect.y);
      path.lineTo(tabRect.x + 10, tabRect.y - 15);
      path.lineTo(tabRect.x + 25, tabRect.y - 15);
      path.lineTo(tabRect.x + 30, tabRect.y );
      path.lineTo(tabRect.x + tabRect.width, tabRect.y);
      path.lineTo(tabRect.x + tabRect.width, tabRect.y + tabRect.height);
      path.lineTo(tabRect.x, tabRect.y + tabRect.height);
      path.closePath();
    }
    return path;
  }
  
  /** {@inheritDoc} */
  public void installDocking(DockingDesktop desktop) {
    this.desktop = desktop;
    desktop.installDockableDragSource(title);
    title.addPropertyChangeListener(DockViewTitleBar.PROPERTY_AUTOHIDE, listener);
    title.addPropertyChangeListener(DockViewTitleBar.PROPERTY_CLOSED, listener);
    title.addPropertyChangeListener(DockViewTitleBar.PROPERTY_MAXIMIZED, listener);
    title.addPropertyChangeListener(DockViewTitleBar.PROPERTY_FLOAT, listener);
    title.installDocking(desktop);
  }
  
  /** {@inheritDoc} */
  public void uninstallDocking(DockingDesktop desktop) {
    if (title != null){ // safety check, as removing is sometimes cascaded and done once more than it should be 2005/12/09
      desktop.uninstallDockableDragSource(title);
      title.removePropertyChangeListener(DockViewTitleBar.PROPERTY_AUTOHIDE, listener);
      title.removePropertyChangeListener(DockViewTitleBar.PROPERTY_CLOSED, listener);
      title.removePropertyChangeListener(DockViewTitleBar.PROPERTY_MAXIMIZED, listener);
      title.removePropertyChangeListener(DockViewTitleBar.PROPERTY_FLOAT, listener);
      title.uninstallDocking(desktop);
    }
    //remove(title);
    title = null;
    this.desktop = null;
    
  }
  
  
  /** Returns (or creates) the title bar of this dockview  */
  public DockViewTitleBar getTitleBar(){
    if (title == null){
      title = DockableContainerFactory.getFactory().createTitleBar();//2007/01/08
    }
    return title;    
  }
  
}
