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