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