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