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