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