]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
Fix timeline thumbs not reloaded on clip change:
[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         update();
533     } else resetThumbs(checkDuration);
534 }
535
536 void ClipItem::slotFetchThumbs()
537 {
538     if (scene() == NULL || m_clipType == AUDIO || m_clipType == COLOR) return;
539     if (m_clipType == IMAGE) {
540         if (m_startPix.isNull()) {
541             m_startPix = KThumb::getImage(KUrl(m_clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
542             update();
543         }
544         return;
545     }
546
547     if (m_clipType == TEXT) {
548         if (m_startPix.isNull()) slotGetStartThumb();
549         return;
550     }
551
552     if (m_endPix.isNull() && m_startPix.isNull()) {
553         m_startThumbRequested = true;
554         m_endThumbRequested = true;
555         emit getThumb((int)m_speedIndependantInfo.cropStart.frames(m_fps), (int)(m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1);
556     } else {
557         if (m_endPix.isNull()) {
558             slotGetEndThumb();
559         }
560         if (m_startPix.isNull()) {
561             slotGetStartThumb();
562         }
563     }
564 }
565
566 void ClipItem::slotGetStartThumb()
567 {
568     m_startThumbRequested = true;
569     emit getThumb((int)m_speedIndependantInfo.cropStart.frames(m_fps), -1);
570 }
571
572 void ClipItem::slotGetEndThumb()
573 {
574     m_endThumbRequested = true;
575     emit getThumb(-1, (int)(m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1);
576 }
577
578
579 void ClipItem::slotSetStartThumb(QImage img)
580 {
581     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
582         QPixmap pix = QPixmap::fromImage(img);
583         m_startPix = pix;
584         QRectF r = sceneBoundingRect();
585         r.setRight(pix.width() + 2);
586         update(r);
587     }
588 }
589
590 void ClipItem::slotSetEndThumb(QImage img)
591 {
592     if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
593         QPixmap pix = QPixmap::fromImage(img);
594         m_endPix = pix;
595         QRectF r = sceneBoundingRect();
596         r.setLeft(r.right() - pix.width() - 2);
597         update(r);
598     }
599 }
600
601 void ClipItem::slotThumbReady(int frame, QImage img)
602 {
603     if (scene() == NULL) return;
604     QRectF r = boundingRect();
605     QPixmap pix = QPixmap::fromImage(img);
606     double width = pix.width() / projectScene()->scale().x();
607     if (m_startThumbRequested && frame == m_speedIndependantInfo.cropStart.frames(m_fps)) {
608         m_startPix = pix;
609         m_startThumbRequested = false;
610         update(r.left(), r.top(), width, pix.height());
611         if (m_clipType == IMAGE || m_clipType == TEXT) {
612             update(r.right() - width, r.top(), width, pix.height());
613         }
614     } else if (m_endThumbRequested && frame == (m_speedIndependantInfo.cropStart + m_speedIndependantInfo.cropDuration).frames(m_fps) - 1) {
615         m_endPix = pix;
616         m_endThumbRequested = false;
617         update(r.right() - width, r.top(), width, pix.height());
618     }
619 }
620
621 void ClipItem::slotSetStartThumb(const QPixmap pix)
622 {
623     m_startPix = pix;
624 }
625
626 void ClipItem::slotSetEndThumb(const QPixmap pix)
627 {
628     m_endPix = pix;
629 }
630
631 QPixmap ClipItem::startThumb() const
632 {
633     return m_startPix;
634 }
635
636 QPixmap ClipItem::endThumb() const
637 {
638     return m_endPix;
639 }
640
641 void ClipItem::slotGotAudioData()
642 {
643     m_audioThumbReady = true;
644     if (m_clipType == AV && !isAudioOnly()) {
645         QRectF r = boundingRect();
646         r.setTop(r.top() + r.height() / 2 - 1);
647         update(r);
648     } else update();
649 }
650
651 int ClipItem::type() const
652 {
653     return AVWIDGET;
654 }
655
656 DocClipBase *ClipItem::baseClip() const
657 {
658     return m_clip;
659 }
660
661 QDomElement ClipItem::xml() const
662 {
663     return itemXml();
664 }
665
666 QDomElement ClipItem::itemXml() const
667 {
668     QDomElement xml = m_clip->toXML();
669     if (m_speed != 1.0) xml.setAttribute("speed", m_speed);
670     if (m_strobe > 1) xml.setAttribute("strobe", m_strobe);
671     if (m_audioOnly) xml.setAttribute("audio_only", 1);
672     else if (m_videoOnly) xml.setAttribute("video_only", 1);
673     return xml;
674 }
675
676 int ClipItem::clipType() const
677 {
678     return m_clipType;
679 }
680
681 QString ClipItem::clipName() const
682 {
683     return m_clipName;
684 }
685
686 void ClipItem::setClipName(const QString &name)
687 {
688     m_clipName = name;
689 }
690
691 const QString ClipItem::clipProducer() const
692 {
693     return m_producer;
694 }
695
696 void ClipItem::flashClip()
697 {
698     if (m_timeLine == 0) {
699         m_timeLine = new QTimeLine(750, this);
700         m_timeLine->setUpdateInterval(80);
701         m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
702         m_timeLine->setFrameRange(0, 100);
703         connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
704     }
705     //m_timeLine->start();
706 }
707
708 void ClipItem::animate(qreal /*value*/)
709 {
710     QRectF r = boundingRect();
711     r.setHeight(20);
712     update(r);
713 }
714
715 // virtual
716 void ClipItem::paint(QPainter *painter,
717                      const QStyleOptionGraphicsItem *option,
718                      QWidget *)
719 {
720     QColor paintColor;
721     if (parentItem()) paintColor = QColor(255, 248, 149);
722     else paintColor = m_baseColor;
723     if (isSelected() || (parentItem() && parentItem()->isSelected())) paintColor = paintColor.darker();
724
725     painter->setMatrixEnabled(false);
726     const QRectF mapped = painter->matrix().mapRect(rect()).adjusted(0.5, 0, 0.5, 0);
727     const QRectF exposed = option->exposedRect;
728     painter->setClipRect(mapped);
729     painter->fillRect(mapped, paintColor);
730
731     // draw thumbnails
732     if (KdenliveSettings::videothumbnails() && !isAudioOnly()) {
733         QPen pen = painter->pen();
734         pen.setColor(QColor(255, 255, 255, 150));
735         painter->setPen(pen);
736         if ((m_clipType == IMAGE || m_clipType == TEXT) && !m_startPix.isNull()) {
737             const QPointF top = mapped.topRight() - QPointF(m_startPix.width() - 1, 0);
738             painter->drawPixmap(top, m_startPix);
739             QLineF l2(top.x(), mapped.top(), top.x(), mapped.bottom());
740             painter->drawLine(l2);
741         } else if (!m_endPix.isNull()) {
742             const QPointF top = mapped.topRight() - QPointF(m_endPix.width() - 1, 0);
743             painter->drawPixmap(top, m_endPix);
744             QLineF l2(top.x(), mapped.top(), top.x(), mapped.bottom());
745             painter->drawLine(l2);
746         }
747         if (!m_startPix.isNull()) {
748             painter->drawPixmap(mapped.topLeft(), m_startPix);
749             QLineF l2(mapped.left() + m_startPix.width(), mapped.top(), mapped.left() + m_startPix.width(), mapped.bottom());
750             painter->drawLine(l2);
751         }
752         if (painter->matrix().m11() == FRAME_SIZE) {
753             int offset = (m_info.startPos - m_info.cropStart).frames(m_fps);
754             int left = qMax((int) m_info.startPos.frames(m_fps) + 1, (int) mapToScene(exposed.left(), 0).x());
755             int right = qMin((int)(m_info.startPos + m_info.cropDuration).frames(m_fps) - 1, (int) mapToScene(exposed.right(), 0).x());
756             doGetIntraThumbs(painter, mapped.topLeft(), m_info.cropStart.frames(m_fps), left - offset, right - offset);
757         }
758         painter->setPen(Qt::black);
759     }
760
761     // draw audio thumbnails
762     if (KdenliveSettings::audiothumbnails() && m_speed == 1.0 && !isVideoOnly() && ((m_clipType == AV && (exposed.bottom() > (rect().height() / 2) || isAudioOnly())) || m_clipType == AUDIO) && m_audioThumbReady) {
763
764         double startpixel = exposed.left();
765         if (startpixel < 0)
766             startpixel = 0;
767         double endpixel = exposed.right();
768         if (endpixel < 0)
769             endpixel = 0;
770         //kDebug()<<"///  REPAINTING AUDIO THMBS ZONE: "<<startpixel<<"x"<<endpixel;
771
772         /*QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;*/
773         QRectF mappedRect;
774         if (m_clipType == AV && !isAudioOnly()) {
775             mappedRect = mapped;
776             mappedRect.setTop(mappedRect.bottom() - mapped.height() / 2);
777         } else mappedRect = mapped;
778
779         double scale = painter->matrix().m11();
780         int channels = 0;
781         if (isEnabled() && m_clip) channels = m_clip->getProperty("channels").toInt();
782         if (scale != m_framePixelWidth)
783             m_audioThumbCachePic.clear();
784         double cropLeft = m_info.cropStart.frames(m_fps);
785         const int clipStart = mappedRect.x();
786         const int mappedStartPixel =  painter->matrix().map(QPointF(startpixel + cropLeft, 0)).x() - clipStart;
787         const int mappedEndPixel =  painter->matrix().map(QPointF(endpixel + cropLeft, 0)).x() - clipStart;
788         cropLeft = cropLeft * scale;
789
790
791         if (channels >= 1) {
792             emit prepareAudioThumb(scale, mappedStartPixel, mappedEndPixel, channels);
793         }
794
795         for (int startCache = mappedStartPixel - (mappedStartPixel) % 100; startCache < mappedEndPixel; startCache += 100) {
796             if (m_audioThumbCachePic.contains(startCache) && !m_audioThumbCachePic[startCache].isNull())
797                 painter->drawPixmap(clipStart + startCache - cropLeft, mappedRect.y(),  m_audioThumbCachePic[startCache]);
798         }
799     }
800
801     // Draw effects names
802     if (!m_effectNames.isEmpty() && mapped.width() > 40) {
803         QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
804         QColor bgColor;
805         if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
806             qreal value = m_timeLine->currentValue();
807             txtBounding.setWidth(txtBounding.width() * value);
808             bgColor.setRgb(50 + 200 *(1.0 - value), 50, 50, 100 + 50 * value);
809         } else bgColor.setRgb(50, 50, 90, 180);
810
811         QPainterPath rounded;
812         rounded.moveTo(txtBounding.bottomRight());
813         rounded.arcTo(txtBounding.right() - txtBounding.height() - 2, txtBounding.top() - txtBounding.height(), txtBounding.height() * 2, txtBounding.height() * 2, 270, 90);
814         rounded.lineTo(txtBounding.topLeft());
815         rounded.lineTo(txtBounding.bottomLeft());
816         painter->fillPath(rounded, bgColor);
817         painter->setPen(Qt::lightGray);
818         painter->drawText(txtBounding.adjusted(1, 0, 1, 0), Qt::AlignCenter, m_effectNames);
819     }
820
821     // Draw clip name
822     QColor frameColor(paintColor.darker());
823     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
824         frameColor = QColor(Qt::red);
825     }
826     frameColor.setAlpha(160);
827
828     const QRectF txtBounding2 = painter->boundingRect(mapped, Qt::AlignHCenter | Qt::AlignVCenter, ' ' + m_clipName + ' ');
829     //painter->fillRect(txtBounding2, frameColor);
830     painter->setBrush(frameColor);
831     painter->setPen(Qt::NoPen);
832     painter->drawRoundedRect(txtBounding2, 3, 3);
833     painter->setBrush(QBrush(Qt::NoBrush));
834
835     //painter->setPen(QColor(0, 0, 0, 180));
836     //painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
837     if (m_videoOnly) {
838         painter->drawPixmap(txtBounding2.topLeft() - QPointF(17, -1), m_videoPix);
839     } else if (m_audioOnly) {
840         painter->drawPixmap(txtBounding2.topLeft() - QPointF(17, -1), m_audioPix);
841     }
842     painter->setPen(Qt::white);
843     painter->drawText(txtBounding2, Qt::AlignCenter, m_clipName);
844
845
846     // draw markers
847     if (isEnabled() && m_clip) {
848         QList < CommentedTime > markers = m_clip->commentedSnapMarkers();
849         QList < CommentedTime >::Iterator it = markers.begin();
850         GenTime pos;
851         double framepos;
852         QBrush markerBrush(QColor(120, 120, 0, 140));
853         QPen pen = painter->pen();
854         pen.setColor(QColor(255, 255, 255, 200));
855         pen.setStyle(Qt::DotLine);
856
857         for (; it != markers.end(); ++it) {
858             pos = GenTime((int)((*it).time().frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
859             if (pos > GenTime()) {
860                 if (pos > cropDuration()) break;
861                 QLineF l(rect().x() + pos.frames(m_fps), rect().y(), rect().x() + pos.frames(m_fps), rect().bottom());
862                 QLineF l2 = painter->matrix().map(l);
863                 painter->setPen(pen);
864                 painter->drawLine(l2);
865                 if (KdenliveSettings::showmarkers()) {
866                     framepos = rect().x() + pos.frames(m_fps);
867                     const QRectF r1(framepos + 0.04, 10, rect().width() - framepos - 2, rect().height() - 10);
868                     const QRectF r2 = painter->matrix().mapRect(r1);
869                     const QRectF txtBounding3 = painter->boundingRect(r2, Qt::AlignLeft | Qt::AlignTop, ' ' + (*it).comment() + ' ');
870                     painter->setBrush(markerBrush);
871                     painter->setPen(Qt::NoPen);
872                     painter->drawRoundedRect(txtBounding3, 3, 3);
873                     painter->setBrush(QBrush(Qt::NoBrush));
874                     painter->setPen(Qt::white);
875                     painter->drawText(txtBounding3, Qt::AlignCenter, (*it).comment());
876                 }
877                 //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
878             }
879         }
880     }
881
882     // draw start / end fades
883     QBrush fades;
884     if (isSelected()) {
885         fades = QBrush(QColor(200, 50, 50, 150));
886     } else fades = QBrush(QColor(200, 200, 200, 200));
887
888     if (m_startFade != 0) {
889         QPainterPath fadeInPath;
890         fadeInPath.moveTo(0, 0);
891         fadeInPath.lineTo(0, rect().height());
892         fadeInPath.lineTo(m_startFade, 0);
893         fadeInPath.closeSubpath();
894         QPainterPath f1 = painter->matrix().map(fadeInPath);
895         painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
896         /*if (isSelected()) {
897             QLineF l(m_startFade * scale, 0, 0, itemHeight);
898             painter->drawLine(l);
899         }*/
900     }
901     if (m_endFade != 0) {
902         QPainterPath fadeOutPath;
903         fadeOutPath.moveTo(rect().width(), 0);
904         fadeOutPath.lineTo(rect().width(), rect().height());
905         fadeOutPath.lineTo(rect().width() - m_endFade, 0);
906         fadeOutPath.closeSubpath();
907         QPainterPath f1 = painter->matrix().map(fadeOutPath);
908         painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
909         /*if (isSelected()) {
910             QLineF l(itemWidth - m_endFade * scale, 0, itemWidth, itemHeight);
911             painter->drawLine(l);
912         }*/
913     }
914
915
916     painter->setPen(QPen(Qt::lightGray));
917     // draw effect or transition keyframes
918     if (mapped.width() > 20) drawKeyFrames(painter, exposed);
919
920     //painter->setMatrixEnabled(true);
921
922     // draw clip border
923     // expand clip rect to allow correct painting of clip border
924     QPen pen1(frameColor);
925     painter->setPen(pen1);
926     painter->setClipping(false);
927     painter->drawRect(painter->matrix().mapRect(rect()));
928 }
929
930
931 OPERATIONTYPE ClipItem::operationMode(QPointF pos)
932 {
933     if (isItemLocked()) return NONE;
934     const double scale = projectScene()->scale().x();
935     double maximumOffset = 6 / scale;
936     if (isSelected() || (parentItem() && parentItem()->isSelected())) {
937         int kf = mouseOverKeyFrames(pos, maximumOffset);
938         if (kf != -1) {
939             m_editedKeyframe = kf;
940             return KEYFRAME;
941         }
942     }
943     QRectF rect = sceneBoundingRect();
944     int addtransitionOffset = 10;
945     // Don't allow add transition if track height is very small
946     if (rect.height() < 30) addtransitionOffset = 0;
947
948     if (qAbs((int)(pos.x() - (rect.x() + m_startFade))) < maximumOffset  && qAbs((int)(pos.y() - rect.y())) < 6) {
949         if (m_startFade == 0) setToolTip(i18n("Add audio fade"));
950         // xgettext:no-c-format
951         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_startFade, m_fps).seconds()));
952         return FADEIN;
953     } else if (pos.x() - rect.x() < maximumOffset && (rect.bottom() - pos.y() > addtransitionOffset)) {
954         // xgettext:no-c-format
955         setToolTip(i18n("Crop from start: %1s", cropStart().seconds()));
956         return RESIZESTART;
957     } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - m_endFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
958         if (m_endFade == 0) setToolTip(i18n("Add audio fade"));
959         // xgettext:no-c-format
960         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_endFade, m_fps).seconds()));
961         return FADEOUT;
962     } else if ((rect.right() - pos.x() < maximumOffset) && (rect.bottom() - pos.y() > addtransitionOffset)) {
963         // xgettext:no-c-format
964         setToolTip(i18n("Clip duration: %1s", cropDuration().seconds()));
965         return RESIZEEND;
966     } else if ((pos.x() - rect.x() < 16 / scale) && (rect.bottom() - pos.y() <= addtransitionOffset)) {
967         setToolTip(i18n("Add transition"));
968         return TRANSITIONSTART;
969     } else if ((rect.right() - pos.x() < 16 / scale) && (rect.bottom() - pos.y() <= addtransitionOffset)) {
970         setToolTip(i18n("Add transition"));
971         return TRANSITIONEND;
972     }
973     QString tooltip = "<b>" + m_clipName + "</b>";
974     if (!baseClip()->fileURL().isEmpty())
975         tooltip.append("<br />" + baseClip()->fileURL().path());
976     if (!baseClip()->description().isEmpty())
977         tooltip.append("<br />" + baseClip()->description());
978     setToolTip(tooltip);
979     return MOVE;
980 }
981
982 QList <GenTime> ClipItem::snapMarkers() const
983 {
984     QList < GenTime > snaps;
985     QList < GenTime > markers = baseClip()->snapMarkers();
986     GenTime pos;
987
988     for (int i = 0; i < markers.size(); i++) {
989         pos = GenTime((int)(markers.at(i).frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
990         if (pos > GenTime()) {
991             if (pos > cropDuration()) break;
992             else snaps.append(pos + startPos());
993         }
994     }
995     return snaps;
996 }
997
998 QList <CommentedTime> ClipItem::commentedSnapMarkers() const
999 {
1000     QList < CommentedTime > snaps;
1001     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
1002     GenTime pos;
1003
1004     for (int i = 0; i < markers.size(); i++) {
1005         pos = GenTime((int)(markers.at(i).time().frames(m_fps) / qAbs(m_speed) + 0.5), m_fps) - cropStart();
1006         if (pos > GenTime()) {
1007             if (pos > cropDuration()) break;
1008             else snaps.append(CommentedTime(pos + startPos(), markers.at(i).comment()));
1009         }
1010     }
1011     return snaps;
1012 }
1013
1014 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, int startpixel, int endpixel, int channels)
1015 {
1016     QRectF re =  sceneBoundingRect();
1017     if (m_clipType == AV && !isAudioOnly()) re.setTop(re.y() + re.height() / 2);
1018
1019     //kDebug() << "// PREP AUDIO THMB FRMO : scale:" << pixelForOneFrame<< ", from: " << startpixel << ", to: " << endpixel;
1020     //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
1021
1022     for (int startCache = startpixel - startpixel % 100; startCache < endpixel; startCache += 100) {
1023         //kDebug() << "creating " << startCache;
1024         //if (framePixelWidth!=pixelForOneFrame  ||
1025         if (m_framePixelWidth == pixelForOneFrame && m_audioThumbCachePic.contains(startCache))
1026             continue;
1027         if (m_audioThumbCachePic[startCache].isNull() || m_framePixelWidth != pixelForOneFrame) {
1028             m_audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
1029             m_audioThumbCachePic[startCache].fill(QColor(180, 180, 200, 140));
1030         }
1031         bool fullAreaDraw = pixelForOneFrame < 10;
1032         QMap<int, QPainterPath > positiveChannelPaths;
1033         QMap<int, QPainterPath > negativeChannelPaths;
1034         QPainter pixpainter(&m_audioThumbCachePic[startCache]);
1035         QPen audiopen;
1036         audiopen.setWidth(0);
1037         pixpainter.setPen(audiopen);
1038         //pixpainter.setRenderHint(QPainter::Antialiasing,true);
1039         //pixpainter.drawLine(0,0,100,re.height());
1040         // Bail out, if caller provided invalid data
1041         if (channels <= 0) {
1042             kWarning() << "Unable to draw image with " << channels << "number of channels";
1043             return;
1044         }
1045
1046         int channelHeight = m_audioThumbCachePic[startCache].height() / channels;
1047
1048         for (int i = 0; i < channels; i++) {
1049
1050             positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
1051             negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
1052         }
1053
1054         for (int samples = 0; samples <= 100; samples++) {
1055             double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
1056             int sample = (int)((frame - (int)(frame)) * 20);   // AUDIO_FRAME_SIZE
1057             if (frame < 0 || sample < 0 || sample > 19)
1058                 continue;
1059             QMap<int, QByteArray> frame_channel_data = baseClip()->m_audioFrameCache[(int)frame];
1060
1061             for (int channel = 0; channel < channels && frame_channel_data[channel].size() > 0; channel++) {
1062
1063                 int y = channelHeight * channel + channelHeight / 2;
1064                 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2)  * channelHeight / 64;
1065                 if (fullAreaDraw) {
1066                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
1067                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
1068                 } else {
1069                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
1070                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
1071                 }
1072             }
1073             for (int channel = 0; channel < channels ; channel++)
1074                 if (fullAreaDraw && samples == 100) {
1075                     positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
1076                     negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
1077                     positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
1078                     negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
1079                 }
1080
1081         }
1082         pixpainter.setPen(QPen(QColor(0, 0, 0)));
1083         pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
1084
1085         for (int i = 0; i < channels; i++) {
1086             if (fullAreaDraw) {
1087                 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
1088                 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
1089             } else
1090                 pixpainter.drawPath(positiveChannelPaths[i]);
1091         }
1092     }
1093     //audioThumbWasDrawn=true;
1094     m_framePixelWidth = pixelForOneFrame;
1095
1096     //}
1097 }
1098
1099 int ClipItem::fadeIn() const
1100 {
1101     return m_startFade;
1102 }
1103
1104 int ClipItem::fadeOut() const
1105 {
1106     return m_endFade;
1107 }
1108
1109
1110 void ClipItem::setFadeIn(int pos)
1111 {
1112     if (pos == m_startFade) return;
1113     int oldIn = m_startFade;
1114     if (pos < 0) pos = 0;
1115     if (pos > cropDuration().frames(m_fps)) pos = (int)(cropDuration().frames(m_fps));
1116     m_startFade = pos;
1117     QRectF rect = boundingRect();
1118     update(rect.x(), rect.y(), qMax(oldIn, pos), rect.height());
1119 }
1120
1121 void ClipItem::setFadeOut(int pos)
1122 {
1123     if (pos == m_endFade) return;
1124     int oldOut = m_endFade;
1125     if (pos < 0) pos = 0;
1126     if (pos > cropDuration().frames(m_fps)) pos = (int)(cropDuration().frames(m_fps));
1127     m_endFade = pos;
1128     QRectF rect = boundingRect();
1129     update(rect.x() + rect.width() - qMax(oldOut, pos), rect.y(), qMax(oldOut, pos), rect.height());
1130
1131 }
1132
1133 void ClipItem::setFades(int in, int out)
1134 {
1135     m_startFade = in;
1136     m_endFade = out;
1137 }
1138
1139 /*
1140 //virtual
1141 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e)
1142 {
1143     //if (e->pos().x() < 20) m_hover = true;
1144     return;
1145     if (isItemLocked()) return;
1146     m_hover = true;
1147     QRectF r = boundingRect();
1148     double width = 35 / projectScene()->scale().x();
1149     double height = r.height() / 2;
1150     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
1151     update(r.x(), r.y() + height, width, height);
1152     update(r.right() - width, r.y() + height, width, height);
1153 }
1154
1155 //virtual
1156 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *)
1157 {
1158     if (isItemLocked()) return;
1159     m_hover = false;
1160     QRectF r = boundingRect();
1161     double width = 35 / projectScene()->scale().x();
1162     double height = r.height() / 2;
1163     //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
1164     update(r.x(), r.y() + height, width, height);
1165     update(r.right() - width, r.y() + height, width, height);
1166 }
1167 */
1168
1169 void ClipItem::resizeStart(int posx, bool /*size*/)
1170 {
1171     bool sizeLimit = false;
1172     if (clipType() != IMAGE && clipType() != COLOR && clipType() != TEXT) {
1173         const int min = (startPos() - cropStart()).frames(m_fps);
1174         if (posx < min) posx = min;
1175         sizeLimit = true;
1176     }
1177
1178     if (posx == startPos().frames(m_fps)) return;
1179     const int previous = cropStart().frames(m_fps);
1180     AbstractClipItem::resizeStart(posx, sizeLimit);
1181
1182     // set speed independant info
1183     m_speedIndependantInfo = m_info;
1184     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * qAbs(m_speed)), m_fps);
1185     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * qAbs(m_speed)), m_fps);
1186
1187     if ((int) cropStart().frames(m_fps) != previous) {
1188         if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
1189             m_startThumbTimer.start(150);
1190         }
1191     }
1192 }
1193
1194 void ClipItem::resizeEnd(int posx)
1195 {
1196     const int max = (startPos() - cropStart() + maxDuration()).frames(m_fps);
1197     if (posx > max && maxDuration() != GenTime()) posx = max;
1198     if (posx == endPos().frames(m_fps)) return;
1199     //kDebug() << "// NEW POS: " << posx << ", OLD END: " << endPos().frames(m_fps);
1200     const int previous = cropDuration().frames(m_fps);
1201     AbstractClipItem::resizeEnd(posx);
1202
1203     // set speed independant info
1204     m_speedIndependantInfo = m_info;
1205     m_speedIndependantInfo.cropStart = GenTime((int)(m_info.cropStart.frames(m_fps) * qAbs(m_speed)), m_fps);
1206     m_speedIndependantInfo.cropDuration = GenTime((int)(m_info.cropDuration.frames(m_fps) * qAbs(m_speed)), m_fps);
1207
1208     if ((int) cropDuration().frames(m_fps) != previous) {
1209         if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
1210             m_endThumbTimer.start(150);
1211         }
1212     }
1213 }
1214
1215
1216 bool ClipItem::checkEffectsKeyframesPos(const int previous, const int current, bool fromStart)
1217 {
1218     bool effModified = false;
1219     for (int i = 0; i < m_effectList.count(); i++) {
1220         QDomElement effect = m_effectList.at(i);
1221         QDomNodeList params = effect.elementsByTagName("parameter");
1222         for (int j = 0; j < params.count(); j++) {
1223             bool modified = false;
1224             QDomElement e = params.item(j).toElement();
1225             if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1226                 // parse keyframes and adjust values
1227                 const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
1228                 QMap <int, double> kfr;
1229                 int pos;
1230                 double val;
1231                 foreach(const QString &str, keyframes) {
1232                     pos = str.section(':', 0, 0).toInt();
1233                     val = str.section(':', 1, 1).toDouble();
1234                     if (pos == previous) {
1235                         // first or last keyframe
1236                         kfr[current] = val;
1237                         modified = true;
1238                     } else {
1239                         if ((fromStart && pos >= current) || (!fromStart && pos <= current)) {
1240                             // only keyframes in range
1241                             kfr[pos] = val;
1242                             modified = true;
1243                         }
1244                     }
1245                 }
1246                 if (modified) {
1247                     effModified = true;
1248                     QString newkfr;
1249                     QMap<int, double>::const_iterator k = kfr.constBegin();
1250                     while (k != kfr.constEnd()) {
1251                         newkfr.append(QString::number(k.key()) + ':' + QString::number(k.value()) + ';');
1252                         ++k;
1253                     }
1254                     e.setAttribute("keyframes", newkfr);
1255                 }
1256             }
1257         }
1258     }
1259     if (effModified && m_selectedEffect >= 0) setSelectedEffect(m_selectedEffect);
1260     return effModified;
1261 }
1262
1263 //virtual
1264 QVariant ClipItem::itemChange(GraphicsItemChange change, const QVariant &value)
1265 {
1266     if (change == QGraphicsItem::ItemSelectedChange) {
1267         if (value.toBool()) setZValue(10);
1268         else setZValue(2);
1269     }
1270     if (change == ItemPositionChange && scene()) {
1271         // calculate new position.
1272         //if (parentItem()) return pos();
1273         QPointF newPos = value.toPointF();
1274         //kDebug() << "/// MOVING CLIP ITEM.------------\n++++++++++";
1275         int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
1276         xpos = qMax(xpos, 0);
1277         newPos.setX(xpos);
1278         int newTrack = newPos.y() / KdenliveSettings::trackheight();
1279         newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
1280         newTrack = qMax(newTrack, 0);
1281         newPos.setY((int)(newTrack  * KdenliveSettings::trackheight() + 1));
1282         // Only one clip is moving
1283         QRectF sceneShape = rect();
1284         sceneShape.translate(newPos);
1285         QList<QGraphicsItem*> items;
1286         if (projectScene()->editMode() == NORMALEDIT)
1287             items = scene()->items(sceneShape, Qt::IntersectsItemShape);
1288         items.removeAll(this);
1289         bool forwardMove = newPos.x() > pos().x();
1290         int offset = 0;
1291         if (!items.isEmpty()) {
1292             for (int i = 0; i < items.count(); i++) {
1293                 if (!items.at(i)->isEnabled()) continue;
1294                 if (items.at(i)->type() == type()) {
1295                     // Collision!
1296                     QPointF otherPos = items.at(i)->pos();
1297                     if ((int) otherPos.y() != (int) pos().y()) {
1298                         return pos();
1299                     }
1300                     if (forwardMove) {
1301                         offset = qMax(offset, (int)(newPos.x() - (static_cast < AbstractClipItem* >(items.at(i))->startPos() - cropDuration()).frames(m_fps)));
1302                     } else {
1303                         offset = qMax(offset, (int)((static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps)) - newPos.x()));
1304                     }
1305
1306                     if (offset > 0) {
1307                         if (forwardMove) {
1308                             sceneShape.translate(QPointF(-offset, 0));
1309                             newPos.setX(newPos.x() - offset);
1310                         } else {
1311                             sceneShape.translate(QPointF(offset, 0));
1312                             newPos.setX(newPos.x() + offset);
1313                         }
1314                         QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
1315                         subitems.removeAll(this);
1316                         for (int j = 0; j < subitems.count(); j++) {
1317                             if (!subitems.at(j)->isEnabled()) continue;
1318                             if (subitems.at(j)->type() == type()) {
1319                                 // move was not successful, revert to previous pos
1320                                 m_info.startPos = GenTime((int) pos().x(), m_fps);
1321                                 return pos();
1322                             }
1323                         }
1324                     }
1325
1326                     m_info.track = newTrack;
1327                     m_info.startPos = GenTime((int) newPos.x(), m_fps);
1328
1329                     return newPos;
1330                 }
1331             }
1332         }
1333         m_info.track = newTrack;
1334         m_info.startPos = GenTime((int) newPos.x(), m_fps);
1335         //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
1336         return newPos;
1337     }
1338     return QGraphicsItem::itemChange(change, value);
1339 }
1340
1341 // virtual
1342 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
1343 }*/
1344
1345 int ClipItem::effectsCounter()
1346 {
1347     return effectsCount() + 1;
1348 }
1349
1350 int ClipItem::effectsCount()
1351 {
1352     return m_effectList.count();
1353 }
1354
1355 int ClipItem::hasEffect(const QString &tag, const QString &id) const
1356 {
1357     return m_effectList.hasEffect(tag, id);
1358 }
1359
1360 QStringList ClipItem::effectNames()
1361 {
1362     return m_effectList.effectNames();
1363 }
1364
1365 QDomElement ClipItem::effectAt(int ix) const
1366 {
1367     if (ix > m_effectList.count() - 1 || ix < 0 || m_effectList.at(ix).isNull()) return QDomElement();
1368     return m_effectList.at(ix).cloneNode().toElement();
1369 }
1370
1371 QDomElement ClipItem::getEffectAt(int ix) const
1372 {
1373     if (ix > m_effectList.count() - 1 || ix < 0 || m_effectList.at(ix).isNull()) return QDomElement();
1374     return m_effectList.at(ix);
1375 }
1376
1377 void ClipItem::setEffectAt(int ix, QDomElement effect)
1378 {
1379     if (ix < 0 || ix > (m_effectList.count() - 1) || effect.isNull()) {
1380         kDebug() << "Invalid effect index: " << ix;
1381         return;
1382     }
1383     //kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1384     effect.setAttribute("kdenlive_ix", ix + 1);
1385     m_effectList.replace(ix, effect);
1386     m_effectNames = m_effectList.effectNames().join(" / ");
1387     QString id = effect.attribute("id");
1388     if (id == "fadein" || id == "fadeout" || id == "fade_from_black" || id == "fade_to_black")
1389         update();
1390     else {
1391         QRectF r = boundingRect();
1392         r.setHeight(20);
1393         update(r);
1394     }
1395 }
1396
1397 EffectsParameterList ClipItem::addEffect(const QDomElement effect, bool /*animate*/)
1398 {
1399     bool needRepaint = false;
1400     int ix;
1401     if (!effect.hasAttribute("kdenlive_ix")) {
1402         ix = effectsCounter();
1403     } else ix = effect.attribute("kdenlive_ix").toInt();
1404     if (!m_effectList.isEmpty() && ix <= m_effectList.count()) {
1405         needRepaint = true;
1406         m_effectList.insert(ix - 1, effect);
1407         for (int i = ix; i < m_effectList.count(); i++) {
1408             int index = m_effectList.item(i).attribute("kdenlive_ix").toInt();
1409             if (index >= ix) m_effectList.item(i).setAttribute("kdenlive_ix", index + 1);
1410         }
1411     } else m_effectList.append(effect);
1412     EffectsParameterList parameters;
1413     parameters.addParam("tag", effect.attribute("tag"));
1414     parameters.addParam("kdenlive_ix", effect.attribute("kdenlive_ix"));
1415     if (effect.hasAttribute("src")) parameters.addParam("src", effect.attribute("src"));
1416     if (effect.hasAttribute("disable")) parameters.addParam("disable", effect.attribute("disable"));
1417
1418     QString effectId = effect.attribute("id");
1419     if (effectId.isEmpty()) effectId = effect.attribute("tag");
1420     parameters.addParam("id", effectId);
1421
1422     // special case: the affine effect needs in / out points
1423     if (effectId == "pan_zoom") {
1424         parameters.addParam("in", QString::number(cropStart().frames(m_fps)));
1425         parameters.addParam("out", QString::number((cropStart() + cropDuration()).frames(m_fps)));
1426     }
1427
1428     QDomNodeList params = effect.elementsByTagName("parameter");
1429     int fade = 0;
1430     for (int i = 0; i < params.count(); i++) {
1431         QDomElement e = params.item(i).toElement();
1432         if (!e.isNull()) {
1433             if (e.attribute("type") == "simplekeyframe") {
1434                 QStringList values = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
1435                 double factor = e.attribute("factor", "1").toDouble();
1436                 if (factor != 1) {
1437                     for (int j = 0; j < values.count(); j++) {
1438                         QString pos = values.at(j).section(':', 0, 0);
1439                         double val = values.at(j).section(':', 1, 1).toDouble() / factor;
1440                         values[j] = pos + "=" + QString::number(val);
1441                     }
1442                 }
1443                 parameters.addParam(e.attribute("name"), values.join(";"));
1444                 /*parameters.addParam("max", e.attribute("max"));
1445                 parameters.addParam("min", e.attribute("min"));
1446                 parameters.addParam("factor", );*/
1447             } else if (e.attribute("type") == "keyframe") {
1448                 parameters.addParam("keyframes", e.attribute("keyframes"));
1449                 parameters.addParam("max", e.attribute("max"));
1450                 parameters.addParam("min", e.attribute("min"));
1451                 parameters.addParam("factor", e.attribute("factor", "1"));
1452                 parameters.addParam("starttag", e.attribute("starttag", "start"));
1453                 parameters.addParam("endtag", e.attribute("endtag", "end"));
1454             } else if (e.attribute("factor", "1") == "1") {
1455                 parameters.addParam(e.attribute("name"), e.attribute("value"));
1456
1457                 // check if it is a fade effect
1458                 if (effectId == "fadein") {
1459                     needRepaint = true;
1460                     if (m_effectList.hasEffect(QString(), "fade_from_black") == -1) {
1461                         if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1462                         else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1463                     } else {
1464                         QDomElement fadein = m_effectList.getEffectByTag(QString(), "fade_from_black");
1465                         if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1466                         else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1467                     }
1468                 } else if (effectId == "fade_from_black") {
1469                     needRepaint = true;
1470                     if (m_effectList.hasEffect(QString(), "fadein") == -1) {
1471                         if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1472                         else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1473                     } else {
1474                         QDomElement fadein = m_effectList.getEffectByTag(QString(), "fadein");
1475                         if (fadein.attribute("name") == "out") fade += fadein.attribute("value").toInt();
1476                         else if (fadein.attribute("name") == "in") fade -= fadein.attribute("value").toInt();
1477                     }
1478                 } else if (effectId == "fadeout") {
1479                     needRepaint = true;
1480                     if (m_effectList.hasEffect(QString(), "fade_to_black") == -1) {
1481                         if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1482                         else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1483                     } else {
1484                         QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fade_to_black");
1485                         if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1486                         else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1487                     }
1488                 } else if (effectId == "fade_to_black") {
1489                     needRepaint = true;
1490                     if (m_effectList.hasEffect(QString(), "fadeout") == -1) {
1491                         if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1492                         else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1493                     } else {
1494                         QDomElement fadeout = m_effectList.getEffectByTag(QString(), "fadeout");
1495                         if (fadeout.attribute("name") == "out") fade -= fadeout.attribute("value").toInt();
1496                         else if (fadeout.attribute("name") == "in") fade += fadeout.attribute("value").toInt();
1497                     }
1498                 }
1499             } else {
1500                 double fact;
1501                 if (e.attribute("factor").startsWith('%')) {
1502                     fact = ProfilesDialog::getStringEval(projectScene()->profile(), e.attribute("factor"));
1503                 } else fact = e.attribute("factor", "1").toDouble();
1504                 parameters.addParam(e.attribute("name"), QString::number(e.attribute("value").toDouble() / fact));
1505             }
1506         }
1507     }
1508     m_effectNames = m_effectList.effectNames().join(" / ");
1509     if (fade > 0) m_startFade = fade;
1510     else if (fade < 0) m_endFade = -fade;
1511
1512     if (m_selectedEffect == -1) {
1513         setSelectedEffect(0);
1514     } else if (m_selectedEffect == ix - 1) setSelectedEffect(m_selectedEffect);
1515     if (needRepaint) update(boundingRect());
1516     /*if (animate) {
1517         flashClip();
1518     } */
1519     else { /*if (!needRepaint) */
1520         QRectF r = boundingRect();
1521         r.setHeight(20);
1522         update(r);
1523     }
1524     return parameters;
1525 }
1526
1527 void ClipItem::deleteEffect(QString index)
1528 {
1529     bool needRepaint = false;
1530     QString ix;
1531
1532     for (int i = 0; i < m_effectList.count(); ++i) {
1533         ix = m_effectList.at(i).attribute("kdenlive_ix");
1534         if (ix == index) {
1535             QString effectId = m_effectList.at(i).attribute("id");
1536             if ((effectId == "fadein" && hasEffect(QString(), "fade_from_black") == -1) ||
1537                     (effectId == "fade_from_black" && hasEffect(QString(), "fadein") == -1)) {
1538                 m_startFade = 0;
1539                 needRepaint = true;
1540             } else if ((effectId == "fadeout" && hasEffect(QString(), "fade_to_black") == -1) ||
1541                        (effectId == "fade_to_black" && hasEffect(QString(), "fadeout") == -1)) {
1542                 m_endFade = 0;
1543                 needRepaint = true;
1544             } else if (EffectsList::hasKeyFrames(m_effectList.at(i))) needRepaint = true;
1545             m_effectList.removeAt(i);
1546             i--;
1547         } else if (ix.toInt() > index.toInt()) {
1548             m_effectList.item(i).setAttribute("kdenlive_ix", ix.toInt() - 1);
1549         }
1550     }
1551     m_effectNames = m_effectList.effectNames().join(" / ");
1552
1553     if (m_effectList.isEmpty() || m_selectedEffect + 1 == index.toInt()) {
1554         // Current effect was removed
1555         if (index.toInt() > m_effectList.count() - 1) {
1556             setSelectedEffect(m_effectList.count() - 1);
1557         } else setSelectedEffect(index.toInt());
1558     }
1559     if (needRepaint) update(boundingRect());
1560     else {
1561         QRectF r = boundingRect();
1562         r.setHeight(20);
1563         update(r);
1564     }
1565     //if (!m_effectList.isEmpty()) flashClip();
1566 }
1567
1568 double ClipItem::speed() const
1569 {
1570     return m_speed;
1571 }
1572
1573 int ClipItem::strobe() const
1574 {
1575     return m_strobe;
1576 }
1577
1578 void ClipItem::setSpeed(const double speed, const int strobe)
1579 {
1580     m_speed = speed;
1581     if (m_speed <= 0 && m_speed > -1)
1582         m_speed = -1.0;
1583     m_strobe = strobe;
1584     if (m_speed == 1.0) m_clipName = baseClip()->name();
1585     else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + '%';
1586     m_info.cropStart = GenTime((int)(m_speedIndependantInfo.cropStart.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1587     m_info.cropDuration = GenTime((int)(m_speedIndependantInfo.cropDuration.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1588     //update();
1589 }
1590
1591 GenTime ClipItem::maxDuration() const
1592 {
1593     return GenTime((int)(m_maxDuration.frames(m_fps) / qAbs(m_speed) + 0.5), m_fps);
1594 }
1595
1596 GenTime ClipItem::speedIndependantCropStart() const
1597 {
1598     return m_speedIndependantInfo.cropStart;
1599 }
1600
1601 GenTime ClipItem::speedIndependantCropDuration() const
1602 {
1603     return m_speedIndependantInfo.cropDuration;
1604 }
1605
1606
1607 const ItemInfo ClipItem::speedIndependantInfo() const
1608 {
1609     return m_speedIndependantInfo;
1610 }
1611
1612 //virtual
1613 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event)
1614 {
1615     const QString effects = QString(event->mimeData()->data("kdenlive/effectslist"));
1616     QDomDocument doc;
1617     doc.setContent(effects, true);
1618     const QDomElement e = doc.documentElement();
1619     if (scene() && !scene()->views().isEmpty()) {
1620         event->accept();
1621         CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1622         if (view) view->slotAddEffect(e, m_info.startPos, track());
1623     }
1624 }
1625
1626 //virtual
1627 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
1628 {
1629     if (isItemLocked()) event->setAccepted(false);
1630     else event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
1631 }
1632
1633 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
1634 {
1635     Q_UNUSED(event);
1636 }
1637
1638 void ClipItem::addTransition(Transition* t)
1639 {
1640     m_transitionsList.append(t);
1641     //CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1642     QDomDocument doc;
1643     QDomElement e = doc.documentElement();
1644     //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1645 }
1646
1647 void ClipItem::setVideoOnly(bool force)
1648 {
1649     m_videoOnly = force;
1650 }
1651
1652 void ClipItem::setAudioOnly(bool force)
1653 {
1654     m_audioOnly = force;
1655     if (m_audioOnly) m_baseColor = QColor(141, 215, 166);
1656     else {
1657         if (m_clipType == COLOR) {
1658             QString colour = m_clip->getProperty("colour");
1659             colour = colour.replace(0, 2, "#");
1660             m_baseColor = QColor(colour.left(7));
1661         } else if (m_clipType == AUDIO) m_baseColor = QColor(141, 215, 166);
1662         else m_baseColor = QColor(141, 166, 215);
1663     }
1664     m_audioThumbCachePic.clear();
1665 }
1666
1667 bool ClipItem::isAudioOnly() const
1668 {
1669     return m_audioOnly;
1670 }
1671
1672 bool ClipItem::isVideoOnly() const
1673 {
1674     return m_videoOnly;
1675 }
1676
1677 void ClipItem::insertKeyframe(QDomElement effect, int pos, int val)
1678 {
1679     if (effect.attribute("disable") == "1") return;
1680     effect.setAttribute("active_keyframe", pos);
1681     m_editedKeyframe = pos;
1682     QDomNodeList params = effect.elementsByTagName("parameter");
1683     for (int i = 0; i < params.count(); i++) {
1684         QDomElement e = params.item(i).toElement();
1685         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1686             QString kfr = e.attribute("keyframes");
1687             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
1688             QStringList newkfr;
1689             bool added = false;
1690             foreach(const QString &str, keyframes) {
1691                 int kpos = str.section(':', 0, 0).toInt();
1692                 double newval = str.section(':', 1, 1).toDouble();
1693                 if (kpos < pos) {
1694                     newkfr.append(str);
1695                 } else if (!added) {
1696                     if (i == m_visibleParam)
1697                         newkfr.append(QString::number(pos) + ":" + QString::number(val));
1698                     else
1699                         newkfr.append(QString::number(pos) + ":" + QString::number(newval));
1700                     if (kpos > pos) newkfr.append(str);
1701                     added = true;
1702                 } else newkfr.append(str);
1703             }
1704             if (!added) {
1705                 if (i == m_visibleParam)
1706                     newkfr.append(QString::number(pos) + ":" + QString::number(val));
1707                 else
1708                     newkfr.append(QString::number(pos) + ":" + e.attribute("default"));
1709             }
1710             e.setAttribute("keyframes", newkfr.join(";"));
1711         }
1712     }
1713 }
1714
1715 void ClipItem::movedKeyframe(QDomElement effect, int oldpos, int newpos, double value)
1716 {
1717     if (effect.attribute("disable") == "1") return;
1718     effect.setAttribute("active_keyframe", newpos);
1719     QDomNodeList params = effect.elementsByTagName("parameter");
1720     int start = cropStart().frames(m_fps);
1721     int end = (cropStart() + cropDuration()).frames(m_fps) - 1;
1722     for (int i = 0; i < params.count(); i++) {
1723         QDomElement e = params.item(i).toElement();
1724         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1725             QString kfr = e.attribute("keyframes");
1726             const QStringList keyframes = kfr.split(';', QString::SkipEmptyParts);
1727             QStringList newkfr;
1728             foreach(const QString &str, keyframes) {
1729                 if (str.section(':', 0, 0).toInt() != oldpos) {
1730                     newkfr.append(str);
1731                 } else if (newpos != -1) {
1732                     newpos = qMax(newpos, start);
1733                     newpos = qMin(newpos, end);
1734                     if (i == m_visibleParam)
1735                         newkfr.append(QString::number(newpos) + ":" + QString::number(value));
1736                     else
1737                         newkfr.append(QString::number(newpos) + ":" + str.section(':', 1, 1));
1738                 }
1739             }
1740             e.setAttribute("keyframes", newkfr.join(";"));
1741         }
1742     }
1743
1744     updateKeyframes(effect);
1745     update();
1746 }
1747
1748 void ClipItem::updateKeyframes(QDomElement effect)
1749 {
1750     m_keyframes.clear();
1751     // parse keyframes
1752     QDomNodeList params = effect.elementsByTagName("parameter");
1753     QDomElement e = params.item(m_visibleParam).toElement();
1754     if (e.attribute("intimeline") != "1") {
1755         setSelectedEffect(m_selectedEffect);
1756         return;
1757     }
1758     const QStringList keyframes = e.attribute("keyframes").split(';', QString::SkipEmptyParts);
1759     foreach(const QString &str, keyframes) {
1760         int pos = str.section(':', 0, 0).toInt();
1761         double val = str.section(':', 1, 1).toDouble();
1762         m_keyframes[pos] = val;
1763     }
1764     if (!m_keyframes.contains(m_selectedKeyframe)) m_selectedKeyframe = -1;
1765 }
1766
1767 void ClipItem::doGetIntraThumbs(QPainter *painter, const QPointF startPos, int offset, int start, int end)
1768 {
1769     if (!m_clip->thumbProducer() || clipType() == COLOR) return;
1770     if (scene() && scene()->views().isEmpty()) return;
1771     CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1772     if (view == NULL) return;
1773     const int theight = KdenliveSettings::trackheight();
1774     const int twidth = FRAME_SIZE;
1775
1776     if (clipType() == IMAGE || clipType() == TEXT) {
1777         for (int i = start; i <= end; i++)
1778             painter->drawPixmap(startPos + QPointF(twidth *(i - offset), 0), m_startPix);
1779     }
1780     QPixmap p;
1781     for (int i = start; i <= end; i++) {
1782         if (!view->pixmapCache->find(m_clip->fileURL().path() + "%" + QString::number(i), p)) {
1783             p = m_clip->thumbProducer()->extractImage(i, twidth, theight);
1784             view->pixmapCache->insert(m_clip->fileURL().path() + "%" + QString::number(i), p);
1785         }
1786         painter->drawPixmap(startPos + QPointF(twidth *(i - offset), 0), p);
1787     }
1788 }
1789
1790 QList <int> ClipItem::updatePanZoom(int width, int height, int cut)
1791 {
1792     QList <int> effectPositions;
1793     for (int i = 0; i < m_effectList.count(); i++) {
1794         QDomElement effect = m_effectList.at(i);
1795         QDomNodeList params = effect.elementsByTagName("parameter");
1796         for (int j = 0; j < params.count(); j++) {
1797             QDomElement e = params.item(j).toElement();
1798             if (e.isNull())
1799                 continue;
1800             if (e.attribute("type") == "geometry" && !e.hasAttribute("fixed")) {
1801                 effectPositions << i;
1802
1803                 int in = cropStart().frames(fps());
1804                 int out = in + cropDuration().frames(fps());
1805                 int dur = out - in - 1;
1806
1807                 effect.setAttribute("in", in);
1808                 effect.setAttribute("out", out);
1809
1810                 Mlt::Geometry geometry(e.attribute("value").toUtf8().data(), dur, width, height);
1811                 Mlt::GeometryItem item;
1812                 bool endFrameAdded = false;
1813                 if (cut == 0) {
1814                     while (!geometry.next_key(&item, dur)) {
1815                         if (!endFrameAdded) {
1816                             // add keyframe at the end with interpolated value
1817
1818                             // but only once ;)
1819                             endFrameAdded = true;
1820
1821                             Mlt::GeometryItem endItem;
1822                             Mlt::GeometryItem interp;
1823                             geometry.fetch(&interp, dur - 1);
1824                             endItem.frame(dur - 1);
1825                             endItem.x(interp.x());
1826                             endItem.y(interp.y());
1827                             endItem.w(interp.w());
1828                             endItem.h(interp.h());
1829                             endItem.mix(interp.mix());
1830                             geometry.insert(&endItem);
1831                         }
1832                         geometry.remove(item.frame());
1833                     }
1834                 } else {
1835                     Mlt::Geometry origGeometry(e.attribute("value").toUtf8().data(), dur, width, height);
1836                     // remove keyframes before cut point
1837                     while (!geometry.prev_key(&item, cut - 1) && item.frame() < cut)
1838                         geometry.remove(item.frame());
1839
1840                     // add a keyframe at new pos 0
1841                     origGeometry.fetch(&item, cut);
1842                     item.frame(0);
1843                     geometry.insert(&item);
1844
1845                     // move exisiting keyframes by -cut
1846                     while (!origGeometry.next_key(&item, cut)) {
1847                         geometry.remove(item.frame());
1848                         origGeometry.remove(item.frame());
1849                         item.frame(item.frame() - cut);
1850                         geometry.insert(&item);
1851                     }
1852                     
1853                 }
1854
1855                 e.setAttribute("value", geometry.serialise());
1856             }
1857         }
1858     }
1859
1860     return effectPositions;
1861 }
1862
1863 Mlt::Producer *ClipItem::getProducer(int track, bool trackSpecific)
1864 {
1865     if (isAudioOnly())
1866         return m_clip->audioProducer(track);
1867     else if (isVideoOnly())
1868         return m_clip->videoProducer();
1869     else
1870         return m_clip->producer(trackSpecific ? track : -1);
1871 }
1872
1873 #include "clipitem.moc"