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