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