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