]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
When cutting a clip with keyframe effect, ensure that both parts of the clip get...
[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 "customtrackscene.h"
36 #include "renderer.h"
37 #include "docclipbase.h"
38 #include "transition.h"
39 #include "kdenlivesettings.h"
40 #include "kthumb.h"
41
42
43 ClipItem::ClipItem(DocClipBase *clip, ItemInfo info, double fps, bool generateThumbs)
44         : AbstractClipItem(info, QRectF(), fps), m_clip(clip), m_resizeMode(NONE), m_grabPoint(0), m_maxTrack(0), m_hasThumbs(false), startThumbTimer(NULL), endThumbTimer(NULL), audioThumbWasDrawn(false), m_opacity(1.0), m_timeLine(0), m_startThumbRequested(false), m_endThumbRequested(false), m_startFade(0), m_endFade(0), m_hover(false), m_selectedEffect(-1), m_speed(1.0), framePixelWidth(0), m_startPix(QPixmap()), m_endPix(QPixmap()) {
45     setRect(0, 0, (info.endPos - info.startPos).frames(fps) - 0.02, (qreal)(KdenliveSettings::trackheight() - 2));
46     setPos((qreal) info.startPos.frames(fps), (qreal)(info.track * KdenliveSettings::trackheight()) + 1);
47
48     m_clipName = clip->name();
49     m_producer = clip->getId();
50     m_clipType = clip->clipType();
51     m_cropStart = info.cropStart;
52     m_maxDuration = clip->maxDuration();
53     setAcceptDrops(true);
54     audioThumbReady = clip->audioThumbCreated();
55
56     /*
57       m_cropStart = xml.attribute("in", 0).toInt();
58       m_maxDuration = xml.attribute("duration", 0).toInt();
59       if (m_maxDuration == 0) m_maxDuration = xml.attribute("out", 0).toInt() - m_cropStart;
60
61       if (duration != -1) m_cropDuration = duration;
62       else m_cropDuration = m_maxDuration;*/
63
64
65     setFlags(QGraphicsItem::ItemClipsToShape | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
66     setAcceptsHoverEvents(true);
67     connect(this , SIGNAL(prepareAudioThumb(double, int, int, int)) , this, SLOT(slotPrepareAudioThumb(double, int, int, int)));
68
69     setBrush(QColor(141, 166, 215));
70     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW || m_clipType == PLAYLIST) {
71         m_hasThumbs = true;
72         startThumbTimer = new QTimer(this);
73         startThumbTimer->setSingleShot(true);
74         connect(startThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetStartThumb()));
75         endThumbTimer = new QTimer(this);
76         endThumbTimer->setSingleShot(true);
77         connect(endThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetEndThumb()));
78
79         connect(this, SIGNAL(getThumb(int, int)), clip->thumbProducer(), SLOT(extractImage(int, int)));
80         //connect(this, SIGNAL(getThumb(int, int)), clip->thumbProducer(), SLOT(getVideoThumbs(int, int)));
81
82         connect(clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));
83         connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
84         if (generateThumbs) QTimer::singleShot(200, this, SLOT(slotFetchThumbs()));
85
86         /*if (m_clip->producer()) {
87             videoThumbProducer.init(this, m_clip->producer(), KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio(), KdenliveSettings::trackheight());
88             slotFetchThumbs();
89         }*/
90     } else if (m_clipType == COLOR) {
91         QString colour = clip->getProperty("colour");
92         colour = colour.replace(0, 2, "#");
93         setBrush(QColor(colour.left(7)));
94     } else if (m_clipType == IMAGE || m_clipType == TEXT) {
95         m_startPix = KThumb::getImage(KUrl(clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
96         m_endPix = m_startPix;
97     } else if (m_clipType == AUDIO) {
98         connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
99     }
100 }
101
102
103 ClipItem::~ClipItem() {
104     if (startThumbTimer) delete startThumbTimer;
105     if (endThumbTimer) delete endThumbTimer;
106     if (m_timeLine) m_timeLine;
107 }
108
109 ClipItem *ClipItem::clone(ItemInfo info) const {
110     ClipItem *duplicate = new ClipItem(m_clip, info, m_fps);
111     if (info.cropStart == cropStart()) duplicate->slotSetStartThumb(m_startPix);
112     if (info.cropStart + (info.endPos - info.startPos) == m_cropStart + m_cropDuration) duplicate->slotSetEndThumb(m_endPix);
113     kDebug() << "// CLoning clip: " << (info.cropStart + (info.endPos - info.startPos)).frames(m_fps) << ", CURRENT end: " << (cropStart() + duration()).frames(m_fps);
114     duplicate->setEffectList(m_effectList.clone());
115     duplicate->setSpeed(m_speed);
116     return duplicate;
117 }
118
119 void ClipItem::setEffectList(const EffectsList effectList) {
120     m_effectList = effectList;
121     m_effectNames = m_effectList.effectNames().join(" / ");
122 }
123
124 const EffectsList ClipItem::effectList() {
125     return m_effectList;
126 }
127
128 int ClipItem::selectedEffectIndex() const {
129     return m_selectedEffect;
130 }
131
132 void ClipItem::initEffect(QDomElement effect) {
133     // the kdenlive_ix int is used to identify an effect in mlt's playlist, should
134     // not be changed
135     if (effect.attribute("kdenlive_ix").toInt() == 0)
136         effect.setAttribute("kdenlive_ix", QString::number(effectsCounter()));
137     // init keyframes if required
138     QDomNodeList params = effect.elementsByTagName("parameter");
139     for (int i = 0; i < params.count(); i++) {
140         QDomElement e = params.item(i).toElement();
141         if (!e.isNull() && e.attribute("type") == "keyframe") {
142             QString def = e.attribute("default");
143             // Effect has a keyframe type parameter, we need to set the values
144             if (e.attribute("keyframes").isEmpty()) {
145                 e.setAttribute("keyframes", QString::number(m_cropStart.frames(m_fps)) + ":" + def + ";" + QString::number((m_cropStart + m_cropDuration).frames(m_fps)) + ":" + def);
146                 //kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
147                 break;
148             }
149         }
150     }
151 }
152
153 bool ClipItem::checkKeyFrames() {
154     bool clipEffectsModified = false;
155     for (int ix = 0; ix < m_effectList.count(); ix ++) {
156         QString kfr = keyframes(ix);
157         if (!kfr.isEmpty()) {
158             const QStringList keyframes = kfr.split(";", QString::SkipEmptyParts);
159             QStringList newKeyFrames;
160             bool cutKeyFrame = false;
161             bool modified = false;
162             int lastPos = -1;
163             double lastValue = -1;
164             int start = m_cropStart.frames(m_fps);
165             int end = (m_cropStart + m_cropDuration).frames(m_fps);
166             foreach(const QString str, keyframes) {
167                 int pos = str.section(":", 0, 0).toInt();
168                 double val = str.section(":", 1, 1).toDouble();
169                 if (pos - start < 0) {
170                     // a keyframe is defined before the start of the clip
171                     cutKeyFrame = true;
172                 } else if (cutKeyFrame) {
173                     // create new keyframe at clip start, calculate interpolated value
174                     if (pos > start) {
175                         int diff = pos - lastPos;
176                         double ratio = (double)(start - lastPos) / diff;
177                         double newValue = lastValue + (val - lastValue) * ratio;
178                         newKeyFrames.append(QString::number(start) + ":" + QString::number(newValue));
179                         modified = true;
180                     }
181                     cutKeyFrame = false;
182                 }
183                 if (!cutKeyFrame) {
184                     if (pos > end) {
185                         // create new keyframe at clip end, calculate interpolated value
186                         int diff = pos - lastPos;
187                         if (diff != 0) {
188                             double ratio = (double)(end - lastPos) / diff;
189                             double newValue = lastValue + (val - lastValue) * ratio;
190                             newKeyFrames.append(QString::number(end) + ":" + QString::number(newValue));
191                             modified = true;
192                         }
193                         break;
194                     } else {
195                         newKeyFrames.append(QString::number(pos) + ":" + QString::number(val));
196                     }
197                 }
198                 lastPos = pos;
199                 lastValue = val;
200             }
201             if (modified) {
202                 // update KeyFrames
203                 setKeyframes(ix, newKeyFrames.join(";"));
204                 clipEffectsModified = true;
205             }
206         }
207     }
208     return clipEffectsModified;
209 }
210
211 void ClipItem::setKeyframes(const int ix, const QString keyframes) {
212     QDomElement effect = effectAt(ix);
213     if (effect.attribute("disabled") == "1") return;
214     QDomNodeList params = effect.elementsByTagName("parameter");
215     for (int i = 0; i < params.count(); i++) {
216         QDomElement e = params.item(i).toElement();
217         if (!e.isNull() && e.attribute("type") == "keyframe") {
218             e.setAttribute("keyframes", keyframes);
219             if (ix == m_selectedEffect) {
220                 m_keyframes.clear();
221                 double max = e.attribute("max").toDouble();
222                 double min = e.attribute("min").toDouble();
223                 m_keyframeFactor = 100.0 / (max - min);
224                 m_keyframeDefault = e.attribute("default").toDouble();
225                 // parse keyframes
226                 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
227                 foreach(const QString str, keyframes) {
228                     int pos = str.section(":", 0, 0).toInt();
229                     double val = str.section(":", 1, 1).toDouble();
230                     m_keyframes[pos] = val;
231                 }
232                 update();
233                 return;
234             }
235             break;
236         }
237     }
238 }
239
240
241 void ClipItem::setSelectedEffect(const int ix) {
242     m_selectedEffect = ix;
243     QDomElement effect = effectAt(m_selectedEffect);
244     QDomNodeList params = effect.elementsByTagName("parameter");
245     if (effect.attribute("disabled") != "1")
246         for (int i = 0; i < params.count(); i++) {
247             QDomElement e = params.item(i).toElement();
248             if (!e.isNull() && e.attribute("type") == "keyframe") {
249                 m_keyframes.clear();
250                 double max = e.attribute("max").toDouble();
251                 double min = e.attribute("min").toDouble();
252                 m_keyframeFactor = 100.0 / (max - min);
253                 m_keyframeDefault = e.attribute("default").toDouble();
254                 // parse keyframes
255                 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
256                 foreach(const QString str, keyframes) {
257                     int pos = str.section(":", 0, 0).toInt();
258                     double val = str.section(":", 1, 1).toDouble();
259                     m_keyframes[pos] = val;
260                 }
261                 update();
262                 return;
263             }
264         }
265     if (!m_keyframes.isEmpty()) {
266         m_keyframes.clear();
267         update();
268     }
269 }
270
271 QString ClipItem::keyframes(const int index) {
272     QString result;
273     QDomElement effect = effectAt(index);
274     QDomNodeList params = effect.elementsByTagName("parameter");
275
276     for (int i = 0; i < params.count(); i++) {
277         QDomElement e = params.item(i).toElement();
278         if (!e.isNull() && e.attribute("type") == "keyframe") {
279             result = e.attribute("keyframes");
280             break;
281         }
282     }
283     return result;
284 }
285
286 void ClipItem::updateKeyframeEffect() {
287     // regenerate xml parameter from the clip keyframes
288     QDomElement effect = effectAt(m_selectedEffect);
289     if (effect.attribute("disabled") == "1") return;
290     QDomNodeList params = effect.elementsByTagName("parameter");
291
292     for (int i = 0; i < params.count(); i++) {
293         QDomElement e = params.item(i).toElement();
294         if (!e.isNull() && e.attribute("type") == "keyframe") {
295             QString keyframes;
296             if (m_keyframes.count() > 1) {
297                 QMap<int, double>::const_iterator i = m_keyframes.constBegin();
298                 double x1;
299                 double y1;
300                 while (i != m_keyframes.constEnd()) {
301                     keyframes.append(QString::number(i.key()) + ":" + QString::number(i.value()) + ";");
302                     ++i;
303                 }
304             }
305             // Effect has a keyframe type parameter, we need to set the values
306             //kDebug() << ":::::::::::::::   SETTING EFFECT KEYFRAMES: " << keyframes;
307             e.setAttribute("keyframes", keyframes);
308             break;
309         }
310     }
311 }
312
313 QDomElement ClipItem::selectedEffect() {
314     if (m_selectedEffect == -1 || m_effectList.isEmpty()) return QDomElement();
315     return effectAt(m_selectedEffect);
316 }
317
318 void ClipItem::resetThumbs() {
319     m_startPix = QPixmap();
320     m_endPix = QPixmap();
321     slotFetchThumbs();
322     audioThumbCachePic.clear();
323 }
324
325
326 void ClipItem::refreshClip() {
327     m_maxDuration = m_clip->maxDuration();
328     if (m_clipType == COLOR) {
329         QString colour = m_clip->getProperty("colour");
330         colour = colour.replace(0, 2, "#");
331         setBrush(QColor(colour.left(7)));
332     } else slotFetchThumbs();
333 }
334
335 void ClipItem::slotFetchThumbs() {
336     if (m_endPix.isNull() && m_startPix.isNull()) {
337         m_startThumbRequested = true;
338         m_endThumbRequested = true;
339         emit getThumb((int)m_cropStart.frames(m_fps), (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1);
340     } else {
341         if (m_endPix.isNull()) {
342             slotGetEndThumb();
343         }
344         if (m_startPix.isNull()) {
345             slotGetStartThumb();
346         }
347     }
348     /*
349         if (m_hasThumbs) {
350             if (m_endPix.isNull() && m_startPix.isNull()) {
351                 int frame1 = (int)m_cropStart.frames(m_fps);
352                 int frame2 = (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1;
353                 //videoThumbProducer.setThumbFrames(m_clip->producer(), frame1, frame2);
354                 //videoThumbProducer.start(QThread::LowestPriority);
355             } else {
356                 if (m_endPix.isNull()) slotGetEndThumb();
357                 else slotGetStartThumb();
358             }
359
360         } else if (m_startPix.isNull()) slotGetStartThumb();*/
361 }
362
363 void ClipItem::slotGetStartThumb() {
364     m_startThumbRequested = true;
365     emit getThumb((int)m_cropStart.frames(m_fps), -1);
366     //videoThumbProducer.setThumbFrames(m_clip->producer(), (int)m_cropStart.frames(m_fps),  - 1);
367     //videoThumbProducer.start(QThread::LowestPriority);
368 }
369
370 void ClipItem::slotGetEndThumb() {
371     m_endThumbRequested = true;
372     emit getThumb(-1, (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1);
373     //videoThumbProducer.setThumbFrames(m_clip->producer(), -1, (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1);
374     //videoThumbProducer.start(QThread::LowestPriority);
375 }
376
377
378 void ClipItem::slotSetStartThumb(QImage img) {
379     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
380         QPixmap pix = QPixmap::fromImage(img);
381         m_startPix = pix;
382         QRectF r = sceneBoundingRect();
383         r.setRight(pix.width() + 2);
384         update(r);
385     }
386 }
387
388 void ClipItem::slotSetEndThumb(QImage img) {
389     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
390         QPixmap pix = QPixmap::fromImage(img);
391         m_endPix = pix;
392         QRectF r = sceneBoundingRect();
393         r.setLeft(r.right() - pix.width() - 2);
394         update(r);
395     }
396 }
397
398 void ClipItem::slotThumbReady(int frame, QPixmap pix) {
399     if (scene() == NULL) return;
400     QRectF r = sceneBoundingRect();
401     double width = m_startPix.width() / projectScene()->scale();
402     if (m_startThumbRequested && frame == m_cropStart.frames(m_fps)) {
403         m_startPix = pix;
404         m_startThumbRequested = false;
405         double height = r.height();
406         update(r.x(), r.y(), width, height);
407     } else if (m_endThumbRequested && frame == (m_cropStart + m_cropDuration).frames(m_fps) - 1) {
408         m_endPix = pix;
409         m_endThumbRequested = false;
410         double height = r.height();
411         update(r.right() - width, r.y(), width, height);
412     }
413 }
414
415 void ClipItem::slotSetStartThumb(QPixmap pix) {
416     m_startPix = pix;
417 }
418
419 void ClipItem::slotSetEndThumb(QPixmap pix) {
420     m_endPix = pix;
421 }
422
423 void ClipItem::slotGotAudioData() {
424     audioThumbReady = true;
425     if (m_clipType == AV) {
426         QRectF r = boundingRect();
427         r.setTop(r.top() + r.height() / 2 - 1);
428         update(r);
429     } else update();
430 }
431
432 int ClipItem::type() const {
433     return AVWIDGET;
434 }
435
436 DocClipBase *ClipItem::baseClip() const {
437     return m_clip;
438 }
439
440 QDomElement ClipItem::xml() const {
441     return m_clip->toXML();
442 }
443
444 int ClipItem::clipType() const {
445     return m_clipType;
446 }
447
448 QString ClipItem::clipName() const {
449     return m_clipName;
450 }
451
452 const QString &ClipItem::clipProducer() const {
453     return m_producer;
454 }
455
456 void ClipItem::flashClip() {
457     if (m_timeLine == 0) {
458         m_timeLine = new QTimeLine(750, this);
459         m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
460         connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
461     }
462     m_timeLine->start();
463 }
464
465 void ClipItem::animate(qreal value) {
466     QRectF r = boundingRect();
467     r.setHeight(20);
468     update(r);
469 }
470
471 // virtual
472 void ClipItem::paint(QPainter *painter,
473                      const QStyleOptionGraphicsItem *option,
474                      QWidget *) {
475     painter->setOpacity(m_opacity);
476     QBrush paintColor = brush();
477     if (isSelected()) paintColor = QBrush(QColor(79, 93, 121));
478     QRectF br = rect();
479     QRectF exposed = option->exposedRect;
480     QRectF mapped = painter->matrix().mapRect(br);
481
482     const double itemWidth = br.width();
483     const double itemHeight = br.height();
484     const double scale = option->matrix.m11();
485
486
487
488     //painter->setRenderHints(QPainter::Antialiasing);
489
490     //QPainterPath roundRectPathUpper = upperRectPart(br), roundRectPathLower = lowerRectPart(br);
491     painter->setClipRect(exposed);
492
493     // build path around clip
494     //QPainterPath resultClipPath = roundRectPathUpper.united(roundRectPathLower);
495     //painter->fillPath(resultClipPath, paintColor);
496     painter->fillRect(br, paintColor);
497
498     //painter->setClipPath(resultClipPath, Qt::IntersectClip);
499
500     // draw thumbnails
501     painter->setMatrixEnabled(false);
502
503     if (KdenliveSettings::videothumbnails()) {
504         QPen pen = painter->pen();
505         pen.setStyle(Qt::DotLine);
506         pen.setColor(Qt::white);
507         painter->setPen(pen);
508         if (m_clipType == IMAGE && !m_startPix.isNull()) {
509             QPointF p1 = painter->matrix().map(QPointF(itemWidth, 0)) - QPointF(m_startPix.width(), 0);
510             QPointF p2 = painter->matrix().map(QPointF(itemWidth, itemHeight)) - QPointF(m_startPix.width(), 0);
511             painter->drawPixmap(p1, m_startPix);
512             QLineF l(p1, p2);
513             painter->drawLine(l);
514         } else if (!m_endPix.isNull()) {
515             QPointF p1 = painter->matrix().map(QPointF(itemWidth, 0)) - QPointF(m_endPix.width(), 0);
516             QPointF p2 = painter->matrix().map(QPointF(itemWidth, itemHeight)) - QPointF(m_endPix.width(), 0);
517             painter->drawPixmap(p1, m_endPix);
518             QLineF l(p1, p2);
519             painter->drawLine(l);
520         }
521         if (!m_startPix.isNull()) {
522             QPointF p1 = painter->matrix().map(QPointF(0, 0));
523             QPointF p2 = painter->matrix().map(QPointF(0, itemHeight));
524             painter->drawPixmap(p1, m_startPix);
525             QLineF l2(p1.x() + m_startPix.width(), p1.y(), p2.x() + m_startPix.width(), p2.y());
526             painter->drawLine(l2);
527         }
528         painter->setPen(Qt::black);
529     }
530
531     // draw audio thumbnails
532     if (KdenliveSettings::audiothumbnails() && ((m_clipType == AV && exposed.bottom() > (itemHeight / 2)) || m_clipType == AUDIO) && audioThumbReady) {
533
534         double startpixel = exposed.left();
535         if (startpixel < 0)
536             startpixel = 0;
537         double endpixel = exposed.right();
538         if (endpixel < 0)
539             endpixel = 0;
540         //kDebug()<<"///  REPAINTING AUDIO THMBS ZONE: "<<startpixel<<"x"<<endpixel;
541
542         /*QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;*/
543         QRectF mappedRect;
544         if (m_clipType == AV) {
545             QRectF re =  br;
546             re.setTop(re.y() + re.height() / 2);
547             mappedRect = painter->matrix().mapRect(re);
548             //painter->fillRect(mappedRect, QBrush(QColor(200, 200, 200, 140)));
549         } else mappedRect = mapped;
550
551         int channels = baseClip()->getProperty("channels").toInt();
552         if (scale != framePixelWidth)
553             audioThumbCachePic.clear();
554         double cropLeft = m_cropStart.frames(m_fps);
555         const int clipStart = mappedRect.x();
556         const int mappedStartPixel =  painter->matrix().map(QPointF(startpixel + cropLeft, 0)).x() - clipStart;
557         const int mappedEndPixel =  painter->matrix().map(QPointF(endpixel + cropLeft, 0)).x() - clipStart;
558         cropLeft = cropLeft * scale;
559
560         emit prepareAudioThumb(scale, mappedStartPixel, mappedEndPixel, channels);
561
562         for (int startCache = mappedStartPixel - (mappedStartPixel) % 100; startCache < mappedEndPixel; startCache += 100) {
563             if (audioThumbCachePic.contains(startCache) && !audioThumbCachePic[startCache].isNull())
564                 painter->drawPixmap(clipStart + startCache - cropLeft, mappedRect.y(),  audioThumbCachePic[startCache]);
565         }
566     }
567
568     // draw markers
569     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
570     QList < CommentedTime >::Iterator it = markers.begin();
571     GenTime pos;
572     double framepos;
573     const int markerwidth = 4;
574     QBrush markerBrush;
575     markerBrush = QBrush(QColor(120, 120, 0, 140));
576     QPen pen = painter->pen();
577     pen.setColor(QColor(255, 255, 255, 200));
578     pen.setStyle(Qt::DotLine);
579     painter->setPen(pen);
580     for (; it != markers.end(); ++it) {
581         pos = (*it).time() - cropStart();
582         if (pos > GenTime()) {
583             if (pos > duration()) break;
584             QLineF l(br.x() + pos.frames(m_fps), br.y() + 5, br.x() + pos.frames(m_fps), br.bottom() - 5);
585             QLineF l2 = painter->matrix().map(l);
586             //framepos = scale * pos.frames(m_fps);
587             //QLineF l(framepos, 5, framepos, itemHeight - 5);
588             painter->drawLine(l2);
589             if (KdenliveSettings::showmarkers()) {
590                 framepos = br.x() + pos.frames(m_fps);
591                 const QRectF r1(framepos + 0.04, 10, itemWidth - framepos - 2, itemHeight - 10);
592                 const QRectF r2 = painter->matrix().mapRect(r1);
593                 const QRectF txtBounding = painter->boundingRect(r2, Qt::AlignLeft | Qt::AlignTop, " " + (*it).comment() + " ");
594
595                 QPainterPath path;
596                 path.addRoundedRect(txtBounding, 3, 3);
597                 painter->fillPath(path, markerBrush);
598                 painter->drawText(txtBounding, Qt::AlignCenter, (*it).comment());
599             }
600             //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
601         }
602     }
603     pen.setColor(Qt::black);
604     pen.setStyle(Qt::SolidLine);
605     painter->setPen(pen);
606
607     // draw start / end fades
608     QBrush fades;
609     if (isSelected()) {
610         fades = QBrush(QColor(200, 50, 50, 150));
611     } else fades = QBrush(QColor(200, 200, 200, 200));
612
613     if (m_startFade != 0) {
614         QPainterPath fadeInPath;
615         fadeInPath.moveTo(0, 0);
616         fadeInPath.lineTo(0, itemHeight);
617         fadeInPath.lineTo(m_startFade, 0);
618         fadeInPath.closeSubpath();
619         QPainterPath f1 = painter->matrix().map(fadeInPath);
620         painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
621         /*if (isSelected()) {
622             QLineF l(m_startFade * scale, 0, 0, itemHeight);
623             painter->drawLine(l);
624         }*/
625     }
626     if (m_endFade != 0) {
627         QPainterPath fadeOutPath;
628         fadeOutPath.moveTo(itemWidth, 0);
629         fadeOutPath.lineTo(itemWidth, itemHeight);
630         fadeOutPath.lineTo(itemWidth - m_endFade, 0);
631         fadeOutPath.closeSubpath();
632         QPainterPath f1 = painter->matrix().map(fadeOutPath);
633         painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
634         /*if (isSelected()) {
635             QLineF l(itemWidth - m_endFade * scale, 0, itemWidth, itemHeight);
636             painter->drawLine(l);
637         }*/
638     }
639
640     // Draw effects names
641     if (!m_effectNames.isEmpty() && itemWidth * scale > 40) {
642         QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
643         txtBounding.setRight(txtBounding.right() + 15);
644         painter->setPen(Qt::white);
645         QBrush markerBrush(Qt::SolidPattern);
646         if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
647             qreal value = m_timeLine->currentValue();
648             txtBounding.setWidth(txtBounding.width() * value);
649             markerBrush.setColor(QColor(50 + 200 * (1.0 - value), 50, 50, 100 + 50 * value));
650         } else markerBrush.setColor(QColor(50, 50, 50, 150));
651         QPainterPath path;
652         path.addRoundedRect(txtBounding, 4, 4);
653         painter->fillPath(path/*.intersected(resultClipPath)*/, markerBrush);
654         painter->drawText(txtBounding, Qt::AlignCenter, m_effectNames);
655         painter->setPen(Qt::black);
656     }
657
658     // Draw clip name
659     QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignHCenter | Qt::AlignVCenter, " " + m_clipName + " ");
660     painter->fillRect(txtBounding, QBrush(QColor(0, 0, 0, 150)));
661     //painter->setPen(QColor(0, 0, 0, 180));
662     //painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
663     txtBounding.translate(QPointF(1, 1));
664     painter->setPen(QColor(255, 255, 255, 255));
665     painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
666
667
668     // draw transition handles on hover
669     if (m_hover && itemWidth * scale > 40) {
670         QPointF p1 = painter->matrix().map(QPointF(0, itemHeight / 2)) + QPointF(10, 0);
671         painter->drawPixmap(p1, projectScene()->m_transitionPixmap);
672         p1 = painter->matrix().map(QPointF(itemWidth, itemHeight / 2)) - QPointF(22, 0);
673         painter->drawPixmap(p1, projectScene()->m_transitionPixmap);
674     }
675
676
677     // draw frame around clip
678     if (isSelected()) {
679         pen.setColor(Qt::red);
680         //pen.setWidth(2);
681     } else {
682         pen.setColor(Qt::black);
683         //pen.setWidth(1);
684     }
685
686     // draw effect or transition keyframes
687     if (itemWidth > 20) drawKeyFrames(painter, exposed);
688
689     painter->setMatrixEnabled(true);
690
691     // draw clip border
692
693     //kDebug()<<"/// ITEM PAINTING:: exposed="<<exposed<<", RECT = "<<rect();
694
695     exposed.setRight(exposed.right() + 1);
696     exposed.setBottom(exposed.bottom() + 1);
697     painter->setClipRect(exposed);
698     //painter->setClipping(false);
699     //painter->fillRect(exposed, Qt::blue);
700     painter->setPen(pen);
701     painter->drawRect(br);
702 }
703
704
705 OPERATIONTYPE ClipItem::operationMode(QPointF pos) {
706     if (isSelected()) {
707         m_editedKeyframe = mouseOverKeyFrames(pos);
708         if (m_editedKeyframe != -1) return KEYFRAME;
709     }
710     QRectF rect = sceneBoundingRect();
711     const double scale = projectScene()->scale();
712     double maximumOffset;
713     if (scale > 3) maximumOffset = 25 / scale;
714     else maximumOffset = 6 / scale;
715
716     //kDebug()<<"// Item rect: "<<rect.x()<<". pos. "<<pos.x()<<", scale: "<<scale<<", ratio: "<<qAbs((int)(pos.x() - rect.x())) / scale;
717
718     if (qAbs((int)(pos.x() - (rect.x() + m_startFade))) < maximumOffset  && qAbs((int)(pos.y() - rect.y())) < 6) {
719         if (m_startFade == 0) setToolTip(i18n("Add audio fade"));
720         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_startFade, m_fps).seconds()));
721         return FADEIN;
722     } else if (pos.x() - rect.x() < maximumOffset) {
723         setToolTip(i18n("Crop from start: %1s", cropStart().seconds()));
724         return RESIZESTART;
725     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - m_endFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
726         if (m_endFade == 0) setToolTip(i18n("Add audio fade"));
727         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_endFade, m_fps).seconds()));
728         return FADEOUT;
729     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width()))) < maximumOffset) {
730         setToolTip(i18n("Clip duration: %1s", duration().seconds()));
731         return RESIZEEND;
732     } else if (qAbs((int)(pos.x() - (rect.x() + 16 / scale))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 9))) < 6) {
733         setToolTip(i18n("Add transition"));
734         return TRANSITIONSTART;
735     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - 21 / scale))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 9))) < 6) {
736         setToolTip(i18n("Add transition"));
737         return TRANSITIONEND;
738     }
739     setToolTip(QString());
740     return MOVE;
741 }
742
743 QList <GenTime> ClipItem::snapMarkers() const {
744     QList < GenTime > snaps;
745     QList < GenTime > markers = baseClip()->snapMarkers();
746     GenTime pos;
747     double framepos;
748
749     for (int i = 0; i < markers.size(); i++) {
750         pos = markers.at(i) - cropStart();
751         if (pos > GenTime()) {
752             if (pos > duration()) break;
753             else snaps.append(pos + startPos());
754         }
755     }
756     return snaps;
757 }
758
759 QList <CommentedTime> ClipItem::commentedSnapMarkers() const {
760     QList < CommentedTime > snaps;
761     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
762     GenTime pos;
763     double framepos;
764
765     for (int i = 0; i < markers.size(); i++) {
766         pos = markers.at(i).time() - cropStart();
767         if (pos > GenTime()) {
768             if (pos > duration()) break;
769             else snaps.append(CommentedTime(pos + startPos(), markers.at(i).comment()));
770         }
771     }
772     return snaps;
773 }
774
775 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, int startpixel, int endpixel, int channels) {
776     QRectF re =  sceneBoundingRect();
777     if (m_clipType == AV) re.setTop(re.y() + re.height() / 2);
778
779     //kDebug() << "// PREP AUDIO THMB FRMO : scale:" << pixelForOneFrame<< ", from: " << startpixel << ", to: " << endpixel;
780     //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
781
782     for (int startCache = startpixel - startpixel % 100;startCache < endpixel;startCache += 100) {
783         //kDebug() << "creating " << startCache;
784         //if (framePixelWidth!=pixelForOneFrame  ||
785         if (framePixelWidth == pixelForOneFrame && audioThumbCachePic.contains(startCache))
786             continue;
787         if (audioThumbCachePic[startCache].isNull() || framePixelWidth != pixelForOneFrame) {
788             audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
789             audioThumbCachePic[startCache].fill(QColor(180, 180, 200, 140));
790         }
791         bool fullAreaDraw = pixelForOneFrame < 10;
792         QMap<int, QPainterPath > positiveChannelPaths;
793         QMap<int, QPainterPath > negativeChannelPaths;
794         QPainter pixpainter(&audioThumbCachePic[startCache]);
795         QPen audiopen;
796         audiopen.setWidth(0);
797         pixpainter.setPen(audiopen);
798         //pixpainter.setRenderHint(QPainter::Antialiasing,true);
799         //pixpainter.drawLine(0,0,100,re.height());
800         int channelHeight = audioThumbCachePic[startCache].height() / channels;
801
802         for (int i = 0;i < channels;i++) {
803
804             positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
805             negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
806         }
807
808         for (int samples = 0;samples <= 100;samples++) {
809             double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
810             int sample = (int)((frame - (int)(frame)) * 20);   // AUDIO_FRAME_SIZE
811             if (frame < 0 || sample < 0 || sample > 19)
812                 continue;
813             QMap<int, QByteArray> frame_channel_data = baseClip()->audioFrameChache[(int)frame];
814
815             for (int channel = 0;channel < channels && frame_channel_data[channel].size() > 0;channel++) {
816
817                 int y = channelHeight * channel + channelHeight / 2;
818                 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2)  * channelHeight / 64;
819                 if (fullAreaDraw) {
820                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
821                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
822                 } else {
823                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
824                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
825                 }
826             }
827             for (int channel = 0;channel < channels ;channel++)
828                 if (fullAreaDraw && samples == 100) {
829                     positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
830                     negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
831                     positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
832                     negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
833                 }
834
835         }
836         if (m_clipType != AV) pixpainter.setBrush(QBrush(QColor(200, 200, 100)));
837         else {
838             pixpainter.setPen(QPen(QColor(0, 0, 0)));
839             pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
840         }
841         for (int i = 0;i < channels;i++) {
842             if (fullAreaDraw) {
843                 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
844                 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
845             } else
846                 pixpainter.drawPath(positiveChannelPaths[i]);
847         }
848     }
849     //audioThumbWasDrawn=true;
850     framePixelWidth = pixelForOneFrame;
851
852     //}
853 }
854
855 uint ClipItem::fadeIn() const {
856     return m_startFade;
857 }
858
859 uint ClipItem::fadeOut() const {
860     return m_endFade;
861 }
862
863
864 void ClipItem::setFadeIn(int pos) {
865     int oldIn = m_startFade;
866     if (pos < 0) pos = 0;
867     if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
868     m_startFade = pos;
869     QRectF rect = boundingRect();
870     update(rect.x(), rect.y(), qMax(oldIn, pos), rect.height());
871 }
872
873 void ClipItem::setFadeOut(int pos) {
874     int oldOut = m_endFade;
875     if (pos < 0) pos = 0;
876     if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
877     m_endFade = pos;
878     QRectF rect = boundingRect();
879     update(rect.x() + rect.width() - qMax(oldOut, pos), rect.y(), pos, rect.height());
880
881 }
882
883 // virtual
884 void ClipItem::mousePressEvent(QGraphicsSceneMouseEvent * event) {
885     /*m_resizeMode = operationMode(event->pos());
886     if (m_resizeMode == MOVE) {
887       m_maxTrack = scene()->sceneRect().height();
888       m_grabPoint = (int) (event->pos().x() - rect().x());
889     }*/
890     QGraphicsRectItem::mousePressEvent(event);
891 }
892
893 // virtual
894 void ClipItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) {
895     m_resizeMode = NONE;
896     QGraphicsRectItem::mouseReleaseEvent(event);
897 }
898
899 //virtual
900 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e) {
901     //if (e->pos().x() < 20) m_hover = true;
902     m_hover = true;
903     QRectF r = boundingRect();
904     double width = 35 / projectScene()->scale();
905     double height = r.height() / 2;
906     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
907     update(r.x(), r.y() + height, width, height);
908     update(r.right() - width, r.y() + height, width, height);
909 }
910
911 //virtual
912 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *) {
913     m_hover = false;
914     QRectF r = boundingRect();
915     double width = 35 / projectScene()->scale();
916     double height = r.height() / 2;
917     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
918     update(r.x(), r.y() + height, width, height);
919     update(r.right() - width, r.y() + height, width, height);
920 }
921
922 void ClipItem::resizeStart(int posx) {
923     const int min = (startPos() - cropStart()).frames(m_fps);
924     if (posx < min) posx = min;
925     if (posx == startPos().frames(m_fps)) return;
926     const int previous = cropStart().frames(m_fps);
927     AbstractClipItem::resizeStart(posx);
928     checkEffectsKeyframesPos(previous, cropStart().frames(m_fps), true);
929     if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
930         /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
931         startThumbTimer->start(100);
932     }
933 }
934
935 void ClipItem::resizeEnd(int posx, bool updateKeyFrames) {
936     const int max = (startPos() - cropStart() + maxDuration()).frames(m_fps) + 1;
937     if (posx > max) posx = max;
938     if (posx == endPos().frames(m_fps)) return;
939     const int previous = (cropStart() + duration()).frames(m_fps);
940     AbstractClipItem::resizeEnd(posx);
941     if (updateKeyFrames) checkEffectsKeyframesPos(previous, (cropStart() + duration()).frames(m_fps), false);
942     if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
943         /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
944         endThumbTimer->start(100);
945     }
946 }
947
948
949 void ClipItem::checkEffectsKeyframesPos(const int previous, const int current, bool fromStart) {
950     for (int i = 0; i < m_effectList.size(); i++) {
951         QDomElement effect = m_effectList.at(i);
952         QDomNodeList params = effect.elementsByTagName("parameter");
953         for (int j = 0; j < params.count(); j++) {
954             QDomElement e = params.item(i).toElement();
955             if (e.attribute("type") == "keyframe") {
956                 // parse keyframes and adjust values
957                 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
958                 QMap <int, double> kfr;
959                 int pos;
960                 double val;
961                 foreach(const QString str, keyframes) {
962                     pos = str.section(":", 0, 0).toInt();
963                     val = str.section(":", 1, 1).toDouble();
964                     if (pos == previous) kfr[current] = val;
965                     else {
966                         if (fromStart && pos >= current) kfr[pos] = val;
967                         else if (!fromStart && pos <= current) kfr[pos] = val;
968                     }
969                 }
970                 QString newkfr;
971                 QMap<int, double>::const_iterator k = kfr.constBegin();
972                 while (k != kfr.constEnd()) {
973                     newkfr.append(QString::number(k.key()) + ":" + QString::number(k.value()) + ";");
974                     ++k;
975                 }
976                 e.setAttribute("keyframes", newkfr);
977                 break;
978             }
979         }
980     }
981     if (m_selectedEffect >= 0) setSelectedEffect(m_selectedEffect);
982 }
983
984
985 //virtual
986 QVariant ClipItem::itemChange(GraphicsItemChange change, const QVariant &value) {
987     if (change == ItemPositionChange && scene()) {
988         // calculate new position.
989         if (group() != 0) return pos();
990         QPointF newPos = value.toPointF();
991         //kDebug() << "/// MOVING CLIP ITEM.------------";
992         int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
993         xpos = qMax(xpos, 0);
994         newPos.setX(xpos);
995         int newTrack = (newPos.y() + KdenliveSettings::trackheight() / 2) / KdenliveSettings::trackheight();
996         newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
997         newTrack = qMax(newTrack, 0);
998         newPos.setY((int)(newTrack  * KdenliveSettings::trackheight() + 1));
999         // Only one clip is moving
1000         QRectF sceneShape = rect();
1001         sceneShape.translate(newPos);
1002         QList<QGraphicsItem*> items = scene()->items(sceneShape, Qt::IntersectsItemShape);
1003         items.removeAll(this);
1004
1005         if (!items.isEmpty()) {
1006             for (int i = 0; i < items.count(); i++) {
1007                 if (items.at(i)->type() == type()) {
1008                     // Collision!
1009                     QPointF otherPos = items.at(i)->pos();
1010                     if ((int) otherPos.y() != (int) pos().y()) return pos();
1011                     if (pos().x() < otherPos.x()) {
1012                         // move clip just before colliding clip
1013                         int npos = (static_cast < AbstractClipItem* >(items.at(i))->startPos() - m_cropDuration).frames(m_fps);
1014                         // check we don't run into another clip
1015                         newPos.setX(npos);
1016                         sceneShape = rect();
1017                         sceneShape.translate(newPos);
1018                         QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
1019                         items.removeAll(this);
1020                         for (int j = 0; j < subitems.count(); j++) {
1021                             if (subitems.at(j)->type() == type()) return pos();
1022                         }
1023                     } else {
1024                         // get pos just after colliding clip
1025                         int npos = static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps);
1026                         // check we don't run into another clip
1027                         newPos.setX(npos);
1028                         sceneShape = rect();
1029                         sceneShape.translate(newPos);
1030                         QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
1031                         items.removeAll(this);
1032                         for (int j = 0; j < subitems.count(); j++) {
1033                             if (subitems.at(j)->type() == type()) return pos();
1034                         }
1035                     }
1036                     m_track = newTrack;
1037                     m_startPos = GenTime((int) newPos.x(), m_fps);
1038                     return newPos;
1039                 }
1040             }
1041         }
1042         m_track = newTrack;
1043         m_startPos = GenTime((int) newPos.x(), m_fps);
1044         //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
1045         return newPos;
1046     }
1047     return QGraphicsItem::itemChange(change, value);
1048 }
1049
1050 // virtual
1051 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
1052 }*/
1053
1054 int ClipItem::effectsCounter() {
1055     return effectsCount() + 1;
1056 }
1057
1058 int ClipItem::effectsCount() {
1059     return m_effectList.size();
1060 }
1061
1062 int ClipItem::hasEffect(const QString &tag, const QString &id) const {
1063     return m_effectList.hasEffect(tag, id);
1064 }
1065
1066 QStringList ClipItem::effectNames() {
1067     return m_effectList.effectNames();
1068 }
1069
1070 QDomElement ClipItem::effectAt(int ix) {
1071     if (ix > m_effectList.count() - 1 || ix < 0) return QDomElement();
1072     return m_effectList.at(ix);
1073 }
1074
1075 void ClipItem::setEffectAt(int ix, QDomElement effect) {
1076     kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1077     effect.setAttribute("kdenlive_ix", ix + 1);
1078     m_effectList.insert(ix, effect);
1079     m_effectList.removeAt(ix + 1);
1080     m_effectNames = m_effectList.effectNames().join(" / ");
1081     if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fadeout") update(boundingRect());
1082     else {
1083         QRectF r = boundingRect();
1084         r.setHeight(20);
1085         update(r);
1086     }
1087 }
1088
1089 QHash <QString, QString> ClipItem::addEffect(QDomElement effect, bool animate) {
1090     QHash <QString, QString> effectParams;
1091     bool needRepaint = false;
1092     /*QDomDocument doc;
1093     doc.appendChild(doc.importNode(effect, true));
1094     kDebug() << "///////  CLIP ADD EFFECT: " << doc.toString();*/
1095     m_effectList.append(effect);
1096     effectParams["tag"] = effect.attribute("tag");
1097     QString effectId = effect.attribute("id");
1098     if (effectId.isEmpty()) effectId = effect.attribute("tag");
1099     effectParams["id"] = effectId;
1100     effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
1101     QString state = effect.attribute("disabled");
1102     if (!state.isEmpty()) effectParams["disabled"] = state;
1103     QDomNodeList params = effect.elementsByTagName("parameter");
1104     int fade = 0;
1105     for (int i = 0; i < params.count(); i++) {
1106         QDomElement e = params.item(i).toElement();
1107         if (!e.isNull()) {
1108             if (e.attribute("type") == "keyframe") {
1109                 effectParams["keyframes"] = e.attribute("keyframes");
1110                 effectParams["min"] = e.attribute("min");
1111                 effectParams["max"] = e.attribute("max");
1112                 effectParams["factor"] = e.attribute("factor", "1");
1113                 effectParams["starttag"] = e.attribute("starttag", "start");
1114                 effectParams["endtag"] = e.attribute("endtag", "end");
1115             }
1116
1117             double f = e.attribute("factor", "1").toDouble();
1118
1119             if (f == 1) {
1120                 effectParams[e.attribute("name")] = e.attribute("value");
1121                 // check if it is a fade effect
1122                 if (effectId == "fadein") {
1123                     needRepaint = true;
1124                     if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1125                     else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1126                 } else if (effectId == "fadeout") {
1127                     needRepaint = true;
1128                     if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1129                     else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1130                 }
1131             } else {
1132                 effectParams[e.attribute("name")] =  QString::number(e.attribute("value").toDouble() / f);
1133             }
1134         }
1135     }
1136     m_effectNames = m_effectList.effectNames().join(" / ");
1137     if (fade > 0) m_startFade = fade;
1138     else if (fade < 0) m_endFade = -fade;
1139     if (needRepaint) update(boundingRect());
1140     if (animate) {
1141         flashClip();
1142     } else if (!needRepaint) {
1143         QRectF r = boundingRect();
1144         r.setHeight(20);
1145         update(r);
1146     }
1147     if (m_selectedEffect == -1) {
1148         m_selectedEffect = 0;
1149         setSelectedEffect(m_selectedEffect);
1150     }
1151     return effectParams;
1152 }
1153
1154 QHash <QString, QString> ClipItem::getEffectArgs(QDomElement effect) {
1155     QHash <QString, QString> effectParams;
1156     effectParams["tag"] = effect.attribute("tag");
1157     effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
1158     effectParams["id"] = effect.attribute("id");
1159     QString state = effect.attribute("disabled");
1160     if (!state.isEmpty()) effectParams["disabled"] = state;
1161     QDomNodeList params = effect.elementsByTagName("parameter");
1162     for (int i = 0; i < params.count(); i++) {
1163         QDomElement e = params.item(i).toElement();
1164         //kDebug() << "/ / / /SENDING EFFECT PARAM: " << e.attribute("type") << ", NAME_ " << e.attribute("tag");
1165         if (e.attribute("type") == "keyframe") {
1166             kDebug() << "/ / / /SENDING KEYFR EFFECT TYPE";
1167             effectParams["keyframes"] = e.attribute("keyframes");
1168             effectParams["max"] = e.attribute("max");
1169             effectParams["min"] = e.attribute("min");
1170             effectParams["factor"] = e.attribute("factor", "1");
1171             effectParams["starttag"] = e.attribute("starttag", "start");
1172             effectParams["endtag"] = e.attribute("endtag", "end");
1173         } else if (e.attribute("namedesc").contains(";")) {
1174             QString format = e.attribute("format");
1175             QStringList separators = format.split("%d", QString::SkipEmptyParts);
1176             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
1177             QString neu;
1178             QTextStream txtNeu(&neu);
1179             if (values.size() > 0)
1180                 txtNeu << (int)values[0].toDouble();
1181             for (int i = 0;i < separators.size() && i + 1 < values.size();i++) {
1182                 txtNeu << separators[i];
1183                 txtNeu << (int)(values[i+1].toDouble());
1184             }
1185             effectParams["start"] = neu;
1186         } else {
1187             if (e.attribute("factor", "1") != "1")
1188                 effectParams[e.attribute("name")] =  QString::number(e.attribute("value").toDouble() / e.attribute("factor").toDouble());
1189             else effectParams[e.attribute("name")] = e.attribute("value");
1190         }
1191     }
1192     return effectParams;
1193 }
1194
1195 void ClipItem::deleteEffect(QString index) {
1196     bool needRepaint = false;
1197     QString ix;
1198     for (int i = 0; i < m_effectList.size(); ++i) {
1199         ix = m_effectList.at(i).attribute("kdenlive_ix");
1200         if (ix == index) {
1201             if (m_effectList.at(i).attribute("id") == "fadein") {
1202                 m_startFade = 0;
1203                 needRepaint = true;
1204             } else if (m_effectList.at(i).attribute("id") == "fadeout") {
1205                 m_endFade = 0;
1206                 needRepaint = true;
1207             }
1208             m_effectList.removeAt(i);
1209         } else if (ix.toInt() > index.toInt()) m_effectList[i].setAttribute("kdenlive_ix", ix.toInt() - 1);
1210     }
1211     m_effectNames = m_effectList.effectNames().join(" / ");
1212     if (needRepaint) update(boundingRect());
1213     flashClip();
1214 }
1215
1216 double ClipItem::speed() const {
1217     return m_speed;
1218 }
1219
1220 void ClipItem::setSpeed(const double speed) {
1221     m_speed = speed;
1222     if (m_speed == 1.0) m_clipName = baseClip()->name();
1223     else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + "%";
1224     update();
1225 }
1226
1227 GenTime ClipItem::maxDuration() const {
1228     return m_maxDuration / m_speed;
1229 }
1230
1231 //virtual
1232 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event) {
1233     QString effects = QString(event->mimeData()->data("kdenlive/effectslist"));
1234     QDomDocument doc;
1235     doc.setContent(effects, true);
1236     QDomElement e = doc.documentElement();
1237     CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1238     if (view) view->slotAddEffect(e, m_startPos, track());
1239 }
1240
1241 //virtual
1242 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
1243     event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
1244 }
1245
1246 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) {
1247     Q_UNUSED(event);
1248 }
1249 void ClipItem::addTransition(Transition* t) {
1250     m_transitionsList.append(t);
1251     CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1252     QDomDocument doc;
1253     QDomElement e = doc.documentElement();
1254     //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1255 }
1256 // virtual
1257 /*
1258 void CustomTrackView::mousePressEvent ( QMouseEvent * event )
1259 {
1260   int pos = event->x();
1261   if (event->modifiers() == Qt::ControlModifier)
1262     setDragMode(QGraphicsView::ScrollHandDrag);
1263   else if (event->modifiers() == Qt::ShiftModifier)
1264     setDragMode(QGraphicsView::RubberBandDrag);
1265   else {
1266     QGraphicsItem * item = itemAt(event->pos());
1267     if (item) {
1268     }
1269     else emit cursorMoved((int) mapToScene(event->x(), 0).x());
1270   }
1271   kDebug()<<pos;
1272   QGraphicsView::mousePressEvent(event);
1273 }
1274
1275 void CustomTrackView::mouseReleaseEvent ( QMouseEvent * event )
1276 {
1277   QGraphicsView::mouseReleaseEvent(event);
1278   setDragMode(QGraphicsView::NoDrag);
1279 }
1280 */
1281
1282 #include "clipitem.moc"