/* ============================================================
 *
 * This file is a part of digiKam project
 * http://www.digikam.org
 *
 * Date        : 2004-06-05
 * Description : digiKam image editor to adjust Brightness, 
                 Contrast, and Gamma of picture.
 *
 * Copyright (C) 2004 by Renchi Raju <renchi@pooh.tam.uiuc.edu>
 * Copyright (C) 2005-2007 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * This program is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General
 * Public License as published by the Free Software Foundation;
 * either version 2, or (at your option)
 * any later version.
 * 
 * This program 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 General Public License for more details.
 * 
 * ============================================================ */

// TQt includes.
 
#include <tqcolor.h>
#include <tqgroupbox.h>
#include <tqhgroupbox.h>
#include <tqvgroupbox.h>
#include <tqhbuttongroup.h> 
#include <tqlabel.h>
#include <tqvbox.h>
#include <tqlayout.h>
#include <tqframe.h>
#include <tqlabel.h>
#include <tqpushbutton.h>
#include <tqcheckbox.h>
#include <tqcombobox.h>
#include <tqwhatsthis.h>
#include <tqtooltip.h>

// KDE includes.

#include <knuminput.h>
#include <tdelocale.h>
#include <tdeapplication.h>
#include <tdeconfig.h>
#include <kcursor.h>
#include <tdestandarddirs.h>

// Digikam includes.

#include "imageiface.h"
#include "imagewidget.h"
#include "histogramwidget.h"
#include "colorgradientwidget.h"
#include "bcgmodifier.h"
#include "dimg.h"

// Local includes.

#include "imageeffect_bcg.h"
#include "imageeffect_bcg.moc"

namespace DigikamImagesPluginCore
{

ImageEffect_BCG::ImageEffect_BCG(TQWidget* parent)
               : Digikam::ImageDlgBase(parent, i18n("Brightness Contrast Gamma Adjustments"), 
                                       "bcgadjust", false)
{
    m_destinationPreviewData = 0L;
    setHelp("bcgadjusttool.anchor", "digikam");

    m_previewWidget = new Digikam::ImageWidget("bcgadjust Tool Dialog", plainPage(),
                                               i18n("<p>Here you can see the image "
                                               "brightness-contrast-gamma adjustments preview. "
                                               "You can pick color on image "
                                               "to see the color level corresponding on histogram."));
    setPreviewAreaWidget(m_previewWidget); 

    // -------------------------------------------------------------
                
    TQWidget *gboxSettings     = new TQWidget(plainPage());
    TQGridLayout* gridSettings = new TQGridLayout( gboxSettings, 9, 4, spacingHint());

    TQLabel *label1 = new TQLabel(i18n("Channel:"), gboxSettings);
    label1->setAlignment ( TQt::AlignRight | TQt::AlignVCenter );
    m_channelCB = new TQComboBox( false, gboxSettings );
    m_channelCB->insertItem( i18n("Luminosity") );
    m_channelCB->insertItem( i18n("Red") );
    m_channelCB->insertItem( i18n("Green") );
    m_channelCB->insertItem( i18n("Blue") );
    TQWhatsThis::add( m_channelCB, i18n("<p>Select the histogram channel to display here:<p>"
                                       "<b>Luminosity</b>: display the image's luminosity values.<p>"
                                       "<b>Red</b>: display the red image-channel values.<p>"
                                       "<b>Green</b>: display the green image-channel values.<p>"
                                       "<b>Blue</b>: display the blue image-channel values.<p>"));

    m_scaleBG = new TQHButtonGroup(gboxSettings);
    m_scaleBG->setExclusive(true);
    m_scaleBG->setFrameShape(TQFrame::NoFrame);
    m_scaleBG->setInsideMargin( 0 );
    TQWhatsThis::add( m_scaleBG, i18n("<p>Select the histogram scale here.<p>"
                                     "If the image's maximal counts are small, you can use the linear scale.<p>"
                                     "Logarithmic scale can be used when the maximal counts are big; "
                                     "if it is used, all values (small and large) will be visible on the graph."));
    
    TQPushButton *linHistoButton = new TQPushButton( m_scaleBG );
    TQToolTip::add( linHistoButton, i18n( "<p>Linear" ) );
    m_scaleBG->insert(linHistoButton, Digikam::HistogramWidget::LinScaleHistogram);
    TDEGlobal::dirs()->addResourceType("histogram-lin", TDEGlobal::dirs()->kde_default("data") + "digikam/data");
    TQString directory = TDEGlobal::dirs()->findResourceDir("histogram-lin", "histogram-lin.png");
    linHistoButton->setPixmap( TQPixmap( directory + "histogram-lin.png" ) );
    linHistoButton->setToggleButton(true);
    
    TQPushButton *logHistoButton = new TQPushButton( m_scaleBG );
    TQToolTip::add( logHistoButton, i18n( "<p>Logarithmic" ) );
    m_scaleBG->insert(logHistoButton, Digikam::HistogramWidget::LogScaleHistogram);
    TDEGlobal::dirs()->addResourceType("histogram-log", TDEGlobal::dirs()->kde_default("data") + "digikam/data");
    directory = TDEGlobal::dirs()->findResourceDir("histogram-log", "histogram-log.png");
    logHistoButton->setPixmap( TQPixmap( directory + "histogram-log.png" ) );
    logHistoButton->setToggleButton(true);       

    TQHBoxLayout* l1 = new TQHBoxLayout();
    l1->addWidget(label1);
    l1->addWidget(m_channelCB);
    l1->addStretch(10);
    l1->addWidget(m_scaleBG);
    
    gridSettings->addMultiCellLayout(l1, 0, 0, 0, 4);

    // -------------------------------------------------------------

    TQVBox *histoBox   = new TQVBox(gboxSettings);
    m_histogramWidget = new Digikam::HistogramWidget(256, 140, histoBox, false, true, true);
    TQWhatsThis::add( m_histogramWidget, i18n("<p>Here you can see the target preview image histogram drawing "
                                             "of the selected image channel. This one is re-computed at any "
                                             "settings changes."));
    TQLabel *space = new TQLabel(histoBox);
    space->setFixedHeight(1);
    m_hGradient = new Digikam::ColorGradientWidget( Digikam::ColorGradientWidget::Horizontal, 10, histoBox );
    m_hGradient->setColors( TQColor( "black" ), TQColor( "white" ) );
    
    gridSettings->addMultiCellWidget(histoBox, 1, 2, 0, 4);

    // -------------------------------------------------------------

    TQLabel *label2 = new TQLabel(i18n("Brightness:"), gboxSettings);
    m_bInput       = new KIntNumInput(gboxSettings);
    m_bInput->setRange(-100, 100, 1, true);
    m_bInput->setValue(0);
    TQWhatsThis::add( m_bInput, i18n("<p>Set here the brightness adjustment of the image."));
    gridSettings->addMultiCellWidget(label2, 3, 3, 0, 4);
    gridSettings->addMultiCellWidget(m_bInput, 4, 4, 0, 4);

    TQLabel *label3 = new TQLabel(i18n("Contrast:"), gboxSettings);
    m_cInput       = new KIntNumInput(gboxSettings);
    m_cInput->setRange(-100, 100, 1, true);
    m_cInput->setValue(0);
    TQWhatsThis::add( m_cInput, i18n("<p>Set here the contrast adjustment of the image."));
    gridSettings->addMultiCellWidget(label3, 5, 5, 0, 4);
    gridSettings->addMultiCellWidget(m_cInput, 6, 6, 0, 4);

    TQLabel *label4 = new TQLabel(i18n("Gamma:"), gboxSettings);
    m_gInput = new KDoubleNumInput(gboxSettings);
    m_gInput->setPrecision(2);
    m_gInput->setRange(0.1, 3.0, 0.01, true);
    m_gInput->setValue(1.0);
    TQWhatsThis::add( m_gInput, i18n("<p>Set here the gamma adjustment of the image."));
    gridSettings->addMultiCellWidget(label4, 7, 7, 0, 4);
    gridSettings->addMultiCellWidget(m_gInput, 8, 8, 0, 4);

    gridSettings->setRowStretch(9, 10);    
    setUserAreaWidget(gboxSettings);
    
    // -------------------------------------------------------------

    connect(m_channelCB, TQ_SIGNAL(activated(int)),
            this, TQ_SLOT(slotChannelChanged(int)));

    connect(m_scaleBG, TQ_SIGNAL(released(int)),
            this, TQ_SLOT(slotScaleChanged(int)));

    connect(m_previewWidget, TQ_SIGNAL(spotPositionChangedFromTarget( const Digikam::DColor &, const TQPoint & )),
            this, TQ_SLOT(slotColorSelectedFromTarget( const Digikam::DColor & )));

    connect(m_bInput, TQ_SIGNAL(valueChanged(int)),
            this, TQ_SLOT(slotTimer()));                        
            
    connect(m_cInput, TQ_SIGNAL(valueChanged(int)),
            this, TQ_SLOT(slotTimer()));                        
            
    connect(m_gInput, TQ_SIGNAL(valueChanged(double)),
            this, TQ_SLOT(slotTimer()));                        

    connect(m_previewWidget, TQ_SIGNAL(signalResized()),
            this, TQ_SLOT(slotEffect()));    
            
    // -------------------------------------------------------------
                
    enableButtonOK( false );
}

ImageEffect_BCG::~ImageEffect_BCG()
{
    m_histogramWidget->stopHistogramComputation();

    if (m_destinationPreviewData) 
       delete [] m_destinationPreviewData;
       
    delete m_histogramWidget;
    delete m_previewWidget;
}

void ImageEffect_BCG::slotChannelChanged(int channel)
{
    switch(channel)
    {
        case LuminosityChannel:
            m_histogramWidget->m_channelType = Digikam::HistogramWidget::ValueHistogram;
            m_hGradient->setColors( TQColor( "black" ), TQColor( "white" ) );
            break;
    
        case RedChannel:
            m_histogramWidget->m_channelType = Digikam::HistogramWidget::RedChannelHistogram;
            m_hGradient->setColors( TQColor( "black" ), TQColor( "red" ) );
            break;
    
        case GreenChannel:         
            m_histogramWidget->m_channelType = Digikam::HistogramWidget::GreenChannelHistogram;
            m_hGradient->setColors( TQColor( "black" ), TQColor( "green" ) );
            break;
    
        case BlueChannel:         
            m_histogramWidget->m_channelType = Digikam::HistogramWidget::BlueChannelHistogram;
            m_hGradient->setColors( TQColor( "black" ), TQColor( "blue" ) );
            break;
    }

    m_histogramWidget->repaint(false);
}

void ImageEffect_BCG::slotScaleChanged(int scale)
{
    m_histogramWidget->m_scaleType = scale;
    m_histogramWidget->repaint(false);
}

void ImageEffect_BCG::slotColorSelectedFromTarget( const Digikam::DColor &color )
{
    m_histogramWidget->setHistogramGuideByColor(color);
}

void ImageEffect_BCG::readUserSettings()
{
    TDEConfig* config = tdeApp->config();
    config->setGroup("bcgadjust Tool Dialog");
    m_channelCB->setCurrentItem(config->readNumEntry("Histogram Channel", 0));    // Luminosity.
    m_scaleBG->setButton(config->readNumEntry("Histogram Scale", Digikam::HistogramWidget::LogScaleHistogram));
    m_bInput->setValue(config->readNumEntry("BrightnessAjustment", 0));
    m_cInput->setValue(config->readNumEntry("ContrastAjustment", 0));
    m_gInput->setValue(config->readDoubleNumEntry("GammaAjustment", 1.0));
    slotChannelChanged(m_channelCB->currentItem());
    slotScaleChanged(m_scaleBG->selectedId());
}

void ImageEffect_BCG::writeUserSettings()
{
    TDEConfig* config = tdeApp->config();
    config->setGroup("bcgadjust Tool Dialog");
    config->writeEntry("Histogram Channel", m_channelCB->currentItem());
    config->writeEntry("Histogram Scale", m_scaleBG->selectedId());
    config->writeEntry("BrightnessAjustment", m_bInput->value());
    config->writeEntry("ContrastAjustment", m_cInput->value());
    config->writeEntry("GammaAjustment", m_gInput->value());
    config->sync();
}

void ImageEffect_BCG::resetValues()
{
    m_bInput->blockSignals(true);	
    m_cInput->blockSignals(true);	
    m_gInput->blockSignals(true);	
    m_bInput->setValue(0);
    m_cInput->setValue(0);
    m_gInput->setValue(1.0);
    m_bInput->blockSignals(false);	
    m_cInput->blockSignals(false);	
    m_gInput->blockSignals(false);	
} 

void ImageEffect_BCG::slotEffect()
{
    tdeApp->setOverrideCursor( KCursor::waitCursor() );

    double b = (double)m_bInput->value()/250.0;
    double c = (double)(m_cInput->value()/100.0) + 1.00;    
    double g = m_gInput->value();

    enableButtonOK( b != 0.0 || c != 1.0 || g != 1.0 );
    
    m_histogramWidget->stopHistogramComputation();

    if (m_destinationPreviewData) 
       delete [] m_destinationPreviewData;

    Digikam::ImageIface* iface = m_previewWidget->imageIface();
    m_destinationPreviewData   = iface->getPreviewImage();
    int w                      = iface->previewWidth();
    int h                      = iface->previewHeight();
    bool a                     = iface->previewHasAlpha();
    bool sb                    = iface->previewSixteenBit();

    Digikam::DImg preview(w, h, sb, a, m_destinationPreviewData);
    Digikam::BCGModifier cmod;
    cmod.setGamma(g);
    cmod.setBrightness(b);
    cmod.setContrast(c);
    cmod.applyBCG(preview);
    iface->putPreviewImage(preview.bits());

    m_previewWidget->updatePreview();

    // Update histogram.
   
    memcpy(m_destinationPreviewData, preview.bits(), preview.numBytes());
    m_histogramWidget->updateData(m_destinationPreviewData, w, h, sb, 0, 0, 0, false);

    tdeApp->restoreOverrideCursor();
}

void ImageEffect_BCG::finalRendering()
{
    tdeApp->setOverrideCursor( KCursor::waitCursor() );
    Digikam::ImageIface* iface = m_previewWidget->imageIface();

    double b = (double)m_bInput->value()/250.0;
    double c = (double)(m_cInput->value()/100.0) + 1.00;    
    double g = m_gInput->value();

    iface->setOriginalBCG(b, c, g);
    tdeApp->restoreOverrideCursor();
    accept();
}

}  // NameSpace DigikamImagesPluginCore

