]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
Add some brackets to make &&/|| precedence explicit
[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
693                 QPainterPath path;
694                 path.addRoundedRect(txtBounding, 3, 3);
695                 painter->fillPath(path, markerBrush);
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         QPainterPath path;
750         path.addRoundedRect(txtBounding, 4, 4);
751         painter->fillPath(path/*.intersected(resultClipPath)*/, markerBrush);
752         painter->drawText(txtBounding, Qt::AlignCenter, m_effectNames);
753         painter->setPen(Qt::black);
754     }
755
756     // Draw clip name
757     // draw frame around clip
758     QColor frameColor(Qt::black);
759     int alphaBase = 60;
760     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
761         frameColor = QColor(Qt::red);
762         alphaBase = 90;
763     }
764     frameColor.setAlpha(150);
765     QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignHCenter | Qt::AlignVCenter, ' ' + m_clipName + ' ');
766     painter->fillRect(txtBounding, frameColor);
767     //painter->setPen(QColor(0, 0, 0, 180));
768     //painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
769     if (m_videoOnly) {
770         painter->drawPixmap(txtBounding.topLeft() - QPointF(17, -1), m_videoPix);
771     } else if (m_audioOnly) {
772         painter->drawPixmap(txtBounding.topLeft() - QPointF(17, -1), m_audioPix);
773     }
774     txtBounding.translate(QPointF(1, 1));
775     painter->setPen(QColor(255, 255, 255, 255));
776     painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
777
778
779     // draw transition handles on hover
780     if (m_hover && itemWidth * scale > 40) {
781         QPointF p1 = painter->matrix().map(QPointF(0, itemHeight / 2)) + QPointF(10, 0);
782         painter->drawPixmap(p1, projectScene()->m_transitionPixmap);
783         p1 = painter->matrix().map(QPointF(itemWidth, itemHeight / 2)) - QPointF(22, 0);
784         painter->drawPixmap(p1, projectScene()->m_transitionPixmap);
785     }
786
787     // draw effect or transition keyframes
788     if (itemWidth > 20) drawKeyFrames(painter, exposed);
789
790     painter->setMatrixEnabled(true);
791
792     // draw clip border
793     // expand clip rect to allow correct painting of clip border
794
795     exposed.setRight(exposed.right() + xoffset + 0.5);
796     exposed.setBottom(exposed.bottom() + 1);
797     painter->setClipRect(exposed);
798
799     frameColor.setAlpha(alphaBase);
800     painter->setPen(frameColor);
801     QLineF line(br.left() + xoffset, br.top(), br.right() - xoffset, br.top());
802     painter->drawLine(line);
803
804     frameColor.setAlpha(alphaBase * 2);
805     painter->setPen(frameColor);
806     line.setLine(br.right(), br.top() + 1.0, br.right(), br.bottom() - 1.0);
807     painter->drawLine(line);
808     line.setLine(br.right() - xoffset, br.bottom(), br.left() + xoffset, br.bottom());
809     painter->drawLine(line);
810     line.setLine(br.left(), br.bottom() - 1.0, br.left(), br.top() + 1.0);
811     painter->drawLine(line);
812
813     painter->setPen(QColor(255, 255, 255, 60));
814     line.setLine(br.right() - xoffset, br.bottom() - 1.0, br.left() + xoffset, br.bottom() - 1.0);
815     painter->drawLine(line);
816     //painter->drawRect(br);
817 }
818
819
820 OPERATIONTYPE ClipItem::operationMode(QPointF pos)
821 {
822     if (isItemLocked()) return NONE;
823
824     if (isSelected()) {
825         m_editedKeyframe = mouseOverKeyFrames(pos);
826         if (m_editedKeyframe != -1) return KEYFRAME;
827     }
828     QRectF rect = sceneBoundingRect();
829     const double scale = projectScene()->scale();
830     double maximumOffset = 6 / scale;
831
832     if (qAbs((int)(pos.x() - (rect.x() + m_startFade))) < maximumOffset  && qAbs((int)(pos.y() - rect.y())) < 6) {
833         if (m_startFade == 0) setToolTip(i18n("Add audio fade"));
834         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_startFade, m_fps).seconds()));
835         return FADEIN;
836     } else if (pos.x() - rect.x() < maximumOffset) {
837         setToolTip(i18n("Crop from start: %1s", cropStart().seconds()));
838         return RESIZESTART;
839     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - m_endFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
840         if (m_endFade == 0) setToolTip(i18n("Add audio fade"));
841         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_endFade, m_fps).seconds()));
842         return FADEOUT;
843     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width()))) < maximumOffset) {
844         setToolTip(i18n("Clip duration: %1s", duration().seconds()));
845         return RESIZEEND;
846     } else if (qAbs((int)(pos.x() - (rect.x() + 16 / scale))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 9))) < 6) {
847         setToolTip(i18n("Add transition"));
848         return TRANSITIONSTART;
849     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - 21 / scale))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 9))) < 6) {
850         setToolTip(i18n("Add transition"));
851         return TRANSITIONEND;
852     }
853     setToolTip(QString());
854     return MOVE;
855 }
856
857 QList <GenTime> ClipItem::snapMarkers() const
858 {
859     QList < GenTime > snaps;
860     QList < GenTime > markers = baseClip()->snapMarkers();
861     GenTime pos;
862
863     for (int i = 0; i < markers.size(); i++) {
864         pos = markers.at(i) - cropStart();
865         if (pos > GenTime()) {
866             if (pos > duration()) break;
867             else snaps.append(pos + startPos());
868         }
869     }
870     return snaps;
871 }
872
873 QList <CommentedTime> ClipItem::commentedSnapMarkers() const
874 {
875     QList < CommentedTime > snaps;
876     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
877     GenTime pos;
878
879     for (int i = 0; i < markers.size(); i++) {
880         pos = markers.at(i).time() - cropStart();
881         if (pos > GenTime()) {
882             if (pos > duration()) break;
883             else snaps.append(CommentedTime(pos + startPos(), markers.at(i).comment()));
884         }
885     }
886     return snaps;
887 }
888
889 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, int startpixel, int endpixel, int channels)
890 {
891     QRectF re =  sceneBoundingRect();
892     if (m_clipType == AV && !isAudioOnly()) re.setTop(re.y() + re.height() / 2);
893
894     //kDebug() << "// PREP AUDIO THMB FRMO : scale:" << pixelForOneFrame<< ", from: " << startpixel << ", to: " << endpixel;
895     //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
896
897     for (int startCache = startpixel - startpixel % 100;startCache < endpixel;startCache += 100) {
898         //kDebug() << "creating " << startCache;
899         //if (framePixelWidth!=pixelForOneFrame  ||
900         if (framePixelWidth == pixelForOneFrame && audioThumbCachePic.contains(startCache))
901             continue;
902         if (audioThumbCachePic[startCache].isNull() || framePixelWidth != pixelForOneFrame) {
903             audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
904             audioThumbCachePic[startCache].fill(QColor(180, 180, 200, 140));
905         }
906         bool fullAreaDraw = pixelForOneFrame < 10;
907         QMap<int, QPainterPath > positiveChannelPaths;
908         QMap<int, QPainterPath > negativeChannelPaths;
909         QPainter pixpainter(&audioThumbCachePic[startCache]);
910         QPen audiopen;
911         audiopen.setWidth(0);
912         pixpainter.setPen(audiopen);
913         //pixpainter.setRenderHint(QPainter::Antialiasing,true);
914         //pixpainter.drawLine(0,0,100,re.height());
915         // Bail out, if caller provided invalid data
916         if (channels <= 0) {
917             kWarning() << "Unable to draw image with " << channels << "number of channels";
918             return;
919         }
920
921         int channelHeight = audioThumbCachePic[startCache].height() / channels;
922
923         for (int i = 0;i < channels;i++) {
924
925             positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
926             negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
927         }
928
929         for (int samples = 0;samples <= 100;samples++) {
930             double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
931             int sample = (int)((frame - (int)(frame)) * 20);   // AUDIO_FRAME_SIZE
932             if (frame < 0 || sample < 0 || sample > 19)
933                 continue;
934             QMap<int, QByteArray> frame_channel_data = baseClip()->audioFrameChache[(int)frame];
935
936             for (int channel = 0;channel < channels && frame_channel_data[channel].size() > 0;channel++) {
937
938                 int y = channelHeight * channel + channelHeight / 2;
939                 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2)  * channelHeight / 64;
940                 if (fullAreaDraw) {
941                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
942                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
943                 } else {
944                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
945                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
946                 }
947             }
948             for (int channel = 0;channel < channels ;channel++)
949                 if (fullAreaDraw && samples == 100) {
950                     positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
951                     negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
952                     positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
953                     negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
954                 }
955
956         }
957         pixpainter.setPen(QPen(QColor(0, 0, 0)));
958         pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
959
960         for (int i = 0;i < channels;i++) {
961             if (fullAreaDraw) {
962                 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
963                 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
964             } else
965                 pixpainter.drawPath(positiveChannelPaths[i]);
966         }
967     }
968     //audioThumbWasDrawn=true;
969     framePixelWidth = pixelForOneFrame;
970
971     //}
972 }
973
974 uint ClipItem::fadeIn() const
975 {
976     return m_startFade;
977 }
978
979 uint ClipItem::fadeOut() const
980 {
981     return m_endFade;
982 }
983
984
985 void ClipItem::setFadeIn(int pos)
986 {
987     if (pos == m_startFade) return;
988     int oldIn = m_startFade;
989     if (pos < 0) pos = 0;
990     if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps));
991     m_startFade = pos;
992     QRectF rect = boundingRect();
993     update(rect.x(), rect.y(), qMax(oldIn, pos), rect.height());
994 }
995
996 void ClipItem::setFadeOut(int pos)
997 {
998     if (pos == m_endFade) return;
999     int oldOut = m_endFade;
1000     if (pos < 0) pos = 0;
1001     if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps));
1002     m_endFade = pos;
1003     QRectF rect = boundingRect();
1004     update(rect.x() + rect.width() - qMax(oldOut, pos), rect.y(), qMax(oldOut, pos), rect.height());
1005
1006 }
1007
1008 // virtual
1009 void ClipItem::mousePressEvent(QGraphicsSceneMouseEvent * event)
1010 {
1011     /*m_resizeMode = operationMode(event->pos());
1012     if (m_resizeMode == MOVE) {
1013       m_maxTrack = scene()->sceneRect().height();
1014       m_grabPoint = (int) (event->pos().x() - rect().x());
1015     }*/
1016     QGraphicsRectItem::mousePressEvent(event);
1017 }
1018
1019 // virtual
1020 void ClipItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event)
1021 {
1022     m_resizeMode = NONE;
1023     QGraphicsRectItem::mouseReleaseEvent(event);
1024 }
1025
1026 //virtual
1027 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent */*e*/)
1028 {
1029     //if (e->pos().x() < 20) m_hover = true;
1030     if (isItemLocked()) return;
1031     m_hover = true;
1032     QRectF r = boundingRect();
1033     double width = 35 / projectScene()->scale();
1034     double height = r.height() / 2;
1035     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
1036     update(r.x(), r.y() + height, width, height);
1037     update(r.right() - width, r.y() + height, width, height);
1038 }
1039
1040 //virtual
1041 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *)
1042 {
1043     if (isItemLocked()) return;
1044     m_hover = false;
1045     QRectF r = boundingRect();
1046     double width = 35 / projectScene()->scale();
1047     double height = r.height() / 2;
1048     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
1049     update(r.x(), r.y() + height, width, height);
1050     update(r.right() - width, r.y() + height, width, height);
1051 }
1052
1053 void ClipItem::resizeStart(int posx, double /*speed*/)
1054 {
1055     const int min = (startPos() - cropStart()).frames(m_fps);
1056     if (posx < min) posx = min;
1057     if (posx == startPos().frames(m_fps)) return;
1058     const int previous = cropStart().frames(m_fps);
1059     AbstractClipItem::resizeStart(posx, m_speed);
1060     if ((int) cropStart().frames(m_fps) != previous) {
1061         checkEffectsKeyframesPos(previous, cropStart().frames(m_fps), true);
1062         if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
1063             /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
1064             startThumbTimer->start(150);
1065         }
1066     }
1067 }
1068
1069 void ClipItem::resizeEnd(int posx, double /*speed*/, bool updateKeyFrames)
1070 {
1071     const int max = (startPos() - cropStart() + maxDuration()).frames(m_fps) + 1;
1072     if (posx > max) posx = max;
1073     if (posx == endPos().frames(m_fps)) return;
1074     //kDebug() << "// NEW POS: " << posx << ", OLD END: " << endPos().frames(m_fps);
1075     const int previous = (cropStart() + duration()).frames(m_fps);
1076     AbstractClipItem::resizeEnd(posx, m_speed);
1077     if ((int)(cropStart() + duration()).frames(m_fps) != previous) {
1078         if (updateKeyFrames) checkEffectsKeyframesPos(previous, (cropStart() + duration()).frames(m_fps), false);
1079         if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
1080             /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
1081             endThumbTimer->start(150);
1082         }
1083     }
1084 }
1085
1086
1087 void ClipItem::checkEffectsKeyframesPos(const int previous, const int current, bool fromStart)
1088 {
1089     for (int i = 0; i < m_effectList.size(); i++) {
1090         QDomElement effect = m_effectList.at(i);
1091         QDomNodeList params = effect.elementsByTagName("parameter");
1092         for (int j = 0; j < params.count(); j++) {
1093             QDomElement e = params.item(i).toElement();
1094             if (e.attribute("type") == "keyframe") {
1095                 // parse keyframes and adjust values
1096                 const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
1097                 QMap <int, double> kfr;
1098                 int pos;
1099                 double val;
1100                 foreach(const QString &str, keyframes) {
1101                     pos = str.section(':', 0, 0).toInt();
1102                     val = str.section(':', 1, 1).toDouble();
1103                     if (pos == previous) kfr[current] = val;
1104                     else {
1105                         if (fromStart && pos >= current) kfr[pos] = val;
1106                         else if (!fromStart && pos <= current) kfr[pos] = val;
1107                     }
1108                 }
1109                 QString newkfr;
1110                 QMap<int, double>::const_iterator k = kfr.constBegin();
1111                 while (k != kfr.constEnd()) {
1112                     newkfr.append(QString::number(k.key()) + ':' + QString::number(k.value()) + ';');
1113                     ++k;
1114                 }
1115                 e.setAttribute("keyframes", newkfr);
1116                 break;
1117             }
1118         }
1119     }
1120     if (m_selectedEffect >= 0) setSelectedEffect(m_selectedEffect);
1121 }
1122
1123 //virtual
1124 QVariant ClipItem::itemChange(GraphicsItemChange change, const QVariant &value)
1125 {
1126     if (change == ItemPositionChange && scene()) {
1127         // calculate new position.
1128         //if (parentItem()) return pos();
1129         QPointF newPos = value.toPointF();
1130         //kDebug() << "/// MOVING CLIP ITEM.------------\n++++++++++";
1131         int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
1132         xpos = qMax(xpos, 0);
1133         newPos.setX(xpos);
1134         int newTrack = newPos.y() / KdenliveSettings::trackheight();
1135         newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
1136         newTrack = qMax(newTrack, 0);
1137         newPos.setY((int)(newTrack  * KdenliveSettings::trackheight() + 1));
1138         // Only one clip is moving
1139         QRectF sceneShape = rect();
1140         sceneShape.translate(newPos);
1141         QList<QGraphicsItem*> items = scene()->items(sceneShape, Qt::IntersectsItemShape);
1142         items.removeAll(this);
1143         bool forwardMove = newPos.x() > pos().x();
1144         int offset = 0;
1145         if (!items.isEmpty()) {
1146             for (int i = 0; i < items.count(); i++) {
1147                 if (items.at(i)->type() == type()) {
1148                     // Collision!
1149                     QPointF otherPos = items.at(i)->pos();
1150                     if ((int) otherPos.y() != (int) pos().y()) {
1151                         return pos();
1152                     }
1153                     if (forwardMove) {
1154                         offset = qMax(offset, (int)(newPos.x() - (static_cast < AbstractClipItem* >(items.at(i))->startPos() - cropDuration()).frames(m_fps)));
1155                     } else {
1156                         offset = qMax(offset, (int)((static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps)) - newPos.x()));
1157                     }
1158
1159                     if (offset > 0) {
1160                         if (forwardMove) {
1161                             sceneShape.translate(QPointF(-offset, 0));
1162                             newPos.setX(newPos.x() - offset);
1163                         } else {
1164                             sceneShape.translate(QPointF(offset, 0));
1165                             newPos.setX(newPos.x() + offset);
1166                         }
1167                         QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
1168                         subitems.removeAll(this);
1169                         for (int j = 0; j < subitems.count(); j++) {
1170                             if (subitems.at(j)->type() == type()) {
1171                                 m_startPos = GenTime((int) pos().x(), m_fps);
1172                                 return pos();
1173                             }
1174                         }
1175                     }
1176
1177                     m_track = newTrack;
1178                     m_startPos = GenTime((int) newPos.x(), m_fps);
1179                     return newPos;
1180                 }
1181             }
1182         }
1183         m_track = newTrack;
1184         m_startPos = GenTime((int) newPos.x(), m_fps);
1185         //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
1186         return newPos;
1187     }
1188     return QGraphicsItem::itemChange(change, value);
1189 }
1190
1191 // virtual
1192 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
1193 }*/
1194
1195 int ClipItem::effectsCounter()
1196 {
1197     return effectsCount() + 1;
1198 }
1199
1200 int ClipItem::effectsCount()
1201 {
1202     return m_effectList.size();
1203 }
1204
1205 int ClipItem::hasEffect(const QString &tag, const QString &id) const
1206 {
1207     return m_effectList.hasEffect(tag, id);
1208 }
1209
1210 QStringList ClipItem::effectNames()
1211 {
1212     return m_effectList.effectNames();
1213 }
1214
1215 QDomElement ClipItem::effectAt(int ix)
1216 {
1217     if (ix > m_effectList.count() - 1 || ix < 0) return QDomElement();
1218     return m_effectList.at(ix);
1219 }
1220
1221 void ClipItem::setEffectAt(int ix, QDomElement effect)
1222 {
1223     kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1224     effect.setAttribute("kdenlive_ix", ix + 1);
1225     m_effectList.insert(ix, effect);
1226     m_effectList.removeAt(ix + 1);
1227     m_effectNames = m_effectList.effectNames().join(" / ");
1228     QString id = effect.attribute("id");
1229     if (id == "fadein" || id == "fadeout" || id == "fade_from_black" || id == "fade_to_black")
1230         update(boundingRect());
1231     else {
1232         QRectF r = boundingRect();
1233         r.setHeight(20);
1234         update(r);
1235     }
1236 }
1237
1238 EffectsParameterList ClipItem::addEffect(QDomElement effect, bool animate)
1239 {
1240
1241     bool needRepaint = false;
1242     /*QDomDocument doc;
1243     doc.appendChild(doc.importNode(effect, true));
1244     kDebug() << "///////  CLIP ADD EFFECT: " << doc.toString();*/
1245     m_effectList.append(effect);
1246
1247     EffectsParameterList parameters;
1248     parameters.addParam("tag", effect.attribute("tag"));
1249     parameters.addParam("kdenlive_ix", effect.attribute("kdenlive_ix"));
1250     if (effect.hasAttribute("src")) parameters.addParam("src", effect.attribute("src"));
1251
1252     QString state = effect.attribute("disabled");
1253     if (!state.isEmpty()) {
1254         parameters.addParam("disabled", state);
1255     }
1256
1257     QString effectId = effect.attribute("id");
1258     if (effectId.isEmpty()) effectId = effect.attribute("tag");
1259     parameters.addParam("id", effectId);
1260
1261     QDomNodeList params = effect.elementsByTagName("parameter");
1262     int fade = 0;
1263     for (int i = 0; i < params.count(); i++) {
1264         QDomElement e = params.item(i).toElement();
1265         if (!e.isNull()) {
1266             if (e.attribute("type") == "keyframe") {
1267                 parameters.addParam("keyframes", e.attribute("keyframes"));
1268                 parameters.addParam("max", e.attribute("max"));
1269                 parameters.addParam("min", e.attribute("min"));
1270                 parameters.addParam("factor", e.attribute("factor", "1"));
1271                 parameters.addParam("starttag", e.attribute("starttag", "start"));
1272                 parameters.addParam("endtag", e.attribute("endtag", "end"));
1273             }
1274
1275             double f = e.attribute("factor", "1").toDouble();
1276
1277             if (f == 1) {
1278                 parameters.addParam(e.attribute("name"), e.attribute("value"));
1279
1280                 // check if it is a fade effect
1281                 if (effectId == "fadein") {
1282                     needRepaint = true;
1283                     if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
1284                         if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1285                         else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1286                     } else {
1287                         QDomElement fadein = m_effectList.getEffectByTag(QString(), "fade_from_black");
1288                         if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1289                         else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1290                     }
1291                 } else if (effectId == "fade_from_black") {
1292                     needRepaint = true;
1293                     if (m_effectList.hasEffect(QString(), "fadein") == -1) {
1294                         if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1295                         else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1296                     } else {
1297                         QDomElement fadein = m_effectList.getEffectByTag(QString(), "fadein");
1298                         if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1299                         else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1300                     }
1301                 } else if (effectId == "fadeout") {
1302                     needRepaint = true;
1303                     if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
1304                         if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1305                         else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1306                     } else {
1307                         QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
1308                         if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1309                         else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1310                     }
1311                 } else if (effectId == "fade_to_black") {
1312                     needRepaint = true;
1313                     if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
1314                         if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1315                         else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1316                     } else {
1317                         QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
1318                         if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1319                         else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1320                     }
1321                 }
1322             } else {
1323                 parameters.addParam(e.attribute("name"), QString::number(e.attribute("value").toDouble() / f));
1324             }
1325         }
1326     }
1327     m_effectNames = m_effectList.effectNames().join(" / ");
1328     if (fade > 0) m_startFade = fade;
1329     else if (fade < 0) m_endFade = -fade;
1330     if (needRepaint) update(boundingRect());
1331     if (animate) {
1332         flashClip();
1333     } else if (!needRepaint) {
1334         QRectF r = boundingRect();
1335         r.setHeight(20);
1336         update(r);
1337     }
1338     if (m_selectedEffect == -1) {
1339         m_selectedEffect = 0;
1340         setSelectedEffect(m_selectedEffect);
1341     }
1342     return parameters;
1343 }
1344
1345 EffectsParameterList ClipItem::getEffectArgs(QDomElement effect)
1346 {
1347     EffectsParameterList parameters;
1348     parameters.addParam("tag", effect.attribute("tag"));
1349     parameters.addParam("kdenlive_ix", effect.attribute("kdenlive_ix"));
1350     parameters.addParam("id", effect.attribute("id"));
1351     if (effect.hasAttribute("src")) parameters.addParam("src", effect.attribute("src"));
1352     QString state = effect.attribute("disabled");
1353     if (!state.isEmpty()) {
1354         parameters.addParam("disabled", state);
1355     }
1356
1357     QDomNodeList params = effect.elementsByTagName("parameter");
1358     for (int i = 0; i < params.count(); i++) {
1359         QDomElement e = params.item(i).toElement();
1360         //kDebug() << "/ / / /SENDING EFFECT PARAM: " << e.attribute("type") << ", NAME_ " << e.attribute("tag");
1361         if (e.attribute("type") == "keyframe") {
1362             kDebug() << "/ / / /SENDING KEYFR EFFECT TYPE";
1363             parameters.addParam("keyframes", e.attribute("keyframes"));
1364             parameters.addParam("max", e.attribute("max"));
1365             parameters.addParam("min", e.attribute("min"));
1366             parameters.addParam("factor", e.attribute("factor", "1"));
1367             parameters.addParam("starttag", e.attribute("starttag", "start"));
1368             parameters.addParam("endtag", e.attribute("endtag", "end"));
1369         } else if (e.attribute("namedesc").contains(';')) {
1370             QString format = e.attribute("format");
1371             QStringList separators = format.split("%d", QString::SkipEmptyParts);
1372             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
1373             QString neu;
1374             QTextStream txtNeu(&neu);
1375             if (values.size() > 0)
1376                 txtNeu << (int)values[0].toDouble();
1377             for (int i = 0;i < separators.size() && i + 1 < values.size();i++) {
1378                 txtNeu << separators[i];
1379                 txtNeu << (int)(values[i+1].toDouble());
1380             }
1381             parameters.addParam("start", neu);
1382         } else {
1383             if (e.attribute("factor", "1") != "1") {
1384                 parameters.addParam(e.attribute("name"), QString::number(e.attribute("value").toDouble() / e.attribute("factor").toDouble()));
1385             } else {
1386                 parameters.addParam(e.attribute("name"), e.attribute("value"));
1387             }
1388         }
1389     }
1390     return parameters;
1391 }
1392
1393 void ClipItem::deleteEffect(QString index)
1394 {
1395     bool needRepaint = false;
1396     QString ix;
1397
1398     for (int i = 0; i < m_effectList.size(); ++i) {
1399         ix = m_effectList.at(i).attribute("kdenlive_ix");
1400         if (ix == index) {
1401             QString effectId = m_effectList.at(i).attribute("id");
1402             if ((effectId == "fadein" && hasEffect(QString(), "fade_from_black") == -1) ||
1403                     (effectId == "fade_from_black" && hasEffect(QString(), "fadein") == -1)) {
1404                 m_startFade = 0;
1405                 needRepaint = true;
1406             } else if ((effectId == "fadeout" && hasEffect(QString(), "fade_to_black") == -1) ||
1407                        (effectId == "fade_to_black" && hasEffect(QString(), "fadeout") == -1)) {
1408                 m_endFade = 0;
1409                 needRepaint = true;
1410             }
1411             m_effectList.removeAt(i);
1412             i--;
1413         } else if (ix.toInt() > index.toInt()) {
1414             m_effectList[i].setAttribute("kdenlive_ix", ix.toInt() - 1);
1415         }
1416     }
1417     m_effectNames = m_effectList.effectNames().join(" / ");
1418     if (needRepaint) update(boundingRect());
1419     flashClip();
1420 }
1421
1422 double ClipItem::speed() const
1423 {
1424     return m_speed;
1425 }
1426
1427 void ClipItem::setSpeed(const double speed)
1428 {
1429     m_speed = speed;
1430     if (m_speed == 1.0) m_clipName = baseClip()->name();
1431     else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + '%';
1432     //update();
1433 }
1434
1435 GenTime ClipItem::maxDuration() const
1436 {
1437     return m_maxDuration / m_speed;
1438 }
1439
1440 GenTime ClipItem::cropStart() const
1441 {
1442     return m_cropStart / m_speed;
1443 }
1444
1445 GenTime ClipItem::cropDuration() const
1446 {
1447     return m_cropDuration / m_speed;
1448 }
1449
1450 GenTime ClipItem::endPos() const
1451 {
1452     return m_startPos + cropDuration();
1453 }
1454
1455 //virtual
1456 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event)
1457 {
1458     QString effects = QString(event->mimeData()->data("kdenlive/effectslist"));
1459     QDomDocument doc;
1460     doc.setContent(effects, true);
1461     QDomElement e = doc.documentElement();
1462     CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1463     if (view) view->slotAddEffect(e, m_startPos, track());
1464 }
1465
1466 //virtual
1467 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
1468 {
1469     if (isItemLocked()) event->setAccepted(false);
1470     else event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
1471 }
1472
1473 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
1474 {
1475     Q_UNUSED(event);
1476 }
1477
1478 void ClipItem::addTransition(Transition* t)
1479 {
1480     m_transitionsList.append(t);
1481     //CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1482     QDomDocument doc;
1483     QDomElement e = doc.documentElement();
1484     //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1485 }
1486
1487 void ClipItem::setVideoOnly(bool force)
1488 {
1489     m_videoOnly = force;
1490 }
1491
1492 void ClipItem::setAudioOnly(bool force)
1493 {
1494     m_audioOnly = force;
1495     if (m_audioOnly) setBrush(QColor(141, 215, 166));
1496     else setBrush(QColor(141, 166, 215));
1497     audioThumbCachePic.clear();
1498 }
1499
1500 bool ClipItem::isAudioOnly() const
1501 {
1502     return m_audioOnly;
1503 }
1504
1505 bool ClipItem::isVideoOnly() const
1506 {
1507     return m_videoOnly;
1508 }
1509
1510
1511 // virtual
1512 /*
1513 void CustomTrackView::mousePressEvent ( QMouseEvent * event )
1514 {
1515   int pos = event->x();
1516   if (event->modifiers() == Qt::ControlModifier)
1517     setDragMode(QGraphicsView::ScrollHandDrag);
1518   else if (event->modifiers() == Qt::ShiftModifier)
1519     setDragMode(QGraphicsView::RubberBandDrag);
1520   else {
1521     QGraphicsItem * item = itemAt(event->pos());
1522     if (item) {
1523     }
1524     else emit cursorMoved((int) mapToScene(event->x(), 0).x());
1525   }
1526   kDebug()<<pos;
1527   QGraphicsView::mousePressEvent(event);
1528 }
1529
1530 void CustomTrackView::mouseReleaseEvent ( QMouseEvent * event )
1531 {
1532   QGraphicsView::mouseReleaseEvent(event);
1533   setDragMode(QGraphicsView::NoDrag);
1534 }
1535 */
1536
1537 #include "clipitem.moc"