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