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