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