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