aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qmldesigner/qmldesignerextension/timelineeditor/preseteditor.cpp
blob: 4e6f9c9f170c1f27e4fb0bf885cd571a751814c1 (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
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include "preseteditor.h"

#include "canvas.h"
#include "easingcurve.h"
#include "timelineicons.h"

#include <QAbstractButton>
#include <QApplication>
#include <QContextMenuEvent>
#include <QMenu>
#include <QMessageBox>
#include <QPainter>
#include <QPixmap>
#include <QSettings>
#include <QStandardItemModel>
#include <QString>

#include <coreplugin/icore.h>
#include <theme.h>

namespace QmlDesigner {

constexpr int iconWidth = 86;
constexpr int iconHeight = 86;
constexpr int itemFrame = 3;
constexpr int itemWidth = iconWidth + 2 * itemFrame;
constexpr int unsavedMarkSize = 18;

constexpr int spacingg = 5;

const QColor background = Qt::white;

const QColor labelBackground = qRgb(0x70, 0x70, 0x70);
const QColor canvasBackground = qRgb(0x46, 0x46, 0x46);
const QColor curveLine = qRgb(0xe6, 0xe7, 0xe8);

PresetItemDelegate::PresetItemDelegate() = default;

void PresetItemDelegate::paint(QPainter *painter,
                               const QStyleOptionViewItem &opt,
                               const QModelIndex &index) const
{
    QStyleOptionViewItem option = opt;
    initStyleOption(&option, index);

    auto *w = option.widget;
    auto *style = w == nullptr ? qApp->style() : w->style();

    QSize textSize = QSize(option.rect.width(),
                           style->subElementRect(QStyle::SE_ItemViewItemText, &option, w).height());

    auto textRect = QRect(option.rect.topLeft(), textSize);
    textRect.moveBottom(option.rect.bottom());

    option.font.setPixelSize(Theme::instance()->smallFontPixelSize());

    painter->save();
    painter->fillRect(option.rect, canvasBackground);

    if (option.text.isEmpty())
        painter->fillRect(textRect, canvasBackground);
    else
        painter->fillRect(textRect, Theme::instance()->qmlDesignerButtonColor());

    style->drawControl(QStyle::CE_ItemViewItem, &option, painter, option.widget);

    QVariant dirty = option.index.data(PresetList::ItemRole_Dirty);
    if (dirty.isValid()) {
        if (dirty.toBool()) {
            QRect asteriskRect(option.rect.right() - unsavedMarkSize,
                               itemFrame,
                               unsavedMarkSize,
                               unsavedMarkSize);

            QFont font = painter->font();
            font.setPixelSize(unsavedMarkSize);
            painter->setFont(font);

            auto pen = painter->pen();
            pen.setColor(Qt::white);
            painter->setPen(pen);

            painter->drawText(asteriskRect, Qt::AlignTop | Qt::AlignRight, "*");
        }
    }
    painter->restore();
}

QSize PresetItemDelegate::sizeHint(const QStyleOptionViewItem &opt, const QModelIndex &index) const
{
    QSize size = QStyledItemDelegate::sizeHint(opt, index);
    size.rwidth() = itemWidth;
    return size;
}

QIcon paintPreview()
{
    QPixmap pm(iconWidth, iconHeight);
    pm.fill(canvasBackground);
    return QIcon(pm);
}

QIcon paintPreview(const EasingCurve &curve)
{
    QPixmap pm(iconWidth, iconHeight);
    pm.fill(canvasBackground);

    QPainter painter(&pm);
    painter.setRenderHint(QPainter::Antialiasing, true);

    Canvas canvas(iconWidth, iconHeight, 2, 2, 9, 6, 0, 1);
    canvas.paintCurve(&painter, curve, curveLine);

    return QIcon(pm);
}

namespace Internal {

static const char settingsKey[] = "EasingCurveList";
static const char settingsFileName[] = "/EasingCurves.ini";

QString settingsFullFilePath(const QSettings::Scope &scope)
{
    if (scope == QSettings::SystemScope)
        return Core::ICore::installerResourcePath() + settingsFileName;

    return Core::ICore::userResourcePath() + settingsFileName;
}

} // namespace Internal

PresetList::PresetList(QSettings::Scope scope, QWidget *parent)
    : QListView(parent)
    , m_scope(scope)
    , m_index(-1)
    , m_filename(Internal::settingsFullFilePath(scope))
{
    int magic = 4;
    int scrollBarWidth = this->style()->pixelMetric(QStyle::PM_ScrollBarExtent);
    const int width = 3 * itemWidth + 4 * spacingg + scrollBarWidth + magic;

    setFixedWidth(width);

    setModel(new QStandardItemModel);

    setItemDelegate(new PresetItemDelegate);

    setSpacing(spacingg);

    setUniformItemSizes(true);

    setIconSize(QSize(iconWidth, iconHeight));

    setSelectionMode(QAbstractItemView::SingleSelection);

    setViewMode(QListView::IconMode);

    setFlow(QListView::LeftToRight);

    setMovement(QListView::Static);

    setWrapping(true);

    setTextElideMode(Qt::ElideMiddle);

    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
}

void PresetList::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
    for (const QModelIndex &index : deselected.indexes()) {
        if (dirty(index)) {
            QMessageBox msgBox;
            msgBox.setText("The preset has been modified.");
            msgBox.setInformativeText("Do you want to save your changes?");
            msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Discard
                                      | QMessageBox::Cancel);
            msgBox.setDefaultButton(QMessageBox::Save);

            if (QAbstractButton *button = msgBox.button(QMessageBox::Discard))
                button->setText("Discard Changes");

            if (QAbstractButton *button = msgBox.button(QMessageBox::Cancel))
                button->setText("Cancel Selection");

            int ret = msgBox.exec();

            switch (ret) {
            case QMessageBox::Save:
                // Save the preset and continue selection.
                writePresets();
                break;
            case QMessageBox::Discard:
                // Discard changes to the curve and continue selection.
                revert(index);
                break;

            case QMessageBox::Cancel:
                // Cancel selection operation and leave the curve untouched.
                selectionModel()->select(index, QItemSelectionModel::ClearAndSelect);
                return;

            default:
                // should never be reachedDiscard
                break;
            }
        }
    }

    for (const auto &index : selected.indexes()) {
        QVariant curveData = model()->data(index, ItemRole_Data);
        if (curveData.isValid())
            emit presetChanged(curveData.value<EasingCurve>());
    }
}

bool PresetList::hasSelection() const
{
    return selectionModel()->hasSelection();
}

bool PresetList::dirty(const QModelIndex &index) const
{
    return model()->data(index, ItemRole_Dirty).toBool();
}

int PresetList::index() const
{
    return m_index;
}

bool PresetList::isEditable(const QModelIndex &index) const
{
    QFlags<Qt::ItemFlag> flags(model()->flags(index));
    return flags.testFlag(Qt::ItemIsEditable);
}

void PresetList::initialize(int index)
{
    m_index = index;

    readPresets();
}

void PresetList::readPresets()
{
    auto *simodel = qobject_cast<QStandardItemModel *>(model());

    simodel->clear();

    QList<NamedEasingCurve> curves = storedCurves();

    for (int i = 0; i < curves.size(); ++i) {
        QVariant curveData = QVariant::fromValue(curves[i].curve());

        auto *item = new QStandardItem(paintPreview(curves[i].curve()), curves[i].name());
        item->setData(curveData, ItemRole_Data);
        item->setEditable(m_scope == QSettings::UserScope);
        item->setToolTip(curves[i].name());

        simodel->setItem(i, item);
    }
}

void PresetList::writePresets()
{
    QList<QVariant> presets;
    for (int i = 0; i < model()->rowCount(); ++i) {
        QModelIndex index = model()->index(i, 0);

        QVariant nameData = model()->data(index, Qt::DisplayRole);
        QVariant curveData = model()->data(index, ItemRole_Data);

        if (nameData.isValid() && curveData.isValid()) {
            NamedEasingCurve curve(nameData.toString(), curveData.value<QmlDesigner::EasingCurve>());

            presets << QVariant::fromValue(curve);
        }

        model()->setData(index, false, ItemRole_Dirty);
    }

    QSettings settings(m_filename, QSettings::IniFormat);
    settings.clear();
    settings.setValue(Internal::settingsKey, QVariant::fromValue(presets));
}

void PresetList::revert(const QModelIndex &index)
{
    auto *simodel = qobject_cast<QStandardItemModel *>(model());
    if (auto *item = simodel->itemFromIndex(index)) {
        QString name = item->data(Qt::DisplayRole).toString();
        QList<NamedEasingCurve> curves = storedCurves();

        for (const auto &curve : curves) {
            if (curve.name() == name) {
                item->setData(false, ItemRole_Dirty);
                item->setData(paintPreview(curve.curve()), Qt::DecorationRole);
                item->setData(QVariant::fromValue(curve.curve()), ItemRole_Data);
                item->setToolTip(name);
                return;
            }
        }
    }
}

void PresetList::updateCurve(const EasingCurve &curve)
{
    if (!selectionModel()->hasSelection())
        return;

    QVariant icon = QVariant::fromValue(paintPreview(curve));
    QVariant curveData = QVariant::fromValue(curve);

    for (const auto &index : selectionModel()->selectedIndexes())
        setItemData(index, curveData, icon);
}

void PresetList::contextMenuEvent(QContextMenuEvent *event)
{
    event->accept();

    if (m_scope == QSettings::SystemScope)
        return;

    QMenu menu;

    QAction *addAction = menu.addAction(tr("Add Preset"));

    connect(addAction, &QAction::triggered, [&]() { createItem(); });

    if (selectionModel()->hasSelection()) {
        QAction *removeAction = menu.addAction(tr("Delete Selected Preset"));
        connect(removeAction, &QAction::triggered, [&]() { removeSelectedItem(); });
    }

    menu.exec(event->globalPos());
}

void PresetList::dataChanged(const QModelIndex &topLeft,
                             const QModelIndex &bottomRight,
                             const QVector<int> &roles)
{
    if (topLeft == bottomRight && roles.contains(0)) {
        const QVariant name = model()->data(topLeft, 0);
        model()->setData(topLeft, name, Qt::ToolTipRole);
    }
}

void PresetList::createItem()
{
    EasingCurve curve;
    curve.makeDefault();
    createItem(createUniqueName(), curve);
}

void PresetList::createItem(const QString &name, const EasingCurve &curve)
{
    auto *item = new QStandardItem(paintPreview(curve), name);
    item->setData(QVariant::fromValue(curve), ItemRole_Data);
    item->setToolTip(name);

    int row = model()->rowCount();
    qobject_cast<QStandardItemModel *>(model())->setItem(row, item);

    QModelIndex index = model()->index(row, 0);

    // Why is that needed? SingleSelection is specified.
    selectionModel()->clear();
    selectionModel()->select(index, QItemSelectionModel::Select);
}

void PresetList::removeSelectedItem()
{
    for (const auto &index : selectionModel()->selectedIndexes())
        model()->removeRow(index.row());

    writePresets();
}

void PresetList::setItemData(const QModelIndex &index, const QVariant &curve, const QVariant &icon)
{
    if (isEditable(index)) {
        model()->setData(index, curve, PresetList::ItemRole_Data);
        model()->setData(index, true, PresetList::ItemRole_Dirty);
        model()->setData(index, icon, Qt::DecorationRole);
    }
}

QString PresetList::createUniqueName() const
{
    QStringList names = allNames();
    auto nameIsUnique = [&](const QString &name) {
        auto iter = std::find(names.begin(), names.end(), name);
        if (iter == names.end())
            return true;
        else
            return false;
    };

    int counter = 0;
    QString tmp("Default");
    QString name = tmp;

    while (!nameIsUnique(name))
        name = tmp + QString(" %1").arg(counter++);

    return name;
}

QStringList PresetList::allNames() const
{
    QStringList names;
    for (int i = 0; i < model()->rowCount(); ++i) {
        QModelIndex index = model()->index(i, 0);
        QVariant nameData = model()->data(index, Qt::DisplayRole);
        if (nameData.isValid())
            names << nameData.toString();
    }

    return names;
}

QList<NamedEasingCurve> PresetList::storedCurves() const
{
    QSettings settings(m_filename, QSettings::IniFormat);
    QVariant presetSettings = settings.value(Internal::settingsKey);

    if (!presetSettings.isValid())
        return QList<NamedEasingCurve>();

    QList<QVariant> presets = presetSettings.toList();

    QList<NamedEasingCurve> out;
    for (const QVariant &preset : presets)
        if (preset.isValid())
            out << preset.value<NamedEasingCurve>();

    return out;
}

PresetEditor::PresetEditor(QWidget *parent)
    : QStackedWidget(parent)
    , m_presets(new PresetList(QSettings::SystemScope))
    , m_customs(new PresetList(QSettings::UserScope))
{
    setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);

    addWidget(m_presets);
    addWidget(m_customs);

    connect(m_presets, &PresetList::presetChanged, this, &PresetEditor::presetChanged);
    connect(m_customs, &PresetList::presetChanged, this, &PresetEditor::presetChanged);
}

void PresetEditor::initialize(QTabBar *bar)
{
    m_presets->initialize(bar->addTab("Presets"));
    m_customs->initialize(bar->addTab("Custom"));

    connect(bar, &QTabBar::currentChanged, this, &PresetEditor::activate);
    connect(this, &PresetEditor::currentChanged, bar, &QTabBar::setCurrentIndex);

    m_presets->selectionModel()->clear();
    m_customs->selectionModel()->clear();

    activate(m_presets->index());
}

void PresetEditor::activate(int id)
{
    if (id == m_presets->index())
        setCurrentWidget(m_presets);
    else
        setCurrentWidget(m_customs);
}

void PresetEditor::update(const EasingCurve &curve)
{
    if (isCurrent(m_presets))
        m_presets->selectionModel()->clear();
    else {
        if (m_customs->selectionModel()->hasSelection()) {
            QVariant icon = QVariant::fromValue(paintPreview(curve));
            QVariant curveData = QVariant::fromValue(curve);
            for (const QModelIndex &index : m_customs->selectionModel()->selectedIndexes())
                m_customs->setItemData(index, curveData, icon);
        }
    }
}

bool PresetEditor::writePresets(const EasingCurve &curve)
{
    if (!curve.isLegal()) {
        QMessageBox msgBox;
        msgBox.setText("Attempting to save invalid curve");
        msgBox.setInformativeText("Please solve the issue before proceeding.");
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.exec();
        return false;
    }

    if (auto current = qobject_cast<const PresetList *>(currentWidget())) {
        if (current->index() == m_presets->index()
            || (current->index() == m_customs->index() && !m_customs->hasSelection())) {
            bool ok;
            QString name = QInputDialog::getText(this,
                                                 tr("Save Preset"),
                                                 tr("Name"),
                                                 QLineEdit::Normal,
                                                 QString(),
                                                 &ok);

            if (ok && !name.isEmpty()) {
                activate(m_customs->index());
                m_customs->createItem(name, curve);
            }
        }

        m_customs->writePresets();
        return true;
    }

    return false;
}

bool PresetEditor::isCurrent(PresetList *list)
{
    if (auto current = qobject_cast<const PresetList *>(currentWidget()))
        return list->index() == current->index();

    return false;
}

} // namespace QmlDesigner