aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/qmldesigner/components/navigator/nameitemdelegate.cpp
blob: f56a5477fecd69dda651a38bea1f9c06165facbd (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
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0

#include "nameitemdelegate.h"

#include <qmath.h>

#include "navigatorview.h"
#include "navigatortreeview.h"
#include "navigatorwidget.h"
#include "choosefrompropertylistdialog.h"
#include "qproxystyle.h"

#include <metainfo.h>
#include <modelnodecontextmenu.h>
#include <qmlobjectnode.h>
#include <theme.h>

#include <coreplugin/messagebox.h>
#include <utils/qtcassert.h>

#include <QLineEdit>
#include <QPen>
#include <QPixmapCache>
#include <QMouseEvent>
#include <QPainter>
#include <QPainterPath>

namespace QmlDesigner {

int NameItemDelegate::iconOffset = 0;

static QPixmap generateWavyPixmap(qreal maxRadius, const QPen &pen)
{
    QPixmap pixmap;

    const qreal radiusBase = qMax(qreal(1), maxRadius);
    const qreal halfPeriod = qMax(qreal(2), qreal(radiusBase * 1.61803399)); // the golden ratio
    const int width = qCeil(100 / (2 * halfPeriod)) * (2 * halfPeriod);
    const int radius = qFloor(radiusBase);

    QPainterPath path;

    qreal xs = 0;
    qreal ys = radius;

    while (xs < width) {
        xs += halfPeriod;
        ys = -ys;
        path.quadTo(xs - halfPeriod / 2, ys, xs, 0);
    }

    pixmap = QPixmap(width, radius * 2);
    pixmap.fill(Qt::transparent);
    {
        QPen wavePen = pen;
        wavePen.setCapStyle(Qt::SquareCap);

        // This is to protect against making the line too fat, as happens on Mac OS X
        // due to it having a rather thick width for the regular underline.
        const qreal maxPenWidth = .8 * radius;
        if (wavePen.widthF() > maxPenWidth)
            wavePen.setWidth(maxPenWidth);

        QPainter imgPainter(&pixmap);
        imgPainter.setPen(wavePen);
        imgPainter.setRenderHint(QPainter::Antialiasing);
        imgPainter.translate(0, radius);
        imgPainter.drawPath(path);
    }

    return pixmap;
}

static QPixmap getWavyPixmap(qreal maxRadius, const QPen &pen)
{
    const QString pixmapKey = QStringLiteral("WaveUnderline-Bauhaus");

    QPixmap pixmap;
    if (QPixmapCache::find(pixmapKey, &pixmap))
        return pixmap;

    pixmap = generateWavyPixmap(maxRadius, pen);

    QPixmapCache::insert(pixmapKey, pixmap);

    return pixmap;
}

NameItemDelegate::NameItemDelegate(QObject *parent)
    : QStyledItemDelegate(parent)
{
}

static int drawIcon(QPainter *painter, const QStyleOptionViewItem &styleOption, const QModelIndex &modelIndex)
{
    const QIcon icon = modelIndex.data(Qt::DecorationRole).value<QIcon>();
    int pixmapSize = icon.isNull() ? 4 : 16;
    QPixmap pixmap = icon.pixmap(pixmapSize, pixmapSize);

    painter->drawPixmap(styleOption.rect.x() + 1 + delegateMargin,
                        styleOption.rect.y() + 2 + delegateMargin,
                        pixmap);

    pixmapSize += delegateMargin;

    return pixmapSize;
}

static QRect drawText(QPainter *painter,
                      const QStyleOptionViewItem &styleOption,
                      const QModelIndex &modelIndex,
                      int iconOffset)
{
    QString displayString = modelIndex.data(Qt::DisplayRole).toString();

    // Check text length does not exceed available space
    const int extraSpace = 12 + iconOffset;

    displayString = styleOption.fontMetrics.elidedText(displayString,
                                                       Qt::ElideMiddle,
                                                       styleOption.rect.width() - extraSpace);
    const QPoint displayStringOffset = QPoint(5 + iconOffset, -5 - delegateMargin);
    const int width = styleOption.fontMetrics.horizontalAdvance(displayString);
    const QPoint textPosition = styleOption.rect.bottomLeft() + displayStringOffset;
    painter->drawText(textPosition, displayString);

    QRect textFrame;
    textFrame.setTopLeft(textPosition);
    textFrame.setWidth(width);

    return textFrame;
}

static bool isThisOrAncestorLocked(const QModelIndex &modelIndex)
{
    return modelIndex.model()->data(modelIndex, ItemOrAncestorLocked).toBool();
}

static ModelNode getModelNode(const QModelIndex &modelIndex)
{
    return modelIndex.model()->data(modelIndex, ModelNodeRole).value<ModelNode>();
}

static void drawRedWavyUnderLine(QPainter *painter,
                                 const QStyleOptionViewItem &styleOption,
                                 const QRect &textFrame)
{
    painter->translate(0, textFrame.y() + 1);
    QPen pen;
    pen.setColor(Qt::red);
    const qreal underlineOffset = styleOption.fontMetrics.underlinePos();
    const QPixmap wave = getWavyPixmap(qMax(underlineOffset, pen.widthF()), pen);
    const int descent = styleOption.fontMetrics.descent();

    painter->setBrushOrigin(painter->brushOrigin().x(), 0);
    painter->fillRect(textFrame.x(), 0, qCeil(textFrame.width()), qMin(wave.height(), descent), wave);
}

static void setId(const QModelIndex &index, const QString &newId)
{
    ModelNode modelNode = getModelNode(index);

    if (!modelNode.isValid())
        return;

    if (modelNode.id() == newId)
        return;

    if (!ModelNode::isValidId(newId)) {
        Core::AsynchronousMessageBox::warning(NavigatorTreeView::tr("Invalid Id"),
                                              NavigatorTreeView::tr("%1 is an invalid id.").arg(newId));
    } else if (modelNode.view()->hasId(newId)) {
        Core::AsynchronousMessageBox::warning(NavigatorTreeView::tr("Invalid Id"),
                                              NavigatorTreeView::tr("%1 already exists.").arg(newId));
    } else {
        modelNode.setIdWithRefactoring(newId);
    }
}

static void openContextMenu(const QModelIndex &index, const QPoint &pos)
{
    const ModelNode modelNode = getModelNode(index);
    QTC_ASSERT(modelNode.isValid(), return);
    ModelNodeContextMenu::showContextMenu(modelNode.view(), pos, QPoint(), false);
}

QSize NameItemDelegate::sizeHint(const QStyleOptionViewItem & /*option*/,
                                 const QModelIndex & /*modelIndex*/) const
{
    return {15, 20 + (2 * delegateMargin)};
}

void NameItemDelegate::paint(QPainter *painter,
                             const QStyleOptionViewItem &styleOption,
                             const QModelIndex &modelIndex) const
{
    painter->save();

    painter->setPen(Theme::getColor(Theme::Color::DSnavigatorText));

    if (styleOption.state & QStyle::State_MouseOver && !isThisOrAncestorLocked(modelIndex)) {
        painter->fillRect(styleOption.rect.adjusted(0, delegateMargin, 0, -delegateMargin),
                          Theme::getColor(Theme::Color::DSnavigatorItemBackgroundHover));
        painter->setPen(Theme::getColor(Theme::Color::DSnavigatorTextHover));
    }

    if (styleOption.state & QStyle::State_Selected) {
        NavigatorTreeView::drawSelectionBackground(painter, styleOption);
        painter->setPen(Theme::getColor(Theme::Color::DSnavigatorTextSelected));
    }

    ModelNode node = getModelNode(modelIndex);
    NavigatorWidget *widget = qobject_cast<NavigatorWidget *>(styleOption.widget->parent());
    if (widget && !widget->dragType().isEmpty()) {
        QByteArray dragType = widget->dragType();
        const NodeMetaInfo metaInfo = node.metaInfo();
        const NodeMetaInfo dragInfo = node.model()->metaInfo(dragType);
        ChooseFromPropertyListFilter *filter = new ChooseFromPropertyListFilter(dragInfo, metaInfo, true);

        if (!filter->propertyList.isEmpty()) {
            painter->setOpacity(0.5);
            painter->fillRect(styleOption.rect.adjusted(0, delegateMargin, 0, -delegateMargin),
                              Theme::getColor(Theme::Color::DSnavigatorDropIndicatorBackground));
            painter->setOpacity(1.0);
            painter->setPen(Theme::getColor(Theme::Color::DSnavigatorTextSelected));
        }
        delete filter;
    }

    iconOffset = drawIcon(painter, styleOption, modelIndex);

    if (isThisOrAncestorLocked(modelIndex))
        painter->setOpacity(0.5);

    QRect textFrame = drawText(painter, styleOption, modelIndex, iconOffset);

    if (QmlObjectNode(getModelNode(modelIndex)).hasError())
        drawRedWavyUnderLine(painter, styleOption, textFrame);

    painter->restore();
}

QWidget *NameItemDelegate::createEditor(QWidget *parent,
                                        const QStyleOptionViewItem &/*option*/,
                                        const QModelIndex &index) const
{
    if (!getModelNode(index).isValid())
        return nullptr;

    return new QLineEdit(parent);
}

void NameItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    const ModelNode node = getModelNode(index);
    const QString value = node.id();

    auto lineEdit = static_cast<QLineEdit*>(editor);
    lineEdit->setText(value);
}

void NameItemDelegate::setModelData(QWidget *editor,
                                    [[maybe_unused]] QAbstractItemModel *model,
                                    const QModelIndex &index) const
{
    auto lineEdit = static_cast<QLineEdit*>(editor);
    setId(index, lineEdit->text());
    lineEdit->clearFocus();
}

bool NameItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *, const QStyleOptionViewItem &, const QModelIndex &index)
{
    if (event->type() == QEvent::MouseButtonRelease) {
        auto mouseEvent = static_cast<QMouseEvent *>(event);
        if (mouseEvent->button() == Qt::RightButton) {
            openContextMenu(index, mouseEvent->globalPos());
            mouseEvent->accept();
            return true;
        }
    }
    return false;
}

void NameItemDelegate::updateEditorGeometry(QWidget *editor,
                                            const QStyleOptionViewItem &option,
                                            const QModelIndex &/*index*/) const
{
    auto lineEdit = static_cast<QLineEdit*>(editor);
    lineEdit->setTextMargins(0, 0, 0, 2);
    // + 2 is shifting the QLineEdit to the left so it will align with the text when activated
    lineEdit->setGeometry(option.rect.adjusted(iconOffset + 2, delegateMargin, 0, -delegateMargin));
}

} // namespace QmlDesigner