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