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