]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
add / edit effect keyframe is now integrated in the undo framework
[kdenlive] / src / clipitem.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
18  ***************************************************************************/
19
20
21
22 #include <QPainter>
23 #include <QTimer>
24 #include <QStyleOptionGraphicsItem>
25 #include <QGraphicsScene>
26 #include <QGraphicsView>
27 #include <QScrollBar>
28 #include <QMimeData>
29 #include <QApplication>
30
31 #include <KDebug>
32
33 #include "clipitem.h"
34 #include "customtrackview.h"
35 #include "renderer.h"
36 #include "docclipbase.h"
37 #include "transition.h"
38 #include "events.h"
39 #include "kdenlivesettings.h"
40 #include "kthumb.h"
41
42 ClipItem::ClipItem(DocClipBase *clip, ItemInfo info, GenTime cropStart, double scale, double fps)
43         : AbstractClipItem(info, QRectF(), fps), m_clip(clip), m_resizeMode(NONE), m_grabPoint(0), m_maxTrack(0), m_hasThumbs(false), startThumbTimer(NULL), endThumbTimer(NULL), m_effectsCounter(1), audioThumbWasDrawn(false), m_opacity(1.0), m_timeLine(0), m_thumbsRequested(0), m_startFade(0), m_endFade(0), m_hover(false), m_selectedEffect(-1) {
44     QRectF rect((double) info.startPos.frames(fps) * scale, (double)(info.track * KdenliveSettings::trackheight() + 1), (double)(info.endPos - info.startPos).frames(fps) * scale, (double)(KdenliveSettings::trackheight() - 1));
45     setRect(rect);
46
47     m_clipName = clip->name();
48     m_producer = clip->getId();
49     m_clipType = clip->clipType();
50     m_cropStart = cropStart;
51     m_maxDuration = clip->maxDuration();
52     setAcceptDrops(true);
53     audioThumbReady = clip->audioThumbCreated();
54
55     /*
56       m_cropStart = xml.attribute("in", 0).toInt();
57       m_maxDuration = xml.attribute("duration", 0).toInt();
58       if (m_maxDuration == 0) m_maxDuration = xml.attribute("out", 0).toInt() - m_cropStart;
59
60       if (duration != -1) m_cropDuration = duration;
61       else m_cropDuration = m_maxDuration;*/
62
63
64     setFlags(QGraphicsItem::ItemClipsToShape | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
65     setAcceptsHoverEvents(true);
66     connect(this , SIGNAL(prepareAudioThumb(double, QPainterPath, int, int)) , this, SLOT(slotPrepareAudioThumb(double, QPainterPath, int, int)));
67
68     setBrush(QColor(141, 166, 215));
69     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW) {
70         m_hasThumbs = true;
71         connect(this, SIGNAL(getThumb(int, int)), clip->thumbProducer(), SLOT(extractImage(int, int)));
72         connect(clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));
73         connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
74         QTimer::singleShot(300, this, SLOT(slotFetchThumbs()));
75
76         startThumbTimer = new QTimer(this);
77         startThumbTimer->setSingleShot(true);
78         connect(startThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetStartThumb()));
79         endThumbTimer = new QTimer(this);
80         endThumbTimer->setSingleShot(true);
81         connect(endThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetEndThumb()));
82     } else if (m_clipType == COLOR) {
83         QString colour = clip->getProperty("colour");
84         colour = colour.replace(0, 2, "#");
85         setBrush(QColor(colour.left(7)));
86     } else if (m_clipType == IMAGE || m_clipType == TEXT) {
87         m_startPix = KThumb::getImage(KUrl(clip->getProperty("resource")), (int)(50 * KdenliveSettings::project_display_ratio()), 50);
88         m_endPix = m_startPix;
89     } else if (m_clipType == AUDIO) {
90         connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
91     }
92 }
93
94
95 ClipItem::~ClipItem() {
96     if (startThumbTimer) delete startThumbTimer;
97     if (endThumbTimer) delete endThumbTimer;
98 }
99
100 int ClipItem::selectedEffectIndex() const {
101     return m_selectedEffect;
102 }
103
104 void ClipItem::initEffect(QDomElement effect) {
105     // the kdenlive_ix int is used to identify an effect in mlt's playlist, should
106     // not be changed
107     if (effect.attribute("kdenlive_ix").toInt() == 0)
108         effect.setAttribute("kdenlive_ix", QString::number(effectsCounter()));
109     // init keyframes if required
110     QDomNodeList params = effect.elementsByTagName("parameter");
111     for (int i = 0; i < params.count(); i++) {
112         QDomElement e = params.item(i).toElement();
113         if (!e.isNull() && e.attribute("type") == "keyframe") {
114             QString def = e.attribute("default");
115             // Effect has a keyframe type parameter, we need to set the values
116             if (e.attribute("keyframes").isEmpty()) {
117                 e.setAttribute("keyframes", QString::number(m_cropStart.frames(m_fps)) + ":" + def + ";" + QString::number((m_cropStart + m_cropDuration).frames(m_fps)) + ":" + def);
118                 //kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
119                 break;
120             }
121         }
122     }
123 }
124
125 void ClipItem::setKeyframes(const int ix, const QString keyframes) {
126     QDomElement effect = effectAt(ix);
127     QDomNodeList params = effect.elementsByTagName("parameter");
128     for (int i = 0; i < params.count(); i++) {
129         QDomElement e = params.item(i).toElement();
130         if (!e.isNull() && e.attribute("type") == "keyframe") {
131             e.setAttribute("keyframes", keyframes);
132             if (ix == m_selectedEffect) {
133               m_keyframes.clear();
134               double max = e.attribute("max").toDouble();
135               double min = e.attribute("min").toDouble();
136               m_keyframeFactor = 100.0 / (max - min);
137               m_keyframeDefault = e.attribute("default").toDouble();
138               // parse keyframes
139               QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
140               foreach(QString str, keyframes) {
141                   int pos = str.section(":", 0, 0).toInt();
142                   double val = str.section(":", 1, 1).toDouble();
143                   m_keyframes[pos] = val;
144               }
145               update();
146               return;
147             }
148             break;
149         }
150     }
151
152 }
153
154
155 void ClipItem::setSelectedEffect(const int ix) {
156
157     m_selectedEffect = ix;
158     QDomElement effect = effectAt(m_selectedEffect);
159     QDomNodeList params = effect.elementsByTagName("parameter");
160     for (int i = 0; i < params.count(); i++) {
161         QDomElement e = params.item(i).toElement();
162         if (!e.isNull() && e.attribute("type") == "keyframe") {
163             m_keyframes.clear();
164             double max = e.attribute("max").toDouble();
165             double min = e.attribute("min").toDouble();
166             m_keyframeFactor = 100.0 / (max - min);
167             m_keyframeDefault = e.attribute("default").toDouble();
168             // parse keyframes
169             QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
170             foreach(QString str, keyframes) {
171                 int pos = str.section(":", 0, 0).toInt();
172                 double val = str.section(":", 1, 1).toDouble();
173                 m_keyframes[pos] = val;
174             }
175             update();
176             return;
177         }
178     }
179     if (!m_keyframes.isEmpty()) {
180         m_keyframes.clear();
181         update();
182     }
183 }
184
185 QString ClipItem::keyframes(const int index) {
186     QString result;
187     QDomElement effect = effectAt(index);
188     QDomNodeList params = effect.elementsByTagName("parameter");
189
190     for (int i = 0; i < params.count(); i++) {
191         QDomElement e = params.item(i).toElement();
192         if (!e.isNull() && e.attribute("type") == "keyframe") {
193             result = e.attribute("keyframes");
194             break;
195         }
196     }
197     return result;
198 }
199
200 void ClipItem::updateKeyframeEffect() {
201     // regenerate xml parameter from the clip keyframes
202     QDomElement effect = effectAt(m_selectedEffect);
203     QDomNodeList params = effect.elementsByTagName("parameter");
204
205     for (int i = 0; i < params.count(); i++) {
206         QDomElement e = params.item(i).toElement();
207         if (!e.isNull() && e.attribute("type") == "keyframe") {
208             QString keyframes;
209             if (m_keyframes.count() > 1) {
210                 QMap<int, double>::const_iterator i = m_keyframes.constBegin();
211                 double x1;
212                 double y1;
213                 while (i != m_keyframes.constEnd()) {
214                     keyframes.append(QString::number(i.key()) + ":" + QString::number(i.value()) + ";");
215                     ++i;
216                 }
217             }
218             // Effect has a keyframe type parameter, we need to set the values
219             //kDebug() << ":::::::::::::::   SETTING EFFECT KEYFRAMES: " << keyframes;
220             e.setAttribute("keyframes", keyframes);
221             break;
222         }
223     }
224 }
225
226 QDomElement ClipItem::selectedEffect() {
227     if (m_selectedEffect == -1 || m_effectList.isEmpty()) return QDomElement();
228     return effectAt(m_selectedEffect);
229 }
230
231 void ClipItem::resetThumbs() {
232     slotFetchThumbs();
233     audioThumbCachePic.clear();
234 }
235
236
237 void ClipItem::refreshClip() {
238     m_maxDuration = m_clip->maxDuration();
239     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW) slotFetchThumbs();
240     else if (m_clipType == COLOR) {
241         QString colour = m_clip->getProperty("colour");
242         colour = colour.replace(0, 2, "#");
243         setBrush(QColor(colour.left(7)));
244     } else if (m_clipType == IMAGE || m_clipType == TEXT) {
245         m_startPix = KThumb::getImage(KUrl(m_clip->getProperty("resource")), (int)(50 * KdenliveSettings::project_display_ratio()), 50);
246         m_endPix = m_startPix;
247     }
248 }
249
250 void ClipItem::slotFetchThumbs() {
251     m_thumbsRequested += 2;
252     emit getThumb((int)m_cropStart.frames(m_fps), (int)(m_cropStart + m_cropDuration).frames(m_fps));
253 }
254
255 void ClipItem::slotGetStartThumb() {
256     m_thumbsRequested++;
257     emit getThumb((int)m_cropStart.frames(m_fps), -1);
258 }
259
260 void ClipItem::slotGetEndThumb() {
261     m_thumbsRequested++;
262     emit getThumb(-1, (int)(m_cropStart + m_cropDuration).frames(m_fps));
263 }
264
265 void ClipItem::slotThumbReady(int frame, QPixmap pix) {
266     if (m_thumbsRequested == 0) return;
267     if (frame == m_cropStart.frames(m_fps)) {
268         m_startPix = pix;
269         QRectF r = boundingRect();
270         r.setRight(pix.width() + 2);
271         update(r);
272     } else {
273         m_endPix = pix;
274         QRectF r = boundingRect();
275         r.setLeft(r.right() - pix.width() - 2);
276         update(r);
277     }
278     m_thumbsRequested--;
279 }
280
281 void ClipItem::slotGotAudioData() {
282     audioThumbReady = true;
283     if (m_clipType == AV) {
284         QRectF r = boundingRect();
285         r.setTop(r.top() + r.height() / 2 - 1);
286         update(r);
287     } else update();
288 }
289
290 int ClipItem::type() const {
291     return AVWIDGET;
292 }
293
294 DocClipBase *ClipItem::baseClip() const {
295     return m_clip;
296 }
297
298 QDomElement ClipItem::xml() const {
299     return m_clip->toXML();
300 }
301
302 int ClipItem::clipType() const {
303     return m_clipType;
304 }
305
306 QString ClipItem::clipName() const {
307     return m_clipName;
308 }
309
310 int ClipItem::clipProducer() const {
311     return m_producer;
312 }
313
314 void ClipItem::flashClip() {
315     if (m_timeLine == 0) {
316         m_timeLine = new QTimeLine(750, this);
317         m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
318         connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
319     }
320     m_timeLine->start();
321 }
322
323 void ClipItem::animate(qreal value) {
324     QRectF r = boundingRect();
325     r.setHeight(20);
326     update(r);
327 }
328
329 // virtual
330 void ClipItem::paint(QPainter *painter,
331                      const QStyleOptionGraphicsItem *option,
332                      QWidget *) {
333     painter->setOpacity(m_opacity);
334     QBrush paintColor = brush();
335     if (isSelected()) paintColor = QBrush(QColor(79, 93, 121));
336     QRectF br = rect();
337     double scale = br.width() / m_cropDuration.frames(m_fps);
338
339     // kDebug()<<"///   EXPOSED RECT: "<<option->exposedRect.x()<<" X "<<option->exposedRect.right();
340
341     int startpixel = (int)option->exposedRect.x() - rect().x();
342
343     if (startpixel < 0)
344         startpixel = 0;
345     int endpixel = (int)option->exposedRect.right() - rect().x();
346     if (endpixel < 0)
347         endpixel = 0;
348
349     //painter->setRenderHints(QPainter::Antialiasing);
350
351     QPainterPath roundRectPathUpper = upperRectPart(br), roundRectPathLower = lowerRectPart(br);
352     painter->setClipRect(option->exposedRect);
353
354     // build path around clip
355     QPainterPath resultClipPath = roundRectPathUpper.united(roundRectPathLower);
356     painter->fillPath(resultClipPath, paintColor);
357
358     painter->setClipPath(resultClipPath, Qt::IntersectClip);
359     // draw thumbnails
360     if (!m_startPix.isNull() && KdenliveSettings::videothumbnails()) {
361         if (m_clipType == IMAGE) {
362             painter->drawPixmap(QPointF(br.right() - m_startPix.width(), br.y()), m_startPix);
363             QLine l(br.right() - m_startPix.width(), br.y(), br.right() - m_startPix.width(), br.y() + br.height());
364             painter->drawLine(l);
365         } else {
366             painter->drawPixmap(QPointF(br.right() - m_endPix.width(), br.y()), m_endPix);
367             QLine l(br.right() - m_endPix.width(), br.y(), br.right() - m_endPix.width(), br.y() + br.height());
368             painter->drawLine(l);
369         }
370
371         painter->drawPixmap(QPointF(br.x(), br.y()), m_startPix);
372         QLine l2(br.x() + m_startPix.width(), br.y(), br.x() + m_startPix.width(), br.y() + br.height());
373         painter->drawLine(l2);
374     }
375
376     // draw audio thumbnails
377     if (KdenliveSettings::audiothumbnails() && ((m_clipType == AV && option->exposedRect.bottom() > br.height() / 2) || m_clipType == AUDIO) && audioThumbReady) {
378
379         QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;
380         if (m_clipType == AV) painter->fillPath(path, QBrush(QColor(200, 200, 200, 140)));
381
382         int channels = 2;
383         if (scale != framePixelWidth)
384             audioThumbCachePic.clear();
385         emit prepareAudioThumb(scale, path, startpixel, endpixel + 200);//200 more for less missing parts before repaint after scrolling
386         int cropLeft = (int)((m_cropStart).frames(m_fps) * scale);
387         for (int startCache = startpixel - startpixel % 100; startCache < endpixel + 300;startCache += 100) {
388             if (audioThumbCachePic.contains(startCache) && !audioThumbCachePic[startCache].isNull())
389                 painter->drawPixmap((int)(roundRectPathUpper.united(roundRectPathLower).boundingRect().x() + startCache - cropLeft), (int)(path.boundingRect().y()), audioThumbCachePic[startCache]);
390         }
391     }
392
393     // draw markers
394     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
395     QList < CommentedTime >::Iterator it = markers.begin();
396     GenTime pos;
397     double framepos;
398     const int markerwidth = 4;
399     QBrush markerBrush;
400     markerBrush = QBrush(QColor(120, 120, 0, 100));
401     QPen pen = painter->pen();
402     pen.setColor(QColor(255, 255, 255, 200));
403     pen.setStyle(Qt::DotLine);
404     painter->setPen(pen);
405     for (; it != markers.end(); ++it) {
406         pos = (*it).time() - cropStart();
407         if (pos > GenTime()) {
408             if (pos > duration()) break;
409             framepos = scale * pos.frames(m_fps);
410             QLineF l(br.x() + framepos, br.y() + 5, br.x() + framepos, br.y() + br.height() - 5);
411             painter->drawLine(l);
412             if (KdenliveSettings::showmarkers()) {
413                 const QRectF txtBounding = painter->boundingRect(br.x() + framepos + 1, br.y() + 10, br.width() - framepos - 2, br.height() - 10, Qt::AlignLeft | Qt::AlignTop, " " + (*it).comment() + " ");
414                 QPainterPath path;
415                 path.addRoundedRect(txtBounding, 3, 3);
416                 painter->fillPath(path, markerBrush);
417                 painter->drawText(txtBounding, Qt::AlignCenter, (*it).comment());
418             }
419             //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
420         }
421     }
422     pen.setColor(Qt::black);
423     pen.setStyle(Qt::SolidLine);
424     painter->setPen(pen);
425
426     // draw start / end fades
427     QBrush fades;
428     if (isSelected()) {
429         fades = QBrush(QColor(200, 50, 50, 150));
430     } else fades = QBrush(QColor(200, 200, 200, 200));
431
432     if (m_startFade != 0) {
433         QPainterPath fadeInPath;
434         fadeInPath.moveTo(br.x() , br.y());
435         fadeInPath.lineTo(br.x() , br.bottom());
436         fadeInPath.lineTo(br.x() + m_startFade * scale, br.y());
437         fadeInPath.closeSubpath();
438         painter->fillPath(fadeInPath/*.intersected(resultClipPath)*/, fades);
439         if (isSelected()) {
440             QLineF l(br.x() + m_startFade * scale, br.y(), br.x(), br.bottom());
441             painter->drawLine(l);
442         }
443     }
444     if (m_endFade != 0) {
445         QPainterPath fadeOutPath;
446         fadeOutPath.moveTo(br.right(), br.y());
447         fadeOutPath.lineTo(br.right(), br.bottom());
448         fadeOutPath.lineTo(br.right() - m_endFade * scale, br.y());
449         fadeOutPath.closeSubpath();
450         painter->fillPath(fadeOutPath/*.intersected(resultClipPath)*/, fades);
451         if (isSelected()) {
452             QLineF l(br.right() - m_endFade * scale, br.y(), br.x() + br.width(), br.bottom());
453             painter->drawLine(l);
454         }
455     }
456
457     // Draw effects names
458     if (!m_effectNames.isEmpty() && br.width() > 30) {
459         QRectF txtBounding = painter->boundingRect(br, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
460         txtBounding.setRight(txtBounding.right() + 15);
461         painter->setPen(Qt::white);
462         QBrush markerBrush(Qt::SolidPattern);
463         if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
464             qreal value = m_timeLine->currentValue();
465             txtBounding.setWidth(txtBounding.width() * value);
466             markerBrush.setColor(QColor(50 + 200 * (1.0 - value), 50, 50, 100 + 50 * value));
467         } else markerBrush.setColor(QColor(50, 50, 50, 150));
468         QPainterPath path;
469         path.addRoundedRect(txtBounding, 4, 4);
470         painter->fillPath(path/*.intersected(resultClipPath)*/, markerBrush);
471         painter->drawText(txtBounding, Qt::AlignCenter, m_effectNames);
472         painter->setPen(Qt::black);
473     }
474
475     // Draw clip name
476     QRectF txtBounding = painter->boundingRect(br, Qt::AlignHCenter | Qt::AlignTop, " " + m_clipName + " ");
477     //painter->fillRect(txtBounding, QBrush(QColor(255, 255, 255, 150)));
478     painter->setPen(QColor(0, 0, 0, 180));
479     painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
480     txtBounding.translate(QPointF(1, 1));
481     painter->setPen(QColor(255, 255, 255, 255));
482     painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
483     // draw frame around clip
484     if (isSelected()) {
485         pen.setColor(Qt::red);
486         //pen.setWidth(2);
487     } else {
488         pen.setColor(Qt::black);
489         //pen.setWidth(1);
490     }
491
492
493     // draw effect or transition keyframes
494     if (br.width() > 20) drawKeyFrames(painter, option->exposedRect);
495
496     // draw clip border
497     painter->setClipRect(option->exposedRect);
498     painter->setPen(pen);
499     //painter->setClipRect(option->exposedRect);
500     painter->drawPath(resultClipPath);
501
502     if (m_hover && br.width() > 30) {
503         painter->setBrush(QColor(180, 180, 50, 180)); //gradient);
504
505         // draw transitions handles
506         QPainterPath transitionHandle;
507         const int handle_size = 4;
508         transitionHandle.moveTo(0, 0);
509         transitionHandle.lineTo(handle_size, handle_size);
510         transitionHandle.lineTo(handle_size * 2, 0);
511         transitionHandle.lineTo(handle_size * 3, handle_size);
512         transitionHandle.lineTo(handle_size * 2, handle_size * 2);
513         transitionHandle.lineTo(handle_size * 3, handle_size * 3);
514         transitionHandle.lineTo(0, handle_size * 3);
515         transitionHandle.closeSubpath();
516         int pointy = (int)(br.y() + br.height() / 2);
517         int pointx1 = (int)(br.x() + 10);
518         int pointx2 = (int)(br.x() + br.width() - (10 + handle_size * 3));
519 #if 0
520         painter->setPen(QPen(Qt::black));
521         painter->setBrush(QBrush(QColor(50, 50, 0)));
522 #else
523         /*QRadialGradient gradient(pointx1 + 5, pointy + 5 , 5, 2, 2);
524         gradient.setColorAt(0.2, Qt::white);
525         gradient.setColorAt(0.8, Qt::yellow);
526         gradient.setColorAt(1, Qt::black);*/
527
528 #endif
529         painter->translate(pointx1, pointy);
530         painter->drawPath(transitionHandle); //Ellipse(0, 0 , 10, 10);
531         painter->translate(-pointx1, -pointy);
532
533         /*        QRadialGradient gradient1(pointx2 + 5, pointy + 5 , 5, 2, 2);
534                 gradient1.setColorAt(0.2, Qt::white);
535                 gradient1.setColorAt(0.8, Qt::yellow);
536                 gradient1.setColorAt(1, Qt::black);
537                 painter->setBrush(gradient1);*/
538         painter->translate(pointx2, pointy);
539         QMatrix m;
540         m.scale(-1.0, 1.0);
541         //painter->setMatrix(m);
542         painter->drawPath(transitionHandle); // Ellipse(0, 0, 10, 10);
543         //painter->setMatrix(m);
544         painter->translate(- pointx2, -pointy);
545     }
546 }
547
548
549 OPERATIONTYPE ClipItem::operationMode(QPointF pos, double scale) {
550     if (isSelected()) {
551         m_editedKeyframe = mouseOverKeyFrames(pos);
552         if (m_editedKeyframe != -1) return KEYFRAME;
553     }
554     if (qAbs((int)(pos.x() - (rect().x() + scale * m_startFade))) < 6 && qAbs((int)(pos.y() - rect().y())) < 6) {
555         if (m_startFade == 0) setToolTip(i18n("Add audio fade"));
556         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_startFade, m_fps).seconds()));
557         return FADEIN;
558     } else if (qAbs((int)(pos.x() - rect().x())) < 6) {
559         setToolTip(i18n("Crop from start: %1s", cropStart().seconds()));
560         return RESIZESTART;
561     } else if (qAbs((int)(pos.x() - (rect().x() + rect().width() - scale * m_endFade))) < 6 && qAbs((int)(pos.y() - rect().y())) < 6) {
562         if (m_endFade == 0) setToolTip(i18n("Add audio fade"));
563         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_endFade, m_fps).seconds()));
564         return FADEOUT;
565     } else if (qAbs((int)(pos.x() - (rect().x() + rect().width()))) < 6) {
566         setToolTip(i18n("Clip duration: %1s", duration().seconds()));
567         return RESIZEEND;
568     } else if (qAbs((int)(pos.x() - (rect().x() + 16))) < 10 && qAbs((int)(pos.y() - (rect().y() + rect().height() / 2 + 5))) < 8) {
569         setToolTip(i18n("Add transition"));
570         return TRANSITIONSTART;
571     } else if (qAbs((int)(pos.x() - (rect().x() + rect().width() - 21))) < 10 && qAbs((int)(pos.y() - (rect().y() + rect().height() / 2 + 5))) < 8) {
572         setToolTip(i18n("Add transition"));
573         return TRANSITIONEND;
574     }
575     setToolTip(QString());
576     return MOVE;
577 }
578
579 QList <GenTime> ClipItem::snapMarkers() const {
580     QList < GenTime > snaps;
581     QList < GenTime > markers = baseClip()->snapMarkers();
582     GenTime pos;
583     double framepos;
584
585     for (int i = 0; i < markers.size(); i++) {
586         pos = markers.at(i) - cropStart();
587         if (pos > GenTime()) {
588             if (pos > duration()) break;
589             else snaps.append(pos + startPos());
590         }
591     }
592     return snaps;
593 }
594
595 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, QPainterPath path, int startpixel, int endpixel) {
596     int channels = 2;
597
598     QRectF re = path.boundingRect();
599
600     //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
601
602     for (int startCache = startpixel - startpixel % 100;startCache + 100 < endpixel ;startCache += 100) {
603         //kDebug() << "creating " << startCache;
604         //if (framePixelWidth!=pixelForOneFrame  ||
605         if (framePixelWidth == pixelForOneFrame && audioThumbCachePic.contains(startCache))
606             continue;
607         if (audioThumbCachePic[startCache].isNull() || framePixelWidth != pixelForOneFrame) {
608             audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
609             audioThumbCachePic[startCache].fill(QColor(200, 200, 200, 0));
610         }
611         bool fullAreaDraw = pixelForOneFrame < 10;
612         QMap<int, QPainterPath > positiveChannelPaths;
613         QMap<int, QPainterPath > negativeChannelPaths;
614         QPainter pixpainter(&audioThumbCachePic[startCache]);
615         QPen audiopen;
616         audiopen.setWidth(0);
617         pixpainter.setPen(audiopen);
618         //pixpainter.setRenderHint(QPainter::Antialiasing,true);
619         //pixpainter.drawLine(0,0,100,re.height());
620         int channelHeight = audioThumbCachePic[startCache].height() / channels;
621
622         for (int i = 0;i < channels;i++) {
623
624             positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
625             negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
626         }
627
628         for (int samples = 0;samples <= 100;samples++) {
629             double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
630             int sample = (int)((frame - (int)(frame)) * 20);   // AUDIO_FRAME_SIZE
631             if (frame < 0 || sample < 0 || sample > 19)
632                 continue;
633             QMap<int, QByteArray> frame_channel_data = baseClip()->audioFrameChache[(int)frame];
634
635             for (int channel = 0;channel < channels && frame_channel_data[channel].size() > 0;channel++) {
636
637                 int y = channelHeight * channel + channelHeight / 2;
638                 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2)  * channelHeight / 64;
639                 if (fullAreaDraw) {
640                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
641                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
642                 } else {
643                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
644                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
645                 }
646             }
647             for (int channel = 0;channel < channels ;channel++)
648                 if (fullAreaDraw && samples == 100) {
649                     positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
650                     negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
651                     positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
652                     negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
653                 }
654
655         }
656         if (m_clipType != AV) pixpainter.setBrush(QBrush(QColor(200, 200, 100)));
657         else {
658             pixpainter.setPen(QPen(QColor(0, 0, 0)));
659             pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
660         }
661         for (int i = 0;i < channels;i++) {
662             if (fullAreaDraw) {
663                 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
664                 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
665             } else
666                 pixpainter.drawPath(positiveChannelPaths[i]);
667         }
668     }
669     //audioThumbWasDrawn=true;
670     framePixelWidth = pixelForOneFrame;
671
672     //}
673 }
674
675 uint ClipItem::fadeIn() const {
676     return m_startFade;
677 }
678
679 uint ClipItem::fadeOut() const {
680     return m_endFade;
681 }
682
683
684 void ClipItem::setFadeIn(int pos, double scale) {
685     int oldIn = m_startFade;
686     if (pos < 0) pos = 0;
687     if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
688     m_startFade = pos;
689     update(rect().x(), rect().y(), qMax(oldIn, pos) * scale, rect().height());
690 }
691
692 void ClipItem::setFadeOut(int pos, double scale) {
693     int oldOut = m_endFade;
694     if (pos < 0) pos = 0;
695     if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
696     m_endFade = pos;
697     update(rect().x() + rect().width() - qMax(oldOut, pos) * scale, rect().y(), pos * scale, rect().height());
698
699 }
700
701 // virtual
702 void ClipItem::mousePressEvent(QGraphicsSceneMouseEvent * event) {
703     /*m_resizeMode = operationMode(event->pos());
704     if (m_resizeMode == MOVE) {
705       m_maxTrack = scene()->sceneRect().height();
706       m_grabPoint = (int) (event->pos().x() - rect().x());
707     }*/
708     QGraphicsRectItem::mousePressEvent(event);
709 }
710
711 // virtual
712 void ClipItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) {
713     m_resizeMode = NONE;
714     QGraphicsRectItem::mouseReleaseEvent(event);
715 }
716
717 //virtual
718 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *) {
719     m_hover = true;
720     QRectF r = boundingRect();
721     qreal width = qMin(25.0, r.width());
722     update(r.x(), r.y(), width, r.height());
723     update(r.right() - width, r.y(), width, r.height());
724 }
725
726 //virtual
727 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *) {
728     m_hover = false;
729     QRectF r = boundingRect();
730     qreal width = qMin(25.0, r.width());
731     update(r.x(), r.y(), width, r.height());
732     update(r.right() - width, r.y(), width, r.height());
733 }
734
735 void ClipItem::resizeStart(int posx, double scale) {
736     const int previous = cropStart().frames(m_fps);
737     AbstractClipItem::resizeStart(posx, scale);
738     checkEffectsKeyframesPos(previous, cropStart().frames(m_fps), true);
739     if (m_hasThumbs && KdenliveSettings::videothumbnails()) startThumbTimer->start(100);
740 }
741
742 void ClipItem::resizeEnd(int posx, double scale) {
743     const int previous = (cropStart() + duration()).frames(m_fps);
744     AbstractClipItem::resizeEnd(posx, scale);
745     checkEffectsKeyframesPos(previous, (cropStart() + duration()).frames(m_fps), false);
746     if (m_hasThumbs && KdenliveSettings::videothumbnails()) endThumbTimer->start(100);
747 }
748
749
750 void ClipItem::checkEffectsKeyframesPos(const int previous, const int current, bool fromStart) {
751     for (int i = 0; i < m_effectList.size(); i++) {
752         QDomElement effect = m_effectList.at(i);
753         QDomNodeList params = effect.elementsByTagName("parameter");
754         for (int j = 0; j < params.count(); j++) {
755             QDomElement e = params.item(i).toElement();
756             if (e.attribute("type") == "keyframe") {
757                 // parse keyframes and adjust values
758                 QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
759                 QMap <int, double> kfr;
760                 foreach(QString str, keyframes) {
761                     int pos = str.section(":", 0, 0).toInt();
762                     double val = str.section(":", 1, 1).toDouble();
763                     if (pos == previous) kfr[current] = val;
764                     else {
765                         if (fromStart && pos >= current) kfr[pos] = val;
766                         else if (!fromStart && pos <= current) kfr[pos] = val;
767                     }
768                 }
769                 QString newkfr;
770                 QMap<int, double>::const_iterator k = kfr.constBegin();
771                 while (k != kfr.constEnd()) {
772                     newkfr.append(QString::number(k.key()) + ":" + QString::number(k.value()) + ";");
773                     ++k;
774                 }
775                 e.setAttribute("keyframes", newkfr);
776                 break;
777             }
778         }
779     }
780     setSelectedEffect(m_selectedEffect);
781 }
782
783
784 // virtual
785 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
786 }*/
787
788 int ClipItem::effectsCounter() {
789     return m_effectsCounter++;
790 }
791
792 int ClipItem::effectsCount() {
793     return m_effectList.size();
794 }
795
796 QStringList ClipItem::effectNames() {
797     return m_effectList.effectNames();
798 }
799
800 QDomElement ClipItem::effectAt(int ix) {
801     if (ix > m_effectList.count() - 1 || ix < 0) return QDomElement();
802     return m_effectList.at(ix);
803 }
804
805 void ClipItem::setEffectAt(int ix, QDomElement effect) {
806     kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
807     m_effectList.insert(ix, effect);
808     m_effectList.removeAt(ix + 1);
809     m_effectNames = m_effectList.effectNames().join(" / ");
810     if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fadeout") update(boundingRect());
811     else {
812         QRectF r = boundingRect();
813         r.setHeight(20);
814         update(r);
815     }
816 }
817
818 QMap <QString, QString> ClipItem::addEffect(QDomElement effect, bool animate) {
819     QMap <QString, QString> effectParams;
820     bool needRepaint = false;
821     /*QDomDocument doc;
822     doc.appendChild(doc.importNode(effect, true));
823     kDebug() << "///////  CLIP ADD EFFECT: "<< doc.toString();*/
824     m_effectList.append(effect);
825     effectParams["tag"] = effect.attribute("tag");
826     QString effectId = effect.attribute("id");
827     if (effectId.isEmpty()) effectId = effect.attribute("tag");
828     effectParams["id"] = effectId;
829     effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
830     QString state = effect.attribute("disabled");
831     if (!state.isEmpty()) effectParams["disabled"] = state;
832     QDomNodeList params = effect.elementsByTagName("parameter");
833     int fade = 0;
834     for (int i = 0; i < params.count(); i++) {
835         QDomElement e = params.item(i).toElement();
836         if (!e.isNull()) {
837             if (e.attribute("type") == "keyframe") {
838                 effectParams["keyframes"] = e.attribute("keyframes");
839                 effectParams["min"] = e.attribute("min");
840                 effectParams["max"] = e.attribute("max");
841                 effectParams["factor"] = e.attribute("factor", "1");
842                 effectParams["starttag"] = e.attribute("starttag", "start");
843                 effectParams["endtag"] = e.attribute("endtag", "end");
844             }
845
846             double f = e.attribute("factor", "1").toDouble();
847
848             if (f == 1) {
849                 effectParams[e.attribute("name")] = e.attribute("value");
850                 // check if it is a fade effect
851                 if (effectId == "fadein") {
852                     needRepaint = true;
853                     if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
854                     else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
855                 } else if (effectId == "fadeout") {
856                     needRepaint = true;
857                     if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
858                     else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
859                 }
860             } else {
861                 effectParams[e.attribute("name")] =  QString::number(effectParams[e.attribute("name")].toDouble() / f);
862             }
863         }
864     }
865     m_effectNames = m_effectList.effectNames().join(" / ");
866     if (fade > 0) m_startFade = fade;
867     else if (fade < 0) m_endFade = -fade;
868     if (needRepaint) update(boundingRect());
869     if (animate) {
870         flashClip();
871     } else if (!needRepaint) {
872         QRectF r = boundingRect();
873         r.setHeight(20);
874         update(r);
875     }
876     return effectParams;
877 }
878
879 QMap <QString, QString> ClipItem::getEffectArgs(QDomElement effect) {
880     QMap <QString, QString> effectParams;
881     effectParams["tag"] = effect.attribute("tag");
882     effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
883     effectParams["id"] = effect.attribute("id");
884     QString state = effect.attribute("disabled");
885     if (!state.isEmpty()) effectParams["disabled"] = state;
886     QDomNodeList params = effect.elementsByTagName("parameter");
887     for (int i = 0; i < params.count(); i++) {
888         QDomElement e = params.item(i).toElement();
889         kDebug() << "/ / / /SENDING EFFECT PARAM: " << e.attribute("type") << ", NAME_ " << e.attribute("tag");
890         if (e.attribute("type") == "keyframe") {
891             kDebug() << "/ / / /SENDING KEYFR EFFECT TYPE";
892             effectParams["keyframes"] = e.attribute("keyframes");
893             effectParams["max"] = e.attribute("max");
894             effectParams["min"] = e.attribute("min");
895             effectParams["factor"] = e.attribute("factor", "1");
896             effectParams["starttag"] = e.attribute("starttag", "start");
897             effectParams["endtag"] = e.attribute("endtag", "end");
898         } else if (e.attribute("namedesc").contains(";")) {
899             QString format = e.attribute("format");
900             QStringList separators = format.split("%d", QString::SkipEmptyParts);
901             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
902             QString neu;
903             QTextStream txtNeu(&neu);
904             if (values.size() > 0)
905                 txtNeu << (int)values[0].toDouble();
906             for (int i = 0;i < separators.size() && i + 1 < values.size();i++) {
907                 txtNeu << separators[i];
908                 txtNeu << (int)(values[i+1].toDouble());
909             }
910             effectParams["start"] = neu;
911         } else {
912             if (e.attribute("factor", "1") != "1")
913                 effectParams[e.attribute("name")] =  QString::number(e.attribute("value").toDouble() / e.attribute("factor").toDouble());
914             else effectParams[e.attribute("name")] = e.attribute("value");
915         }
916     }
917     return effectParams;
918 }
919
920 void ClipItem::deleteEffect(QString index) {
921     bool needRepaint = false;
922     for (int i = 0; i < m_effectList.size(); ++i) {
923         if (m_effectList.at(i).attribute("kdenlive_ix") == index) {
924             if (m_effectList.at(i).attribute("id") == "fadein") {
925                 m_startFade = 0;
926                 needRepaint = true;
927             } else if (m_effectList.at(i).attribute("id") == "fadeout") {
928                 m_endFade = 0;
929                 needRepaint = true;
930             }
931             m_effectList.removeAt(i);
932             break;
933         }
934     }
935     m_effectNames = m_effectList.effectNames().join(" / ");
936     if (needRepaint) update(boundingRect());
937     flashClip();
938 }
939
940 //virtual
941 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event) {
942     QString effects = QString(event->mimeData()->data("kdenlive/effectslist"));
943     QDomDocument doc;
944     doc.setContent(effects, true);
945     QDomElement e = doc.documentElement();
946     CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
947     if (view) view->slotAddEffect(e, m_startPos, track());
948 }
949
950 //virtual
951 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
952     event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
953 }
954
955 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) {
956     Q_UNUSED(event);
957 }
958 void ClipItem::addTransition(Transition* t) {
959     m_transitionsList.append(t);
960     CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
961     QDomDocument doc;
962     QDomElement e = doc.documentElement();
963     //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
964 }
965 // virtual
966 /*
967 void CustomTrackView::mousePressEvent ( QMouseEvent * event )
968 {
969   int pos = event->x();
970   if (event->modifiers() == Qt::ControlModifier)
971     setDragMode(QGraphicsView::ScrollHandDrag);
972   else if (event->modifiers() == Qt::ShiftModifier)
973     setDragMode(QGraphicsView::RubberBandDrag);
974   else {
975     QGraphicsItem * item = itemAt(event->pos());
976     if (item) {
977     }
978     else emit cursorMoved((int) mapToScene(event->x(), 0).x());
979   }
980   kDebug()<<pos;
981   QGraphicsView::mousePressEvent(event);
982 }
983
984 void CustomTrackView::mouseReleaseEvent ( QMouseEvent * event )
985 {
986   QGraphicsView::mouseReleaseEvent(event);
987   setDragMode(QGraphicsView::NoDrag);
988 }
989 */
990
991 #include "clipitem.moc"