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