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