summaryrefslogtreecommitdiffstats
path: root/src/imageplugins/adjustlevels/adjustlevels.cpp
blob: 72d5e46b03af98a6f2a0e08300d96eb3e58bd126 (plain)
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
/* ============================================================
 *
 * This file is a part of digiKam project
 * http://www.digikam.org
 *
 * Date        : 2004-07-20
 * Description : image histogram adjust levels.
 *
 * Copyright (C) 2004-2008 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.
 *
 * ============================================================ */

// C++ includes.

#include <cmath>

// TQt includes.

#include <tqlayout.h>
#include <tqcolor.h>
#include <tqgroupbox.h>
#include <tqhgroupbox.h>
#include <tqvgroupbox.h>
#include <tqlabel.h>
#include <tqpainter.h>
#include <tqcombobox.h>
#include <tqspinbox.h>
#include <tqwhatsthis.h>
#include <tqtooltip.h>
#include <tqpushbutton.h>
#include <tqlayout.h>
#include <tqframe.h>
#include <tqtimer.h>
#include <tqhbuttongroup.h> 
#include <tqpixmap.h>

// KDE includes.

#include <tdeconfig.h>
#include <kcursor.h>
#include <tdelocale.h>
#include <knuminput.h>
#include <tdemessagebox.h>
#include <tdeselect.h>
#include <tdefiledialog.h>
#include <tdeglobalsettings.h>
#include <tdeaboutdata.h>
#include <khelpmenu.h>
#include <kiconloader.h>
#include <tdeapplication.h>
#include <tdepopupmenu.h>
#include <kstandarddirs.h>

// Local includes.

#include "version.h"
#include "ddebug.h"
#include "imageiface.h"
#include "imagewidget.h"
#include "imagehistogram.h"
#include "imagelevels.h"
#include "histogramwidget.h"
#include "dimgimagefilters.h"
#include "adjustlevels.h"
#include "adjustlevels.moc"

namespace DigikamAdjustLevelsImagesPlugin
{

AdjustLevelDialog::AdjustLevelDialog(TQWidget* parent)
                 : Digikam::ImageDlgBase(parent, i18n("Adjust Color Levels"), 
                   "adjustlevels", true, false)
{
    m_destinationPreviewData = 0L;

    Digikam::ImageIface iface(0, 0);
    uchar *data     = iface.getOriginalImage();
    int w           = iface.originalWidth();
    int h           = iface.originalHeight();
    bool sixteenBit = iface.originalSixteenBit();
    bool hasAlpha   = iface.originalHasAlpha();
    m_originalImage = Digikam::DImg(w, h, sixteenBit, hasAlpha ,data);
    delete [] data;

    m_histoSegments = m_originalImage.sixteenBit() ? 65535 : 255;
    m_levels = new Digikam::ImageLevels(m_originalImage.sixteenBit());

    // About data and help button.

    TDEAboutData* about = new TDEAboutData("digikam",
                                       I18N_NOOP("Adjust Color Levels"),
                                       digikam_version,
                                       I18N_NOOP("An image-histogram-levels adjustment plugin for digiKam."),
                                       TDEAboutData::License_GPL,
                                       "(c) 2004-2008, Gilles Caulier",
                                       0,
                                       "http://www.digikam.org");

    about->addAuthor("Gilles Caulier", I18N_NOOP("Author and maintainer"),
                     "caulier dot gilles at gmail dot com");

    setAboutData(about);

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

    m_previewWidget = new Digikam::ImageWidget("adjustlevels Tool Dialog", plainPage(),
                                               i18n("<p>Here you can see the image's "
                                                    "level-adjustments preview. You can pick a spot on the image "
                                                    "to see the corresponding level in the histogram."));
    setPreviewAreaWidget(m_previewWidget); 

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

    TQWidget *gboxSettings = new TQWidget(plainPage());
    TQGridLayout* grid     = new TQGridLayout(gboxSettings, 16, 8, spacingHint(), 0);

    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") );
    m_channelCB->insertItem( i18n("Alpha") );
    m_channelCB->setCurrentText( i18n("Luminosity") );
    TQWhatsThis::add( m_channelCB, i18n("<p>Here select the histogram channel to display:<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>"
                                       "<b>Alpha</b>: display the alpha image-channel values. "
                                       "This channel corresponds to the transparency value and "
                                       "is supported by some image formats, such as PNG or TIF."));

    m_scaleBG = new TQHButtonGroup(gboxSettings);
    m_scaleBG->setExclusive(true);
    m_scaleBG->setFrameShape(TQFrame::NoFrame);
    m_scaleBG->setInsideMargin( 0 );
    TQWhatsThis::add( m_scaleBG, i18n("<p>Here select the histogram scale.<p>"
                                     "If the image's maximal counts are small, you can use the linear scale.<p>"
                                     "The 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);

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

    m_histogramWidget = new Digikam::HistogramWidget(256, 140, gboxSettings, 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 levels "
                                             "settings changes."));
    
    m_levelsHistogramWidget = new Digikam::HistogramWidget(256, 140, m_originalImage.bits(), m_originalImage.width(),
                                                     m_originalImage.height(), m_originalImage.sixteenBit(), gboxSettings, false);
    TQWhatsThis::add( m_levelsHistogramWidget, i18n("<p>This is the histogram drawing of the selected channel "
                                                   "from original image"));

    // -------------------------------------------------------------
    
    m_hGradientMinInput = new KGradientSelector( TDESelector::Horizontal, gboxSettings );
    m_hGradientMinInput->setFixedHeight( 20 );
    m_hGradientMinInput->setMinValue(0);
    m_hGradientMinInput->setMaxValue(m_histoSegments);
    TQWhatsThis::add( m_hGradientMinInput, i18n("<p>Select the minimal intensity input value of the histogram."));
    TQToolTip::add( m_hGradientMinInput, i18n( "Minimal intensity input." ) );
    m_hGradientMinInput->setColors( TQColor( "black" ), TQColor( "white" ) );
    m_hGradientMinInput->installEventFilter(this);

    m_hGradientMaxInput = new KGradientSelector( TDESelector::Horizontal, gboxSettings );
    m_hGradientMaxInput->setFixedHeight( 20 );
    m_hGradientMaxInput->setMinValue(0);
    m_hGradientMaxInput->setMaxValue(m_histoSegments);
    TQWhatsThis::add( m_hGradientMaxInput, i18n("<p>Select the maximal intensity input value of the histogram."));
    TQToolTip::add( m_hGradientMaxInput, i18n( "Maximal intensity input." ) );
    m_hGradientMaxInput->setColors( TQColor( "black" ), TQColor( "white" ) );
    m_hGradientMaxInput->installEventFilter(this);

    m_minInput = new TQSpinBox(0, m_histoSegments, 1, gboxSettings);
    m_minInput->setValue(0);
    TQWhatsThis::add( m_minInput, i18n("<p>Select the minimal intensity input value of the histogram."));
    TQToolTip::add( m_minInput, i18n( "Minimal intensity input." ) );
    
    m_gammaInput = new KDoubleNumInput(gboxSettings);
    m_gammaInput->setPrecision(2);
    m_gammaInput->setRange(0.1, 3.0, 0.01);
    m_gammaInput->setValue(1.0);
    TQToolTip::add( m_gammaInput, i18n( "Gamma input value." ) );
    TQWhatsThis::add( m_gammaInput, i18n("<p>Select the gamma input value."));
    
    m_maxInput = new TQSpinBox(0, m_histoSegments, 1, gboxSettings);
    m_maxInput->setValue(m_histoSegments);
    TQToolTip::add( m_maxInput, i18n( "Maximal intensity input." ) );
    TQWhatsThis::add( m_maxInput, i18n("<p>Select the maximal intensity input value of the histogram."));

    m_hGradientMinOutput = new KGradientSelector( TDESelector::Horizontal, gboxSettings );
    m_hGradientMinOutput->setColors( TQColor( "black" ), TQColor( "white" ) );
    TQWhatsThis::add( m_hGradientMinOutput, i18n("<p>Select the minimal intensity output value of the histogram."));    
    TQToolTip::add( m_hGradientMinOutput, i18n( "Minimal intensity output." ) );
    m_hGradientMinOutput->setFixedHeight( 20 );
    m_hGradientMinOutput->setMinValue(0);
    m_hGradientMinOutput->setMaxValue(m_histoSegments);
    m_hGradientMinOutput->installEventFilter(this);
    
    m_hGradientMaxOutput = new KGradientSelector( TDESelector::Horizontal, gboxSettings );
    m_hGradientMaxOutput->setColors( TQColor( "black" ), TQColor( "white" ) );
    TQWhatsThis::add( m_hGradientMaxOutput, i18n("<p>Select the maximal intensity output value of the histogram."));
    TQToolTip::add( m_hGradientMaxOutput, i18n( "Maximal intensity output." ) );
    m_hGradientMaxOutput->setFixedHeight( 20 );
    m_hGradientMaxOutput->setMinValue(0);
    m_hGradientMaxOutput->setMaxValue(m_histoSegments);
    m_hGradientMaxOutput->installEventFilter(this);
    
    m_minOutput = new TQSpinBox(0, m_histoSegments, 1, gboxSettings);
    m_minOutput->setValue(0);
    TQToolTip::add( m_minOutput, i18n( "Minimal intensity output." ) );
    TQWhatsThis::add( m_minOutput, i18n("<p>Select the minimal intensity output value of the histogram."));
    
    m_maxOutput = new TQSpinBox(0, m_histoSegments, 1, gboxSettings);
    m_maxOutput->setValue(m_histoSegments);
    TQToolTip::add( m_maxOutput, i18n( "Maximal intensity output." ) );
    TQWhatsThis::add( m_maxOutput, i18n("<p>Select the maximal intensity output value of the histogram."));

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

    m_pickerColorButtonGroup = new TQHButtonGroup(gboxSettings);
    m_pickBlack = new TQPushButton(m_pickerColorButtonGroup);
    m_pickerColorButtonGroup->insert(m_pickBlack, BlackTonal);
    TDEGlobal::dirs()->addResourceType("color-picker-black", TDEGlobal::dirs()->kde_default("data") +
                                     "digikam/data");
    directory = TDEGlobal::dirs()->findResourceDir("color-picker-black", "color-picker-black.png");
    m_pickBlack->setPixmap( TQPixmap( directory + "color-picker-black.png" ) );
    m_pickBlack->setToggleButton(true);
    TQToolTip::add( m_pickBlack, i18n( "All channels shadow tone color picker" ) );
    TQWhatsThis::add( m_pickBlack, i18n("<p>With this button, you can pick the color from original image used to set <b>Shadow Tone</b> "
                                       "levels input on Red, Green, Blue, and Luminosity channels."));
    m_pickGray  = new TQPushButton(m_pickerColorButtonGroup);
    m_pickerColorButtonGroup->insert(m_pickGray, GrayTonal);
    TDEGlobal::dirs()->addResourceType("color-picker-gray", TDEGlobal::dirs()->kde_default("data") +
                                     "digikam/data");
    directory = TDEGlobal::dirs()->findResourceDir("color-picker-gray", "color-picker-gray.png");
    m_pickGray->setPixmap( TQPixmap( directory + "color-picker-gray.png" ) );
    m_pickGray->setToggleButton(true);
    TQToolTip::add( m_pickGray, i18n( "All channels middle tone color picker" ) );
    TQWhatsThis::add( m_pickGray, i18n("<p>With this button, you can pick the color from original image used to set <b>Middle Tone</b> "
                                      "levels input on Red, Green, Blue, and Luminosity channels."));
    m_pickWhite = new TQPushButton(m_pickerColorButtonGroup);
    m_pickerColorButtonGroup->insert(m_pickWhite, WhiteTonal);
    TDEGlobal::dirs()->addResourceType("color-picker-white", TDEGlobal::dirs()->kde_default("data") +
                                     "digikam/data");
    directory = TDEGlobal::dirs()->findResourceDir("color-picker-white", "color-picker-white.png");
    m_pickWhite->setPixmap( TQPixmap( directory + "color-picker-white.png" ) );
    m_pickWhite->setToggleButton(true);
    TQToolTip::add( m_pickWhite, i18n( "All channels highlight tone color picker" ) );
    TQWhatsThis::add( m_pickWhite, i18n("<p>With this button, you can pick the color from original image used to set <b>Highlight Tone</b> "
                                       "levels input on Red, Green, Blue, and Luminosity channels."));
    m_pickerColorButtonGroup->setExclusive(true);
    m_pickerColorButtonGroup->setFrameShape(TQFrame::NoFrame);    

    m_autoButton = new TQPushButton(gboxSettings);
    m_autoButton->setPixmap(kapp->iconLoader()->loadIcon("system-run", (TDEIcon::Group)TDEIcon::Toolbar));    TQToolTip::add( m_autoButton, i18n( "Adjust all levels automatically." ) );
    TQWhatsThis::add( m_autoButton, i18n("<p>If you press this button, all channel levels will be adjusted "
                                        "automatically."));

    m_resetButton = new TQPushButton(i18n("&Reset"), gboxSettings);
    m_resetButton->setPixmap(kapp->iconLoader()->loadIcon("reload_page", (TDEIcon::Group)TDEIcon::Toolbar));     
    TQToolTip::add( m_resetButton, i18n( "Reset current channel levels' values." ) );
    TQWhatsThis::add( m_resetButton, i18n("<p>If you press this button, all levels' values "
                                         "from the current selected channel "
                                         "will be reset to the default values."));

    TQLabel *space = new TQLabel(gboxSettings);
    space->setFixedWidth(spacingHint());    

    TQHBoxLayout* l3 = new TQHBoxLayout();
    l3->addWidget(m_pickerColorButtonGroup);
    l3->addWidget(m_autoButton);
    l3->addWidget(space);
    l3->addWidget(m_resetButton);
    l3->addStretch(10);

    // -------------------------------------------------------------
    
    grid->addMultiCellLayout(l1, 0, 0, 0, 6);
    grid->setRowSpacing(1, spacingHint());
    grid->addMultiCellWidget(m_histogramWidget, 2, 2, 1, 5);
    grid->setRowSpacing(3, spacingHint());
    grid->addMultiCellWidget(m_levelsHistogramWidget, 4, 4, 1, 5);
    grid->addMultiCellWidget(m_hGradientMinInput, 5, 5, 0, 6);
    grid->addMultiCellWidget(m_minInput, 5, 5, 8, 8);
    grid->setRowSpacing(6, spacingHint());
    grid->addMultiCellWidget(m_hGradientMaxInput, 7, 7, 0, 6);
    grid->addMultiCellWidget(m_maxInput, 7, 7, 8, 8);
    grid->setRowSpacing(8, spacingHint());
    grid->addMultiCellWidget(m_gammaInput, 9, 9, 0, 8);
    grid->setRowSpacing(10, spacingHint());
    grid->addMultiCellWidget(m_hGradientMinOutput, 11, 11, 0, 6);
    grid->addMultiCellWidget(m_minOutput, 11, 11, 8, 8);
    grid->setRowSpacing(12, spacingHint());
    grid->addMultiCellWidget(m_hGradientMaxOutput, 13, 13, 0, 6);
    grid->addMultiCellWidget(m_maxOutput, 13, 13, 8, 8);
    grid->setRowSpacing(14, spacingHint());
    grid->addMultiCellLayout(l3, 15, 15, 0, 8);
    grid->setRowStretch(16, 10);
    grid->setColStretch(2, 10);
    grid->setColSpacing(0, 5);
    grid->setColSpacing(6, 5);
    grid->setColSpacing(7, spacingHint());
    
    setUserAreaWidget(gboxSettings);    
                    
    // -------------------------------------------------------------
    // Channels and scale selection slots.

    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(spotPositionChangedFromOriginal( const Digikam::DColor &, const TQPoint & )),
            this, TQ_SLOT(slotSpotColorChanged( const Digikam::DColor & )));

    connect(m_previewWidget, TQ_SIGNAL(spotPositionChangedFromTarget( const Digikam::DColor &, const TQPoint & )),
            this, TQ_SLOT(slotColorSelectedFromTarget( const Digikam::DColor & )));
            
    connect(m_previewWidget, TQ_SIGNAL(signalResized()),
            this, TQ_SLOT(slotEffect()));                                                            
                        
    // -------------------------------------------------------------
    // Color sliders and spinbox slots.

    connect(m_hGradientMinInput, TQ_SIGNAL(valueChanged(int)),
            this, TQ_SLOT(slotAdjustMinInputSpinBox(int)));

    connect(m_minInput, TQ_SIGNAL(valueChanged (int)),
            this, TQ_SLOT(slotAdjustSliders()));

    connect(m_gammaInput, TQ_SIGNAL(valueChanged (double)),
            this, TQ_SLOT(slotGammaInputchanged(double)));

    connect(m_hGradientMaxInput, TQ_SIGNAL(valueChanged(int)),
            this, TQ_SLOT(slotAdjustMaxInputSpinBox(int)));

    connect(m_maxInput, TQ_SIGNAL(valueChanged (int)),
            this, TQ_SLOT(slotAdjustSliders()));

    connect(m_hGradientMinOutput, TQ_SIGNAL(valueChanged(int)),
            this, TQ_SLOT(slotAdjustMinOutputSpinBox(int)));

    connect(m_minOutput, TQ_SIGNAL(valueChanged (int)),
            this, TQ_SLOT(slotAdjustSliders()));

    connect(m_hGradientMaxOutput, TQ_SIGNAL(valueChanged(int)),
            this, TQ_SLOT(slotAdjustMaxOutputSpinBox(int)));

    connect(m_maxOutput, TQ_SIGNAL(valueChanged (int)),
            this, TQ_SLOT(slotAdjustSliders()));

    // -------------------------------------------------------------
    // Bouttons slots.

    connect(m_autoButton, TQ_SIGNAL(clicked()),
            this, TQ_SLOT(slotAutoLevels()));

    connect(m_resetButton, TQ_SIGNAL(clicked()),
            this, TQ_SLOT(slotResetCurrentChannel()));
    
    connect(m_pickerColorButtonGroup, TQ_SIGNAL(released(int)),
            this, TQ_SLOT(slotPickerColorButtonActived()));
            
}

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

    if (m_destinationPreviewData) 
       delete [] m_destinationPreviewData;
       
    delete m_histogramWidget;
    delete m_levelsHistogramWidget;
    delete m_levels;
}

void AdjustLevelDialog::slotPickerColorButtonActived()
{
    // Save previous rendering mode and toggle to original image.
    m_currentPreviewMode = m_previewWidget->getRenderingPreviewMode();
    m_previewWidget->setRenderingPreviewMode(Digikam::ImageGuideWidget::PreviewOriginalImage);
}

void AdjustLevelDialog::slotSpotColorChanged(const Digikam::DColor &color)
{
    if ( m_pickBlack->isOn() )
    {
       // Black tonal levels point.
       m_levels->levelsBlackToneAdjustByColors(m_channelCB->currentItem(), color);      
       m_pickBlack->setOn(false);
    }
    else if ( m_pickGray->isOn() )
    {
       // Gray tonal levels point.
       m_levels->levelsGrayToneAdjustByColors(m_channelCB->currentItem(), color);      
       m_pickGray->setOn(false);
    }
    else if ( m_pickWhite->isOn() )
    {
       // White tonal levels point.
       m_levels->levelsWhiteToneAdjustByColors(m_channelCB->currentItem(), color);      
       m_pickWhite->setOn(false);
    }
    else
    {
       m_levelsHistogramWidget->setHistogramGuideByColor(color);
       return;
    }

    // Refresh the current levels config.
    slotChannelChanged(m_channelCB->currentItem());
       
    // restore previous rendering mode.
    m_previewWidget->setRenderingPreviewMode(m_currentPreviewMode);
              
    slotEffect();                
}

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

void AdjustLevelDialog::slotGammaInputchanged(double val)
{
    blockSignals(true);
    m_levels->setLevelGammaValue(m_channelCB->currentItem(), val);
    blockSignals(false);
    slotTimer();
}

void AdjustLevelDialog::slotAdjustMinInputSpinBox(int val)
{
    blockSignals(true);

    if ( val < m_hGradientMaxInput->value() )
       val = m_hGradientMaxInput->value();

    m_minInput->setValue(m_histoSegments - val);
    m_hGradientMinInput->setValue( val );
    m_levels->setLevelLowInputValue(m_channelCB->currentItem(), m_histoSegments - val);
    blockSignals(false);
    slotTimer();
}

void AdjustLevelDialog::slotAdjustMaxInputSpinBox(int val)
{
    blockSignals(true);

    if ( val > m_hGradientMinInput->value() )
       val = m_hGradientMinInput->value();

    m_maxInput->setValue(m_histoSegments - val);
    m_hGradientMaxInput->setValue( val );
    m_levels->setLevelHighInputValue(m_channelCB->currentItem(), m_histoSegments - val);
    blockSignals(false);
    slotTimer();
}

void AdjustLevelDialog::slotAdjustMinOutputSpinBox(int val)
{
    blockSignals(true);

    if ( val < m_hGradientMaxOutput->value() )
       val = m_hGradientMaxOutput->value();

    m_minOutput->setValue(m_histoSegments - val);
    m_hGradientMinOutput->setValue( val );
    m_levels->setLevelLowOutputValue(m_channelCB->currentItem(), m_histoSegments - val);
    blockSignals(false);
    slotTimer();
}

void AdjustLevelDialog::slotAdjustMaxOutputSpinBox(int val)
{
    blockSignals(true);

    if ( val > m_hGradientMinOutput->value() )
       val = m_hGradientMinOutput->value();

    m_maxOutput->setValue(m_histoSegments - val);
    m_hGradientMaxOutput->setValue( val );
    m_levels->setLevelHighOutputValue(m_channelCB->currentItem(), m_histoSegments - val);
    blockSignals(false);
    slotTimer();
}

void AdjustLevelDialog::slotAdjustSliders()
{
    adjustSliders(m_minInput->value(), m_gammaInput->value(),
                  m_maxInput->value(), m_minOutput->value(),
                  m_maxOutput->value());
}

void AdjustLevelDialog::adjustSliders(int minIn, double gamIn, int maxIn, int minOut, int maxOut)
{
    m_hGradientMinInput->setValue(m_histoSegments - minIn);
    m_hGradientMaxInput->setValue(m_histoSegments - maxIn);
    m_gammaInput->setValue(gamIn);
    m_hGradientMinOutput->setValue(m_histoSegments - minOut);
    m_hGradientMaxOutput->setValue(m_histoSegments - maxOut);
}

void AdjustLevelDialog::slotResetCurrentChannel()
{
    m_levels->levelsChannelReset(m_channelCB->currentItem());

    // Refresh the current levels config.
    slotChannelChanged(m_channelCB->currentItem());
    m_levelsHistogramWidget->reset();

    slotEffect();
    m_histogramWidget->reset();
}

void AdjustLevelDialog::slotAutoLevels()
{
    // Calculate Auto levels.
    m_levels->levelsAuto(m_levelsHistogramWidget->m_imageHistogram);

    // Refresh the current levels config.
    slotChannelChanged(m_channelCB->currentItem());

    slotEffect();
}

void AdjustLevelDialog::slotEffect()
{
    Digikam::ImageIface* iface = m_previewWidget->imageIface();
    uchar *orgData             = iface->getPreviewImage();
    int w                      = iface->previewWidth();
    int h                      = iface->previewHeight();
    bool sb                    = iface->previewSixteenBit();
    
    // Create the new empty destination image data space.
    m_histogramWidget->stopHistogramComputation();

    if (m_destinationPreviewData) 
       delete [] m_destinationPreviewData;
    
    m_destinationPreviewData = new uchar[w*h*(sb ? 8 : 4)];

    // Calculate the LUT to apply on the image.
    m_levels->levelsLutSetup(Digikam::ImageHistogram::AlphaChannel);

    // Apply the lut to the image.
    m_levels->levelsLutProcess(orgData, m_destinationPreviewData, w, h);

    iface->putPreviewImage(m_destinationPreviewData);
    m_previewWidget->updatePreview();

    // Update histogram.
    m_histogramWidget->updateData(m_destinationPreviewData, w, h, sb, 0, 0, 0, false);
    
    delete [] orgData;
}

void AdjustLevelDialog::finalRendering()
{
    kapp->setOverrideCursor( KCursor::waitCursor() );
    Digikam::ImageIface* iface = m_previewWidget->imageIface();
    uchar *orgData             = iface->getOriginalImage();
    int w                      = iface->originalWidth();
    int h                      = iface->originalHeight();
    bool sb                    = iface->originalSixteenBit();

    // Create the new empty destination image data space.
    uchar* desData = new uchar[w*h*(sb ? 8 : 4)];

    // Calculate the LUT to apply on the image.
    m_levels->levelsLutSetup(Digikam::ImageHistogram::AlphaChannel);

    // Apply the lut to the image.
    m_levels->levelsLutProcess(orgData, desData, w, h);

    iface->putOriginalImage(i18n("Adjust Level"), desData);
    kapp->restoreOverrideCursor();

    delete [] orgData;
    delete [] desData;
    accept();
}

void AdjustLevelDialog::slotChannelChanged(int channel)
{
    switch(channel)
    {
       case LuminosityChannel:
          m_histogramWidget->m_channelType = Digikam::HistogramWidget::ValueHistogram;
          m_levelsHistogramWidget->m_channelType = Digikam::HistogramWidget::ValueHistogram;
          m_hGradientMinInput->setColors( TQColor( "black" ), TQColor( "white" ) );
          m_hGradientMaxInput->setColors( TQColor( "black" ), TQColor( "white" ) );
          m_hGradientMinOutput->setColors( TQColor( "black" ), TQColor( "white" ) );
          m_hGradientMaxOutput->setColors( TQColor( "black" ), TQColor( "white" ) );
          break;
       
       case RedChannel:
          m_histogramWidget->m_channelType = Digikam::HistogramWidget::RedChannelHistogram;       
          m_levelsHistogramWidget->m_channelType = Digikam::HistogramWidget::RedChannelHistogram;
          m_hGradientMinInput->setColors( TQColor( "black" ), TQColor( "red" ) );
          m_hGradientMaxInput->setColors( TQColor( "black" ), TQColor( "red" ) );
          m_hGradientMinOutput->setColors( TQColor( "black" ), TQColor( "red" ) );
          m_hGradientMaxOutput->setColors( TQColor( "black" ), TQColor( "red" ) );
          break;

       case GreenChannel:
          m_histogramWidget->m_channelType = Digikam::HistogramWidget::GreenChannelHistogram;       
          m_levelsHistogramWidget->m_channelType = Digikam::HistogramWidget::GreenChannelHistogram;
          m_hGradientMinInput->setColors( TQColor( "black" ), TQColor( "green" ) );
          m_hGradientMaxInput->setColors( TQColor( "black" ), TQColor( "green" ) );
          m_hGradientMinOutput->setColors( TQColor( "black" ), TQColor( "green" ) );
          m_hGradientMaxOutput->setColors( TQColor( "black" ), TQColor( "green" ) );
          break;

       case BlueChannel:
          m_histogramWidget->m_channelType = Digikam::HistogramWidget::BlueChannelHistogram;
          m_levelsHistogramWidget->m_channelType = Digikam::HistogramWidget::BlueChannelHistogram;
          m_hGradientMinInput->setColors( TQColor( "black" ), TQColor( "blue" ) );
          m_hGradientMaxInput->setColors( TQColor( "black" ), TQColor( "blue" ) );
          m_hGradientMinOutput->setColors( TQColor( "black" ), TQColor( "blue" ) );
          m_hGradientMaxOutput->setColors( TQColor( "black" ), TQColor( "blue" ) );
          break;

       case AlphaChannel:
          m_histogramWidget->m_channelType = Digikam::HistogramWidget::AlphaChannelHistogram;       
          m_levelsHistogramWidget->m_channelType = Digikam::HistogramWidget::AlphaChannelHistogram;
          m_hGradientMinInput->setColors( TQColor( "black" ), TQColor( "white" ) );
          m_hGradientMaxInput->setColors( TQColor( "black" ), TQColor( "white" ) );
          m_hGradientMinOutput->setColors( TQColor( "black" ), TQColor( "white" ) );
          m_hGradientMaxOutput->setColors( TQColor( "black" ), TQColor( "white" ) );
          break;
    }

    adjustSliders(m_levels->getLevelLowInputValue(channel),
                  m_levels->getLevelGammaValue(channel),
                  m_levels->getLevelHighInputValue(channel),
                  m_levels->getLevelLowOutputValue(channel),
                  m_levels->getLevelHighOutputValue(channel));

    m_levelsHistogramWidget->repaint(false);
    m_histogramWidget->repaint(false);    
}

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

void AdjustLevelDialog::readUserSettings()
{
    TDEConfig* config = kapp->config();
    config->setGroup("adjustlevels Tool Dialog");

    m_channelCB->setCurrentItem(config->readNumEntry("Histogram Channel", 0));    // Luminosity.
    m_scaleBG->setButton(config->readNumEntry("Histogram Scale", Digikam::HistogramWidget::LogScaleHistogram));

    for (int i = 0 ; i < 5 ; i++)
    {
        bool sb        = m_originalImage.sixteenBit();
        int max        = sb ? 65535 : 255;
        double gamma   = config->readDoubleNumEntry(TQString("GammaChannel%1").arg(i), 1.0);
        int lowInput   = config->readNumEntry(TQString("LowInputChannel%1").arg(i), 0);
        int lowOutput  = config->readNumEntry(TQString("LowOutputChannel%1").arg(i), 0);
        int highInput  = config->readNumEntry(TQString("HighInputChannel%1").arg(i), max);
        int highOutput = config->readNumEntry(TQString("HighOutputChannel%1").arg(i), max);
    
        m_levels->setLevelGammaValue(i, gamma);
        m_levels->setLevelLowInputValue(i, sb ? lowInput*255 : lowInput);
        m_levels->setLevelHighInputValue(i, sb ? highInput*255 : highInput);
        m_levels->setLevelLowOutputValue(i, sb ? lowOutput*255 : lowOutput);
        m_levels->setLevelHighOutputValue(i, sb ? highOutput*255 : highOutput);
    }

    m_levelsHistogramWidget->reset();
    m_histogramWidget->reset();
    slotChannelChanged(m_channelCB->currentItem());
    slotScaleChanged(m_scaleBG->selectedId());

    // This is mandatory here to set spinbox values because slot connections 
    // can be not set completely at plugin startup.
    m_minInput->setValue(m_levels->getLevelLowInputValue(m_channelCB->currentItem()));
    m_minOutput->setValue(m_levels->getLevelLowOutputValue(m_channelCB->currentItem()));
    m_maxInput->setValue(m_levels->getLevelHighInputValue(m_channelCB->currentItem()));
    m_maxOutput->setValue(m_levels->getLevelHighOutputValue(m_channelCB->currentItem()));
}

void AdjustLevelDialog::writeUserSettings()
{
    TDEConfig* config = kapp->config();
    config->setGroup("adjustlevels Tool Dialog");
    config->writeEntry("Histogram Channel", m_channelCB->currentItem());
    config->writeEntry("Histogram Scale", m_scaleBG->selectedId());

    for (int i = 0 ; i < 5 ; i++)
    {
        bool sb        = m_originalImage.sixteenBit();
        double gamma   = m_levels->getLevelGammaValue(i);
        int lowInput   = m_levels->getLevelLowInputValue(i);
        int lowOutput  = m_levels->getLevelLowOutputValue(i);
        int highInput  = m_levels->getLevelHighInputValue(i);
        int highOutput = m_levels->getLevelHighOutputValue(i);

        config->writeEntry(TQString("GammaChannel%1").arg(i), gamma);
        config->writeEntry(TQString("LowInputChannel%1").arg(i), sb ? lowInput/255 : lowInput);
        config->writeEntry(TQString("LowOutputChannel%1").arg(i), sb ? lowOutput/255 : lowOutput);
        config->writeEntry(TQString("HighInputChannel%1").arg(i), sb ? highInput/255 : highInput);
        config->writeEntry(TQString("HighOutputChannel%1").arg(i), sb ? highOutput/255 : highOutput);
    }

    config->sync();
}

void AdjustLevelDialog::resetValues()
{
    for (int channel = 0 ; channel < 5 ; ++channel)
       m_levels->levelsChannelReset(channel);

    // Refresh the current levels config.
    slotChannelChanged(m_channelCB->currentItem());
    m_levelsHistogramWidget->reset();
    m_histogramWidget->reset();
}

// Load all settings.
void AdjustLevelDialog::slotUser3()
{
    KURL loadLevelsFile;

    loadLevelsFile = KFileDialog::getOpenURL(TDEGlobalSettings::documentPath(),
                                             TQString( "*" ), this,
                                             TQString( i18n("Select Gimp Levels File to Load")) );
    if( loadLevelsFile.isEmpty() )
       return;

    if ( m_levels->loadLevelsFromGimpLevelsFile( loadLevelsFile ) == false )
    {
       KMessageBox::error(this, i18n("Cannot load from the Gimp levels text file."));
       return;
    }

    // Refresh the current levels config.
    slotChannelChanged(m_channelCB->currentItem());
}

// Save all settings.
void AdjustLevelDialog::slotUser2()
{
    KURL saveLevelsFile;

    saveLevelsFile = KFileDialog::getSaveURL(TDEGlobalSettings::documentPath(),
                                             TQString( "*" ), this,
                                             TQString( i18n("Gimp Levels File to Save")) );
    if( saveLevelsFile.isEmpty() )
       return;

    if ( m_levels->saveLevelsToGimpLevelsFile( saveLevelsFile ) == false )
    {
       KMessageBox::error(this, i18n("Cannot save to the Gimp levels text file."));
       return;
    }

    // Refresh the current levels config.
    slotChannelChanged(m_channelCB->currentItem());
}

// See B.K.O #146636: use event filter with all level slider to display a
// guide over level histogram.
bool AdjustLevelDialog::eventFilter(TQObject *obj, TQEvent *ev)
{
    if ( obj == m_hGradientMinInput )
    {
        if ( ev->type() == TQEvent::MouseButtonPress)
        {
            connect(m_minInput, TQ_SIGNAL(valueChanged(int)),
                    this, TQ_SLOT(slotShowHistogramGuide(int)));
            
            return false;
        }
        if ( ev->type() == TQEvent::MouseButtonRelease)
        {
            disconnect(m_minInput, TQ_SIGNAL(valueChanged(int)),
                       this, TQ_SLOT(slotShowHistogramGuide(int)));

            m_levelsHistogramWidget->reset();
            return false;
        }
        else
        {
            return false;
        }
    }
    if ( obj == m_hGradientMaxInput )
    {
        if ( ev->type() == TQEvent::MouseButtonPress)
        {
            connect(m_maxInput, TQ_SIGNAL(valueChanged(int)),
                    this, TQ_SLOT(slotShowHistogramGuide(int)));
            
            return false;
        }
        if ( ev->type() == TQEvent::MouseButtonRelease)
        {
            disconnect(m_maxInput, TQ_SIGNAL(valueChanged(int)),
                       this, TQ_SLOT(slotShowHistogramGuide(int)));

            m_levelsHistogramWidget->reset();
            return false;
        }
        else
        {
            return false;
        }
    }
    if ( obj == m_hGradientMinOutput )
    {
        if ( ev->type() == TQEvent::MouseButtonPress)
        {
            connect(m_minOutput, TQ_SIGNAL(valueChanged(int)),
                    this, TQ_SLOT(slotShowHistogramGuide(int)));
            
            return false;
        }
        if ( ev->type() == TQEvent::MouseButtonRelease)
        {
            disconnect(m_minOutput, TQ_SIGNAL(valueChanged(int)),
                       this, TQ_SLOT(slotShowHistogramGuide(int)));

            m_levelsHistogramWidget->reset();
            return false;
        }
        else
        {
            return false;
        }
    }
    if ( obj == m_hGradientMaxOutput )
    {
        if ( ev->type() == TQEvent::MouseButtonPress)
        {
            connect(m_maxOutput, TQ_SIGNAL(valueChanged(int)),
                    this, TQ_SLOT(slotShowHistogramGuide(int)));
            
            return false;
        }
        if ( ev->type() == TQEvent::MouseButtonRelease)
        {
            disconnect(m_maxOutput, TQ_SIGNAL(valueChanged(int)),
                       this, TQ_SLOT(slotShowHistogramGuide(int)));

            m_levelsHistogramWidget->reset();
            return false;
        }
        else
        {
            return false;
        }
    }
    else
    {
        // pass the event on to the parent class
        return KDialogBase::eventFilter(obj, ev);
    }
}

void AdjustLevelDialog::slotShowHistogramGuide(int v)
{
    Digikam::DColor color(v, v, v, v, m_originalImage.sixteenBit());
    m_levelsHistogramWidget->setHistogramGuideByColor(color);
}

}  // NameSpace DigikamAdjustLevelsImagesPlugin