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