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