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