graphicsscenerectmove.cpp 43.1 KB
Newer Older
1
/*
Alexander Lohnau's avatar
Alexander Lohnau committed
2
3
    SPDX-FileCopyrightText: 2008 Marco Gittler <g.marco@freenet.de>
    SPDX-FileCopyrightText: 2008 Jean-Baptiste Mardelle <jb@kdenlive.org>
4

Camille Moulin's avatar
Camille Moulin committed
5
SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
6
*/
7
8
9
10

#include "graphicsscenerectmove.h"
#include "titler/gradientwidget.h"
#include "titler/titledocument.h"
11
#include "kdenlivesettings.h"
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

#include "kdenlive_debug.h"
#include <QApplication>
#include <QCursor>
#include <QGraphicsRectItem>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsSvgItem>
#include <QGraphicsView>
#include <QKeyEvent>
#include <QList>
#include <QScrollBar>
#include <QTextBlock>
#include <QTextCursor>
#include <QTextDocument>
#include <utility>

MyQGraphicsEffect::MyQGraphicsEffect(QObject *parent)
    : QGraphicsEffect(parent)
Nicolas Carion's avatar
Nicolas Carion committed
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
{
}

void MyQGraphicsEffect::setShadow(const QImage &image)
{
    m_shadow = image;
}

void MyQGraphicsEffect::setOffset(int xOffset, int yOffset, int blur)
{
    m_xOffset = xOffset;
    m_yOffset = yOffset;
    m_blur = blur;
    updateBoundingRect();
}

void MyQGraphicsEffect::draw(QPainter *painter)
{
    painter->fillRect(boundingRect(), Qt::transparent);
    painter->drawImage(-2 * m_blur + m_xOffset, -2 * m_blur + m_yOffset, m_shadow);
    drawSource(painter);
}

MyTextItem::MyTextItem(const QString &txt, QGraphicsItem *parent)
    : QGraphicsTextItem(txt, parent)
56
    , m_alignment(QFlags<Qt::AlignmentFlag>())
57
{
58
59
    //Disabled because cache makes text cursor invisible and borders ugly
    //setCacheMode(QGraphicsItem::ItemCoordinateCache);
60
61
62
63
64
65
    setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
    document()->setDocumentMargin(0);
    m_shadowEffect = new MyQGraphicsEffect(this);
    m_shadowEffect->setEnabled(false);
    setGraphicsEffect(m_shadowEffect);
    updateGeometry();
66
    connect(document(), &QTextDocument::contentsChange, this, &MyTextItem::doUpdateGeometry);
67
    updateTW(false, 2, 1, 0, 0);
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
}

Qt::Alignment MyTextItem::alignment() const
{
    return m_alignment;
}

void MyTextItem::updateShadow(bool enabled, int blur, int xoffset, int yoffset, QColor color)
{
    m_shadowOffset = QPoint(xoffset, yoffset);
    m_shadowBlur = blur;
    m_shadowColor = std::move(color);
    m_shadowEffect->setEnabled(enabled);
    m_shadowEffect->setOffset(xoffset, yoffset, blur);
    if (enabled) {
        updateShadow();
    }
    update();
}

void MyTextItem::setTextColor(const QColor &col)
{
    setDefaultTextColor(col);
    refreshFormat();
}

QStringList MyTextItem::shadowInfo() const
{
    QStringList info;
    info << QString::number(static_cast<int>(m_shadowEffect->isEnabled())) << m_shadowColor.name(QColor::HexArgb) << QString::number(m_shadowBlur)
         << QString::number(m_shadowOffset.x()) << QString::number(m_shadowOffset.y());
    return info;
}

void MyTextItem::loadShadow(const QStringList &info)
{
    if (info.count() < 5) {
        return;
    }
    updateShadow((static_cast<bool>(info.at(0).toInt())), info.at(2).toInt(), info.at(3).toInt(), info.at(4).toInt(), QColor(info.at(1)));
}

void MyTextItem::setAlignment(Qt::Alignment alignment)
{
    m_alignment = alignment;
    QTextBlockFormat format;
    format.setAlignment(alignment);
    QTextCursor cursor = textCursor(); // save cursor position
    int position = textCursor().position();
    cursor.select(QTextCursor::Document);
    cursor.mergeBlockFormat(format);
    cursor.clearSelection();
    cursor.setPosition(position); // restore cursor position
    setTextCursor(cursor);
}

void MyTextItem::refreshFormat()
{
    QString gradientData = data(TitleDocument::Gradient).toString();
    QTextCursor cursor = textCursor();
    QTextCharFormat cformat;
    cursor.select(QTextCursor::Document);
    int position = textCursor().position();

    // Formatting can be lost on paste, since our QTextCursor gets overwritten, so re-apply all formatting here
    QColor fgColor = defaultTextColor();
    cformat.setForeground(fgColor);
    cformat.setFont(font());

    if (!gradientData.isEmpty()) {
        QRectF rect = boundingRect();
Vincent Pinon's avatar
Vincent Pinon committed
139
        QLinearGradient gr = GradientWidget::gradientFromString(gradientData, int(rect.width()), int(rect.height()));
140
141
142
143
144
145
146
147
148
149
150
        cformat.setForeground(QBrush(gr));
    }

    // Apply
    cursor.mergeCharFormat(cformat);
    // restore cursor position
    cursor.clearSelection();
    cursor.setPosition(position);
    setTextCursor(cursor);
}

151
void MyTextItem::doUpdateGeometry()
152
153
154
155
156
157
158
{
    updateGeometry();
    // update gradient if necessary
    refreshFormat();

    QString text = toPlainText();
    m_path = QPainterPath();
159
    m_path.setFillRule(Qt::WindingFill);
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    if (text.isEmpty()) {
        //
    } else {
        QFontMetrics metrics(font());
        double lineSpacing = data(TitleDocument::LineSpacing).toInt() + metrics.lineSpacing();

        // Calculate line width
        const QStringList lines = text.split(QLatin1Char('\n'));
        double linePos = metrics.ascent();
        QRectF bounding = boundingRect();
        /*if (lines.count() > 0) {
            lineSpacing = bounding.height() / lines.count();
            if (lineSpacing != data(TitleDocument::LineSpacing).toInt() + metrics.lineSpacing()) {
                linePos = 2 * lineSpacing - metrics.descent() - metrics.height();
            }
        }*/

        for (const QString &line : lines) {
            QPainterPath linePath;
            linePath.addText(0, linePos, font(), line);
            linePos += lineSpacing;
            if (m_alignment == Qt::AlignHCenter) {
Vincent Pinon's avatar
Vincent Pinon committed
182
                double offset = (bounding.width() - metrics.horizontalAdvance(line)) / 2;
183
184
                linePath.translate(offset, 0);
            } else if (m_alignment == Qt::AlignRight) {
Vincent Pinon's avatar
Vincent Pinon committed
185
                double offset = bounding.width() - metrics.horizontalAdvance(line);
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
                linePath.translate(offset, 0);
            }
            m_path.addPath(linePath);
        }
    }

    if (m_shadowEffect->isEnabled()) {
        updateShadow();
    }
    update();
}

void MyTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *w)
{
    if ((textInteractionFlags() & static_cast<int>((Qt::TextEditable) != 0)) != 0) {
201
        document()->setDocumentMargin(0);
202
203
204
205
        QGraphicsTextItem::paint(painter, option, w);
    } else {
        painter->setRenderHint(QPainter::Antialiasing);
        int outline = data(TitleDocument::OutlineWidth).toInt();
206
        QString gradientData = data(TitleDocument::Gradient).toString();
207
208
        QTextCursor cursor(document());
        cursor.select(QTextCursor::Document);
209
210
211
212
213
        QBrush paintBrush;
        if (gradientData.isEmpty()) {
            paintBrush = QBrush(cursor.charFormat().foreground().color());
        } else {
            QRectF rect = boundingRect();
Vincent Pinon's avatar
Vincent Pinon committed
214
            paintBrush = QBrush(GradientWidget::gradientFromString(gradientData, int(rect.width()), int(rect.height())));
215
216
        }
        painter->fillPath(m_path, paintBrush);
217
218
219
220
221
222
223
        if (outline > 0) {
            QVariant variant = data(TitleDocument::OutlineColor);
            QColor outlineColor = variant.value<QColor>();
            QPen pen(outlineColor);
            pen.setWidthF(outline);
            painter->strokePath(m_path, pen);
        }
224
225
226
        document()->setDocumentMargin(toPlainText().isEmpty() ? 6 : 0);
        if (isSelected() || toPlainText().isEmpty()) {
            QPen pen(isSelected() ? Qt::red : Qt::blue);
227
228
229
230
231
232
233
            pen.setStyle(Qt::DashLine);
            painter->setPen(pen);
            painter->drawRect(boundingRect());
        }
    }
}

234
235
void MyTextItem::updateTW(bool enabled, int step, int mode, int sigma, int seed)
{
236
237
238
239
240
    m_tw_enabled = enabled;
    m_tw_step = step;
    m_tw_mode = mode;
    m_tw_sigma = sigma;
    m_tw_seed = seed;
241
242
243
244
245
246
247
248
249
250
251
252
253
254
}

void MyTextItem::loadTW(const QStringList &info)
{
    if (info.count() < 5) {
        return;
    }
    updateTW((static_cast<bool>(info.at(0).toInt())), info.at(1).toInt(),
             info.at(2).toInt(), info.at(3).toInt(), info.at(4).toInt());
}

QStringList MyTextItem::twInfo() const
{
    QStringList info;
255
256
257
    info << QString::number(int(m_tw_enabled)) << QString::number(m_tw_step)
         << QString::number(m_tw_mode)
         << QString::number(m_tw_sigma) << QString::number(m_tw_seed);
258
259
260
    return info;
}

261
262
263
264
265
266
267
268
269
270
271
272
void MyTextItem::updateShadow()
{
    QString text = toPlainText();
    if (text.isEmpty()) {
        m_shadowEffect->setShadow(QImage());
        return;
    }
    QRectF bounding = boundingRect();
    QPainterPath path = m_path;
    // Calculate position of text in parent item
    path.translate(QPointF(2 * m_shadowBlur, 2 * m_shadowBlur));
    QRectF fullSize = bounding.united(path.boundingRect());
Vincent Pinon's avatar
Vincent Pinon committed
273
    QImage shadow(int(fullSize.width()) + qAbs(m_shadowOffset.x()) + 4 * m_shadowBlur, int(fullSize.height()) + qAbs(m_shadowOffset.y()) + 4 * m_shadowBlur,
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
                  QImage::Format_ARGB32_Premultiplied);
    shadow.fill(Qt::transparent);
    QPainter painter(&shadow);
    painter.fillPath(path, QBrush(m_shadowColor));
    painter.end();
    if (m_shadowBlur > 0) {
        blurShadow(shadow, m_shadowBlur);
    }
    m_shadowEffect->setShadow(shadow);
}

void MyTextItem::blurShadow(QImage &result, int radius)
{
    int tab[] = {14, 10, 8, 6, 5, 5, 4, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2};
    int alpha = (radius < 1) ? 16 : (radius > 17) ? 1 : tab[radius - 1];

    int r1 = 0;
    int r2 = result.height() - 1;
    int c1 = 0;
    int c2 = result.width() - 1;

    int bpl = result.bytesPerLine();
    int rgba[4];
    unsigned char *p;

    int i1 = 0;
    int i2 = 3;

    for (int col = c1; col <= c2; col++) {
        p = result.scanLine(r1) + col * 4;
        for (int i = i1; i <= i2; i++) {
            rgba[i] = p[i] << 4;
        }

        p += bpl;
        for (int j = r1; j < r2; j++, p += bpl)
            for (int i = i1; i <= i2; i++) {
Vincent Pinon's avatar
Vincent Pinon committed
311
                p[i] = uchar((rgba[i] += ((p[i] << 4) - rgba[i]) * alpha / 16) >> 4);
312
313
314
315
316
317
318
319
320
321
322
323
            }
    }

    for (int row = r1; row <= r2; row++) {
        p = result.scanLine(row) + c1 * 4;
        for (int i = i1; i <= i2; i++) {
            rgba[i] = p[i] << 4;
        }

        p += 4;
        for (int j = c1; j < c2; j++, p += 4)
            for (int i = i1; i <= i2; i++) {
Vincent Pinon's avatar
Vincent Pinon committed
324
                p[i] = uchar((rgba[i] += ((p[i] << 4) - rgba[i]) * alpha / 16) >> 4);
325
326
327
328
329
330
331
332
333
334
335
336
            }
    }

    for (int col = c1; col <= c2; col++) {
        p = result.scanLine(r2) + col * 4;
        for (int i = i1; i <= i2; i++) {
            rgba[i] = p[i] << 4;
        }

        p -= bpl;
        for (int j = r1; j < r2; j++, p -= bpl)
            for (int i = i1; i <= i2; i++) {
Vincent Pinon's avatar
Vincent Pinon committed
337
                p[i] = uchar((rgba[i] += ((p[i] << 4) - rgba[i]) * alpha / 16) >> 4);
338
339
340
341
342
343
344
345
346
347
348
349
            }
    }

    for (int row = r1; row <= r2; row++) {
        p = result.scanLine(row) + c2 * 4;
        for (int i = i1; i <= i2; i++) {
            rgba[i] = p[i] << 4;
        }

        p -= 4;
        for (int j = c1; j < c2; j++, p -= 4)
            for (int i = i1; i <= i2; i++) {
Vincent Pinon's avatar
Vincent Pinon committed
350
                p[i] = uchar((rgba[i] += ((p[i] << 4) - rgba[i]) * alpha / 16) >> 4);
351
352
353
354
355
356
357
358
359
360
361
362
            }
    }
}

void MyTextItem::updateGeometry()
{
    QPointF topRightPrev = boundingRect().topRight();
    setTextWidth(-1);
    setTextWidth(boundingRect().width());
    setAlignment(m_alignment);
    QPointF topRight = boundingRect().topRight();

Eric Jiang's avatar
Eric Jiang committed
363
364
365
    // if the text is right-aligned, then shift the container leftwards by the
    // same amount it grew to maintain right-alignment
    if (m_alignment & Qt::AlignRight) {
366
367
        setPos(pos() + (topRightPrev - topRight));
    }
Eric Jiang's avatar
Eric Jiang committed
368
369
370
371
    // likewise, shift it halfway if we're center-aligned
    else if (m_alignment & Qt::AlignHCenter) {
        setPos(pos() + (topRightPrev - topRight) / 2);
    }
372
373
374
375
376
377
378
379
}

QRectF MyTextItem::baseBoundingRect() const
{
    QRectF base = QGraphicsTextItem::boundingRect();
    QTextCursor cur(document());
    cur.select(QTextCursor::Document);
    QTextBlockFormat format = cur.blockFormat();
Vincent Pinon's avatar
Vincent Pinon committed
380
    int lineHeight = int(format.lineHeight());
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
    int lineHeight2 = QFontMetrics(font()).lineSpacing();
    int lines = document()->lineCount();
    if (lines > 1) {
        base.setHeight(lines * lineHeight2 + lineHeight * (lines - 1));
    }
    return base;
}

QRectF MyTextItem::boundingRect() const
{
    QRectF base = baseBoundingRect();
    if (m_shadowEffect->isEnabled() && m_shadowOffset.x() > 0) {
        base.setRight(base.right() + m_shadowOffset.x());
    }
    if (m_shadowEffect->isEnabled() && m_shadowOffset.y() > 0) {
        base.setBottom(base.bottom() + m_shadowOffset.y());
    }
    return base;
}

QVariant MyTextItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == ItemPositionChange && (scene() != nullptr)) {
        QPoint newPos = value.toPoint();
        if (QApplication::mouseButtons() == Qt::LeftButton && (qobject_cast<GraphicsSceneRectMove *>(scene()) != nullptr)) {
Nicolas Carion's avatar
Nicolas Carion committed
406
            auto *customScene = qobject_cast<GraphicsSceneRectMove *>(scene());
407
408
409
            int gridSize = customScene->gridSize();
            int xV = (newPos.x() / gridSize) * gridSize;
            int yV = (newPos.y() / gridSize) * gridSize;
410
411
412
413
414
415
            if (QApplication::keyboardModifiers() == Qt::ShiftModifier) {
                xV = pos().x();
            }
            if (QApplication::keyboardModifiers() == (Qt::ShiftModifier | Qt::AltModifier)) {
                yV = pos().y();
            }
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
            newPos = QPoint(xV, yV);
        }
        return newPos;
    }
    if (change == QGraphicsItem::ItemSelectedHasChanged) {
        if (!value.toBool()) {
            // Make sure to deselect text when item loses focus
            QTextCursor cur(document());
            cur.clearSelection();
            setTextCursor(cur);
        }
    }
    return QGraphicsItem::itemChange(change, value);
}

void MyTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *evt)
{
    if (textInteractionFlags() == Qt::TextEditorInteraction) {
        // if editor mode is already on: pass double click events on to the editor:
        QGraphicsTextItem::mouseDoubleClickEvent(evt);
        return;
    }
    // if editor mode is off:
    // 1. turn editor mode on and set selected and focused:
    // SetTextInteraction(true);
    setTextInteractionFlags(Qt::TextEditorInteraction);
    setFocus(Qt::MouseFocusReason);
443
    setCursor(QCursor(Qt::IBeamCursor));
444
445
446
447
448
449
450
451
452
453
454
455
    // 2. send a single click to this QGraphicsTextItem (this will set the cursor to the mouse position):
    // create a new mouse event with the same parameters as evt
    auto *click = new QGraphicsSceneMouseEvent(QEvent::GraphicsSceneMousePress);
    click->setButton(evt->button());
    click->setPos(evt->pos());
    QGraphicsTextItem::mousePressEvent(click);
    delete click; // don't forget to delete the event
}

MyRectItem::MyRectItem(QGraphicsItem *parent)
    : QGraphicsRectItem(parent)
{
456
457
    //Disabled because cache makes text cursor invisible and borders ugly
    //setCacheMode(QGraphicsItem::ItemCoordinateCache);
458
459
460
461
462
463
464
465
    setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
}

void MyRectItem::setRect(const QRectF &rectangle)
{
    QGraphicsRectItem::setRect(rectangle);
    if (m_rect != rectangle && !data(TitleDocument::Gradient).isNull()) {
        m_rect = rectangle;
Vincent Pinon's avatar
Vincent Pinon committed
466
        QLinearGradient gr = GradientWidget::gradientFromString(data(TitleDocument::Gradient).toString(), int(m_rect.width()), int(m_rect.height()));
467
468
469
470
471
472
473
474
475
        setBrush(QBrush(gr));
    }
}

QVariant MyRectItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == ItemPositionChange && (scene() != nullptr)) {
        QPoint newPos = value.toPoint();
        if (QApplication::mouseButtons() == Qt::LeftButton && (qobject_cast<GraphicsSceneRectMove *>(scene()) != nullptr)) {
Nicolas Carion's avatar
Nicolas Carion committed
476
            auto *customScene = qobject_cast<GraphicsSceneRectMove *>(scene());
477
478
479
            int gridSize = customScene->gridSize();
            int xV = (newPos.x() / gridSize) * gridSize;
            int yV = (newPos.y() / gridSize) * gridSize;
480
481
482
483
484
485
            if (QApplication::keyboardModifiers() == Qt::ShiftModifier) {
                xV = pos().x();
            }
            if (QApplication::keyboardModifiers() == (Qt::ShiftModifier | Qt::AltModifier)) {
                yV = pos().y();
            }
486
487
488
489
490
491
492
            newPos = QPoint(xV, yV);
        }
        return newPos;
    }
    return QGraphicsItem::itemChange(change, value);
}

Julius Künzel's avatar
Julius Künzel committed
493
494
495
496
497
498
499
500
501
502
503
504
505
MyEllipseItem::MyEllipseItem(QGraphicsItem *parent)
    : QGraphicsEllipseItem(parent)
{
    //Disabled because cache makes text cursor invisible and borders ugly
    //setCacheMode(QGraphicsItem::ItemCoordinateCache);
    setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
}

void MyEllipseItem::setRect(const QRectF &rectangle)
{
    QGraphicsEllipseItem::setRect(rectangle);
    if (m_ellipse != rectangle && !data(TitleDocument::Gradient).isNull()) {
        m_ellipse = rectangle;
Vincent Pinon's avatar
Vincent Pinon committed
506
        QLinearGradient gr = GradientWidget::gradientFromString(data(TitleDocument::Gradient).toString(), int(m_ellipse.width()), int(m_ellipse.height()));
Julius Künzel's avatar
Julius Künzel committed
507
508
509
510
511
512
513
514
515
516
517
518
519
        setBrush(QBrush(gr));
    }
}

QVariant MyEllipseItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == ItemPositionChange && (scene() != nullptr)) {
        QPoint newPos = value.toPoint();
        if (QApplication::mouseButtons() == Qt::LeftButton && (qobject_cast<GraphicsSceneRectMove *>(scene()) != nullptr)) {
            auto *customScene = qobject_cast<GraphicsSceneRectMove *>(scene());
            int gridSize = customScene->gridSize();
            int xV = (newPos.x() / gridSize) * gridSize;
            int yV = (newPos.y() / gridSize) * gridSize;
520
521
522
523
524
525
            if (QApplication::keyboardModifiers() == Qt::ShiftModifier) {
                xV = pos().x();
            }
            if (QApplication::keyboardModifiers() == (Qt::ShiftModifier | Qt::AltModifier)) {
                yV = pos().y();
            }
Julius Künzel's avatar
Julius Künzel committed
526
527
528
529
530
531
532
            newPos = QPoint(xV, yV);
        }
        return newPos;
    }
    return QGraphicsItem::itemChange(change, value);
}

533
534
535
MyPixmapItem::MyPixmapItem(const QPixmap &pixmap, QGraphicsItem *parent)
    : QGraphicsPixmapItem(pixmap, parent)
{
536
537
    //Disabled because cache makes text cursor invisible and borders ugly
    //setCacheMode(QGraphicsItem::ItemCoordinateCache);
538
539
540
541
542
543
544
545
    setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
}

QVariant MyPixmapItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == ItemPositionChange && (scene() != nullptr)) {
        QPoint newPos = value.toPoint();
        if (QApplication::mouseButtons() == Qt::LeftButton && (qobject_cast<GraphicsSceneRectMove *>(scene()) != nullptr)) {
Nicolas Carion's avatar
Nicolas Carion committed
546
            auto *customScene = qobject_cast<GraphicsSceneRectMove *>(scene());
547
548
549
            int gridSize = customScene->gridSize();
            int xV = (newPos.x() / gridSize) * gridSize;
            int yV = (newPos.y() / gridSize) * gridSize;
550
551
552
553
554
555
            if (QApplication::keyboardModifiers() == Qt::ShiftModifier) {
                xV = pos().x();
            }
            if (QApplication::keyboardModifiers() == (Qt::ShiftModifier | Qt::AltModifier)) {
                yV = pos().y();
            }
556
557
558
559
560
561
562
563
564
565
            newPos = QPoint(xV, yV);
        }
        return newPos;
    }
    return QGraphicsItem::itemChange(change, value);
}

MySvgItem::MySvgItem(const QString &fileName, QGraphicsItem *parent)
    : QGraphicsSvgItem(fileName, parent)
{
566
567
    //Disabled because cache makes text cursor invisible and borders ugly
    //setCacheMode(QGraphicsItem::ItemCoordinateCache);
568
569
570
571
572
573
574
575
    setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
}

QVariant MySvgItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == ItemPositionChange && (scene() != nullptr)) {
        QPoint newPos = value.toPoint();
        if (QApplication::mouseButtons() == Qt::LeftButton && (qobject_cast<GraphicsSceneRectMove *>(scene()) != nullptr)) {
Nicolas Carion's avatar
Nicolas Carion committed
576
            auto *customScene = qobject_cast<GraphicsSceneRectMove *>(scene());
577
578
579
            int gridSize = customScene->gridSize();
            int xV = (newPos.x() / gridSize) * gridSize;
            int yV = (newPos.y() / gridSize) * gridSize;
580
581
582
583
584
585
            if (QApplication::keyboardModifiers() == Qt::ShiftModifier) {
                xV = pos().x();
            }
            if (QApplication::keyboardModifiers() == (Qt::ShiftModifier | Qt::AltModifier)) {
                yV = pos().y();
            }
586
587
588
589
590
591
592
593
            newPos = QPoint(xV, yV);
        }
        return newPos;
    }
    return QGraphicsItem::itemChange(change, value);
}
GraphicsSceneRectMove::GraphicsSceneRectMove(QObject *parent)
    : QGraphicsScene(parent)
Nicolas Carion's avatar
Nicolas Carion committed
594

595
596
597
598
599
600
601
{
    // grabMouse();
    m_zoom = 1.0;
    setBackgroundBrush(QBrush(Qt::transparent));
    m_fontSize = 0;
}

602
603
604
605
606
void GraphicsSceneRectMove::contextMenuEvent(QGraphicsSceneContextMenuEvent *)
{
    // Disable QGraphicsScene standard context menu that was crashing
}

607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
void GraphicsSceneRectMove::setSelectedItem(QGraphicsItem *item)
{
    clearSelection();
    m_selectedItem = item;
    item->setSelected(true);
    update();
}

TITLETOOL GraphicsSceneRectMove::tool() const
{
    return m_tool;
}

void GraphicsSceneRectMove::setTool(TITLETOOL tool)
{
    m_tool = tool;
    switch (m_tool) {
Julius Künzel's avatar
Julius Künzel committed
624
    case TITLE_ELLIPSE:
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
    case TITLE_RECTANGLE:
        setCursor(Qt::CrossCursor);
        break;
    case TITLE_TEXT:
        setCursor(Qt::IBeamCursor);
        break;
    default:
        setCursor(Qt::ArrowCursor);
    }
}

void GraphicsSceneRectMove::keyPressEvent(QKeyEvent *keyEvent)
{
    if (m_selectedItem == nullptr || !(m_selectedItem->flags() & QGraphicsItem::ItemIsMovable)) {
        QGraphicsScene::keyPressEvent(keyEvent);
        return;
    }
    if (m_selectedItem->type() == QGraphicsTextItem::Type) {
Nicolas Carion's avatar
Nicolas Carion committed
643
        auto *t = static_cast<MyTextItem *>(m_selectedItem);
644
645
646
647
648
649
650
651
652
653
654
        if ((t->textInteractionFlags() & static_cast<int>((Qt::TextEditorInteraction) != 0)) != 0) {
            QGraphicsScene::keyPressEvent(keyEvent);
            return;
        }
    }
    int diff = m_gridSize;
    if ((keyEvent->modifiers() & Qt::ControlModifier) != 0u) {
        diff = m_gridSize * 5;
    }
    switch (keyEvent->key()) {
    case Qt::Key_Left:
Vincent Pinon's avatar
Vincent Pinon committed
655
        foreach (QGraphicsItem *qgi, selectedItems()) {
656
657
658
659
660
            qgi->moveBy(-diff, 0);
        }
        emit itemMoved();
        break;
    case Qt::Key_Right:
Vincent Pinon's avatar
Vincent Pinon committed
661
        foreach (QGraphicsItem *qgi, selectedItems()) {
662
663
664
665
666
            qgi->moveBy(diff, 0);
        }
        emit itemMoved();
        break;
    case Qt::Key_Up:
Vincent Pinon's avatar
Vincent Pinon committed
667
        foreach (QGraphicsItem *qgi, selectedItems()) {
668
669
670
671
672
            qgi->moveBy(0, -diff);
        }
        emit itemMoved();
        break;
    case Qt::Key_Down:
Vincent Pinon's avatar
Vincent Pinon committed
673
        foreach (QGraphicsItem *qgi, selectedItems()) {
674
675
676
677
678
679
            qgi->moveBy(0, diff);
        }
        emit itemMoved();
        break;
    case Qt::Key_Delete:
    case Qt::Key_Backspace:
Vincent Pinon's avatar
Vincent Pinon committed
680
        foreach (QGraphicsItem *qgi, selectedItems()) {
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
            if (qgi->data(-1).toInt() == -1) {
                continue;
            }
            removeItem(qgi);
            delete qgi;
        }
        m_selectedItem = nullptr;
        emit selectionChanged();
        break;
    default:
        QGraphicsScene::keyPressEvent(keyEvent);
    }
    emit actionFinished();
}

void GraphicsSceneRectMove::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *e)
{
    QPointF p = e->scenePos();
    p += QPoint(-2, -2);
    m_resizeMode = NoResize;
    m_selectedItem = nullptr;

Yuri Chornoivan's avatar
Yuri Chornoivan committed
703
    // http://web.archive.org/web/20140728070013/http://www.kdenlive.org/mantis/view.php?id=1035
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
    QList<QGraphicsItem *> i = items(QRectF(p, QSizeF(4, 4)).toRect());
    if (i.isEmpty()) {
        return;
    }

    int ix = 1;
    QGraphicsItem *g = i.constFirst();
    while (!(g->flags() & QGraphicsItem::ItemIsSelectable) && ix < i.count()) {
        g = i.at(ix);
        ix++;
    }
    if ((g != nullptr) && g->type() == QGraphicsTextItem::Type && (((g->flags() & static_cast<int>((QGraphicsItem::ItemIsSelectable) != 0))) != 0)) {
        m_selectedItem = g;
    } else {
        emit doubleClickEvent();
    }
    QGraphicsScene::mouseDoubleClickEvent(e);
}

void GraphicsSceneRectMove::mouseReleaseEvent(QGraphicsSceneMouseEvent *e)
{
    m_pan = false;
    if (m_tool == TITLE_RECTANGLE && (m_selectedItem != nullptr)) {
        setSelectedItem(m_selectedItem);
    }
729
    if (m_createdText && m_selectedItem) {
730
        m_selectedItem->setSelected(true);
Nicolas Carion's avatar
Nicolas Carion committed
731
        auto *newText = static_cast<MyTextItem *>(m_selectedItem);
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
        QTextCursor cur(newText->document());
        cur.select(QTextCursor::Document);
        newText->setTextCursor(cur);
        m_createdText = false;
    }
    if ((e->modifiers() & Qt::ShiftModifier) != 0u) {
        e->accept();
    } else {
        QGraphicsScene::mouseReleaseEvent(e);
    }
    QList<QGraphicsView *> viewlist = views();
    if (!viewlist.isEmpty()) {
        viewlist.constFirst()->setDragMode(QGraphicsView::RubberBandDrag);
    }
    emit actionFinished();
}

void GraphicsSceneRectMove::mousePressEvent(QGraphicsSceneMouseEvent *e)
{
    if ((e->buttons() & Qt::MiddleButton) != 0u) {
        clearTextSelection();
        QList<QGraphicsView *> viewlist = views();
        if (!viewlist.isEmpty()) {
            viewlist.constFirst()->setDragMode(QGraphicsView::ScrollHandDrag);
            m_pan = true;
            e->accept();
            QGraphicsScene::mousePressEvent(e);
            return;
        }
    }
Vincent Pinon's avatar
Vincent Pinon committed
762
763
    int xPos = (int(e->scenePos().x()) / m_gridSize) * m_gridSize;
    int yPos = (int(e->scenePos().y()) / m_gridSize) * m_gridSize;
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
    m_moveStarted = false;
    m_clickPoint = e->scenePos();
    m_resizeMode = m_possibleAction;
    const QList<QGraphicsItem *> list = items(e->scenePos());
    QGraphicsItem *item = nullptr;
    if (m_tool == TITLE_SELECT) {
        QList<QGraphicsView *> viewlist = views();
        if ((e->modifiers() & Qt::ControlModifier) != 0u) {
            clearTextSelection();
            if (!viewlist.isEmpty()) {
                viewlist.constFirst()->setDragMode(QGraphicsView::ScrollHandDrag);
                e->ignore();
                // QGraphicsScene::mousePressEvent(e);
                return;
            }
        } else {
            if (!viewlist.isEmpty()) {
                viewlist.constFirst()->setRubberBandSelectionMode(Qt::IntersectsItemShape);
            }
        }
        bool alreadySelected = false;
        for (QGraphicsItem *g : list) {
            // qDebug() << " - - CHECKING ITEM Z:" << g->zValue() << ", TYPE: " << g->type();
            // check is there is a selected item in list
            if (!(g->flags() & QGraphicsItem::ItemIsSelectable)) {
                continue;
            }
            if (g->zValue() > -1000 /* && g->isSelected()*/) {
                alreadySelected = g->isSelected();
                if (!alreadySelected) {
                    g->setSelected(true);
                }
                item = g;
                break;
            }
        }
        if (item == nullptr || (e->modifiers() != Qt::ShiftModifier && !alreadySelected)) {
            clearTextSelection();
        } else if ((e->modifiers() & Qt::ShiftModifier) != 0u) {
            clearTextSelection(false);
        }
        if ((item != nullptr) && ((item->flags() & QGraphicsItem::ItemIsMovable) != 0)) {
            m_sceneClickPoint = e->scenePos();
            m_selectedItem = item;
            // qCDebug(KDENLIVE_LOG) << "/////////  ITEM TYPE: " << item->type();
            if (item->type() == QGraphicsTextItem::Type) {
Nicolas Carion's avatar
Nicolas Carion committed
810
                auto *t = static_cast<MyTextItem *>(item);
811
812
813
814
815
816
817
                if (t->textInteractionFlags() == Qt::TextEditorInteraction) {
                    QGraphicsScene::mousePressEvent(e);
                    return;
                }
                t->setTextInteractionFlags(Qt::NoTextInteraction);
                t->setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
                setCursor(Qt::ClosedHandCursor);
Julius Künzel's avatar
Julius Künzel committed
818
            } else if (item->type() == QGraphicsRectItem::Type || item->type() == QGraphicsEllipseItem::Type || item->type() == QGraphicsSvgItem::Type || item->type() == QGraphicsPixmapItem::Type) {
819
820
                QRectF r1;
                if (m_selectedItem->type() == QGraphicsRectItem::Type) {
Vincent Pinon's avatar
Vincent Pinon committed
821
                    r1 = static_cast<QGraphicsRectItem *>(m_selectedItem)->rect().normalized();
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
                } else {
                    r1 = m_selectedItem->boundingRect().normalized();
                }

                r1.translate(m_selectedItem->scenePos());
                switch (m_resizeMode) {
                case BottomRight:
                case Right:
                case Down:
                    m_clickPoint = r1.topLeft();
                    e->accept();
                    break;
                case TopLeft:
                case Left:
                case Up:
                    m_clickPoint = r1.bottomRight();
                    e->accept();
                    break;
                case TopRight:
                    m_clickPoint = r1.bottomLeft();
                    e->accept();
                    break;
                case BottomLeft:
                    m_clickPoint = r1.topRight();
                    e->accept();
                    break;
                default:
                    break;
                }
            }
        }
        QGraphicsScene::mousePressEvent(e);
Julius Künzel's avatar
Julius Künzel committed
854
    } else if (m_tool == TITLE_RECTANGLE || m_tool == TITLE_ELLIPSE) {
855
856
857
858
859
        clearTextSelection();
        m_sceneClickPoint = QPointF(xPos, yPos);
        m_selectedItem = nullptr;
        e->ignore();
    } else if (m_tool == TITLE_TEXT) {
860
861
862
        if (e->button() == Qt::LeftButton) {
            clearTextSelection();
            MyTextItem *textItem = new MyTextItem(i18n("Text"), nullptr);
Vincent Pinon's avatar
Vincent Pinon committed
863
            yPos = ((int(e->scenePos().y()) - (m_fontSize / 2)) / m_gridSize) * m_gridSize;
864
865
866
867
868
            textItem->setPos(xPos, yPos);
            addItem(textItem);
            textItem->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
            textItem->setTextInteractionFlags(Qt::TextEditorInteraction);
            textItem->setFocus(Qt::MouseFocusReason);
869
            textItem->setAlignment(QFlags<Qt::AlignmentFlag>(KdenliveSettings::titlerAlign()));
870
871
872
873
874
875
876
            emit newText(textItem);
            m_selectedItem = textItem;
            m_selectedItem->setSelected(true);
            m_createdText = true;
        } else {
            QGraphicsScene::mousePressEvent(e);
        }
877
878
879
880
881
882
883
884
    }
    // qCDebug(KDENLIVE_LOG) << "//////  MOUSE CLICK, RESIZE MODE: " << m_resizeMode;
}

void GraphicsSceneRectMove::clearTextSelection(bool reset)
{
    if ((m_selectedItem != nullptr) && m_selectedItem->type() == QGraphicsTextItem::Type) {
        // disable text editing
Nicolas Carion's avatar
Nicolas Carion committed
885
        auto *t = static_cast<MyTextItem *>(m_selectedItem);
886
887
888
889
        t->textCursor().setPosition(0);
        QTextBlock cur = t->textCursor().block();
        t->setTextCursor(QTextCursor(cur));
        t->setTextInteractionFlags(Qt::NoTextInteraction);
890
        t->unsetCursor();
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
    }
    if (reset) {
        m_selectedItem = nullptr;
        clearSelection();
    }
}

void GraphicsSceneRectMove::mouseMoveEvent(QGraphicsSceneMouseEvent *e)
{
    QList<QGraphicsView *> viewlist = views();
    if (viewlist.isEmpty()) {
        e->ignore();
        return;
    }
    QGraphicsView *view = viewlist.constFirst();
    if (m_pan) {
        QPoint diff = e->lastScreenPos() - e->screenPos();
        view->horizontalScrollBar()->setValue(view->horizontalScrollBar()->value() + diff.x());
        view->verticalScrollBar()->setValue(view->verticalScrollBar()->value() + diff.y());
        e->accept();
        QGraphicsScene::mouseMoveEvent(e);
        return;
    }
    if (e->buttons() != Qt::NoButton && !m_moveStarted) {
        if ((view->mapFromScene(e->scenePos()) - view->mapFromScene(m_clickPoint)).manhattanLength() < QApplication::startDragDistance()) {
            e->ignore();
            return;
        }
        m_moveStarted = true;
    }
    if ((m_selectedItem != nullptr) && ((e->buttons() & Qt::LeftButton) != 0u)) {
Julius Künzel's avatar
Julius Künzel committed
922
923
        if (m_selectedItem->type() == QGraphicsRectItem::Type || m_selectedItem->type() == QGraphicsEllipseItem::Type || m_selectedItem->type() == QGraphicsSvgItem::Type ||
                m_selectedItem->type() == QGraphicsPixmapItem::Type) {
924
925
            QRectF newrect;
            if (m_selectedItem->type() == QGraphicsRectItem::Type) {
Vincent Pinon's avatar
Vincent Pinon committed
926
                newrect = static_cast<QGraphicsRectItem *>(m_selectedItem)->rect();
927
928
929
            } else {
                newrect = m_selectedItem->boundingRect();
            }
Vincent Pinon's avatar
Vincent Pinon committed
930
931
            int xPos = (int(e->scenePos().x()) / m_gridSize) * m_gridSize;
            int yPos = (int(e->scenePos().y()) / m_gridSize) * m_gridSize;
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
            QPointF newpoint(xPos, yPos);
            switch (m_resizeMode) {
            case BottomRight:
            case BottomLeft:
            case TopRight:
            case TopLeft:
                newrect = QRectF(m_clickPoint, newpoint).normalized();
                break;
            case Up:
                newrect = QRectF(m_clickPoint, QPointF(m_clickPoint.x() - newrect.width(), newpoint.y())).normalized();
                break;
            case Down:
                newrect = QRectF(m_clickPoint, QPointF(newrect.width() + m_clickPoint.x(), newpoint.y())).normalized();
                break;
            case Right:
                newrect = QRectF(m_clickPoint, QPointF(newpoint.x(), m_clickPoint.y() + newrect.height())).normalized();
                break;
            case Left:
                newrect = QRectF(m_clickPoint, QPointF(newpoint.x(), m_clickPoint.y() - newrect.height())).normalized();
                break;
            default:
                break;
            }

            if (m_selectedItem->type() == QGraphicsRectItem::Type && m_resizeMode != NoResize) {
Nicolas Carion's avatar
Nicolas Carion committed
957
                auto *gi = static_cast<MyRectItem *>(m_selectedItem);
958
959
960
                // Resize using aspect ratio
                if (!m_selectedItem->data(0).isNull()) {
                    // we want to keep aspect ratio
Vincent Pinon's avatar
Vincent Pinon committed
961
962
                    double hRatio = newrect.width() / m_selectedItem->data(0).toInt();
                    double vRatio = newrect.height() / m_selectedItem->data(1).toInt();
963
964
965
966
967
968
969
970
971
972
                    if (hRatio < vRatio) {
                        newrect.setHeight(m_selectedItem->data(1).toInt() * hRatio);
                    } else {
                        newrect.setWidth(m_selectedItem->data(0).toInt() * vRatio);
                    }
                }
                gi->setPos(newrect.topLeft());
                gi->setRect(QRectF(QPointF(), newrect.bottomRight() - newrect.topLeft()));
                return;
            }
Julius Künzel's avatar
Julius Künzel committed
973
974
975
976
977
            if (m_selectedItem->type() == QGraphicsEllipseItem::Type && m_resizeMode != NoResize) {
                auto *gi = static_cast<MyEllipseItem *>(m_selectedItem);
                // Resize using aspect ratio
                if (!m_selectedItem->data(0).isNull()) {
                    // we want to keep aspect ratio
Vincent Pinon's avatar
Vincent Pinon committed
978
979
                    double hRatio = newrect.width() / m_selectedItem->data(0).toInt();
                    double vRatio = newrect.height() / m_selectedItem->data(1).toInt();
Julius Künzel's avatar
Julius Künzel committed
980
981
982
983
984
985
986
987
988
989
                    if (hRatio < vRatio) {
                        newrect.setHeight(m_selectedItem->data(1).toInt() * hRatio);
                    } else {
                        newrect.setWidth(m_selectedItem->data(0).toInt() * vRatio);
                    }
                }
                gi->setPos(newrect.topLeft());
                gi->setRect(QRectF(QPointF(), newrect.bottomRight() - newrect.topLeft()));
                return;
            }
990
991
            QGraphicsScene::mouseMoveEvent(e);
        } else if (m_selectedItem->type() == QGraphicsTextItem::Type) {
Nicolas Carion's avatar
Nicolas Carion committed
992
            auto *t = static_cast<MyTextItem *>(m_selectedItem);
993
994
995
996
997
998
999
1000
            if ((t->textInteractionFlags() & static_cast<int>((Qt::TextEditorInteraction) != 0)) != 0) {
                QGraphicsScene::mouseMoveEvent(e);
                return;
            }
            QGraphicsScene::mouseMoveEvent(e);
            m_sceneClickPoint = e->scenePos();
        }
        emit itemMoved();