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