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