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