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