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