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