1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
/* ============================================================
 *
 * This file is a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2004-12-01
 * Description : a widget to draw histogram curves
 *
 * SPDX-FileCopyrightText: 2004-2024 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * ============================================================ */

#include "curveswidget.h"

// C++ includes

#include <cmath>
#include <cstdlib>

// Qt includes

#include <QPixmap>
#include <QPainter>
#include <QPoint>
#include <QPen>
#include <QTimer>
#include <QRect>
#include <QColor>
#include <QFont>
#include <QFontMetrics>
#include <QPainterPath>

// KDE includes

#include <kconfiggroup.h>
#include <klocalizedstring.h>

// Local includes

#include "dlayoutbox.h"
#include "dimg.h"
#include "imagehistogram.h"
#include "imagecurves.h"
#include "digikam_debug.h"
#include "histogrampainter.h"
#include "dworkingpixmap.h"

namespace Digikam
{

class Q_DECL_HIDDEN CurvesWidget::Private
{
public:

    enum RepaintType
    {
        HistogramDataLoading = 0, ///< Image Data loading in progress.
        HistogramNone,            ///< No current histogram values calculation.
        HistogramStarted,         ///< Histogram values calculation started.
        HistogramCompleted,       ///< Histogram values calculation completed.
        HistogramFailed           ///< Histogram values calculation failed.
    };

public:

    explicit Private(CurvesWidget* const qq)
        : q(qq)
    {
    }

    bool                           readOnlyMode     = false;
    bool                           guideVisible     = false;

    int                            clearFlag        = HistogramNone;        // Clear drawing zone with message.
    int                            leftMost         = 0;
    int                            rightMost        = 0;
    int                            grabPoint        = -1;
    int                            last             = 0;
    int                            xMouseOver       = -1;
    int                            yMouseOver       = -1;
    int                            progressCount    = 0;                    // Position of animation during loading/calculation.
    ChannelType                    channelType      = LuminosityChannel;    // Channel type to draw
    HistogramScale                 scaleType        = LinScaleHistogram;    // Scale to use for drawing
    ImageHistogram*                imageHistogram   = nullptr;              // Full image

    QTimer*                        progressTimer    = nullptr;

    DWorkingPixmap*                progressPix      = nullptr;

    DColor                         colorGuide;

    ImageCurves*                   curves           = nullptr;              // Curves data instance.

    HistogramPainter*              histogramPainter = nullptr;

private:

    CurvesWidget*                  q                = nullptr;

public:

    // --- misc methods ---

    int getDelta() const
    {
        // TODO magic number, what is this?

        return imageHistogram->getHistogramSegments() / 16;
    }

    void getHistogramCoordinates(const QPoint& mousePosition, int& x, int& y, int& closestPoint)
    {
        x = CLAMP((int)(mousePosition.x() *
                        ((float)(imageHistogram->getMaxSegmentIndex()) / (float)q->width())),
                  0, imageHistogram->getMaxSegmentIndex());
        y = CLAMP((int)(mousePosition.y() *
                        ((float)(imageHistogram->getMaxSegmentIndex()) / (float)q->height())),
                  0, imageHistogram->getMaxSegmentIndex());

        int distance = NUM_SEGMENTS_16BIT;

        closestPoint = 0;

        for (int i = 0 ; i < ImageCurves::NUMBER_OF_POINTS ; ++i)
        {
            int xcurvepoint = curves->getCurvePointX(channelType, i);

            if (xcurvepoint != -1)
            {
                if (abs(x - xcurvepoint) < distance)
                {
                    distance     = abs(x - xcurvepoint);
                    closestPoint = i;
                }
            }
        }

        // TODO magic number, what is this?

        if (distance > 8)
        {
            closestPoint = (x + getDelta() / 2) / getDelta();
        }
    }

    // --- rendering ---

    void renderLoadingAnimation()
    {

        QPixmap anim(progressPix->frameAt(progressCount));
        ++progressCount;

        if (progressCount >= progressPix->frameCount())
        {
            progressCount = 0;
        }

        // ... and we render busy text.

        QPainter p1(q);
        p1.fillRect(0, 0, q->width(), q->height(), q->palette().color(QPalette::Active, QPalette::Window));
        p1.setPen(QPen(q->palette().color(QPalette::Active, QPalette::WindowText), 1, Qt::SolidLine));
        p1.drawRect(0, 0, q->width() - 1, q->height() - 1);
        p1.drawPixmap(q->width() / 2 - anim.width() / 2, anim.height(), anim);
        p1.setPen(q->palette().color(QPalette::Active, QPalette::Text));

        if (clearFlag == Private::HistogramDataLoading)
        {
            p1.drawText(0, 0, q->width(), q->height(), Qt::AlignCenter,
                        i18n("Loading image..."));
        }
        else
        {
            p1.drawText(0, 0, q->width(), q->height(), Qt::AlignCenter,
                        i18n("Histogram calculation..."));
        }

        p1.end();
    }

    void renderHistogramFailed()
    {
        QPainter p1(q);
        p1.fillRect(0, 0, q->width(), q->height(), q->palette().color(QPalette::Active, QPalette::Window));
        p1.setPen(QPen(q->palette().color(QPalette::Active, QPalette::WindowText), 1, Qt::SolidLine));
        p1.drawRect(0, 0, q->width() - 1, q->height() - 1);
        p1.setPen(q->palette().color(QPalette::Active, QPalette::Text));
        p1.drawText(0, 0, q->width(), q->height(), Qt::AlignCenter,
                    i18n("Histogram\ncalculation\nfailed."));
        p1.end();
    }

    void renderCurve(QPixmap& pm)
    {
        QPainter p1;
        p1.begin(&pm);
        initPainterFromWidget(&p1);

        int wWidth  = pm.width();
        int wHeight = pm.height();

        // Drawing curves.

        QPainterPath curvePath;
        curvePath.moveTo(0, wHeight);

        for (int x = 0 ; x < wWidth ; ++x)
        {

            // TODO duplicate code...

            int i = (x * imageHistogram->getHistogramSegments()) / wWidth;

            int curveVal = curves->getCurveValue(channelType, i);
            curvePath.lineTo(x, wHeight - ((curveVal * wHeight) / imageHistogram->getHistogramSegments()));
        }

        curvePath.lineTo(wWidth, wHeight);

        p1.save();
        p1.setRenderHint(QPainter::Antialiasing);
        p1.setPen(QPen(q->palette().color(QPalette::Active, QPalette::Link), 2, Qt::SolidLine));
        p1.drawPath(curvePath);
        p1.restore();

        // Drawing curves points.

        if (!readOnlyMode && curves->getCurveType(channelType) == ImageCurves::CURVE_SMOOTH)
        {
            p1.save();
            p1.setPen(QPen(Qt::red, 3, Qt::SolidLine));
            p1.setRenderHint(QPainter::Antialiasing);

            for (int p = 0 ; p < ImageCurves::NUMBER_OF_POINTS ; ++p)
            {
                QPoint curvePoint = curves->getCurvePoint(channelType, p);

                if (curvePoint.x() >= 0)
                {
                    p1.drawEllipse(((curvePoint.x() * wWidth) / imageHistogram->getHistogramSegments()) - 2,
                                   wHeight - 2 - ((curvePoint.y() * wHeight) / imageHistogram->getHistogramSegments()),
                                   4, 4);
                }
            }

            p1.restore();
        }
    }

    void renderGrid(QPixmap& pm)
    {
        QPainter p1;
        p1.begin(&pm);
        initPainterFromWidget(&p1);

        int wWidth  = pm.width();
        int wHeight = pm.height();

        // Drawing black/middle/highlight tone grid separators.

        p1.setPen(QPen(q->palette().color(QPalette::Active, QPalette::Base), 1, Qt::SolidLine));
        p1.drawLine(wWidth / 4, 0, wWidth / 4, wHeight);
        p1.drawLine(wWidth / 2, 0, wWidth / 2, wHeight);
        p1.drawLine(3 * wWidth / 4, 0, 3 * wWidth / 4, wHeight);
        p1.drawLine(0, wHeight / 4, wWidth, wHeight / 4);
        p1.drawLine(0, wHeight / 2, wWidth, wHeight / 2);
        p1.drawLine(0, 3 * wHeight / 4, wWidth, 3 * wHeight / 4);
    }

    void renderMousePosition(QPixmap& pm)
    {
        QPainter p1;
        p1.begin(&pm);
        initPainterFromWidget(&p1);

        int wWidth  = pm.width();
        int wHeight = pm.height();

        // Drawing X,Y point position dragged by mouse over widget.

        p1.setPen(QPen(Qt::red, 1, Qt::DotLine));

        if ((xMouseOver != -1) && (yMouseOver != -1))
        {
            QString string = i18n("x:%1\ny:%2", xMouseOver, yMouseOver);
            QFontMetrics fontMt(string);
            QRect rect     = fontMt.boundingRect(0, 0, wWidth, wHeight, 0, string);
            rect.moveRight(wWidth);
            rect.moveBottom(wHeight);
            p1.drawText(rect, Qt::AlignLeft | Qt::AlignTop, string);
        }
    }

    void renderFrame(QPixmap& pm)
    {
        QPainter p1;
        p1.begin(&pm);
        initPainterFromWidget(&p1);

        p1.setPen(QPen(q->palette().color(QPalette::Active,
                                          QPalette::WindowText), 1, Qt::SolidLine));
        p1.drawRect(0, 0, pm.width() - 1, pm.height() - 1);
    }

    void initPainterFromWidget(QPainter* const p)
    {
        if (!p || !q)
        {
            return;
        }

        const QPalette& pal = q->palette();
        p->setPen(QPen(pal.brush(q->foregroundRole()), 0));
        p->setBackground(pal.brush(q->backgroundRole()));
        p->setFont(q->font());
    }

    // --- patterns for storing / restoring state ---

    static QString getChannelTypeOption(const QString& prefix, int channel)
    {
        return QString(prefix + QString::fromLatin1("Channel%1Type")).arg(channel);
    }

    static QString getPointOption(const QString& prefix, int channel, int point)
    {
        return QString(prefix + QString::fromLatin1("Channel%1Point%2")).arg(channel).arg(point);
    }
};

CurvesWidget::CurvesWidget(int w, int h, QWidget* const parent, bool readOnly)
    : QWidget(parent),
      d      (new Private(this))
{
    setAttribute(Qt::WA_DeleteOnClose);
    setup(w, h, readOnly);
}

CurvesWidget::~CurvesWidget()
{
    d->progressTimer->stop();

    delete d->imageHistogram;
    delete d->curves;
    delete d;
}

void CurvesWidget::setup(int w, int h, bool readOnly)
{
    d->progressPix      = new DWorkingPixmap(this);
    d->readOnlyMode     = readOnly;
    d->curves           = new ImageCurves(true);
    d->histogramPainter = new HistogramPainter(this);
    d->histogramPainter->setChannelType(LuminosityChannel);
    d->histogramPainter->setRenderXGrid(false);
    d->histogramPainter->setHighlightSelection(false);
    d->histogramPainter->initFrom(this);
    d->channelType      = LuminosityChannel;
    d->scaleType        = LogScaleHistogram;
    d->imageHistogram   = nullptr;

    setMouseTracking(true);
    setMinimumSize(w, h);

    d->progressTimer = new QTimer(this);

    connect(d->progressTimer, SIGNAL(timeout()),
            this, SLOT(slotProgressTimerDone()));
}

void CurvesWidget::saveCurve(KConfigGroup& group, const QString& prefix)
{
    qCDebug(DIGIKAM_DIMG_LOG) << "Storing curves";

    for (int channel = 0 ; channel < ImageCurves::NUM_CHANNELS ; ++channel)
    {

        group.writeEntry(Private::getChannelTypeOption(prefix, channel),
                         (int) curves()->getCurveType(channel));

        for (int point = 0 ; point <= ImageCurves::NUMBER_OF_POINTS ; ++point)
        {
            QPoint p = curves()->getCurvePoint(channel, point);

            if (!isSixteenBits() && (p != ImageCurves::getDisabledValue()))
            {
                // Store point as 16 bits depth.

                p.setX(p.x() * ImageCurves::MULTIPLIER_16BIT);
                p.setY(p.y() * ImageCurves::MULTIPLIER_16BIT);
            }

            group.writeEntry(Private::getPointOption(prefix, channel, point), p);
        }
    }
}

void CurvesWidget::restoreCurve(KConfigGroup& group, const QString& prefix)<--- Parameter 'group' can be declared as reference to const
{
    qCDebug(DIGIKAM_DIMG_LOG) << "Restoring curves";

    reset();

    qCDebug(DIGIKAM_DIMG_LOG) << "curves " << curves() << " isSixteenBits = " << isSixteenBits();

    for (int channel = 0 ; channel < ImageCurves::NUM_CHANNELS ; ++channel)
    {

        curves()->setCurveType(channel, (ImageCurves::CurveType) group.readEntry(
                                   Private::getChannelTypeOption(
                                       prefix, channel), 0));

        for (int point = 0 ; point <= ImageCurves::NUMBER_OF_POINTS ; ++point)
        {
            QPoint p = group.readEntry(Private::getPointOption(prefix,
                                                               channel, point),
                                                               ImageCurves::getDisabledValue());

            // always load a 16 bit curve and stretch it to 8 bit if necessary

            if (!isSixteenBits() && (p != ImageCurves::getDisabledValue()))
            {
                p.setX(p.x() / ImageCurves::MULTIPLIER_16BIT);
                p.setY(p.y() / ImageCurves::MULTIPLIER_16BIT);
            }

            curves()->setCurvePoint(channel, point, p);
        }

        curves()->curvesCalculateCurve(channel);
    }
}

void CurvesWidget::updateData(const DImg& img)
{
    qCDebug(DIGIKAM_DIMG_LOG) << "updating data";

    stopHistogramComputation();

    // Remove old histogram data from memory.

    delete d->imageHistogram;
    d->imageHistogram = new ImageHistogram(img);

    connect(d->imageHistogram, SIGNAL(calculationStarted()),
            this, SLOT(slotCalculationStarted()));

    connect(d->imageHistogram, SIGNAL(calculationFinished(bool)),
            this, SLOT(slotCalculationFinished(bool)));

    d->imageHistogram->calculateInThread();

    // keep the old curve

    ImageCurves* const newCurves = new ImageCurves(img.sixteenBit());
    newCurves->setCurveType(ImageCurves::CURVE_SMOOTH);

    if (d->curves)
    {
        newCurves->fillFromOtherCurves(d->curves);
        delete d->curves;
    }

    d->curves = newCurves;

    resetUI();
}

bool CurvesWidget::isSixteenBits() const
{
    return curves()->isSixteenBits();
}

void CurvesWidget::reset()
{
    if (d->curves)
    {
        d->curves->curvesReset();
    }

    resetUI();
}

void CurvesWidget::resetUI()
{
    d->grabPoint    = -1;
    d->guideVisible = false;
    update();
}

ImageCurves* CurvesWidget::curves() const
{
    return d->curves;
}

void CurvesWidget::setDataLoading()
{
    if (d->clearFlag != Private::HistogramDataLoading)
    {
        setCursor(Qt::WaitCursor);
        d->clearFlag     = Private::HistogramDataLoading;
        d->progressCount = 0;
        d->progressTimer->start(100);
    }
}

void CurvesWidget::setLoadingFailed()
{
    d->clearFlag     = Private::HistogramFailed;
    d->progressCount = 0;
    d->progressTimer->stop();
    update();
    setCursor(Qt::ArrowCursor);
}

void CurvesWidget::setCurveGuide(const DColor& color)
{
    d->guideVisible = true;
    d->colorGuide   = color;
    update();
}

void CurvesWidget::curveTypeChanged()
{
    switch (d->curves->getCurveType(d->channelType))
    {
        case ImageCurves::CURVE_SMOOTH:
        {
            //  pick representative points from the curve and make them control points

            int index;

            for (int i = 0 ; i <= 16 ; ++i)
            {
                index = CLAMP(i * d->imageHistogram->getHistogramSegments() / 16, 0, d->imageHistogram->getMaxSegmentIndex());
                d->curves->setCurvePoint(d->channelType, i, QPoint(index, d->curves->getCurveValue(d->channelType, index)));
            }

            d->curves->curvesCalculateCurve(d->channelType);
            break;
        }

        case ImageCurves::CURVE_FREE:
        {
            break;
        }
    }

    update();
    Q_EMIT signalCurvesChanged();
}

void CurvesWidget::slotCalculationStarted()
{
    setCursor(Qt::WaitCursor);
    d->clearFlag = Private::HistogramStarted;
    d->progressTimer->start(200);
    update();
}

void CurvesWidget::slotCalculationFinished(bool success)
{
    if (success)
    {
        // Repaint histogram

        d->clearFlag = Private::HistogramCompleted;
        d->progressTimer->stop();
        update();
        setCursor(Qt::ArrowCursor);
    }
    else
    {
        d->clearFlag = Private::HistogramFailed;
        d->progressTimer->stop();
        update();
        setCursor(Qt::ArrowCursor);

        Q_EMIT signalHistogramComputationFailed();
    }
}

void CurvesWidget::stopHistogramComputation()
{
    if (d->imageHistogram)
    {
        d->imageHistogram->stopCalculation();
    }

    d->progressTimer->stop();
    d->progressCount = 0;
}

void CurvesWidget::slotProgressTimerDone()
{
    update();
    d->progressTimer->start(200);
}

void CurvesWidget::paintEvent(QPaintEvent*)
{
    // special cases

    if      (d->clearFlag == Private::HistogramDataLoading ||
             d->clearFlag == Private::HistogramStarted)
    {
        d->renderLoadingAnimation();

        return;
    }
    else if (d->clearFlag == Private::HistogramFailed)
    {
        d->renderHistogramFailed();

        return;
    }

    // normal case, histogram present

    if (!d->imageHistogram)
    {
        qCWarning(DIGIKAM_DIMG_LOG) << "Should render a histogram, but did not get one.";

        return;
    }

    // render subelements on a pixmap (double buffering)

    QPixmap pm(size());

    d->histogramPainter->setScale(d->scaleType);
    d->histogramPainter->setHistogram(d->imageHistogram);
    d->histogramPainter->setChannelType(d->channelType);

    if (d->guideVisible)
    {
        d->histogramPainter->enableHistogramGuideByColor(d->colorGuide);
    }
    else
    {
        d->histogramPainter->disableHistogramGuide();
    }

    d->histogramPainter->render(pm);
    d->renderCurve(pm);
    d->renderGrid(pm);
    d->renderMousePosition(pm);
    d->renderFrame(pm);

    // render pixmap on widget

    QPainter p2(this);
    p2.drawPixmap(0, 0, pm);
    p2.end();
}

void CurvesWidget::mousePressEvent(QMouseEvent* e)
{
    if (d->readOnlyMode || !d->imageHistogram)
    {
        return;
    }

    if (d->clearFlag == Private::HistogramStarted)
    {
        return;
    }

    int x, y, closest_point;
    d->getHistogramCoordinates(e->pos(), x, y, closest_point);

    setCursor(Qt::CrossCursor);

    switch (d->curves->getCurveType(d->channelType))
    {
        case ImageCurves::CURVE_SMOOTH:
        {
            // Determine the leftmost and rightmost points.

            d->leftMost = -1;

            for (int i = closest_point - 1 ; i >= 0 ; --i)
            {
                if (d->curves->getCurvePointX(d->channelType, i) != -1)
                {
                    d->leftMost = d->curves->getCurvePointX(d->channelType, i);
                    break;
                }
            }

            d->rightMost = d->imageHistogram->getHistogramSegments();

            for (int i = closest_point + 1 ; i < ImageCurves::NUMBER_OF_POINTS ; ++i)
            {
                if (d->curves->getCurvePointX(d->channelType, i) != -1)
                {
                    d->rightMost = d->curves->getCurvePointX(d->channelType, i);
                    break;
                }
            }

            d->grabPoint = closest_point;

            if      (e->button() == Qt::LeftButton)
            {
                d->curves->setCurvePoint(d->channelType, d->grabPoint,
                                         QPoint(x, d->imageHistogram->getHistogramSegments() - y));

            }
            else if (e->button() == Qt::RightButton)
            {
                int interval = x - d->curves->getCurvePointX(d->channelType, closest_point);

                if (interval <= 3 && interval >= -3)
                {
                    d->curves->unsetCurvePoint(d->channelType, closest_point);
                }
            }

            break;
        }

        case ImageCurves::CURVE_FREE:
        {
            d->curves->setCurveValue(d->channelType, x, d->imageHistogram->getHistogramSegments() - y);
            d->grabPoint = x;
            d->last      = y;
            break;
        }
    }

    d->curves->curvesCalculateCurve(d->channelType);
    Q_EMIT signalCurvesChanged();
    update();
}

void CurvesWidget::mouseReleaseEvent(QMouseEvent* e)
{
    if (d->readOnlyMode || !d->imageHistogram)
    {
        return;
    }

    if (((e->button() == Qt::LeftButton)          &&
         (e->button() == Qt::RightButton))        ||
        d->clearFlag == Private::HistogramStarted)
    {
        return;
    }

    setCursor(Qt::ArrowCursor);
    d->grabPoint = -1;
}

void CurvesWidget::mouseMoveEvent(QMouseEvent* e)
{
    if (d->readOnlyMode || !d->imageHistogram)
    {
        return;
    }

    if ((e->buttons() == Qt::RightButton) ||
        (d->clearFlag == Private::HistogramStarted))
    {
        return;
    }

    int x, y, closest_point;
    d->getHistogramCoordinates(e->pos(), x, y, closest_point);

    switch (d->curves->getCurveType(d->channelType))
    {
        case ImageCurves::CURVE_SMOOTH:
        {
            if (d->grabPoint == -1)   // If no point is grabbed...
            {
                if (d->curves->getCurvePointX(d->channelType, closest_point) != -1)
                {
                    setCursor(Qt::ArrowCursor);
                }
                else
                {
                    setCursor(Qt::CrossCursor);
                }
            }
            else                      // Else, drag the grabbed point
            {
                setCursor(Qt::CrossCursor);

                d->curves->setCurvePointX(d->channelType, d->grabPoint, -1);

                if (x > d->leftMost && x < d->rightMost)
                {
                    closest_point = (x + d->getDelta() / 2) / d->getDelta();

                    if (d->curves->getCurvePointX(d->channelType, closest_point) == -1)
                    {
                        d->grabPoint = closest_point;
                    }

                    d->curves->setCurvePoint(d->channelType, d->grabPoint,
                                             QPoint(x, d->imageHistogram->getMaxSegmentIndex() - y));
                }

                d->curves->curvesCalculateCurve(d->channelType);

                Q_EMIT signalCurvesChanged();
            }

            break;
        }

        case ImageCurves::CURVE_FREE:
        {
            if (d->grabPoint != -1)
            {
                int x1, x2, y1, y2;

                if (d->grabPoint > x)
                {
                    x1 = x;
                    x2 = d->grabPoint;
                    y1 = y;
                    y2 = d->last;
                }
                else
                {
                    x1 = d->grabPoint;
                    x2 = x;
                    y1 = d->last;
                    y2 = y;
                }

                if (x2 != x1)
                {
                    for (int i = x1 ; i <= x2 ; ++i)
                        d->curves->setCurveValue(d->channelType, i, d->imageHistogram->getMaxSegmentIndex() -
                                                 (y1 + ((y2 - y1) * (i - x1)) / (x2 - x1)));
                }
                else
                {
                    d->curves->setCurveValue(d->channelType, x, d->imageHistogram->getMaxSegmentIndex() - y);
                }

                d->grabPoint = x;
                d->last      = y;

                Q_EMIT signalCurvesChanged();
            }

            break;
        }
    }

    d->xMouseOver = x;
    d->yMouseOver = d->imageHistogram->getMaxSegmentIndex() - y;

    Q_EMIT signalMouseMoved(d->xMouseOver, d->yMouseOver);

    update();
}

void CurvesWidget::leaveEvent(QEvent*)
{
    d->xMouseOver = -1;
    d->yMouseOver = -1;

    Q_EMIT signalMouseMoved(d->xMouseOver, d->yMouseOver);

    update();
}

void CurvesWidget::setChannelType(ChannelType channel)
{
    d->channelType = channel;
    update();
}

void CurvesWidget::setScaleType(HistogramScale scale)
{
    d->scaleType = scale;
    update();
}

} // namespace Digikam

#include "moc_curveswidget.cpp"