]> git.sesse.net Git - kdenlive/blob - src/beziercurve/beziersplineeditor.cpp
Use QPainterPath's cubicTo to draw cubic bezier spline
[kdenlive] / src / beziercurve / beziersplineeditor.cpp
1 /***************************************************************************
2  *   Copyright (C) 2010 by Till Theato (root@ttill.de)                     *
3  *   This file is part of Kdenlive (www.kdenlive.org).                     *
4  *                                                                         *
5  *   Kdenlive is free software: you can redistribute it and/or modify      *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation, either version 2 of the License, or     *
8  *   (at your option) any later version.                                   *
9  *                                                                         *
10  *   Kdenlive is distributed in the hope that it will be useful,           *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with Kdenlive.  If not, see <http://www.gnu.org/licenses/>.     *
17  ***************************************************************************/
18
19 #include "beziersplineeditor.h"
20
21 #include <QPainter>
22 #include <QMouseEvent>
23
24
25 BezierSplineEditor::BezierSplineEditor(QWidget* parent) :
26         QWidget(parent),
27         m_mode(ModeNormal),
28         m_zoomLevel(0),
29         m_gridLines(3),
30         m_showAllHandles(true),
31         m_pixmapCache(NULL),
32         m_pixmapIsDirty(true),
33         m_currentPointIndex(-1)
34 {
35     setMouseTracking(true);
36     setAutoFillBackground(false);
37     setAttribute(Qt::WA_OpaquePaintEvent);
38     setMinimumSize(150, 150);
39     setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
40 }
41
42 BezierSplineEditor::~BezierSplineEditor()
43 {
44     if (m_pixmapCache)
45         delete m_pixmapCache;
46 }
47
48 CubicBezierSpline BezierSplineEditor::spline()
49 {
50     return m_spline;
51 }
52
53 void BezierSplineEditor::setSpline(const CubicBezierSpline& spline)
54 {
55     m_spline = spline;
56     m_currentPointIndex = -1;
57     m_mode = ModeNormal;
58     emit currentPoint(BPoint());
59     emit modified();
60     update();
61 }
62
63 BPoint BezierSplineEditor::getCurrentPoint()
64 {
65     if (m_currentPointIndex >= 0)
66         return m_spline.points()[m_currentPointIndex];
67     else
68         return BPoint();
69 }
70
71 void BezierSplineEditor::updateCurrentPoint(const BPoint& p)
72 {
73     if (m_currentPointIndex >= 0) {
74         m_spline.setPoint(m_currentPointIndex, p);
75         // during validation the point might have changed
76         emit currentPoint(m_spline.points()[m_currentPointIndex]);
77         emit modified();
78         update();
79     }
80 }
81
82 void BezierSplineEditor::setPixmap(const QPixmap& pixmap)
83 {
84     m_pixmap = pixmap;
85     m_pixmapIsDirty = true;
86     update();
87 }
88
89 void BezierSplineEditor::slotZoomIn()
90 {
91     m_zoomLevel = qMax(m_zoomLevel-1, 0);
92     m_pixmapIsDirty = true;
93     update();
94 }
95
96 void BezierSplineEditor::slotZoomOut()
97 {
98     m_zoomLevel = qMin(m_zoomLevel+1, 3);
99     m_pixmapIsDirty = true;
100     update();
101 }
102
103 void BezierSplineEditor::setShowAllHandles(bool show)
104 {
105     m_showAllHandles = show;
106     update();
107 }
108
109 int BezierSplineEditor::gridLines()
110 {
111     return m_gridLines;
112 }
113
114 void BezierSplineEditor::setGridLines(int lines)
115 {
116     m_gridLines = qBound(0, lines, 8);
117     update();
118 }
119
120 void BezierSplineEditor::paintEvent(QPaintEvent* event)
121 {
122     Q_UNUSED(event);
123
124     QPainter p(this);
125
126     /*
127      * Zoom
128      */
129     int wWidth = width() - 1;
130     int wHeight = height() - 1;
131     int offset = 1/8. * m_zoomLevel * (wWidth > wHeight ? wWidth : wHeight);
132     wWidth -= 2 * offset;
133     wHeight -= 2 * offset;
134
135     p.translate(offset, offset);
136
137     /*
138      * Background
139      */
140     p.fillRect(rect().translated(-offset, -offset), palette().background());
141     if (!m_pixmap.isNull()) {
142         if (m_pixmapIsDirty || !m_pixmapCache) {
143             if (m_pixmapCache)
144                 delete m_pixmapCache;
145             m_pixmapCache = new QPixmap(wWidth + 1, wHeight + 1);
146             QPainter cachePainter(m_pixmapCache);
147
148             cachePainter.scale(1.0*(wWidth+1) / m_pixmap.width(), 1.0*(wHeight+1) / m_pixmap.height());
149             cachePainter.drawPixmap(0, 0, m_pixmap);
150             m_pixmapIsDirty = false;
151         }
152         p.drawPixmap(0, 0, *m_pixmapCache);
153     }
154
155
156     p.setPen(QPen(Qt::gray, 1, Qt::SolidLine));
157
158     /*
159      * Borders
160      */
161     if (m_zoomLevel != 0) {
162         p.drawRect(0, 0, wWidth, wHeight);
163     }
164
165     /*
166      * Grid
167      */
168     if (m_gridLines != 0) {
169         double stepH = wWidth / (double)(m_gridLines + 1);
170         double stepV = wHeight / (double)(m_gridLines + 1);
171         for (int i = 1; i <= m_gridLines; ++i) {
172             p.drawLine(QLineF(i * stepH, 0, i * stepH, wHeight));
173             p.drawLine(QLineF(0, i * stepV, wWidth, i * stepV));
174         }
175     }
176
177     p.setRenderHint(QPainter::Antialiasing);
178
179     /*
180      * Standard line
181      */
182     p.drawLine(QLineF(0, wHeight, wWidth, 0));
183
184
185     /*
186      * Prepare Spline, Points
187      */
188     int max = m_spline.points().count() - 1;
189     if (max < 1)
190         return;
191     BPoint point(m_spline.getPoint(0, wWidth, wHeight, true));
192
193     /*
194      * Spline
195      */
196     BPoint next;
197     
198     QPainterPath splinePath(QPointF(point.p.x(), point.p.y()));
199     for (int i = 0; i < max; ++i) {
200         point = m_spline.getPoint(i, wWidth, wHeight, true);
201         next = m_spline.getPoint(i + 1, wWidth, wHeight, true);
202         splinePath.cubicTo(point.h2, next.h1, next.p);
203     }
204     p.setPen(QPen(Qt::black, 1, Qt::SolidLine));
205     p.drawPath(splinePath);
206
207
208     /*
209      * Points + Handles
210      */
211     p.setPen(QPen(Qt::red, 1, Qt::SolidLine));
212
213     QPolygonF handle = QPolygonF() << QPointF(0, -3) << QPointF(3, 0) << QPointF(0, 3) << QPointF(-3, 0);
214 #if QT_VERSION < 0x040600
215     QPolygonF tmp;
216 #endif
217
218     for (int i = 0; i <= max; ++i) {
219         point = m_spline.getPoint(i, wWidth, wHeight, true);
220
221         if (i == m_currentPointIndex) {
222             // selected point: fill p and handles
223             p.setBrush(QBrush(QColor(Qt::red), Qt::SolidPattern));
224             // connect p and handles with lines
225             if (i != 0)
226                 p.drawLine(QLineF(point.h1.x(), point.h1.y(), point.p.x(),point.p.y()));
227             if (i != max)
228                 p.drawLine(QLineF(point.p.x(), point.p.y(), point.h2.x(), point.h2.y()));
229         }
230
231         p.drawEllipse(QRectF(point.p.x() - 3,
232                              point.p.y() - 3, 6, 6));
233         if (i != 0 && (i == m_currentPointIndex || m_showAllHandles)) {
234 #if QT_VERSION >= 0x040600
235             p.drawConvexPolygon(handle.translated(point.h1.x(), point.h1.y()));
236 #else
237             tmp = handle;
238             tmp.translate(point.h1.x(), point.h1.y());
239             p.drawConvexPolygon(tmp);
240 #endif
241         }
242         if (i != max && (i == m_currentPointIndex || m_showAllHandles)) {
243 #if QT_VERSION >= 0x040600
244             p.drawConvexPolygon(handle.translated(point.h2.x(), point.h2.y()));
245 #else
246             tmp = handle;
247             tmp.translate(point.h2.x(), point.h2.y());
248             p.drawConvexPolygon(tmp);
249 #endif
250         }
251
252         if ( i == m_currentPointIndex)
253             p.setBrush(QBrush(Qt::NoBrush));
254     }
255 }
256
257 void BezierSplineEditor::resizeEvent(QResizeEvent* event)
258 {
259     m_pixmapIsDirty = true;
260     QWidget::resizeEvent(event);
261 }
262
263 void BezierSplineEditor::mousePressEvent(QMouseEvent* event)
264 {
265     int wWidth = width() - 1;
266     int wHeight = height() - 1;
267     int offset = 1/8. * m_zoomLevel * (wWidth > wHeight ? wWidth : wHeight);
268     wWidth -= 2 * offset;
269     wHeight -= 2 * offset;
270
271     double x = (event->pos().x() - offset) / (double)(wWidth);
272     double y = 1.0 - (event->pos().y() - offset) / (double)(wHeight);
273
274     point_types selectedPoint;
275     int closestPointIndex = nearestPointInRange(QPointF(x, y), wWidth, wHeight, &selectedPoint);
276
277     if (event->button() == Qt::RightButton && closestPointIndex > 0 && closestPointIndex < m_spline.points().count() - 1 && selectedPoint == PTypeP) {
278         m_spline.removePoint(closestPointIndex);
279         setCursor(Qt::ArrowCursor);
280         m_mode = ModeNormal;
281         if (closestPointIndex < m_currentPointIndex)
282             --m_currentPointIndex;
283         update();
284         if (m_currentPointIndex >= 0)
285             emit currentPoint(m_spline.points()[m_currentPointIndex]);
286         else
287             emit currentPoint(BPoint());
288         emit modified();
289         return;
290     } else if (event->button() != Qt::LeftButton) {
291         return;
292     }
293
294     if (closestPointIndex < 0) {
295         m_currentPointIndex = m_spline.addPoint(BPoint(QPointF(x-0.05, y-0.05),
296                                                        QPointF(x, y),
297                                                        QPointF(x+0.05, y+0.05)));
298         m_currentPointType = PTypeP;
299     } else {
300         m_currentPointIndex = closestPointIndex;
301         m_currentPointType = selectedPoint;
302     }
303
304     BPoint point = m_spline.points()[m_currentPointIndex];
305
306     m_grabPOriginal = point;
307     if (m_currentPointIndex > 0)
308         m_grabPPrevious = m_spline.points()[m_currentPointIndex - 1];
309     if (m_currentPointIndex < m_spline.points().count() - 1)
310         m_grabPNext = m_spline.points()[m_currentPointIndex + 1];
311     m_grabOffsetX = point[(int)m_currentPointType].x() - x;
312     m_grabOffsetY = point[(int)m_currentPointType].y() - y;
313
314     point[(int)m_currentPointType] = QPointF(x + m_grabOffsetX, y + m_grabOffsetY);
315
316     m_spline.setPoint(m_currentPointIndex, point);
317
318     m_mode = ModeDrag;
319
320     emit currentPoint(point);
321     update();
322 }
323
324 void BezierSplineEditor::mouseReleaseEvent(QMouseEvent* event)
325 {
326     if (event->button() != Qt::LeftButton)
327         return;
328
329     setCursor(Qt::ArrowCursor);
330     m_mode = ModeNormal;
331
332     emit modified();
333 }
334
335 void BezierSplineEditor::mouseMoveEvent(QMouseEvent* event)
336 {
337     int wWidth = width() - 1;
338     int wHeight = height() - 1;
339     int offset = 1/8. * m_zoomLevel * (wWidth > wHeight ? wWidth : wHeight);
340     wWidth -= 2 * offset;
341     wHeight -= 2 * offset;
342
343     double x = (event->pos().x() - offset) / (double)(wWidth);
344     double y = 1.0 - (event->pos().y() - offset) / (double)(wHeight);
345     
346     if (m_mode == ModeNormal) {
347         // If no point is selected set the the cursor shape if on top
348         point_types type;
349         int nearestPointIndex = nearestPointInRange(QPointF(x, y), wWidth, wHeight, &type);
350
351         if (nearestPointIndex < 0)
352             setCursor(Qt::ArrowCursor);
353         else
354             setCursor(Qt::CrossCursor);
355     } else {
356         // Else, drag the selected point
357         setCursor(Qt::CrossCursor);
358
359         x += m_grabOffsetX;
360         y += m_grabOffsetY;
361
362         double leftX = 0.;
363         double rightX = 1.;
364         BPoint point = m_spline.points()[m_currentPointIndex];
365         switch (m_currentPointType) {
366         case PTypeH1:
367             rightX = point.p.x();
368             if (m_currentPointIndex == 0)
369                 leftX = -4;
370             else
371                 leftX = m_spline.points()[m_currentPointIndex - 1].p.x();
372
373             x = qBound(leftX, x, rightX);
374             point.setH1(QPointF(x, y));
375             break;
376
377         case PTypeP:
378             if (m_currentPointIndex == 0)
379                 rightX = 0.0;
380             else if (m_currentPointIndex == m_spline.points().count() - 1)
381                 leftX = 1.0;
382
383             x = qBound(leftX, x, rightX);
384             y = qBound(0., y, 1.);
385
386             // handles might have changed because we neared another point
387             // try to restore
388             point.h1 = m_grabPOriginal.h1;
389             point.h2 = m_grabPOriginal.h2;
390             // and move by same offset
391             // (using update handle in point.setP won't work because the offset between new and old point is very small)
392             point.h1 += QPointF(x, y) - m_grabPOriginal.p;
393             point.h2 += QPointF(x, y) - m_grabPOriginal.p;
394
395             point.setP(QPointF(x, y), false);
396             break;
397
398         case PTypeH2:
399             leftX = point.p.x();
400             if (m_currentPointIndex == m_spline.points().count() - 1)
401                 rightX = 5;
402             else
403                 rightX = m_spline.points()[m_currentPointIndex + 1].p.x();
404
405             x = qBound(leftX, x, rightX);
406             point.setH2(QPointF(x, y));
407         };
408
409         int index = m_currentPointIndex;
410         m_currentPointIndex = m_spline.setPoint(m_currentPointIndex, point);
411
412         if (m_currentPointType == PTypeP) {
413             // we might have changed the handles of other points
414             // try to restore
415             if (index == m_currentPointIndex) {
416                 if (m_currentPointIndex > 0)
417                     m_spline.setPoint(m_currentPointIndex - 1, m_grabPPrevious);
418                 if (m_currentPointIndex < m_spline.points().count() -1)
419                     m_spline.setPoint(m_currentPointIndex + 1, m_grabPNext);
420             } else {
421                 if (m_currentPointIndex < index) {
422                     m_spline.setPoint(index, m_grabPPrevious);
423                     m_grabPNext = m_grabPPrevious;
424                     if (m_currentPointIndex > 0)
425                         m_grabPPrevious = m_spline.points()[m_currentPointIndex - 1];
426                 } else {
427                     m_spline.setPoint(index, m_grabPNext);
428                     m_grabPPrevious = m_grabPNext;
429                     if (m_currentPointIndex < m_spline.points().count() - 1)
430                         m_grabPNext = m_spline.points()[m_currentPointIndex + 1];
431                 }
432             }
433         }
434
435         emit currentPoint(point);
436         update();
437     }
438 }
439
440 void BezierSplineEditor::leaveEvent(QEvent* event)
441 {
442     QWidget::leaveEvent(event);
443 }
444
445 int BezierSplineEditor::nearestPointInRange(QPointF p, int wWidth, int wHeight, BezierSplineEditor::point_types* sel)
446 {
447     double nearestDistanceSquared = 1000;
448     point_types selectedPoint;
449     int nearestIndex = -1;
450     int i = 0;
451
452     double distanceSquared;
453     // find out distance using the Pythagorean theorem
454     foreach(const BPoint & point, m_spline.points()) {
455         for (int j = 0; j < 3; ++j) {
456             distanceSquared = pow(point[j].x() - p.x(), 2) + pow(point[j].y() - p.y(), 2);
457             if (distanceSquared < nearestDistanceSquared) {
458                 nearestIndex = i;
459                 nearestDistanceSquared = distanceSquared;
460                 selectedPoint = (point_types)j;
461             }
462         }
463         ++i;
464     }
465
466     if (nearestIndex >= 0 && (nearestIndex == m_currentPointIndex || selectedPoint == PTypeP || m_showAllHandles)) {
467         // a point was found and it is not a hidden handle
468         BPoint point = m_spline.points()[nearestIndex];
469         if (qAbs(p.x() - point[(int)selectedPoint].x()) * wWidth < 5 && qAbs(p.y() - point[(int)selectedPoint].y()) * wHeight < 5) {
470             *sel = selectedPoint;
471             return nearestIndex;
472         }
473     }
474
475     return -1;
476 }
477
478 #include "beziersplineeditor.moc"