kpColorCells.cpp 17 KB
Newer Older
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

/*
   Copyright (c) 2003-2007 Clarence Dang <dang@kde.org>
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
   IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


Clarence Dang's avatar
Clarence Dang committed
29
#define DEBUG_KP_COLOR_CELLS 0
30 31 32 33 34 35


#include <kpColorCells.h>

#include <QContextMenuEvent>
#include <QMouseEvent>
36
#include <QScrollBar>
37

38 39
#include <KColorDialog>
#include <KDebug>
40
#include <KLocale>
41

42
#include <kpColor.h>
43 44
#include <kpColorCollection.h>
#include <kpDefaultColorCollection.h>
45

46
//---------------------------------------------------------------------
47 48 49 50 51
//
// Table Geometry
//


52 53
// The number of columns that the table normally has.
const int TableDefaultNumColumns = 11;
54

55
const int TableDefaultWidth = ::TableDefaultNumColumns * 26;
56

57 58
const int TableDefaultHeight = 52;

59

60
static int TableNumColumns (const kpColorCollection &colorCol)
61
{
62 63 64 65
    if (colorCol.count () == 0)
        return 0;

    return ::TableDefaultNumColumns;
66 67
}

68
static int TableNumRows (const kpColorCollection &colorCol)
69
{
70 71 72
    const int cols = ::TableNumColumns (colorCol);
    if (cols == 0)
        return 0;
73 74 75 76 77

    return (colorCol.count () + (cols - 1)) / cols;
}


78
static int TableCellWidth (const kpColorCollection &colorCol)
79
{
80 81 82
    Q_UNUSED (colorCol);

    return ::TableDefaultWidth / ::TableDefaultNumColumns;
83 84
}

85
static int TableCellHeight (const kpColorCollection &colorCol)
86
{
87 88
    if (::TableNumRows (colorCol) <= 2)
        return ::TableDefaultHeight / 2;
89
    else
90
        return ::TableDefaultHeight / 3;
91 92 93
}


94 95 96 97 98
//
// kpColorCells
//


99 100 101 102
struct kpColorCellsPrivate
{
    Qt::Orientation orientation;

103 104
    // REFACTOR: This is data duplication with kpColorCellsBase::color[].
    //           We've probably forgotten to synchronize them in some points.
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    //
    // Calls to kpColorCellsBase::setColor() (which also come from
    // kpColorCellsBase itself) will automatically update both
    // kpColorCellsBase::d->color[] and the table cells.  setColor() emits
    // colorChanged(), which is caught by our slotColorChanged(),
    // which synchronizes this color collection and updates the modified flag.
    //
    // Avoid calling our grandparent's, QTableWidget's, mutating methods as we
    // don't override enough of them, to fire signals that we can catch to update
    // this color collection.
    //
    // If you modify this color collection directly (e.g. in setColorCollection(),
    // openColorCollection(), appendRow(), deleteLastRow(), ...), you must work
    // the other way and call makeCellsMatchColorCollection() to synchronize
    // kpColorCellsBase::d->color[] and the table cells.  You still need to update
    // the modified flag.
121
    kpColorCollection colorCol;
122

Christoph Feck's avatar
Christoph Feck committed
123
    QUrl url;
124
    bool isModified;
125

126
    bool blockColorChangedSig;
127 128
};

129 130
//---------------------------------------------------------------------

131 132
kpColorCells::kpColorCells (QWidget *parent,
                            Qt::Orientation o)
133
    : kpColorCellsBase (parent, 0/*rows for now*/, 0/*cols for now*/),
134
      d (new kpColorCellsPrivate ())
135
{
136
    d->orientation = o;
137
    d->isModified = false;
138 139
    d->blockColorChangedSig = false;

140 141 142 143

    // When a text box is active, clicking to change the background color
    // should not move the keyboard focus away from the text box.
    setFocusPolicy (Qt::TabFocus);
144

145 146 147 148 149
    setShading (false);  // no 3D look

    setAcceptDrops (true);
    setAcceptDrags (true);

150 151 152 153 154

    setCellsResizable (false);

    if (o == Qt::Horizontal)
    {
155 156
        // Reserve enough room for the default color collection's cells _and_
        // a vertical scrollbar, which only appears when it's required.
157
        // This ensures that if the vertical scrollbar appears, it does not obscure
158 159 160
        // any cells or require the addition of a horizontal scrollbar, which would
        // look ugly and take even more precious room.
        //
Clarence Dang's avatar
Clarence Dang committed
161
        // We do not dynamically reserve room based on the actual number of rows
162
        // of cells, as that would make our containing widgets too big.
163
        setMinimumSize (::TableDefaultWidth + frameWidth () * 2 +
164
                         verticalScrollBar()->sizeHint().width(),
165 166 167 168 169 170 171
                        ::TableDefaultHeight + frameWidth () * 2);
    }
    else
    {
        Q_ASSERT (!"implemented");
    }

172
    setVerticalScrollBarPolicy (Qt::ScrollBarAsNeeded);
173 174

    // The default QTableWidget policy of QSizePolicy::Expanding forces our
175
    // containing widgets to get too big.  Override it.
176 177 178 179 180 181 182 183 184
    setSizePolicy (QSizePolicy::Minimum, QSizePolicy::Minimum);


    connect (this, SIGNAL (colorSelected (int, const QColor &, Qt::MouseButton)),
             SLOT (slotColorSelected (int, const QColor &, Qt::MouseButton)));
    connect (this, SIGNAL (colorDoubleClicked (int, const QColor &)),
             SLOT (slotColorDoubleClicked (int, const QColor &)));
    connect (this, SIGNAL (colorChanged (int, const QColor &)),
             SLOT (slotColorChanged (int, const QColor &)));
185

186

187
    setColorCollection (DefaultColorCollection ());
188 189


190
    setWhatsThis (
191 192 193
        i18n (
            "<qt>"

Malcolm Hunter's avatar
Malcolm Hunter committed
194
            "<p>To select the foreground color that tools use to draw,"
195 196 197 198
            " left-click on a filled-in color cell."
            " To select the background color, right-click instead.</p>"

            "<p>To change the color of a color cell itself, double-click on it.</p>"
199

200 201
            "<p>You can also swap the color of a filled-in cell with any other"
            " cell using drag and drop."
Malcolm Hunter's avatar
Malcolm Hunter committed
202
            " Also, if you hold down the <b>Ctrl</b> key, the destination"
203 204
            " cell's color will be"
            " overwritten, instead of being swapped with the color of the source cell.</p>"
205 206

            "</qt>"));
207 208
}

209 210
//---------------------------------------------------------------------

211 212
kpColorCells::~kpColorCells ()
{
213 214 215
    delete d;
}

216 217
//---------------------------------------------------------------------

218

219 220 221 222
// public static
kpColorCollection kpColorCells::DefaultColorCollection ()
{
    return kpDefaultColorCollection ();
223 224
}

225 226
//---------------------------------------------------------------------

227 228

// public
229 230
Qt::Orientation kpColorCells::orientation () const
{
231
    return d->orientation;
232 233
}

234 235
//---------------------------------------------------------------------

236
// public
237
void kpColorCells::setOrientation (Qt::Orientation o)
238 239 240 241 242 243
{
    d->orientation = o;

    makeCellsMatchColorCollection ();
}

244 245
//---------------------------------------------------------------------

246 247 248 249

// protected
// OPT: Find out why this is being called multiple times on startup.
void kpColorCells::makeCellsMatchColorCollection ()
250 251 252
{
    int c, r;

253
    if (orientation () == Qt::Horizontal)
254
    {
255 256
        c = ::TableNumColumns (d->colorCol);
        r = ::TableNumRows (d->colorCol);
257 258 259
    }
    else
    {
260 261
        c = ::TableNumRows (d->colorCol);
        r = ::TableNumColumns (d->colorCol);;
262 263 264
    }

#if DEBUG_KP_COLOR_CELLS
265
    kDebug () << "kpColorCells::makeCellsMatchColorCollection():"
266 267 268 269 270 271
              << "r=" << r << "c=" << c;
    kDebug () << "verticalScrollBar=" << verticalScrollBar ()
              << " sizeHint="
              << (verticalScrollBar () ?
                    verticalScrollBar ()->sizeHint () :
                    QSize (-12, -34));
272 273
#endif

274 275 276
    // Delete all cell widgets.  This ensures that there will be no left-over
    // cell widgets, for the colors in the new color collection that are
    // actually invalid (which should not have cell widgets).
277 278
    clearContents ();

279 280
    setRowCount (r);
    setColumnCount (c);
281

282

283 284
    int CellWidth = ::TableCellWidth (d->colorCol),
        CellHeight = ::TableCellHeight (d->colorCol);
285

286 287 288 289
    // TODO: Take a screenshot of KolourPaint, magnify it and you'll find the
    //       cells don't have exactly the sizes requested here.  e.g. the
    //       top row of cells is 1 pixel shorter than the bottom row.  There
    //       are probably other glitches.
290 291 292 293
    for (int y = 0; y < r; y++)
        setRowHeight (y, CellHeight);
    for (int x = 0; x < c; x++)
        setColumnWidth (x, CellWidth);
294 295


296 297 298 299 300
    const bool oldBlockColorChangedSig = d->blockColorChangedSig;
    d->blockColorChangedSig = true;
    // The last "(rowCount() * columnCount()) - d->colorCol.count()" cells
    // will be empty because we did not initialize them.
    for (int i = 0; i < d->colorCol.count (); i++)
301 302 303 304
    {
        int y, x;
        int pos;

305
        if (orientation () == Qt::Horizontal)
306
        {
307 308
            y = i / c;
            x = i % c;
309 310 311 312
            pos = i;
        }
        else
        {
313 314 315 316
            y = i % r;
            x = i / r;
            // int x = c - 1 - i / r;
            pos = y * c + x;
317
        }
318
    #if DEBUG_KP_COLOR_CELLS && 0
319 320
        kDebug () << "\tSetting cell " << i << ": y=" << y << " x=" << x
                  << " pos=" << pos << endl;
321
        kDebug () << "\t\tcolor=" << (int *) d->colorCol.color (i).rgba()
322
                  << "isValid=" << d->colorCol.color (i).isValid ();
323
    #endif
324

325 326
        // (color may be invalid resulting in a hole in the middle of the table)
        setColor (pos, d->colorCol.color (i));
327 328
        //this->setToolTip( cellGeometry (y, x), colors [i].name ());
    }
329
    d->blockColorChangedSig = oldBlockColorChangedSig;
330 331
}

332 333
//---------------------------------------------------------------------

334 335 336 337 338 339

bool kpColorCells::isModified () const
{
    return d->isModified;
}

340 341
//---------------------------------------------------------------------

342 343
void kpColorCells::setModified (bool yes)
{
344
#if DEBUG_KP_COLOR_CELLS
345
    kDebug () << "kpColorCells::setModified(" << yes << ")";
346 347 348
#endif

    if (yes == d->isModified)
349 350 351
        return;

    d->isModified = yes;
352 353 354 355

    emit isModifiedChanged (yes);
}

356 357
//---------------------------------------------------------------------

358 359 360
void kpColorCells::setModified ()
{
    setModified (true);
361 362
}

363 364
//---------------------------------------------------------------------

365

Christoph Feck's avatar
Christoph Feck committed
366
QUrl kpColorCells::url () const
367 368 369 370
{
    return d->url;
}

371 372
//---------------------------------------------------------------------

373 374 375 376 377
QString kpColorCells::name () const
{
    return d->colorCol.name ();
}

378 379
//---------------------------------------------------------------------

380

381 382 383 384 385
const kpColorCollection *kpColorCells::colorCollection () const
{
    return &d->colorCol;
}

386 387
//---------------------------------------------------------------------

388 389 390 391 392 393 394

void kpColorCells::ensureHaveAtLeastOneRow ()
{
    if (d->colorCol.count () == 0)
        d->colorCol.resize (::TableDefaultNumColumns);
}

395 396
//---------------------------------------------------------------------

Christoph Feck's avatar
Christoph Feck committed
397
void kpColorCells::setColorCollection (const kpColorCollection &colorCol, const QUrl &url)
398 399
{
    d->colorCol = colorCol;
400 401
    ensureHaveAtLeastOneRow ();

402
    d->url = url;
403
    setModified (false);
404 405

    makeCellsMatchColorCollection ();
406

407
    emit rowCountChanged (rowCount ());
408 409
    emit urlChanged (d->url);
    emit nameChanged (name ());
410 411
}

412 413
//---------------------------------------------------------------------

414

Christoph Feck's avatar
Christoph Feck committed
415
bool kpColorCells::openColorCollection (const QUrl &url)
416
{
417
    // (this will pop up an error dialog on failure)
418
    if (d->colorCol.open (url, this))
419
    {
420 421
        ensureHaveAtLeastOneRow ();

422
        d->url = url;
423
        setModified (false);
424 425

        makeCellsMatchColorCollection ();
426

427
        emit rowCountChanged (rowCount ());
428 429
        emit urlChanged (d->url);
        emit nameChanged (name ());
430 431 432

        return true;
    }
433

434
    return false;
435 436
}

437 438
//---------------------------------------------------------------------

Christoph Feck's avatar
Christoph Feck committed
439
bool kpColorCells::saveColorCollectionAs (const QUrl &url)
440
{
441 442
    // (this will pop up an error dialog on failure)
    if (d->colorCol.saveAs (url, true/*show overwrite prompt*/, this))
443 444
    {
        d->url = url;
445 446
        setModified (false);

447
        emit urlChanged (d->url);
448 449 450
        return true;
    }

451 452 453
    return false;
}

454 455
//---------------------------------------------------------------------

456 457 458 459 460 461 462 463 464 465
bool kpColorCells::saveColorCollection ()
{
    // (this will pop up an error dialog on failure)
    if (d->colorCol.saveAs (d->url, false/*no overwrite prompt*/, this))
    {
        setModified (false);
        return true;
    }

    return false;
466 467
}

468 469
//---------------------------------------------------------------------

470 471 472

void kpColorCells::appendRow ()
{
473 474 475 476
    // This is the easiest implementation: change the color collection
    // and then synchronize the table cells.  The other way is to call
    // setRowCount() and then, synchronize the color collection.

477 478
    const int targetNumCells = (rowCount () + 1) * ::TableDefaultNumColumns;
    d->colorCol.resize (targetNumCells);
479

480 481
    setModified (true);

482 483
    makeCellsMatchColorCollection ();

484
    emit rowCountChanged (rowCount ());
485 486
}

487 488
//---------------------------------------------------------------------

489
void kpColorCells::deleteLastRow ()
490
{
491 492 493 494
    // This is the easiest implementation: change the color collection
    // and then synchronize the table cells.  The other way is to call
    // setRowCount() and then, synchronize the color collection.

495
    const int targetNumCells =
496
        qMax (0, (rowCount () - 1) * ::TableDefaultNumColumns);
497
    d->colorCol.resize (targetNumCells);
498

499 500 501 502
    // If there was only one row of colors to start with, the effect of this
    // line (after the above resize()) is to change that row to a row of
    // invalid colors.
    ensureHaveAtLeastOneRow ();
503

504
    setModified (true);
505

506
    makeCellsMatchColorCollection ();
507

508
    emit rowCountChanged (rowCount ());
509 510
}

511 512
//---------------------------------------------------------------------

513 514 515 516 517 518 519 520

// protected virtual [base QWidget]
void kpColorCells::contextMenuEvent (QContextMenuEvent *e)
{
    // Eat right-mouse press to prevent it from getting to the toolbar.
    e->accept ();
}

521 522
//---------------------------------------------------------------------

523 524 525
// protected slot
void kpColorCells::slotColorSelected (int cell, const QColor &color,
        Qt::MouseButton button)
526 527
{
#if DEBUG_KP_COLOR_CELLS
528 529
    kDebug () << "kpColorCells::slotColorSelected(cell=" << cell
               << ") mouseButton = " << button
530
               << " rgb=" << (int *) color.rgba()
531
               << endl;
532 533
#else
    Q_UNUSED (cell);
534
#endif
535 536

    if (button == Qt::LeftButton)
537
    {
538
        emit foregroundColorChanged (kpColor (color.rgba()));
539 540 541
    }
    else if (button == Qt::RightButton)
    {
542
        emit backgroundColorChanged (kpColor (color.rgba()));
543 544
    }

545 546
    // REFACTOR: Make selectedness configurable inside kpColorCellsBase?
    //
547
    // Deselect the selected cell (selected by above kpColorCellsBase::mouseReleaseEvent()).
548 549 550 551
    // KolourPaint's palette has no concept of a current cell/color: you can
    // pick a color but you can't mark a cell as selected.  In any case, a
    // selected cell would be rendered as violet, which would ruin the cell.
    //
552
    // setSelectionMode (kpColorCellsBase::NoSelection); does not work so we
553
    // clearSelection().  I think setSelectionMode() concerns when the user
554
    // directly selects a cell - not when kpColorCellsBase::mouseReleaseEvent()
555 556
    // selects a cell programmatically.
    clearSelection ();
557 558
}

559 560
//---------------------------------------------------------------------

561
// protected slot
562
void kpColorCells::slotColorDoubleClicked (int cell, const QColor &)
563
{
564 565 566 567 568 569
    KColorDialog dialog(this);
    dialog.setColor(kpColorCellsBase::color(cell));
    dialog.setAlphaChannelEnabled(true);
    dialog.setButtons(KDialog::Ok | KDialog::Cancel);
    if ( dialog.exec() == QDialog::Accepted )
      setColor (cell, dialog.color());
570 571
}

572 573
//---------------------------------------------------------------------

574 575 576 577
// protected slot
void kpColorCells::slotColorChanged (int cell, const QColor &color)
{
#if DEBUG_KP_COLOR_CELLS
578
    kDebug () << "cell=" << cell << "color=" << (const int *) color.rgba()
579 580 581 582 583 584 585
              << "d->colorCol.count()=" << d->colorCol.count ();
#endif

    if (d->blockColorChangedSig)
        return;

    // Cater for adding new colors to the end.
586 587
    if (cell >= d->colorCol.count ())
        d->colorCol.resize (cell + 1);
588 589 590 591 592

    // TODO: We lose color names on a color swap (during drag-and-drop).
    const int ret = d->colorCol.changeColor (cell, color,
        QString ()/*color name*/);
    Q_ASSERT (ret == cell);
593

594 595
    setModified (true);
}
596 597

#include <kpColorCells.moc>