/***************************************************************************
**
**  This file is part of QGpGuiTools.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This file is distributed in the hope that it will be useful, but WITHOUT
**  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
**  FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
**  License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2006-06-04
**  Copyright: 2006-2019
**    Marc Wathelet
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#include "ColorButton.h"

namespace QGpGuiTools {

/*!
  \class ColorButton ColorButton.h
  \brief A pushbutton to select a color

  By default a click displays a QColorDialog. Whenever the color is changed, signal
  colorChanged() is emited. If exec() exits with Rejected, the original color is
  restored by emitting signal with the original color.
*/

/*!
  Description of constructor still missing
*/
ColorButton::ColorButton(QWidget * parent)
    : QPushButton(parent)
{
  TRACE;
  setColor(Qt::gray);
  connect(this, SIGNAL(clicked()), this, SLOT(setColor()));
}

ColorButton::~ColorButton()
{
  TRACE;
}

void ColorButton::disconnect()
{
  TRACE;
  QPushButton::disconnect(this, SIGNAL(clicked()), this, SLOT(setColor()));
}

void ColorButton::setColor(const QColor& c)
{
  TRACE;
  _color=c;
  QPixmap pm(iconSize());
  QPainter p;
  p.begin(&pm);
  p.fillRect(0, 0, iconSize().width(), iconSize().height(), _color);
  p.end();
  setIcon(pm);
}

/*!
  Creates a QColorDialog that may delete this object (observed for a delegate in a QTableView).
  If using a ColorButton in a delegate, call disconnect() after creation and re-implement setColor().
*/
void ColorButton::setColor()
{
  TRACE;
  QColorDialog * d=new QColorDialog(qApp->activeWindow());
  QColor originalColor=color();
  d->setCurrentColor(originalColor);
  connect(d, SIGNAL(currentColorChanged(QColor)), this, SLOT(setColor(const QColor&)));
  connect(d, SIGNAL(currentColorChanged(QColor)), this, SIGNAL(colorChanged(QColor)));
  if(d->exec()!=QDialog::Accepted) {
    setColor(originalColor);
    emit colorChanged(originalColor);
  }
  delete d;
}

} // namespace QGpGuiTools
