]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
This will hopefully fix most clip & group move issues. Should solve points b) and...
[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(const QPixmap pix) {
431     m_startPix = pix;
432 }
433
434 void ClipItem::slotSetEndThumb(const QPixmap pix) {
435     m_endPix = pix;
436 }
437
438 QPixmap ClipItem::startThumb() const {
439     return m_startPix;
440 }
441
442 QPixmap ClipItem::endThumb() const {
443     return m_endPix;
444 }
445
446 void ClipItem::slotGotAudioData() {
447     audioThumbReady = true;
448     if (m_clipType == AV) {
449         QRectF r = boundingRect();
450         r.setTop(r.top() + r.height() / 2 - 1);
451         update(r);
452     } else update();
453 }
454
455 int ClipItem::type() const {
456     return AVWIDGET;
457 }
458
459 DocClipBase *ClipItem::baseClip() const {
460     return m_clip;
461 }
462
463 QDomElement ClipItem::xml() const {
464     return m_clip->toXML();
465 }
466
467 int ClipItem::clipType() const {
468     return m_clipType;
469 }
470
471 QString ClipItem::clipName() const {
472     return m_clipName;
473 }
474
475 const QString &ClipItem::clipProducer() const {
476     return m_producer;
477 }
478
479 void ClipItem::flashClip() {
480     if (m_timeLine == 0) {
481         m_timeLine = new QTimeLine(750, this);
482         m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
483         connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
484     }
485     m_timeLine->start();
486 }
487
488 void ClipItem::animate(qreal value) {
489     QRectF r = boundingRect();
490     r.setHeight(20);
491     update(r);
492 }
493
494 // virtual
495 void ClipItem::paint(QPainter *painter,
496                      const QStyleOptionGraphicsItem *option,
497                      QWidget *) {
498     /*if (parentItem()) m_opacity = 0.5;
499     else m_opacity = 1.0;
500     painter->setOpacity(m_opacity);*/
501     QBrush paintColor = brush();
502     if (isSelected()) paintColor = QBrush(QColor(79, 93, 121));
503     QRectF br = rect();
504     QRectF exposed = option->exposedRect;
505     QRectF mapped = painter->matrix().mapRect(br);
506
507     const double itemWidth = br.width();
508     const double itemHeight = br.height();
509     const double scale = option->matrix.m11();
510
511
512     //painter->setRenderHints(QPainter::Antialiasing);
513
514     //QPainterPath roundRectPathUpper = upperRectPart(br), roundRectPathLower = lowerRectPart(br);
515     painter->setClipRect(exposed);
516
517     //build path around clip
518     //QPainterPath resultClipPath = roundRectPathUpper.united(roundRectPathLower);
519     //painter->fillPath(resultClipPath, paintColor);
520     painter->fillRect(exposed, paintColor);
521
522     //painter->setClipPath(resultClipPath, Qt::IntersectClip);
523
524     // draw thumbnails
525     painter->setMatrixEnabled(false);
526
527     if (KdenliveSettings::videothumbnails()) {
528         QPen pen = painter->pen();
529         pen.setStyle(Qt::DotLine);
530         pen.setColor(Qt::white);
531         painter->setPen(pen);
532         if (m_clipType == IMAGE && !m_startPix.isNull()) {
533             QPointF p1 = painter->matrix().map(QPointF(itemWidth, 0)) - QPointF(m_startPix.width(), 0);
534             QPointF p2 = painter->matrix().map(QPointF(itemWidth, itemHeight)) - QPointF(m_startPix.width(), 0);
535             painter->drawPixmap(p1, m_startPix);
536             QLineF l(p1, p2);
537             painter->drawLine(l);
538         } else if (!m_endPix.isNull()) {
539             QPointF p1 = painter->matrix().map(QPointF(itemWidth, 0)) - QPointF(m_endPix.width(), 0);
540             QPointF p2 = painter->matrix().map(QPointF(itemWidth, itemHeight)) - QPointF(m_endPix.width(), 0);
541             painter->drawPixmap(p1, m_endPix);
542             QLineF l(p1, p2);
543             painter->drawLine(l);
544         }
545         if (!m_startPix.isNull()) {
546             QPointF p1 = painter->matrix().map(QPointF(0, 0));
547             QPointF p2 = painter->matrix().map(QPointF(0, itemHeight));
548             painter->drawPixmap(p1, m_startPix);
549             QLineF l2(p1.x() + m_startPix.width(), p1.y(), p2.x() + m_startPix.width(), p2.y());
550             painter->drawLine(l2);
551         }
552         painter->setPen(Qt::black);
553     }
554
555     // draw audio thumbnails
556     if (KdenliveSettings::audiothumbnails() && m_speed == 1.0 && ((m_clipType == AV && exposed.bottom() > (itemHeight / 2)) || m_clipType == AUDIO) && audioThumbReady) {
557
558         double startpixel = exposed.left();
559         if (startpixel < 0)
560             startpixel = 0;
561         double endpixel = exposed.right();
562         if (endpixel < 0)
563             endpixel = 0;
564         //kDebug()<<"///  REPAINTING AUDIO THMBS ZONE: "<<startpixel<<"x"<<endpixel;
565
566         /*QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;*/
567         QRectF mappedRect;
568         if (m_clipType == AV) {
569             QRectF re =  br;
570             re.setTop(re.y() + re.height() / 2);
571             mappedRect = painter->matrix().mapRect(re);
572             //painter->fillRect(mappedRect, QBrush(QColor(200, 200, 200, 140)));
573         } else mappedRect = mapped;
574
575         int channels = baseClip()->getProperty("channels").toInt();
576         if (scale != framePixelWidth)
577             audioThumbCachePic.clear();
578         double cropLeft = m_cropStart.frames(m_fps);
579         const int clipStart = mappedRect.x();
580         const int mappedStartPixel =  painter->matrix().map(QPointF(startpixel + cropLeft, 0)).x() - clipStart;
581         const int mappedEndPixel =  painter->matrix().map(QPointF(endpixel + cropLeft, 0)).x() - clipStart;
582         cropLeft = cropLeft * scale;
583
584         if (channels >= 1) {
585             emit prepareAudioThumb(scale, mappedStartPixel, mappedEndPixel, channels);
586         }
587
588         for (int startCache = mappedStartPixel - (mappedStartPixel) % 100; startCache < mappedEndPixel; startCache += 100) {
589             if (audioThumbCachePic.contains(startCache) && !audioThumbCachePic[startCache].isNull())
590                 painter->drawPixmap(clipStart + startCache - cropLeft, mappedRect.y(),  audioThumbCachePic[startCache]);
591         }
592     }
593
594     // draw markers
595     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
596     QList < CommentedTime >::Iterator it = markers.begin();
597     GenTime pos;
598     double framepos;
599     const int markerwidth = 4;
600     QBrush markerBrush;
601     markerBrush = QBrush(QColor(120, 120, 0, 140));
602     QPen pen = painter->pen();
603     pen.setColor(QColor(255, 255, 255, 200));
604     pen.setStyle(Qt::DotLine);
605     painter->setPen(pen);
606     for (; it != markers.end(); ++it) {
607         pos = (*it).time() - cropStart();
608         if (pos > GenTime()) {
609             if (pos > duration()) break;
610             QLineF l(br.x() + pos.frames(m_fps), br.y() + 5, br.x() + pos.frames(m_fps), br.bottom() - 5);
611             QLineF l2 = painter->matrix().map(l);
612             //framepos = scale * pos.frames(m_fps);
613             //QLineF l(framepos, 5, framepos, itemHeight - 5);
614             painter->drawLine(l2);
615             if (KdenliveSettings::showmarkers()) {
616                 framepos = br.x() + pos.frames(m_fps);
617                 const QRectF r1(framepos + 0.04, 10, itemWidth - framepos - 2, itemHeight - 10);
618                 const QRectF r2 = painter->matrix().mapRect(r1);
619                 const QRectF txtBounding = painter->boundingRect(r2, Qt::AlignLeft | Qt::AlignTop, " " + (*it).comment() + " ");
620
621                 QPainterPath path;
622                 path.addRoundedRect(txtBounding, 3, 3);
623                 painter->fillPath(path, markerBrush);
624                 painter->drawText(txtBounding, Qt::AlignCenter, (*it).comment());
625             }
626             //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
627         }
628     }
629     pen.setColor(Qt::black);
630     pen.setStyle(Qt::SolidLine);
631     painter->setPen(pen);
632
633     // draw start / end fades
634     QBrush fades;
635     if (isSelected()) {
636         fades = QBrush(QColor(200, 50, 50, 150));
637     } else fades = QBrush(QColor(200, 200, 200, 200));
638
639     if (m_startFade != 0) {
640         QPainterPath fadeInPath;
641         fadeInPath.moveTo(0, 0);
642         fadeInPath.lineTo(0, itemHeight);
643         fadeInPath.lineTo(m_startFade, 0);
644         fadeInPath.closeSubpath();
645         QPainterPath f1 = painter->matrix().map(fadeInPath);
646         painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
647         /*if (isSelected()) {
648             QLineF l(m_startFade * scale, 0, 0, itemHeight);
649             painter->drawLine(l);
650         }*/
651     }
652     if (m_endFade != 0) {
653         QPainterPath fadeOutPath;
654         fadeOutPath.moveTo(itemWidth, 0);
655         fadeOutPath.lineTo(itemWidth, itemHeight);
656         fadeOutPath.lineTo(itemWidth - m_endFade, 0);
657         fadeOutPath.closeSubpath();
658         QPainterPath f1 = painter->matrix().map(fadeOutPath);
659         painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
660         /*if (isSelected()) {
661             QLineF l(itemWidth - m_endFade * scale, 0, itemWidth, itemHeight);
662             painter->drawLine(l);
663         }*/
664     }
665
666     // Draw effects names
667     if (!m_effectNames.isEmpty() && itemWidth * scale > 40) {
668         QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
669         txtBounding.setRight(txtBounding.right() + 15);
670         painter->setPen(Qt::white);
671         QBrush markerBrush(Qt::SolidPattern);
672         if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
673             qreal value = m_timeLine->currentValue();
674             txtBounding.setWidth(txtBounding.width() * value);
675             markerBrush.setColor(QColor(50 + 200 * (1.0 - value), 50, 50, 100 + 50 * value));
676         } else markerBrush.setColor(QColor(50, 50, 50, 150));
677         QPainterPath path;
678         path.addRoundedRect(txtBounding, 4, 4);
679         painter->fillPath(path/*.intersected(resultClipPath)*/, markerBrush);
680         painter->drawText(txtBounding, Qt::AlignCenter, m_effectNames);
681         painter->setPen(Qt::black);
682     }
683
684     // Draw clip name
685     QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignHCenter | Qt::AlignVCenter, " " + m_clipName + " ");
686     painter->fillRect(txtBounding, QBrush(QColor(0, 0, 0, 150)));
687     //painter->setPen(QColor(0, 0, 0, 180));
688     //painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
689     txtBounding.translate(QPointF(1, 1));
690     painter->setPen(QColor(255, 255, 255, 255));
691     painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
692
693
694     // draw transition handles on hover
695     if (m_hover && itemWidth * scale > 40) {
696         QPointF p1 = painter->matrix().map(QPointF(0, itemHeight / 2)) + QPointF(10, 0);
697         painter->drawPixmap(p1, projectScene()->m_transitionPixmap);
698         p1 = painter->matrix().map(QPointF(itemWidth, itemHeight / 2)) - QPointF(22, 0);
699         painter->drawPixmap(p1, projectScene()->m_transitionPixmap);
700     }
701
702
703     // draw frame around clip
704     if (isSelected()) {
705         pen.setColor(Qt::red);
706         //pen.setWidth(2);
707     } else {
708         pen.setColor(Qt::black);
709         //pen.setWidth(1);
710     }
711
712     // draw effect or transition keyframes
713     if (itemWidth > 20) drawKeyFrames(painter, exposed);
714
715     painter->setMatrixEnabled(true);
716
717     // draw clip border
718
719     //kDebug()<<"/// ITEM PAINTING:: exposed="<<exposed<<", RECT = "<<rect();
720
721     // expand clip rect to allow correct painting of clip border
722     exposed.setRight(exposed.right() + 1 / scale + 0.5);
723     exposed.setBottom(exposed.bottom() + 1);
724     painter->setClipRect(exposed);
725     painter->setPen(pen);
726     painter->drawRect(br);
727 }
728
729
730 OPERATIONTYPE ClipItem::operationMode(QPointF pos) {
731     if (isSelected()) {
732         m_editedKeyframe = mouseOverKeyFrames(pos);
733         if (m_editedKeyframe != -1) return KEYFRAME;
734     }
735     QRectF rect = sceneBoundingRect();
736     const double scale = projectScene()->scale();
737     double maximumOffset = 6 / scale;
738
739     if (qAbs((int)(pos.x() - (rect.x() + m_startFade))) < maximumOffset  && qAbs((int)(pos.y() - rect.y())) < 6) {
740         if (m_startFade == 0) setToolTip(i18n("Add audio fade"));
741         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_startFade, m_fps).seconds()));
742         return FADEIN;
743     } else if (pos.x() - rect.x() < maximumOffset) {
744         setToolTip(i18n("Crop from start: %1s", cropStart().seconds()));
745         return RESIZESTART;
746     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - m_endFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
747         if (m_endFade == 0) setToolTip(i18n("Add audio fade"));
748         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_endFade, m_fps).seconds()));
749         return FADEOUT;
750     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width()))) < maximumOffset) {
751         setToolTip(i18n("Clip duration: %1s", duration().seconds()));
752         return RESIZEEND;
753     } else if (qAbs((int)(pos.x() - (rect.x() + 16 / scale))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 9))) < 6) {
754         setToolTip(i18n("Add transition"));
755         return TRANSITIONSTART;
756     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - 21 / scale))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 9))) < 6) {
757         setToolTip(i18n("Add transition"));
758         return TRANSITIONEND;
759     }
760     setToolTip(QString());
761     return MOVE;
762 }
763
764 QList <GenTime> ClipItem::snapMarkers() const {
765     QList < GenTime > snaps;
766     QList < GenTime > markers = baseClip()->snapMarkers();
767     GenTime pos;
768     double framepos;
769
770     for (int i = 0; i < markers.size(); i++) {
771         pos = markers.at(i) - cropStart();
772         if (pos > GenTime()) {
773             if (pos > duration()) break;
774             else snaps.append(pos + startPos());
775         }
776     }
777     return snaps;
778 }
779
780 QList <CommentedTime> ClipItem::commentedSnapMarkers() const {
781     QList < CommentedTime > snaps;
782     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
783     GenTime pos;
784     double framepos;
785
786     for (int i = 0; i < markers.size(); i++) {
787         pos = markers.at(i).time() - cropStart();
788         if (pos > GenTime()) {
789             if (pos > duration()) break;
790             else snaps.append(CommentedTime(pos + startPos(), markers.at(i).comment()));
791         }
792     }
793     return snaps;
794 }
795
796 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, int startpixel, int endpixel, int channels) {
797     QRectF re =  sceneBoundingRect();
798     if (m_clipType == AV) re.setTop(re.y() + re.height() / 2);
799
800     //kDebug() << "// PREP AUDIO THMB FRMO : scale:" << pixelForOneFrame<< ", from: " << startpixel << ", to: " << endpixel;
801     //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
802
803     for (int startCache = startpixel - startpixel % 100;startCache < endpixel;startCache += 100) {
804         //kDebug() << "creating " << startCache;
805         //if (framePixelWidth!=pixelForOneFrame  ||
806         if (framePixelWidth == pixelForOneFrame && audioThumbCachePic.contains(startCache))
807             continue;
808         if (audioThumbCachePic[startCache].isNull() || framePixelWidth != pixelForOneFrame) {
809             audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
810             audioThumbCachePic[startCache].fill(QColor(180, 180, 200, 140));
811         }
812         bool fullAreaDraw = pixelForOneFrame < 10;
813         QMap<int, QPainterPath > positiveChannelPaths;
814         QMap<int, QPainterPath > negativeChannelPaths;
815         QPainter pixpainter(&audioThumbCachePic[startCache]);
816         QPen audiopen;
817         audiopen.setWidth(0);
818         pixpainter.setPen(audiopen);
819         //pixpainter.setRenderHint(QPainter::Antialiasing,true);
820         //pixpainter.drawLine(0,0,100,re.height());
821         // Bail out, if caller provided invalid data
822         if (channels <= 0) {
823             kWarning() << "Unable to draw image with " << channels << "number of channels";
824             return;
825         }
826
827         int channelHeight = audioThumbCachePic[startCache].height() / channels;
828
829         for (int i = 0;i < channels;i++) {
830
831             positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
832             negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
833         }
834
835         for (int samples = 0;samples <= 100;samples++) {
836             double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
837             int sample = (int)((frame - (int)(frame)) * 20);   // AUDIO_FRAME_SIZE
838             if (frame < 0 || sample < 0 || sample > 19)
839                 continue;
840             QMap<int, QByteArray> frame_channel_data = baseClip()->audioFrameChache[(int)frame];
841
842             for (int channel = 0;channel < channels && frame_channel_data[channel].size() > 0;channel++) {
843
844                 int y = channelHeight * channel + channelHeight / 2;
845                 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2)  * channelHeight / 64;
846                 if (fullAreaDraw) {
847                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
848                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
849                 } else {
850                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
851                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
852                 }
853             }
854             for (int channel = 0;channel < channels ;channel++)
855                 if (fullAreaDraw && samples == 100) {
856                     positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
857                     negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
858                     positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
859                     negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
860                 }
861
862         }
863         if (m_clipType != AV) pixpainter.setBrush(QBrush(QColor(200, 200, 100)));
864         else {
865             pixpainter.setPen(QPen(QColor(0, 0, 0)));
866             pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
867         }
868         for (int i = 0;i < channels;i++) {
869             if (fullAreaDraw) {
870                 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
871                 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
872             } else
873                 pixpainter.drawPath(positiveChannelPaths[i]);
874         }
875     }
876     //audioThumbWasDrawn=true;
877     framePixelWidth = pixelForOneFrame;
878
879     //}
880 }
881
882 uint ClipItem::fadeIn() const {
883     return m_startFade;
884 }
885
886 uint ClipItem::fadeOut() const {
887     return m_endFade;
888 }
889
890
891 void ClipItem::setFadeIn(int pos) {
892     if (pos == m_startFade) return;
893     int oldIn = m_startFade;
894     if (pos < 0) pos = 0;
895     if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps));
896     m_startFade = pos;
897     QRectF rect = boundingRect();
898     update(rect.x(), rect.y(), qMax(oldIn, pos), rect.height());
899 }
900
901 void ClipItem::setFadeOut(int pos) {
902     if (pos == m_endFade) return;
903     int oldOut = m_endFade;
904     if (pos < 0) pos = 0;
905     if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps));
906     m_endFade = pos;
907     QRectF rect = boundingRect();
908     update(rect.x() + rect.width() - qMax(oldOut, pos), rect.y(), qMax(oldOut, pos), rect.height());
909
910 }
911
912 // virtual
913 void ClipItem::mousePressEvent(QGraphicsSceneMouseEvent * event) {
914     /*m_resizeMode = operationMode(event->pos());
915     if (m_resizeMode == MOVE) {
916       m_maxTrack = scene()->sceneRect().height();
917       m_grabPoint = (int) (event->pos().x() - rect().x());
918     }*/
919     QGraphicsRectItem::mousePressEvent(event);
920 }
921
922 // virtual
923 void ClipItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) {
924     m_resizeMode = NONE;
925     QGraphicsRectItem::mouseReleaseEvent(event);
926 }
927
928 //virtual
929 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e) {
930     //if (e->pos().x() < 20) m_hover = true;
931     m_hover = true;
932     QRectF r = boundingRect();
933     double width = 35 / projectScene()->scale();
934     double height = r.height() / 2;
935     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
936     update(r.x(), r.y() + height, width, height);
937     update(r.right() - width, r.y() + height, width, height);
938 }
939
940 //virtual
941 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *) {
942     m_hover = false;
943     QRectF r = boundingRect();
944     double width = 35 / projectScene()->scale();
945     double height = r.height() / 2;
946     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
947     update(r.x(), r.y() + height, width, height);
948     update(r.right() - width, r.y() + height, width, height);
949 }
950
951 void ClipItem::resizeStart(int posx, double speed) {
952     const int min = (startPos() - cropStart()).frames(m_fps);
953     if (posx < min) posx = min;
954     if (posx == startPos().frames(m_fps)) return;
955     const int previous = cropStart().frames(m_fps);
956     AbstractClipItem::resizeStart(posx, m_speed);
957     checkEffectsKeyframesPos(previous, cropStart().frames(m_fps), true);
958     if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
959         /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
960         startThumbTimer->start(100);
961     }
962 }
963
964 void ClipItem::resizeEnd(int posx, double speed, bool updateKeyFrames) {
965     const int max = (startPos() - cropStart() + maxDuration()).frames(m_fps) + 1;
966     if (posx > max) posx = max;
967     if (posx == endPos().frames(m_fps)) return;
968     //kDebug() << "// NEW POS: " << posx << ", OLD END: " << endPos().frames(m_fps);
969     const int previous = (cropStart() + duration()).frames(m_fps);
970     AbstractClipItem::resizeEnd(posx, m_speed);
971     if (updateKeyFrames) checkEffectsKeyframesPos(previous, (cropStart() + duration()).frames(m_fps), false);
972     if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
973         /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
974         endThumbTimer->start(100);
975     }
976 }
977
978
979 void ClipItem::checkEffectsKeyframesPos(const int previous, const int current, bool fromStart) {
980     for (int i = 0; i < m_effectList.size(); i++) {
981         QDomElement effect = m_effectList.at(i);
982         QDomNodeList params = effect.elementsByTagName("parameter");
983         for (int j = 0; j < params.count(); j++) {
984             QDomElement e = params.item(i).toElement();
985             if (e.attribute("type") == "keyframe") {
986                 // parse keyframes and adjust values
987                 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
988                 QMap <int, double> kfr;
989                 int pos;
990                 double val;
991                 foreach(const QString str, keyframes) {
992                     pos = str.section(":", 0, 0).toInt();
993                     val = str.section(":", 1, 1).toDouble();
994                     if (pos == previous) kfr[current] = val;
995                     else {
996                         if (fromStart && pos >= current) kfr[pos] = val;
997                         else if (!fromStart && pos <= current) kfr[pos] = val;
998                     }
999                 }
1000                 QString newkfr;
1001                 QMap<int, double>::const_iterator k = kfr.constBegin();
1002                 while (k != kfr.constEnd()) {
1003                     newkfr.append(QString::number(k.key()) + ":" + QString::number(k.value()) + ";");
1004                     ++k;
1005                 }
1006                 e.setAttribute("keyframes", newkfr);
1007                 break;
1008             }
1009         }
1010     }
1011     if (m_selectedEffect >= 0) setSelectedEffect(m_selectedEffect);
1012 }
1013
1014 //virtual
1015 QVariant ClipItem::itemChange(GraphicsItemChange change, const QVariant &value) {
1016     if (change == ItemPositionChange && scene()) {
1017         // calculate new position.
1018         if (parentItem()) return pos();
1019         QPointF newPos = value.toPointF();
1020         //kDebug() << "/// MOVING CLIP ITEM.------------\n++++++++++";
1021         int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
1022         xpos = qMax(xpos, 0);
1023         newPos.setX(xpos);
1024         int newTrack = newPos.y() / KdenliveSettings::trackheight();
1025         newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
1026         newTrack = qMax(newTrack, 0);
1027         newPos.setY((int)(newTrack  * KdenliveSettings::trackheight() + 1));
1028         // Only one clip is moving
1029         QRectF sceneShape = rect();
1030         sceneShape.translate(newPos);
1031         QList<QGraphicsItem*> items = scene()->items(sceneShape, Qt::IntersectsItemShape);
1032         items.removeAll(this);
1033         bool forwardMove = newPos.x() > pos().x();
1034         int offset = 0;
1035         if (!items.isEmpty()) {
1036             for (int i = 0; i < items.count(); i++) {
1037                 if (items.at(i)->type() == type()) {
1038                     // Collision!
1039                     QPointF otherPos = items.at(i)->pos();
1040                     if ((int) otherPos.y() != (int) pos().y()) {
1041                         return pos();
1042                     }
1043                     if (forwardMove) {
1044                         offset = qMax(offset, (int)(newPos.x() - (static_cast < AbstractClipItem* >(items.at(i))->startPos() - m_cropDuration).frames(m_fps)));
1045                     } else {
1046                         offset = qMax(offset, (int)((static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps)) - newPos.x()));
1047                     }
1048
1049                     if (offset > 0) {
1050                         if (forwardMove) {
1051                             sceneShape.translate(QPointF(-offset, 0));
1052                             newPos.setX(newPos.x() - offset);
1053                         } else {
1054                             sceneShape.translate(QPointF(offset, 0));
1055                             newPos.setX(newPos.x() + offset);
1056                         }
1057                         QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
1058                         subitems.removeAll(this);
1059                         for (int j = 0; j < subitems.count(); j++) {
1060                             if (subitems.at(j)->type() == type()) return pos();
1061                         }
1062                     }
1063
1064                     m_track = newTrack;
1065                     m_startPos = GenTime((int) newPos.x(), m_fps);
1066                     return newPos;
1067                 }
1068             }
1069         }
1070         m_track = newTrack;
1071         m_startPos = GenTime((int) newPos.x(), m_fps);
1072         //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
1073         return newPos;
1074     }
1075     return QGraphicsItem::itemChange(change, value);
1076 }
1077
1078 // virtual
1079 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
1080 }*/
1081
1082 int ClipItem::effectsCounter() {
1083     return effectsCount() + 1;
1084 }
1085
1086 int ClipItem::effectsCount() {
1087     return m_effectList.size();
1088 }
1089
1090 int ClipItem::hasEffect(const QString &tag, const QString &id) const {
1091     return m_effectList.hasEffect(tag, id);
1092 }
1093
1094 QStringList ClipItem::effectNames() {
1095     return m_effectList.effectNames();
1096 }
1097
1098 QDomElement ClipItem::effectAt(int ix) {
1099     if (ix > m_effectList.count() - 1 || ix < 0) return QDomElement();
1100     return m_effectList.at(ix);
1101 }
1102
1103 void ClipItem::setEffectAt(int ix, QDomElement effect) {
1104     kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1105     effect.setAttribute("kdenlive_ix", ix + 1);
1106     m_effectList.insert(ix, effect);
1107     m_effectList.removeAt(ix + 1);
1108     m_effectNames = m_effectList.effectNames().join(" / ");
1109     if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fadeout") update(boundingRect());
1110     else {
1111         QRectF r = boundingRect();
1112         r.setHeight(20);
1113         update(r);
1114     }
1115 }
1116
1117 QHash <QString, QString> ClipItem::addEffect(QDomElement effect, bool animate) {
1118     QHash <QString, QString> effectParams;
1119     bool needRepaint = false;
1120     /*QDomDocument doc;
1121     doc.appendChild(doc.importNode(effect, true));
1122     kDebug() << "///////  CLIP ADD EFFECT: " << doc.toString();*/
1123     m_effectList.append(effect);
1124     effectParams["tag"] = effect.attribute("tag");
1125     QString effectId = effect.attribute("id");
1126     if (effectId.isEmpty()) effectId = effect.attribute("tag");
1127     effectParams["id"] = effectId;
1128     effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
1129     QString state = effect.attribute("disabled");
1130     if (!state.isEmpty()) effectParams["disabled"] = state;
1131     QDomNodeList params = effect.elementsByTagName("parameter");
1132     int fade = 0;
1133     for (int i = 0; i < params.count(); i++) {
1134         QDomElement e = params.item(i).toElement();
1135         if (!e.isNull()) {
1136             if (e.attribute("type") == "keyframe") {
1137                 effectParams["keyframes"] = e.attribute("keyframes");
1138                 effectParams["min"] = e.attribute("min");
1139                 effectParams["max"] = e.attribute("max");
1140                 effectParams["factor"] = e.attribute("factor", "1");
1141                 effectParams["starttag"] = e.attribute("starttag", "start");
1142                 effectParams["endtag"] = e.attribute("endtag", "end");
1143             }
1144
1145             double f = e.attribute("factor", "1").toDouble();
1146
1147             if (f == 1) {
1148                 effectParams[e.attribute("name")] = e.attribute("value");
1149                 // check if it is a fade effect
1150                 if (effectId == "fadein") {
1151                     needRepaint = true;
1152                     if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1153                     else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1154                 } else if (effectId == "fadeout") {
1155                     needRepaint = true;
1156                     if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1157                     else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1158                 }
1159             } else {
1160                 effectParams[e.attribute("name")] =  QString::number(e.attribute("value").toDouble() / f);
1161             }
1162         }
1163     }
1164     m_effectNames = m_effectList.effectNames().join(" / ");
1165     if (fade > 0) m_startFade = fade;
1166     else if (fade < 0) m_endFade = -fade;
1167     if (needRepaint) update(boundingRect());
1168     if (animate) {
1169         flashClip();
1170     } else if (!needRepaint) {
1171         QRectF r = boundingRect();
1172         r.setHeight(20);
1173         update(r);
1174     }
1175     if (m_selectedEffect == -1) {
1176         m_selectedEffect = 0;
1177         setSelectedEffect(m_selectedEffect);
1178     }
1179     return effectParams;
1180 }
1181
1182 QHash <QString, QString> ClipItem::getEffectArgs(QDomElement effect) {
1183     QHash <QString, QString> effectParams;
1184     effectParams["tag"] = effect.attribute("tag");
1185     effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
1186     effectParams["id"] = effect.attribute("id");
1187     QString state = effect.attribute("disabled");
1188     if (!state.isEmpty()) effectParams["disabled"] = state;
1189     QDomNodeList params = effect.elementsByTagName("parameter");
1190     for (int i = 0; i < params.count(); i++) {
1191         QDomElement e = params.item(i).toElement();
1192         //kDebug() << "/ / / /SENDING EFFECT PARAM: " << e.attribute("type") << ", NAME_ " << e.attribute("tag");
1193         if (e.attribute("type") == "keyframe") {
1194             kDebug() << "/ / / /SENDING KEYFR EFFECT TYPE";
1195             effectParams["keyframes"] = e.attribute("keyframes");
1196             effectParams["max"] = e.attribute("max");
1197             effectParams["min"] = e.attribute("min");
1198             effectParams["factor"] = e.attribute("factor", "1");
1199             effectParams["starttag"] = e.attribute("starttag", "start");
1200             effectParams["endtag"] = e.attribute("endtag", "end");
1201         } else if (e.attribute("namedesc").contains(";")) {
1202             QString format = e.attribute("format");
1203             QStringList separators = format.split("%d", QString::SkipEmptyParts);
1204             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
1205             QString neu;
1206             QTextStream txtNeu(&neu);
1207             if (values.size() > 0)
1208                 txtNeu << (int)values[0].toDouble();
1209             for (int i = 0;i < separators.size() && i + 1 < values.size();i++) {
1210                 txtNeu << separators[i];
1211                 txtNeu << (int)(values[i+1].toDouble());
1212             }
1213             effectParams["start"] = neu;
1214         } else {
1215             if (e.attribute("factor", "1") != "1")
1216                 effectParams[e.attribute("name")] =  QString::number(e.attribute("value").toDouble() / e.attribute("factor").toDouble());
1217             else effectParams[e.attribute("name")] = e.attribute("value");
1218         }
1219     }
1220     return effectParams;
1221 }
1222
1223 void ClipItem::deleteEffect(QString index) {
1224     bool needRepaint = false;
1225     QString ix;
1226     for (int i = 0; i < m_effectList.size(); ++i) {
1227         ix = m_effectList.at(i).attribute("kdenlive_ix");
1228         if (ix == index) {
1229             if (m_effectList.at(i).attribute("id") == "fadein") {
1230                 m_startFade = 0;
1231                 needRepaint = true;
1232             } else if (m_effectList.at(i).attribute("id") == "fadeout") {
1233                 m_endFade = 0;
1234                 needRepaint = true;
1235             }
1236             m_effectList.removeAt(i);
1237         } else if (ix.toInt() > index.toInt()) m_effectList[i].setAttribute("kdenlive_ix", ix.toInt() - 1);
1238     }
1239     m_effectNames = m_effectList.effectNames().join(" / ");
1240     if (needRepaint) update(boundingRect());
1241     flashClip();
1242 }
1243
1244 double ClipItem::speed() const {
1245     return m_speed;
1246 }
1247
1248 void ClipItem::setSpeed(const double speed) {
1249     m_speed = speed;
1250     if (m_speed == 1.0) m_clipName = baseClip()->name();
1251     else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + "%";
1252     //update();
1253 }
1254
1255 GenTime ClipItem::maxDuration() const {
1256     return m_maxDuration / m_speed;
1257 }
1258
1259 GenTime ClipItem::cropStart() const {
1260     return m_cropStart / m_speed;
1261 }
1262
1263 GenTime ClipItem::cropDuration() const {
1264     return m_cropDuration / m_speed;
1265 }
1266
1267 GenTime ClipItem::endPos() const {
1268     return m_startPos + cropDuration();
1269 }
1270
1271 //virtual
1272 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event) {
1273     QString effects = QString(event->mimeData()->data("kdenlive/effectslist"));
1274     QDomDocument doc;
1275     doc.setContent(effects, true);
1276     QDomElement e = doc.documentElement();
1277     CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1278     if (view) view->slotAddEffect(e, m_startPos, track());
1279 }
1280
1281 //virtual
1282 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
1283     event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
1284 }
1285
1286 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) {
1287     Q_UNUSED(event);
1288 }
1289 void ClipItem::addTransition(Transition* t) {
1290     m_transitionsList.append(t);
1291     CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1292     QDomDocument doc;
1293     QDomElement e = doc.documentElement();
1294     //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1295 }
1296 // virtual
1297 /*
1298 void CustomTrackView::mousePressEvent ( QMouseEvent * event )
1299 {
1300   int pos = event->x();
1301   if (event->modifiers() == Qt::ControlModifier)
1302     setDragMode(QGraphicsView::ScrollHandDrag);
1303   else if (event->modifiers() == Qt::ShiftModifier)
1304     setDragMode(QGraphicsView::RubberBandDrag);
1305   else {
1306     QGraphicsItem * item = itemAt(event->pos());
1307     if (item) {
1308     }
1309     else emit cursorMoved((int) mapToScene(event->x(), 0).x());
1310   }
1311   kDebug()<<pos;
1312   QGraphicsView::mousePressEvent(event);
1313 }
1314
1315 void CustomTrackView::mouseReleaseEvent ( QMouseEvent * event )
1316 {
1317   QGraphicsView::mouseReleaseEvent(event);
1318   setDragMode(QGraphicsView::NoDrag);
1319 }
1320 */
1321
1322 #include "clipitem.moc"