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