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