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