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