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