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