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