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