themeeditor.cpp 52.6 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
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
/******************************************************************************
 *
 *  Copyright 2008 Szymon Tomasz Stefanek <pragma@kvirc.net>
 *
 *  This program is free softhisare; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Softhisare Foundation; either version 2 of the License, 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.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Softhisare
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *******************************************************************************/

#include "utils/themeeditor.h"
#include "core/theme.h"
#include "core/groupheaderitem.h"
#include "core/messageitem.h"
#include "core/modelinvariantrowmapper.h"
#include "core/manager.h"
#include "utils/comboboxutils.h"

#include <Akonadi/KMime/MessageStatus>

#include <KTextEdit>

#include <QActionGroup>
#include <QCheckBox>
#include <QCursor>
#include <QDrag>
#include <QGridLayout>
#include <QGroupBox>
#include <QHeaderView>
#include <QLabel>
#include <QMouseEvent>
#include <QTreeWidget>
#include <QPainter>
#include <QPaintEvent>
#include <QPixmap>
#include <QPushButton>
#include <QStringList>
#include <QMimeData>

#include <QColorDialog>
#include <KComboBox>
#include <KLineEdit>
#include <KLocalizedString>
#include <QMenu>
#include <KIconLoader>
#include <KPluralHandlingSpinBox>

#include <time.h> // for time_t
#include <QDialogButtonBox>
#include <QVBoxLayout>

using namespace MessageList::Utils;
using namespace MessageList::Core;

static const char gThemeContentItemTypeDndMimeDataFormat[] = "application/x-kmail-messagelistview-theme-contentitem-type";

ThemeColumnPropertiesDialog::ThemeColumnPropertiesDialog(QWidget *parent, Theme::Column *column, const QString &title)
    : QDialog(parent), mColumn(column)
{
    setWindowModality(Qt::ApplicationModal);   // FIXME: Sure ?
Laurent Montel's avatar
Laurent Montel committed
71
72
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
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
    QPushButton *okButton = buttonBox->button(QDialogButtonBox::Ok);
    okButton->setDefault(true);
    okButton->setShortcut(Qt::CTRL | Qt::Key_Return);
    connect(buttonBox, &QDialogButtonBox::rejected, this, &ThemeColumnPropertiesDialog::reject);
    setWindowTitle(title);

    QWidget *base = new QWidget(this);
    mainLayout->addWidget(base);
    mainLayout->addWidget(buttonBox);

    QGridLayout *g = new QGridLayout(base);

    QLabel *l;

    l = new QLabel(i18nc("@label:textbox Property name", "Name:"), base);
    g->addWidget(l, 0, 0);

    mNameEdit = new KLineEdit(base);
    mNameEdit->setToolTip(i18n("The label that will be displayed in the column header."));
    g->addWidget(mNameEdit, 0, 1);

    l = new QLabel(i18n("Header click sorts messages:"), base);
    g->addWidget(l, 1, 0);

    mMessageSortingCombo = new KComboBox(base);
    mMessageSortingCombo->setToolTip(i18n("The sorting order that clicking on this column header will switch to."));
    g->addWidget(mMessageSortingCombo, 1, 1);

    mVisibleByDefaultCheck = new QCheckBox(i18n("Visible by default"), base);
    mVisibleByDefaultCheck->setToolTip(i18n("Check this if this column should be visible when the theme is selected."));
    g->addWidget(mVisibleByDefaultCheck, 2, 1);

    mIsSenderOrReceiverCheck = new QCheckBox(i18n("Contains \"Sender or Receiver\" field"), base);
    mIsSenderOrReceiverCheck->setToolTip(i18n("Check this if this column label should be updated depending on the folder \"inbound\"/\"outbound\" type."));
    g->addWidget(mIsSenderOrReceiverCheck, 3, 1);

    g->setColumnStretch(1, 1);
    g->setRowStretch(10, 1);

    connect(okButton, &QPushButton::clicked, this, &ThemeColumnPropertiesDialog::slotOkButtonClicked);

    // Display the current settings
    mNameEdit->setText(mColumn->label());
    mVisibleByDefaultCheck->setChecked(mColumn->visibleByDefault());
    mIsSenderOrReceiverCheck->setChecked(mColumn->isSenderOrReceiver());
    ComboBoxUtils::fillIntegerOptionCombo(mMessageSortingCombo, SortOrder::enumerateMessageSortingOptions(Aggregation::PerfectReferencesAndSubject));
    ComboBoxUtils::setIntegerOptionComboValue(mMessageSortingCombo, mColumn->messageSorting());

}

void ThemeColumnPropertiesDialog::slotOkButtonClicked()
{
    QString text = mNameEdit->text();
    if (text.isEmpty()) {
        text = i18n("Unnamed Column");
    }
    mColumn->setLabel(text);
    mColumn->setVisibleByDefault(mVisibleByDefaultCheck->isChecked());
    mColumn->setIsSenderOrReceiver(mIsSenderOrReceiverCheck->isChecked());
    mColumn->setMessageSorting(
        static_cast< SortOrder::MessageSorting >(
            ComboBoxUtils::getIntegerOptionComboValue(mMessageSortingCombo, SortOrder::NoMessageSorting)
        )
    );

    accept();
}

ThemeContentItemSourceLabel::ThemeContentItemSourceLabel(QWidget *parent, Theme::ContentItem::Type type)
    : QLabel(parent), mType(type)
{
    setFrameStyle(QFrame::StyledPanel | QFrame::Raised);
}

ThemeContentItemSourceLabel::~ThemeContentItemSourceLabel()
{
}

MessageList::Core::Theme::ContentItem::Type ThemeContentItemSourceLabel::type() const
{
    return mType;
}

void ThemeContentItemSourceLabel::mousePressEvent(QMouseEvent *e)
{
    if (e->button() == Qt::LeftButton) {
        mMousePressPoint = e->pos();
    }
}

void ThemeContentItemSourceLabel::mouseMoveEvent(QMouseEvent *e)
{
    if (e->buttons() & Qt::LeftButton) {
        const QPoint diff = mMousePressPoint - e->pos();
        if (diff.manhattanLength() > 4) {
            startDrag();
        }
    }
}

void ThemeContentItemSourceLabel::startDrag()
{
    //QPixmap pix = QPixmap::grabWidget( this );
    //QPixmap alpha( pix.width(), pix.height() );
    //alpha.fill(0x0f0f0f0f);
    //pix.setAlphaChannel( alpha ); // <-- this crashes... no alpha for dragged pixmap :(
    QMimeData *data = new QMimeData();
    QByteArray arry;
    arry.resize(sizeof(Theme::ContentItem::Type));
    *((Theme::ContentItem::Type *) arry.data()) = mType;
    data->setData(QLatin1String(gThemeContentItemTypeDndMimeDataFormat), arry);
    QDrag *drag = new QDrag(this);
    drag->setMimeData(data);
    //drag->setPixmap( pix );
    //drag->setHotSpot( mapFromGlobal( QCursor::pos() ) );
    drag->exec(Qt::CopyAction, Qt::CopyAction);
}

ThemePreviewDelegate::ThemePreviewDelegate(QAbstractItemView *parent)
    : ThemeDelegate(parent)
{
    mRowMapper = new ModelInvariantRowMapper();

    mSampleGroupHeaderItem = new GroupHeaderItem(i18n("Message Group"));

Laurent Montel's avatar
Laurent Montel committed
198
199
    mSampleGroupHeaderItem->setDate(time(nullptr));
    mSampleGroupHeaderItem->setMaxDate(time(nullptr) + 31337);
200
201
202
203
    mSampleGroupHeaderItem->setSubject(i18n("Very long subject very long subject very long subject very long subject very long subject very long"));

    mSampleMessageItem = new FakeItem();

Laurent Montel's avatar
Laurent Montel committed
204
    mSampleMessageItem->setDate(time(nullptr));
205
    mSampleMessageItem->setSize(0x31337);
Laurent Montel's avatar
Laurent Montel committed
206
    mSampleMessageItem->setMaxDate(time(nullptr) + 31337);
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
    mSampleMessageItem->setSender(i18n("Sender"));
    mSampleMessageItem->setReceiver(i18n("Receiver"));
    mSampleMessageItem->setSubject(i18n("Very long subject very long subject very long subject very long subject very long subject very long"));
    mSampleMessageItem->setSignatureState(MessageItem::FullySigned);
    mSampleMessageItem->setEncryptionState(MessageItem::FullyEncrypted);

    QList< MessageItem::Tag * > list;
    list.append(new MessageItem::Tag(SmallIcon(QStringLiteral("feed-subscribe")), i18n("Sample Tag 1"), QString()));
    list.append(new MessageItem::Tag(SmallIcon(QStringLiteral("feed-subscribe")), i18n("Sample Tag 2"), QString()));
    list.append(new MessageItem::Tag(SmallIcon(QStringLiteral("feed-subscribe")), i18n("Sample Tag 3"), QString()));
    mSampleMessageItem->setFakeTags(list);

    mRowMapper->createModelInvariantIndex(0, mSampleMessageItem);

    mSampleGroupHeaderItem->rawAppendChildItem(mSampleMessageItem);
    mSampleMessageItem->setParent(mSampleGroupHeaderItem);

    Akonadi::MessageStatus stat;

    stat.fromQInt32(0x7fffffff);
    stat.setQueued(false);
    stat.setSent(false);
    stat.setSpam(true);
    stat.setWatched(true);
    stat.setHasInvitation();
    //stat.setHasAttachment( false );

    mSampleMessageItem->setStatus(stat);
}

ThemePreviewDelegate::~ThemePreviewDelegate()
{
    delete mSampleGroupHeaderItem;
    //delete mSampleMessageItem; (deleted by the parent)
    delete mRowMapper;
}

Item *ThemePreviewDelegate::itemFromIndex(const QModelIndex &index) const
{
    if (index.parent().isValid()) {
        return mSampleMessageItem;
    }

    return mSampleGroupHeaderItem;
}

ThemePreviewWidget::ThemePreviewWidget(QWidget *parent)
    : QTreeWidget(parent),
Laurent Montel's avatar
Laurent Montel committed
255
      mTheme(nullptr)
256
{
Laurent Montel's avatar
Laurent Montel committed
257
258
    mSelectedThemeContentItem = nullptr;
    mSelectedThemeColumn = nullptr;
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
    mFirstShow = true;
    mReadOnly = false;

    mDelegate = new ThemePreviewDelegate(this);
    setItemDelegate(mDelegate);
    setRootIsDecorated(false);
    viewport()->setAcceptDrops(true);

    header()->setContextMenuPolicy(Qt::CustomContextMenu);   // make sure it's true
    connect(header(), &QWidget::customContextMenuRequested,
            this, &ThemePreviewWidget::slotHeaderContextMenuRequested);

    mGroupHeaderSampleItem = new QTreeWidgetItem(this);
    mGroupHeaderSampleItem->setText(0, QString());
    mGroupHeaderSampleItem->setFlags(Qt::ItemIsEnabled);

    QTreeWidgetItem *m = new QTreeWidgetItem(mGroupHeaderSampleItem);
    m->setText(0, QString());

    mGroupHeaderSampleItem->setExpanded(true);
    header()->setMovable(false);
}

void ThemePreviewWidget::changeEvent(QEvent *event)
{
    if (event->type() == QEvent::FontChange) {
        mDelegate->generalFontChanged();
    }
    QTreeWidget::changeEvent(event);
}

ThemePreviewWidget::~ThemePreviewWidget()
{
}

QSize ThemePreviewWidget::sizeHint() const
{
    return QSize(350, 180);
}

void ThemePreviewWidget::setReadOnly(bool readOnly)
{
    mReadOnly = readOnly;
}

void ThemePreviewWidget::applyThemeColumnWidths()
{
    if (!mTheme) {
        return;
    }

    const QList< Theme::Column * > &columns = mTheme->columns();

    if (columns.isEmpty()) {
        viewport()->update(); // trigger a repaint
        return;
    }

    // Now we want to distribute the available width on all the columns.
    // The algorithm used here is very similar to the one used in View::applyThemeColumns().
    // It just takes care of ALL the columns instead of the visible ones.

    QList< Theme::Column * >::ConstIterator it;

    // Gather size hints for all sections.
    int idx = 0;
    int totalVisibleWidthHint = 0;
    QList< Theme::Column * >::ConstIterator end(columns.constEnd());

    for (it = columns.constBegin(); it != end; ++it) {
        totalVisibleWidthHint += mDelegate->sizeHintForItemTypeAndColumn(Item::Message, idx).width();
        idx++;
    }

    if (totalVisibleWidthHint < 16) {
        totalVisibleWidthHint = 16;    // be reasonable
    }

    // Now we can compute proportional widths.

    idx = 0;

    QList< int > realWidths;
    realWidths.reserve(columns.count());
    int totalVisibleWidth = 0;

    end = columns.constEnd();
    for (it = columns.constBegin(); it != end; ++it) {
        int hintWidth = mDelegate->sizeHintForItemTypeAndColumn(Item::Message, idx).width();
        int realWidth;
        if ((*it)->containsTextItems()) {
            // the column contains text items, it should get more space
            realWidth = ((hintWidth * viewport()->width()) / totalVisibleWidthHint) - 2;     // -2 is heuristic
            if (realWidth < (hintWidth + 2)) {
                realWidth = hintWidth + 2;    // can't be less
            }
        } else {
            // the column contains no text items, it should get just a little bit more than its sizeHint().
            realWidth = hintWidth + 2;
        }

        realWidths.append(realWidth);
        totalVisibleWidth += realWidth;

        idx++;
    }

    idx = 0;

    totalVisibleWidth += 4; // account for some view's border

    if (totalVisibleWidth < viewport()->width()) {
        // give the additional space to the text columns
        // also give more space to the first ones and less space to the last ones
        int available = viewport()->width() - totalVisibleWidth;

        for (it = columns.begin(); it != columns.end(); ++it) {
            if (((*it)->visibleByDefault() || (idx == 0)) && (*it)->containsTextItems()) {
                // give more space to this column
                available >>= 1; // eat half of the available space
                realWidths[ idx ] += available; // and give it to this column
            }

            idx++;
        }

        // if any space is still available, give it to the first column
        if (available) {
            realWidths[ 0 ] += available;
        }
    }

    idx = 0;

    // We're ready.
    // Assign widths. Hide the sections that are not visible by default, show the other ones.
    for (it = columns.begin(); it != columns.end(); ++it) {
        header()->resizeSection(idx, realWidths[ idx ]);
        idx++;
    }

#if 0
    if (mTheme->viewHeaderPolicy() == Theme::NeverShowHeader) {
        header()->hide();
    } else {
        header()->show();
    }
#endif
}

void ThemePreviewWidget::setTheme(Theme *theme)
{
    bool themeChanged = theme != mTheme;

Laurent Montel's avatar
Laurent Montel committed
413
    mSelectedThemeContentItem = nullptr;
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
    mThemeSelectedContentItemRect = QRect();
    mDropIndicatorPoint1 = QPoint();
    mDropIndicatorPoint2 = QPoint();
    mTheme = theme;
    mDelegate->setTheme(theme);
    if (!mTheme) {
        return;
    }
    mGroupHeaderSampleItem->setExpanded(true);

    const QList< Theme::Column * > &columns = mTheme->columns();

    setColumnCount(columns.count());

    QStringList headerLabels;
    headerLabels.reserve(columns.count());
    QList< Theme::Column * >::ConstIterator end(columns.constEnd());
    for (QList< Theme::Column * >::ConstIterator it = columns.constBegin(); it != end; ++it) {
        QString label = (*it)->label();
        if ((*it)->visibleByDefault()) {
            label += QStringLiteral(" (%1)").arg(i18nc("Indicates whether or not a header label is visible", "Visible"));
        }

        headerLabels.append(label);
    }

    setHeaderLabels(headerLabels);

    if (themeChanged) {
        applyThemeColumnWidths();
    }

    viewport()->update(); // trigger a repaint
}

void ThemePreviewWidget::internalHandleDragEnterEvent(QDragEnterEvent *e)
{
    e->ignore();

    if (!e->mimeData()) {
        return;
    }
    if (!e->mimeData()->hasFormat(QLatin1String(gThemeContentItemTypeDndMimeDataFormat))) {
        return;
    }

    e->accept();
}

void ThemePreviewWidget::showEvent(QShowEvent *e)
{
    QTreeWidget::showEvent(e);

    if (mFirstShow) {
        // Make sure we re-apply column widths the first time we're shown.
        // The first "apply" call was made while the widget was still hidden and
        // almost surely had wrong sizes.
        applyThemeColumnWidths();
        mFirstShow = false;
    }
}

void ThemePreviewWidget::dragEnterEvent(QDragEnterEvent *e)
{
    internalHandleDragEnterEvent(e);

    mThemeSelectedContentItemRect = QRect();

    viewport()->update(); // trigger a repaint
}

void ThemePreviewWidget::internalHandleDragMoveEvent(QDragMoveEvent *e)
{
    e->ignore();

    if (mReadOnly) {
        return;
    }

    if (!e->mimeData()) {
        return;
    }
    if (!e->mimeData()->hasFormat(QLatin1String(gThemeContentItemTypeDndMimeDataFormat))) {
        return;
    }

    QByteArray arry = e->mimeData()->data(QLatin1String(gThemeContentItemTypeDndMimeDataFormat));

    if (arry.size() != sizeof(Theme::ContentItem::Type)) {
        return;    // ugh
    }

    Theme::ContentItem::Type type = *((Theme::ContentItem::Type *) arry.data());

    if (!computeContentItemInsertPosition(e->pos(), type)) {
        return;
    }

    e->accept();
}

void ThemePreviewWidget::dragMoveEvent(QDragMoveEvent *e)
{
    if (mReadOnly) {
        return;
    }

    internalHandleDragMoveEvent(e);

    mThemeSelectedContentItemRect = QRect();

    viewport()->update(); // trigger a repaint
}

void ThemePreviewWidget::dropEvent(QDropEvent *e)
{
    mDropIndicatorPoint1 = mDropIndicatorPoint2;

    e->ignore();

    if (mReadOnly) {
        return;
    }

    if (!e->mimeData()) {
        return;
    }

    if (!e->mimeData()->hasFormat(QLatin1String(gThemeContentItemTypeDndMimeDataFormat))) {
        return;
    }

    QByteArray arry = e->mimeData()->data(QLatin1String(gThemeContentItemTypeDndMimeDataFormat));

    if (arry.size() != sizeof(Theme::ContentItem::Type)) {
        return;    // ugh
    }

    Theme::ContentItem::Type type = *((Theme::ContentItem::Type *) arry.data());

    if (!computeContentItemInsertPosition(e->pos(), type)) {
        viewport()->update();
        return;
    }

Laurent Montel's avatar
Laurent Montel committed
559
    Theme::Row *row = nullptr;
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

    switch (mRowInsertPosition) {
    case AboveRow:
        row = new Theme::Row();
        if (mDelegate->hitItem()->type() == Item::Message) {
            const_cast< Theme::Column * >(mDelegate->hitColumn())->insertMessageRow(mDelegate->hitRowIndex(), row);
        } else {
            const_cast< Theme::Column * >(mDelegate->hitColumn())->insertGroupHeaderRow(mDelegate->hitRowIndex(), row);
        }
        break;
    case InsideRow:
        row = const_cast< Theme::Row * >(mDelegate->hitRow());
        break;
    case BelowRow:
        row = new Theme::Row();
        if (mDelegate->hitItem()->type() == Item::Message) {
            const_cast< Theme::Column * >(mDelegate->hitColumn())->insertMessageRow(mDelegate->hitRowIndex() + 1, row);
        } else {
            const_cast< Theme::Column * >(mDelegate->hitColumn())->insertGroupHeaderRow(mDelegate->hitRowIndex() + 1, row);
        }
        break;
    }

    if (!row) {
        return;
    }

    Theme::ContentItem *ci = new Theme::ContentItem(type);
    if (ci->canBeDisabled()) {
        if (ci->isClickable()) {
            ci->setSoftenByBlendingWhenDisabled(true);    // default to softened
        } else {
            ci->setHideWhenDisabled(true);    // default to hidden
        }
    }

    int idx;

    switch (mItemInsertPosition) {
    case OnLeftOfItem:
        if (!mDelegate->hitContentItem()) {
            // bleah
            delete ci;
            return;
        }
        idx = mDelegate->hitContentItemRight() ? \
              row->rightItems().indexOf(const_cast< Theme::ContentItem * >(mDelegate->hitContentItem())) : \
              row->leftItems().indexOf(const_cast< Theme::ContentItem * >(mDelegate->hitContentItem()));
        if (idx < 0) {
            // bleah
            delete ci;
            return;
        }
        if (mDelegate->hitContentItemRight()) {
            row->insertRightItem(idx + 1, ci);
        } else {
            row->insertLeftItem(idx, ci);
        }
        break;
    case OnRightOfItem:
        if (!mDelegate->hitContentItem()) {
            // bleah
            delete ci;
            return;
        }
        idx = mDelegate->hitContentItemRight() ? \
              row->rightItems().indexOf(const_cast< Theme::ContentItem * >(mDelegate->hitContentItem())) : \
              row->leftItems().indexOf(const_cast< Theme::ContentItem * >(mDelegate->hitContentItem()));
        if (idx < 0) {
            // bleah
            delete ci;
            return;
        }
        if (mDelegate->hitContentItemRight()) {
            row->insertRightItem(idx, ci);
        } else {
            row->insertLeftItem(idx + 1, ci);
        }
        break;
    case AsLastLeftItem:
        row->addLeftItem(ci);
        break;
    case AsLastRightItem:
        row->addRightItem(ci);
        break;
    case AsFirstLeftItem:
        row->insertLeftItem(0, ci);
        break;
    case AsFirstRightItem:
        row->insertRightItem(0, ci);
        break;
    default: // should never happen
        row->addRightItem(ci);
        break;
    }

    e->acceptProposedAction();

    mThemeSelectedContentItemRect = QRect();
    mDropIndicatorPoint1 = mDropIndicatorPoint2;
Laurent Montel's avatar
Laurent Montel committed
660
    mSelectedThemeContentItem = nullptr;
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

    setTheme(mTheme);   // this will reset theme cache and trigger a global update
}

bool ThemePreviewWidget::computeContentItemInsertPosition(const QPoint &pos, Theme::ContentItem::Type type)
{
    mDropIndicatorPoint1 = mDropIndicatorPoint2; // this marks the position as invalid

    if (!mDelegate->hitTest(pos, false)) {
        return false;
    }

    if (!mDelegate->hitRow()) {
        return false;
    }

    if (mDelegate->hitRowIsMessageRow()) {
        if (!Theme::ContentItem::applicableToMessageItems(type)) {
            return false;
        }
    } else {
        if (!Theme::ContentItem::applicableToGroupHeaderItems(type)) {
            return false;
        }
    }

    QRect rowRect = mDelegate->hitRowRect();

    if (pos.y() < rowRect.top() + 3) {
        // above a row
        mRowInsertPosition = AboveRow;
        if (pos.x() < (rowRect.left() + (rowRect.width() / 2))) {
            mDropIndicatorPoint1 = rowRect.topLeft();
            mItemInsertPosition = AsLastLeftItem;
        } else {
            mDropIndicatorPoint1 = rowRect.topRight();
            mItemInsertPosition = AsLastRightItem;
        }
        mDropIndicatorPoint2 = QPoint(rowRect.left() + (rowRect.width() / 2), rowRect.top());
        return true;
    }

    if (pos.y() > rowRect.bottom() - 3) {
        // below a row
        mRowInsertPosition = BelowRow;
        if (pos.x() < (rowRect.left() + (rowRect.width() / 2))) {
            mDropIndicatorPoint1 = rowRect.bottomLeft();
            mItemInsertPosition = AsLastLeftItem;
        } else {
            mDropIndicatorPoint1 = rowRect.bottomRight();
            mItemInsertPosition = AsLastRightItem;
        }
        mDropIndicatorPoint2 = QPoint(rowRect.left() + (rowRect.width() / 2), rowRect.bottom());
        return true;
    }

    mRowInsertPosition = InsideRow;

    if (!mDelegate->hitContentItem()) {
        // didn't hit anything... probably no items in the row
        if (pos.x() < (rowRect.left() + (rowRect.width() / 2))) {
            mItemInsertPosition =  AsLastLeftItem;
            mDropIndicatorPoint1 = QPoint(rowRect.left(), rowRect.top());
            mDropIndicatorPoint2 = QPoint(rowRect.left(), rowRect.bottom());
        } else {
            mItemInsertPosition =  AsLastRightItem;
            mDropIndicatorPoint1 = QPoint(rowRect.right(), rowRect.top());
            mDropIndicatorPoint2 = QPoint(rowRect.right(), rowRect.bottom());
        }
        return true;
    }

    // hit something, maybe inexactly
    QRect itemRect = mDelegate->hitContentItemRect();

    if (!itemRect.contains(pos)) {
        // inexact hit: outside an item
        if (pos.x() > itemRect.right()) {
            // right side of an item
            if (mDelegate->hitRow()->rightItems().count() < 1) {
                // between the last left item and the right side
                if (pos.x() > (itemRect.right() + ((rowRect.right() - itemRect.right()) / 2))) {
                    // first/last right item
                    mItemInsertPosition = AsFirstRightItem;
                    mDropIndicatorPoint1 = rowRect.topRight();
                    mDropIndicatorPoint2 = rowRect.bottomRight();
                }
                return true;
            }
            // either there were some right items (so the theme delegate knows that the reported item is the closest)
            // or there were no right items but the position is closest to the left item than the right row end
            mItemInsertPosition = OnRightOfItem;
            mDropIndicatorPoint1 = itemRect.topRight();
            mDropIndicatorPoint2 = itemRect.bottomRight();
            return true;
        }

        // left side of an item
        if (mDelegate->hitRow()->leftItems().count() < 1) {
            // between the left side and the leftmost right item
            if (pos.x() < (itemRect.left() - ((itemRect.left() - rowRect.left()) / 2))) {
                mItemInsertPosition = AsFirstLeftItem;
                mDropIndicatorPoint1 = rowRect.topLeft();
                mDropIndicatorPoint2 = rowRect.bottomLeft();
                return true;
            }
        }
        mItemInsertPosition = OnLeftOfItem;
        mDropIndicatorPoint1 = itemRect.topLeft();
        mDropIndicatorPoint2 = itemRect.bottomLeft();
        return true;
    }

    // exact hit
    if (pos.x() < (itemRect.left() + (itemRect.width() / 2))) {
        // left side
        mItemInsertPosition = OnLeftOfItem;
        mDropIndicatorPoint1 = itemRect.topLeft();
        mDropIndicatorPoint2 = itemRect.bottomLeft();
        return true;
    }

    // right side
    mItemInsertPosition = OnRightOfItem;
    mDropIndicatorPoint1 = itemRect.topRight();
    mDropIndicatorPoint2 = itemRect.bottomRight();
    return true;
}

void ThemePreviewWidget::mouseMoveEvent(QMouseEvent *e)
{
    if (!(mSelectedThemeContentItem && (e->buttons() & Qt::LeftButton)) || mReadOnly) {
        QTreeWidget::mouseMoveEvent(e);
        return;
    }

    if (mSelectedThemeContentItem != mDelegate->hitContentItem()) {
        QTreeWidget::mouseMoveEvent(e);
        return; // ugh.. something weird happened
    }

    // starting a drag ?
    const QPoint diff = e->pos() - mMouseDownPoint;
    if (diff.manhattanLength() <= 4) {
        QTreeWidget::mouseMoveEvent(e);
        return; // ugh.. something weird happened
    }

    // starting a drag
    QMimeData *data = new QMimeData();
    QByteArray arry;
    arry.resize(sizeof(Theme::ContentItem::Type));
    *((Theme::ContentItem::Type *) arry.data()) = mSelectedThemeContentItem->type();
    data->setData(QLatin1String(gThemeContentItemTypeDndMimeDataFormat), arry);
    QDrag *drag = new QDrag(this);
    drag->setMimeData(data);

    // remove the Theme::ContentItem from the Theme
    if (mDelegate->hitContentItemRight()) {
        const_cast< Theme::Row * >(mDelegate->hitRow())->removeRightItem(mSelectedThemeContentItem);
    } else {
        const_cast< Theme::Row * >(mDelegate->hitRow())->removeLeftItem(mSelectedThemeContentItem);
    }

    delete mSelectedThemeContentItem;

    if (mDelegate->hitRow()->rightItems().isEmpty() && mDelegate->hitRow()->leftItems().isEmpty()) {
        if (mDelegate->hitItem()->type() == Item::Message) {
            if (mDelegate->hitColumn()->messageRows().count() > 1) {
                const_cast< Theme::Column * >(mDelegate->hitColumn())->removeMessageRow(const_cast< Theme::Row * >(mDelegate->hitRow()));
                delete mDelegate->hitRow();
            }
        } else {
            if (mDelegate->hitColumn()->groupHeaderRows().count() > 1) {
                const_cast< Theme::Column * >(mDelegate->hitColumn())->removeGroupHeaderRow(const_cast< Theme::Row * >(mDelegate->hitRow()));
                delete mDelegate->hitRow();
            }
        }
    }

Laurent Montel's avatar
Laurent Montel committed
841
    mSelectedThemeContentItem = nullptr;
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
    mThemeSelectedContentItemRect = QRect();
    mDropIndicatorPoint1 = mDropIndicatorPoint2;

    setTheme(mTheme);   // this will reset theme cache and trigger a global update

    // and do drag
    drag->exec(Qt::CopyAction, Qt::CopyAction);
}

void ThemePreviewWidget::mousePressEvent(QMouseEvent *e)
{
    if (mReadOnly) {
        QTreeWidget::mousePressEvent(e);
        return;
    }

    mMouseDownPoint = e->pos();

    if (mDelegate->hitTest(mMouseDownPoint)) {
        mSelectedThemeContentItem = const_cast< Theme::ContentItem * >(mDelegate->hitContentItem());
        mThemeSelectedContentItemRect = mSelectedThemeContentItem ? mDelegate->hitContentItemRect() : QRect();
    } else {
Laurent Montel's avatar
Laurent Montel committed
864
        mSelectedThemeContentItem = nullptr;
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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
        mThemeSelectedContentItemRect = QRect();
    }

    QTreeWidget::mousePressEvent(e);
    viewport()->update();

    if (e->button() == Qt::RightButton) {
        QMenu menu;

        if (mSelectedThemeContentItem) {

            menu.addSection(Theme::ContentItem::description(mSelectedThemeContentItem->type()));

            if (mSelectedThemeContentItem->displaysText()) {
                QAction *act;
                act = menu.addAction(i18nc("@action:inmenu soften the text color", "Soften"));
                act->setCheckable(true);
                act->setChecked(mSelectedThemeContentItem->softenByBlending());
                connect(act, &QAction::triggered, this, &ThemePreviewWidget::slotSoftenActionTriggered);

                QMenu *childmenu = new QMenu(&menu);

                act = childmenu->addAction(i18nc("@action:inmenu Font setting", "Bold"));
                act->setData(QVariant(static_cast<int>(Theme::ContentItem::IsBold)));
                act->setCheckable(true);
                act->setChecked(mSelectedThemeContentItem->isBold());
                act = childmenu->addAction(i18nc("@action:inmenu Font setting", "Italic"));
                act->setData(QVariant(static_cast<int>(Theme::ContentItem::IsItalic)));
                act->setCheckable(true);
                act->setChecked(mSelectedThemeContentItem->isItalic());

                connect(childmenu, &QMenu::triggered, this, &ThemePreviewWidget::slotFontMenuTriggered);

                menu.addMenu(childmenu)->setText(i18n("Font"));
            }

            if (mSelectedThemeContentItem->canUseCustomColor()) {
                QMenu *childmenu = new QMenu(&menu);

                QActionGroup *grp = new QActionGroup(childmenu);

                QAction *act;
                act = childmenu->addAction(i18nc("@action:inmenu Foreground color setting", "Default"));
                act->setData(QVariant(static_cast< int >(0)));
                act->setCheckable(true);
                act->setChecked(!mSelectedThemeContentItem->useCustomColor());
                grp->addAction(act);
                act = childmenu->addAction(i18nc("@action:inmenu Foreground color setting", "Custom..."));
                act->setData(QVariant(static_cast< int >(Theme::ContentItem::UseCustomColor)));
                act->setCheckable(true);
                act->setChecked(mSelectedThemeContentItem->useCustomColor());
                grp->addAction(act);

                connect(childmenu, &QMenu::triggered, this, &ThemePreviewWidget::slotForegroundColorMenuTriggered);

                menu.addMenu(childmenu)->setText(i18n("Foreground Color"));
            }

            if (mSelectedThemeContentItem->canBeDisabled()) {
                QMenu *childmenu = new QMenu(&menu);

                QActionGroup *grp = new QActionGroup(childmenu);

                QAction *act;
                act = childmenu->addAction(i18nc("Hide a mark if the mail does not have the attribute, e.g. Important mark on a non important mail", "Hide"));
                act->setData(QVariant(static_cast< int >(Theme::ContentItem::HideWhenDisabled)));
                act->setCheckable(true);
                act->setChecked(mSelectedThemeContentItem->hideWhenDisabled());
                grp->addAction(act);
                act = childmenu->addAction(i18nc("Keep a empty space in the list if the mail does not have the attribute, e.g. Important mark on a non important mail", "Keep Empty Space"));
                act->setData(QVariant(static_cast< int >(0)));
                act->setCheckable(true);
                act->setChecked(!(mSelectedThemeContentItem->softenByBlendingWhenDisabled() || mSelectedThemeContentItem->hideWhenDisabled()));
                grp->addAction(act);
                act = childmenu->addAction(i18nc("Show the icon softened in the list if the mail does not have the attribute, e.g. Important mark on a non important mail", "Keep Softened Icon"));
                act->setData(QVariant(static_cast< int >(Theme::ContentItem::SoftenByBlendingWhenDisabled)));
                act->setCheckable(true);
                act->setChecked(mSelectedThemeContentItem->softenByBlendingWhenDisabled());
                grp->addAction(act);

                connect(childmenu, &QMenu::triggered, this, &ThemePreviewWidget::slotDisabledFlagsMenuTriggered);

                menu.addMenu(childmenu)->setText(i18n("When Disabled"));
            }

        }

        if (mDelegate->hitItem()) {
            if (mDelegate->hitItem()->type() == Item::GroupHeader) {
                menu.addSection(i18n("Group Header"));

                // Background color (mode) submenu
                QMenu *childmenu = new QMenu(&menu);

                QActionGroup *grp = new QActionGroup(childmenu);

                QAction *act;
                act = childmenu->addAction(i18nc("@action:inmenu Group header background color setting", "None"));
                act->setData(QVariant(static_cast< int >(Theme::Transparent)));
                act->setCheckable(true);
                act->setChecked(mTheme->groupHeaderBackgroundMode() == Theme::Transparent);
                grp->addAction(act);
                act = childmenu->addAction(i18nc("@action:inmenu Group header background color setting", "Automatic"));
                act->setData(QVariant(static_cast< int >(Theme::AutoColor)));
                act->setCheckable(true);
                act->setChecked(mTheme->groupHeaderBackgroundMode() == Theme::AutoColor);
                grp->addAction(act);
                act = childmenu->addAction(i18nc("@action:inmenu Group header background color setting", "Custom..."));
                act->setData(QVariant(static_cast< int >(Theme::CustomColor)));
                act->setCheckable(true);
                act->setChecked(mTheme->groupHeaderBackgroundMode() == Theme::CustomColor);
                grp->addAction(act);

                connect(childmenu, &QMenu::triggered, this, &ThemePreviewWidget::slotGroupHeaderBackgroundModeMenuTriggered);

                menu.addMenu(childmenu)->setText(i18n("Background Color"));

                // Background style submenu
                childmenu = new QMenu(&menu);

                grp = new QActionGroup(childmenu);
                QList< QPair< QString, int > > styles = Theme::enumerateGroupHeaderBackgroundStyles();
                QList< QPair< QString, int > >::ConstIterator end(styles.constEnd());

                for (QList< QPair< QString, int > >::ConstIterator it = styles.constBegin(); it != end; ++it) {
                    act = childmenu->addAction((*it).first);
                    act->setData(QVariant((*it).second));
                    act->setCheckable(true);
                    act->setChecked(mTheme->groupHeaderBackgroundStyle() == static_cast< Theme::GroupHeaderBackgroundStyle >((*it).second));
                    grp->addAction(act);
                }

                connect(childmenu, &QMenu::triggered, this, &ThemePreviewWidget::slotGroupHeaderBackgroundStyleMenuTriggered);

                act = menu.addMenu(childmenu);
                act->setText(i18n("Background Style"));
                if (mTheme->groupHeaderBackgroundMode() == Theme::Transparent) {
                    act->setEnabled(false);
                }

            }
        }

        if (menu.isEmpty()) {
            return;
        }

        menu.exec(viewport()->mapToGlobal(e->pos()));

    }
}

void ThemePreviewWidget::slotDisabledFlagsMenuTriggered(QAction *act)
{
    if (!mSelectedThemeContentItem) {
        return;
    }

    bool ok;
    const int flags = act->data().toInt(&ok);
    if (!ok) {
        return;
    }

    mSelectedThemeContentItem->setHideWhenDisabled(flags == Theme::ContentItem::HideWhenDisabled);
    mSelectedThemeContentItem->setSoftenByBlendingWhenDisabled(flags == Theme::ContentItem::SoftenByBlendingWhenDisabled);

    setTheme(mTheme);   // this will reset theme cache and trigger a global update
}

void ThemePreviewWidget::slotForegroundColorMenuTriggered(QAction *act)
{
    if (!mSelectedThemeContentItem) {
        return;
    }

    bool ok;
    const int flag = act->data().toInt(&ok);
    if (!ok) {
        return;
    }

    if (flag == 0) {
        mSelectedThemeContentItem->setUseCustomColor(false);
        setTheme(mTheme);   // this will reset theme cache and trigger a global update
        return;
    }

    QColor clr;
    clr = QColorDialog::getColor(mSelectedThemeContentItem->customColor(), this);
    if (!clr.isValid()) {
        return;
    }

    mSelectedThemeContentItem->setCustomColor(clr);
    mSelectedThemeContentItem->setUseCustomColor(true);

    setTheme(mTheme);   // this will reset theme cache and trigger a global update
}

void ThemePreviewWidget::slotSoftenActionTriggered(bool)
{
    if (!mSelectedThemeContentItem) {
        return;
    }

    mSelectedThemeContentItem->setSoftenByBlending(!mSelectedThemeContentItem->softenByBlending());
    setTheme(mTheme);   // this will reset theme cache and trigger a global update
}

void ThemePreviewWidget::slotFontMenuTriggered(QAction *act)
{
    if (!mSelectedThemeContentItem) {
        return;
    }

    bool ok;
    const int flag = act->data().toInt(&ok);
    if (!ok) {
        return;
    }

    if (flag == Theme::ContentItem::IsBold && mSelectedThemeContentItem->isBold() != act->isChecked()) {
        mSelectedThemeContentItem->setBold(act->isChecked());
        setTheme(mTheme);
    } else if (flag == Theme::ContentItem::IsItalic && mSelectedThemeContentItem->isItalic() != act->isChecked()) {
        mSelectedThemeContentItem->setItalic(act->isChecked());
        setTheme(mTheme);
    }
}

void ThemePreviewWidget::slotGroupHeaderBackgroundModeMenuTriggered(QAction *act)
{
    bool ok;
    Theme::GroupHeaderBackgroundMode mode = static_cast< Theme::GroupHeaderBackgroundMode >(act->data().toInt(&ok));
    if (!ok) {
        return;
    }

    switch (mode) {
    case Theme::Transparent:
        mTheme->setGroupHeaderBackgroundMode(Theme::Transparent);
        break;
    case Theme::AutoColor:
        mTheme->setGroupHeaderBackgroundMode(Theme::AutoColor);
        break;
    case Theme::CustomColor: {
        QColor clr;
        clr = QColorDialog::getColor(mTheme->groupHeaderBackgroundColor(), this);
1114
        if (!clr.isValid()) {
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
            return;
        }

        mTheme->setGroupHeaderBackgroundMode(Theme::CustomColor);
        mTheme->setGroupHeaderBackgroundColor(clr);
    }
    break;
    }

    setTheme(mTheme);   // this will reset theme cache and trigger a global update
}

void ThemePreviewWidget::slotGroupHeaderBackgroundStyleMenuTriggered(QAction *act)
{
    bool ok;
    Theme::GroupHeaderBackgroundStyle mode = static_cast< Theme::GroupHeaderBackgroundStyle >(act->data().toInt(&ok));
    if (!ok) {
        return;
    }

    mTheme->setGroupHeaderBackgroundStyle(mode);

    setTheme(mTheme);   // this will reset theme cache and trigger a global update
}

void ThemePreviewWidget::paintEvent(QPaintEvent *e)
{
    QTreeWidget::paintEvent(e);

    if (
        mThemeSelectedContentItemRect.isValid() ||
        (mDropIndicatorPoint1 != mDropIndicatorPoint2)
    ) {
        QPainter painter(viewport());

        if (mThemeSelectedContentItemRect.isValid()) {
            painter.setPen(QPen(Qt::black));
            painter.drawRect(mThemeSelectedContentItemRect);
        }
        if (mDropIndicatorPoint1 != mDropIndicatorPoint2) {
            painter.setPen(QPen(Qt::black, 3));
            painter.drawLine(mDropIndicatorPoint1, mDropIndicatorPoint2);
        }
    }
}

void ThemePreviewWidget::slotHeaderContextMenuRequested(const QPoint &pos)
{
    if (mReadOnly) {
        return;
    }

    QTreeWidgetItem *hitem = headerItem();
    if (!hitem) {
        return;    // ooops
    }

    int col = header()->logicalIndexAt(pos);

    if (col < 0) {
        return;
    }

    if (col >= mTheme->columns().count()) {
        return;
    }

    mSelectedThemeColumn = mTheme->column(col);
    if (!mSelectedThemeColumn) {
        return;
    }

    QMenu menu;

    menu.setTitle(mSelectedThemeColumn->label());

    QAction *act;

    act = menu.addAction(i18n("Column Properties..."));
    connect(act, &QAction::triggered, this, &ThemePreviewWidget::slotColumnProperties);

    act = menu.addAction(i18n("Add Column..."));
    connect(act, &QAction::triggered, this, &ThemePreviewWidget::slotAddColumn);

    act = menu.addAction(i18n("Delete Column"));
    connect(act, &QAction::triggered, this, &ThemePreviewWidget::slotDeleteColumn);
    act->setEnabled(col > 0);

    menu.addSeparator();

    act = menu.addAction(i18n("Move Column to Left"));
    connect(act, &QAction::triggered, this, &ThemePreviewWidget::slotMoveColumnToLeft);
    act->setEnabled(col > 0);

    act = menu.addAction(i18n("Move Column to Right"));
    connect(act, &QAction::triggered, this, &ThemePreviewWidget::slotMoveColumnToRight);
    act->setEnabled(col < mTheme->columns().count() - 1);

    menu.exec(header()->mapToGlobal(pos));
}

void ThemePreviewWidget::slotMoveColumnToLeft()
{
    if (!mSelectedThemeColumn) {
        return;
    }

    const int columnIndex = mTheme->columns().indexOf(mSelectedThemeColumn);
    mTheme->moveColumn(columnIndex, columnIndex - 1);
    setTheme(mTheme);   // this will reset theme cache and trigger a global update
}

void ThemePreviewWidget::slotMoveColumnToRight()
{
    if (!mSelectedThemeColumn) {
        return;
    }

    const int columnIndex = mTheme->columns().indexOf(mSelectedThemeColumn);
    mTheme->moveColumn(columnIndex, columnIndex + 1);
    setTheme(mTheme);   // this will reset theme cache and trigger a global update
}

void ThemePreviewWidget::slotAddColumn()
{
    int newColumnIndex = mTheme->columns().count();

    if (mSelectedThemeColumn) {
        newColumnIndex = mTheme->columns().indexOf(mSelectedThemeColumn);
        if (newColumnIndex < 0) {
            newColumnIndex = mTheme->columns().count();
        } else {
            newColumnIndex++;
        }
    }

    mSelectedThemeColumn = new Theme::Column();
    mSelectedThemeColumn->setLabel(i18n("New Column"));
    mSelectedThemeColumn->setVisibleByDefault(true);

    mSelectedThemeColumn->addMessageRow(new Theme::Row());
    mSelectedThemeColumn->addGroupHeaderRow(new Theme::Row());

    ThemeColumnPropertiesDialog *dlg =
        new ThemeColumnPropertiesDialog(this, mSelectedThemeColumn, i18n("Add New Column"));

    if (dlg->exec() == QDialog::Accepted) {
        mTheme->insertColumn(newColumnIndex, mSelectedThemeColumn);

Laurent Montel's avatar
Laurent Montel committed
1264
        mSelectedThemeContentItem = nullptr;
1265
1266
1267
1268
1269
1270
1271
1272
        mThemeSelectedContentItemRect = QRect();
        mDropIndicatorPoint1 = mDropIndicatorPoint2;

        setTheme(mTheme);   // this will reset theme cache and trigger a global update

    } else {

        delete mSelectedThemeColumn;
Laurent Montel's avatar
Laurent Montel committed
1273
        mSelectedThemeColumn = nullptr;
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
    }

    delete dlg;
}

void ThemePreviewWidget::slotColumnProperties()
{
    if (!mSelectedThemeColumn) {
        return;
    }

    ThemeColumnPropertiesDialog *dlg =
        new ThemeColumnPropertiesDialog(this, mSelectedThemeColumn, i18n("Column Properties"));

    if (dlg->exec() == QDialog::Accepted) {
Laurent Montel's avatar
Laurent Montel committed
1289
        mSelectedThemeContentItem = nullptr;
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
        mThemeSelectedContentItemRect = QRect();
        mDropIndicatorPoint1 = mDropIndicatorPoint2;

        setTheme(mTheme);   // this will reset theme cache and trigger a global update
    }

    delete dlg;
}

void ThemePreviewWidget::slotDeleteColumn()
{
    if (!mSelectedThemeColumn) {
        return;
    }

    const int idx = mTheme->columns().indexOf(mSelectedThemeColumn);
    if (idx < 1) { // first column can't be deleted
        return;
    }

    mTheme->removeColumn(mSelectedThemeColumn);
    delete mSelectedThemeColumn;
Laurent Montel's avatar
Laurent Montel committed
1312
    mSelectedThemeColumn = nullptr;
1313

Laurent Montel's avatar
Laurent Montel committed
1314
    mSelectedThemeContentItem = nullptr;
1315
1316
1317
1318
1319
1320
1321
1322
1323
    mThemeSelectedContentItemRect = QRect();
    mDropIndicatorPoint1 = mDropIndicatorPoint2;

    setTheme(mTheme);   // this will reset theme cache and trigger a global update
}

ThemeEditor::ThemeEditor(QWidget *parent)
    : OptionSetEditor(parent)
{
Laurent Montel's avatar
Laurent Montel committed
1324
    mCurrentTheme = nullptr;
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336

    // Appearance tab
    QWidget *tab = new QWidget(this);
    addTab(tab, i18n("Appearance"));

    QGridLayout *tabg = new QGridLayout(tab);

    QGroupBox *gb = new QGroupBox(i18n("Content Items"), tab);
    tabg->addWidget(gb, 0, 0);

    QGridLayout *gblayout = new QGridLayout(gb);

1337
1338
    Theme dummyTheme;

1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
    ThemeContentItemSourceLabel *cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::Subject);
    cil->setText(Theme::ContentItem::description(cil->type()));
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 0, 0);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::Date);
    cil->setText(Theme::ContentItem::description(cil->type()));
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 1, 0);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::Size);
    cil->setText(Theme::ContentItem::description(cil->type()));
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 2, 0);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::Sender);
    cil->setText(Theme::ContentItem::description(cil->type()));
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 0, 1);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::Receiver);
    cil->setText(Theme::ContentItem::description(cil->type()));
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 1, 1);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::SenderOrReceiver);
    cil->setText(Theme::ContentItem::description(cil->type()));
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 2, 1);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::MostRecentDate);
    cil->setText(Theme::ContentItem::description(cil->type()));
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 0, 2);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::TagList);
    cil->setText(Theme::ContentItem::description(cil->type()));
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 1, 2);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::CombinedReadRepliedStateIcon);
1380
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconRepliedAndForwarded));
1381
1382
1383
1384
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 0, 3);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::ReadStateIcon);
1385
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconNew));
1386
1387
1388
1389
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 1, 3);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::RepliedStateIcon);
1390
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconReplied));
1391
1392
1393
1394
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 2, 3);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::AttachmentStateIcon);
1395
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconAttachment));
1396
1397
1398
1399
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 0, 4);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::EncryptionStateIcon);
1400
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconFullyEncrypted));
1401
1402
1403
1404
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 1, 4);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::SignatureStateIcon);
1405
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconFullySigned));
1406
1407
1408
1409
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 2, 4);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::ActionItemStateIcon);
1410
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconActionItem));
1411
1412
1413
1414
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 0, 5);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::AnnotationIcon);
1415
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconAnnotation));
1416
1417
1418
1419
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 1, 5);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::InvitationIcon);
1420
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconInvitation));
1421
1422
1423
1424
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 2, 5);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::ImportantStateIcon);
1425
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconImportant));
1426
1427
1428
1429
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 0, 6);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::SpamHamStateIcon);
1430
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconSpam));
1431
1432
1433
1434
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 1, 6);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::WatchedIgnoredStateIcon);
1435
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconWatched));
1436
1437
1438
1439
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 2, 6);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::ExpandedStateIcon);
1440
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconShowMore));
1441
1442
1443
1444
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 0, 7);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::VerticalLine);
1445
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconVerticalLine));
1446
1447
1448
1449
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 1, 7);

    cil = new ThemeContentItemSourceLabel(gb, Theme::ContentItem::HorizontalSpacer);
1450
    cil->setPixmap(*dummyTheme.pixmap(Theme::IconHorizontalSpacer));
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
    cil->setToolTip(Theme::ContentItem::description(cil->type()));
    gblayout->addWidget(cil, 2, 7);

    mPreviewWidget = new ThemePreviewWidget(tab);
    tabg->addWidget(mPreviewWidget, 1, 0);

    QLabel *l = new QLabel(tab);
    l->setText(i18n("Right click on the header to add or modify columns. Drag the content items and drop them on the columns in order to compose your theme. Right click on the items inside the view for more options."));
    l->setWordWrap(true);
    l->setAlignment(Qt::AlignCenter);
    tabg->addWidget(l, 2, 0);

    tabg->setRowStretch(1, 1);

    // Advanced tab
    tab = new QWidget(this);
    addTab(tab, i18nc("@title:tab Advanced theme settings", "Advanced"));

    tabg = new QGridLayout(tab);

    l = new QLabel(i18n("Header:"), tab);
    tabg->addWidget(l, 0, 0);

    mViewHeaderPolicyCombo = new KComboBox(tab);
    tabg->addWidget(mViewHeaderPolicyCombo, 0, 1);

    l = new QLabel(i18n("Icon size:"), tab);
    tabg->addWidget(l, 1, 0);

    mIconSizeSpinBox = new KPluralHandlingSpinBox(tab);
    mIconSizeSpinBox->setMinimum(8);
    mIconSizeSpinBox->setMaximum(64);
    mIconSizeSpinBox->setSuffix(ki18ncp("suffix in a spinbox", " pixel", " pixels"));

    QObject::connect(mIconSizeSpinBox, static_cast<void (KPluralHandlingSpinBox::*)(int)>(&KPluralHandlingSpinBox::valueChanged), this, &ThemeEditor::slotIconSizeSpinBoxValueChanged);

    tabg->addWidget(mIconSizeSpinBox, 1, 1);

    tabg->setColumnStretch(1, 1);
    tabg->setRowStretch(2, 1);
    fillViewHeaderPolicyCombo();

}

ThemeEditor::~ThemeEditor()
{
}

void ThemeEditor::editTheme(Theme *set)
{
    mCurrentTheme = set;
    mPreviewWidget->setTheme(mCurrentTheme);

    if (!mCurrentTheme) {
        setEnabled(false);
        return;
    }
    setEnabled(true);

    nameEdit()->setText(set->name());
    descriptionEdit()->setPlainText(set->description());

    ComboBoxUtils::setIntegerOptionComboValue(mViewHeaderPolicyCombo, (int)mCurrentTheme->viewHeaderPolicy());

    mIconSizeSpinBox->setValue(set->iconSize());
    setReadOnly(mCurrentTheme->readOnly());
}

void ThemeEditor::setReadOnly(bool readOnly)
{
    mPreviewWidget->setReadOnly(readOnly);
    mViewHeaderPolicyCombo->setEnabled(!readOnly);
    mIconSizeSpinBox->setEnabled(!readOnly);
    OptionSetEditor::setReadOnly(readOnly);
}

void ThemeEditor::commit()
{
    if (!mCurrentTheme || mCurrentTheme->readOnly()) {
        return;
    }

    mCurrentTheme->setName(nameEdit()->text());
    mCurrentTheme->setDescription(descriptionEdit()->toPlainText());

    mCurrentTheme->setViewHeaderPolicy(
        (Theme::ViewHeaderPolicy)ComboBoxUtils::getIntegerOptionComboValue(mViewHeaderPolicyCombo, 0)
    );
    mCurrentTheme->setIconSize(mIconSizeSpinBox->value());
    // other settings are already committed to this theme
}

void ThemeEditor::fillViewHeaderPolicyCombo()
{
    ComboBoxUtils::fillIntegerOptionCombo(
        mViewHeaderPolicyCombo,
        Theme::enumerateViewHeaderPolicyOptions()
    );
}

void ThemeEditor::slotNameEditTextEdited(const QString &newName)
{
    if (!mCurrentTheme) {
        return;
    }
    mCurrentTheme->setName(newName);
    Q_EMIT themeNameChanged();
}

void ThemeEditor::slotIconSizeSpinBoxValueChanged(int val)
{
    if (!mCurrentTheme) {
        return;
    }
    mCurrentTheme->setIconSize(val);

    mPreviewWidget->setTheme(mCurrentTheme);   // will trigger a cache reset and a view update
}

MessageList::Core::Theme *ThemeEditor::editedTheme() const
{
    return mCurrentTheme;
}