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