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