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