]> git.sesse.net Git - kdenlive/blob - src/clipitem.cpp
8235ff55a51b781f2f73e199113dbb67c9883540
[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
22 #include <QPainter>
23 #include <QTimer>
24 #include <QStyleOptionGraphicsItem>
25 #include <QGraphicsScene>
26 #include <QGraphicsView>
27 #include <QScrollBar>
28 #include <QMimeData>
29 #include <QApplication>
30
31 #include <KDebug>
32
33 #include "clipitem.h"
34 #include "customtrackview.h"
35 #include "renderer.h"
36 #include "docclipbase.h"
37 #include "transition.h"
38 #include "events.h"
39 #include "kdenlivesettings.h"
40 #include "kthumb.h"
41
42 ClipItem::ClipItem(DocClipBase *clip, ItemInfo info, double scale, double fps)
43         : AbstractClipItem(info, QRectF(), fps), m_clip(clip), m_resizeMode(NONE), m_grabPoint(0), m_maxTrack(0), m_hasThumbs(false), startThumbTimer(NULL), endThumbTimer(NULL), m_effectsCounter(1), audioThumbWasDrawn(false), m_opacity(1.0), m_timeLine(0), m_thumbsRequested(0), m_startFade(0), m_endFade(0), m_hover(false), m_selectedEffect(-1), m_speed(1.0) {
44     QRectF rect((double) info.startPos.frames(fps) * scale, (double)(info.track * KdenliveSettings::trackheight() + 1), (double)(info.endPos - info.startPos).frames(fps) * scale, (double)(KdenliveSettings::trackheight() - 1));
45     setRect(rect);
46
47     m_clipName = clip->name();
48     m_producer = clip->getId();
49     m_clipType = clip->clipType();
50     m_cropStart = info.cropStart;
51     m_maxDuration = clip->maxDuration();
52     setAcceptDrops(true);
53     audioThumbReady = clip->audioThumbCreated();
54
55     /*
56       m_cropStart = xml.attribute("in", 0).toInt();
57       m_maxDuration = xml.attribute("duration", 0).toInt();
58       if (m_maxDuration == 0) m_maxDuration = xml.attribute("out", 0).toInt() - m_cropStart;
59
60       if (duration != -1) m_cropDuration = duration;
61       else m_cropDuration = m_maxDuration;*/
62
63
64     setFlags(QGraphicsItem::ItemClipsToShape | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
65     setAcceptsHoverEvents(true);
66     connect(this , SIGNAL(prepareAudioThumb(double, QPainterPath, int, int, int)) , this, SLOT(slotPrepareAudioThumb(double, QPainterPath, int, int, int)));
67
68     setBrush(QColor(141, 166, 215));
69     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW) {
70         m_hasThumbs = true;
71         connect(this, SIGNAL(getThumb(int, int)), clip->thumbProducer(), SLOT(extractImage(int, int)));
72         connect(clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));
73         connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
74         QTimer::singleShot(300, this, SLOT(slotFetchThumbs()));
75
76         startThumbTimer = new QTimer(this);
77         startThumbTimer->setSingleShot(true);
78         connect(startThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetStartThumb()));
79         endThumbTimer = new QTimer(this);
80         endThumbTimer->setSingleShot(true);
81         connect(endThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetEndThumb()));
82     } else if (m_clipType == COLOR) {
83         QString colour = clip->getProperty("colour");
84         colour = colour.replace(0, 2, "#");
85         setBrush(QColor(colour.left(7)));
86     } else if (m_clipType == IMAGE || m_clipType == TEXT) {
87         m_startPix = KThumb::getImage(KUrl(clip->getProperty("resource")), (int)(50 * KdenliveSettings::project_display_ratio()), 50);
88         m_endPix = m_startPix;
89     } else if (m_clipType == AUDIO) {
90         connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
91     }
92 }
93
94
95 ClipItem::~ClipItem() {
96     if (startThumbTimer) delete startThumbTimer;
97     if (endThumbTimer) delete endThumbTimer;
98 }
99
100 ClipItem *ClipItem::clone(double scale) const {
101     ClipItem *duplicate = new ClipItem(m_clip, info(), scale, m_fps);
102     duplicate->setEffectList(m_effectList);
103     return duplicate;
104 }
105
106 void ClipItem::setEffectList(const EffectsList effectList) {
107     m_effectList = effectList;
108     m_effectNames = m_effectList.effectNames().join(" / ");
109 }
110
111 const EffectsList ClipItem::effectList() {
112     return m_effectList;
113 }
114
115 int ClipItem::selectedEffectIndex() const {
116     return m_selectedEffect;
117 }
118
119 void ClipItem::initEffect(QDomElement effect) {
120     // the kdenlive_ix int is used to identify an effect in mlt's playlist, should
121     // not be changed
122     if (effect.attribute("kdenlive_ix").toInt() == 0)
123         effect.setAttribute("kdenlive_ix", QString::number(effectsCounter()));
124     // init keyframes if required
125     QDomNodeList params = effect.elementsByTagName("parameter");
126     for (int i = 0; i < params.count(); i++) {
127         QDomElement e = params.item(i).toElement();
128         if (!e.isNull() && e.attribute("type") == "keyframe") {
129             QString def = e.attribute("default");
130             // Effect has a keyframe type parameter, we need to set the values
131             if (e.attribute("keyframes").isEmpty()) {
132                 e.setAttribute("keyframes", QString::number(m_cropStart.frames(m_fps)) + ":" + def + ";" + QString::number((m_cropStart + m_cropDuration).frames(m_fps)) + ":" + def);
133                 //kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
134                 break;
135             }
136         }
137     }
138 }
139
140 void ClipItem::setKeyframes(const int ix, const QString keyframes) {
141     QDomElement effect = effectAt(ix);
142     if (effect.attribute("disabled") == "1") return;
143     QDomNodeList params = effect.elementsByTagName("parameter");
144     for (int i = 0; i < params.count(); i++) {
145         QDomElement e = params.item(i).toElement();
146         if (!e.isNull() && e.attribute("type") == "keyframe") {
147             e.setAttribute("keyframes", keyframes);
148             if (ix == m_selectedEffect) {
149                 m_keyframes.clear();
150                 double max = e.attribute("max").toDouble();
151                 double min = e.attribute("min").toDouble();
152                 m_keyframeFactor = 100.0 / (max - min);
153                 m_keyframeDefault = e.attribute("default").toDouble();
154                 // parse keyframes
155                 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
156                 foreach(const QString str, keyframes) {
157                     int pos = str.section(":", 0, 0).toInt();
158                     double val = str.section(":", 1, 1).toDouble();
159                     m_keyframes[pos] = val;
160                 }
161                 update();
162                 return;
163             }
164             break;
165         }
166     }
167 }
168
169
170 void ClipItem::setSelectedEffect(const int ix) {
171     m_selectedEffect = ix;
172     QDomElement effect = effectAt(m_selectedEffect);
173     QDomNodeList params = effect.elementsByTagName("parameter");
174     if (effect.attribute("disabled") != "1")
175         for (int i = 0; i < params.count(); i++) {
176             QDomElement e = params.item(i).toElement();
177             if (!e.isNull() && e.attribute("type") == "keyframe") {
178                 m_keyframes.clear();
179                 double max = e.attribute("max").toDouble();
180                 double min = e.attribute("min").toDouble();
181                 m_keyframeFactor = 100.0 / (max - min);
182                 m_keyframeDefault = e.attribute("default").toDouble();
183                 // parse keyframes
184                 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
185                 foreach(const QString str, keyframes) {
186                     int pos = str.section(":", 0, 0).toInt();
187                     double val = str.section(":", 1, 1).toDouble();
188                     m_keyframes[pos] = val;
189                 }
190                 update();
191                 return;
192             }
193         }
194     if (!m_keyframes.isEmpty()) {
195         m_keyframes.clear();
196         update();
197     }
198 }
199
200 QString ClipItem::keyframes(const int index) {
201     QString result;
202     QDomElement effect = effectAt(index);
203     QDomNodeList params = effect.elementsByTagName("parameter");
204
205     for (int i = 0; i < params.count(); i++) {
206         QDomElement e = params.item(i).toElement();
207         if (!e.isNull() && e.attribute("type") == "keyframe") {
208             result = e.attribute("keyframes");
209             break;
210         }
211     }
212     return result;
213 }
214
215 void ClipItem::updateKeyframeEffect() {
216     // regenerate xml parameter from the clip keyframes
217     QDomElement effect = effectAt(m_selectedEffect);
218     if (effect.attribute("disabled") == "1") return;
219     QDomNodeList params = effect.elementsByTagName("parameter");
220
221     for (int i = 0; i < params.count(); i++) {
222         QDomElement e = params.item(i).toElement();
223         if (!e.isNull() && e.attribute("type") == "keyframe") {
224             QString keyframes;
225             if (m_keyframes.count() > 1) {
226                 QMap<int, double>::const_iterator i = m_keyframes.constBegin();
227                 double x1;
228                 double y1;
229                 while (i != m_keyframes.constEnd()) {
230                     keyframes.append(QString::number(i.key()) + ":" + QString::number(i.value()) + ";");
231                     ++i;
232                 }
233             }
234             // Effect has a keyframe type parameter, we need to set the values
235             //kDebug() << ":::::::::::::::   SETTING EFFECT KEYFRAMES: " << keyframes;
236             e.setAttribute("keyframes", keyframes);
237             break;
238         }
239     }
240 }
241
242 QDomElement ClipItem::selectedEffect() {
243     if (m_selectedEffect == -1 || m_effectList.isEmpty()) return QDomElement();
244     return effectAt(m_selectedEffect);
245 }
246
247 void ClipItem::resetThumbs() {
248     slotFetchThumbs();
249     audioThumbCachePic.clear();
250 }
251
252
253 void ClipItem::refreshClip() {
254     m_maxDuration = m_clip->maxDuration();
255     if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW) slotFetchThumbs();
256     else if (m_clipType == COLOR) {
257         QString colour = m_clip->getProperty("colour");
258         colour = colour.replace(0, 2, "#");
259         setBrush(QColor(colour.left(7)));
260     } else if (m_clipType == IMAGE || m_clipType == TEXT) {
261         m_startPix = KThumb::getImage(KUrl(m_clip->getProperty("resource")), (int)(50 * KdenliveSettings::project_display_ratio()), 50);
262         m_endPix = m_startPix;
263     }
264 }
265
266 void ClipItem::slotFetchThumbs() {
267     m_thumbsRequested += 2;
268     emit getThumb((int)m_cropStart.frames(m_fps), (int)(m_cropStart + m_cropDuration).frames(m_fps));
269 }
270
271 void ClipItem::slotGetStartThumb() {
272     m_thumbsRequested++;
273     emit getThumb((int)m_cropStart.frames(m_fps), -1);
274 }
275
276 void ClipItem::slotGetEndThumb() {
277     m_thumbsRequested++;
278     emit getThumb(-1, (int)(m_cropStart + m_cropDuration).frames(m_fps));
279 }
280
281 void ClipItem::slotThumbReady(int frame, QPixmap pix) {
282     if (m_thumbsRequested == 0) return;
283     if (frame == m_cropStart.frames(m_fps)) {
284         m_startPix = pix;
285         QRectF r = boundingRect();
286         r.setRight(pix.width() + 2);
287         update(r);
288     } else {
289         m_endPix = pix;
290         QRectF r = boundingRect();
291         r.setLeft(r.right() - pix.width() - 2);
292         update(r);
293     }
294     m_thumbsRequested--;
295 }
296
297 void ClipItem::slotGotAudioData() {
298     audioThumbReady = true;
299     if (m_clipType == AV) {
300         QRectF r = boundingRect();
301         r.setTop(r.top() + r.height() / 2 - 1);
302         update(r);
303     } else update();
304 }
305
306 int ClipItem::type() const {
307     return AVWIDGET;
308 }
309
310 DocClipBase *ClipItem::baseClip() const {
311     return m_clip;
312 }
313
314 QDomElement ClipItem::xml() const {
315     return m_clip->toXML();
316 }
317
318 int ClipItem::clipType() const {
319     return m_clipType;
320 }
321
322 QString ClipItem::clipName() const {
323     return m_clipName;
324 }
325
326 int ClipItem::clipProducer() const {
327     return m_producer;
328 }
329
330 void ClipItem::flashClip() {
331     if (m_timeLine == 0) {
332         m_timeLine = new QTimeLine(750, this);
333         m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
334         connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
335     }
336     m_timeLine->start();
337 }
338
339 void ClipItem::animate(qreal value) {
340     QRectF r = boundingRect();
341     r.setHeight(20);
342     update(r);
343 }
344
345 // virtual
346 void ClipItem::paint(QPainter *painter,
347                      const QStyleOptionGraphicsItem *option,
348                      QWidget *) {
349     painter->setOpacity(m_opacity);
350     QBrush paintColor = brush();
351     if (isSelected()) paintColor = QBrush(QColor(79, 93, 121));
352     QRectF br = rect();
353     double scale = br.width() / m_cropDuration.frames(m_fps);
354
355     // kDebug()<<"///   EXPOSED RECT: "<<option->exposedRect.x()<<" X "<<option->exposedRect.right();
356
357     int startpixel = (int)option->exposedRect.x() - rect().x();
358
359     if (startpixel < 0)
360         startpixel = 0;
361     int endpixel = (int)option->exposedRect.right();
362     if (endpixel < 0)
363         endpixel = 0;
364
365     //painter->setRenderHints(QPainter::Antialiasing);
366
367     QPainterPath roundRectPathUpper = upperRectPart(br), roundRectPathLower = lowerRectPart(br);
368     painter->setClipRect(option->exposedRect);
369
370     // build path around clip
371     QPainterPath resultClipPath = roundRectPathUpper.united(roundRectPathLower);
372     painter->fillPath(resultClipPath, paintColor);
373
374     painter->setClipPath(resultClipPath, Qt::IntersectClip);
375     // draw thumbnails
376     if (!m_startPix.isNull() && KdenliveSettings::videothumbnails()) {
377         if (m_clipType == IMAGE) {
378             painter->drawPixmap(QPointF(br.right() - m_startPix.width(), br.y()), m_startPix);
379             QLine l(br.right() - m_startPix.width(), br.y(), br.right() - m_startPix.width(), br.y() + br.height());
380             painter->drawLine(l);
381         } else {
382             painter->drawPixmap(QPointF(br.right() - m_endPix.width(), br.y()), m_endPix);
383             QLine l(br.right() - m_endPix.width(), br.y(), br.right() - m_endPix.width(), br.y() + br.height());
384             painter->drawLine(l);
385         }
386
387         painter->drawPixmap(QPointF(br.x(), br.y()), m_startPix);
388         QLine l2(br.x() + m_startPix.width(), br.y(), br.x() + m_startPix.width(), br.y() + br.height());
389         painter->drawLine(l2);
390     }
391
392     // draw audio thumbnails
393     if (KdenliveSettings::audiothumbnails() && ((m_clipType == AV && option->exposedRect.bottom() > (br.y() + br.height() / 2)) || m_clipType == AUDIO) && audioThumbReady) {
394
395         QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;
396         if (m_clipType == AV) painter->fillPath(path, QBrush(QColor(200, 200, 200, 140)));
397
398         int channels = baseClip()->getProperty("channels").toInt();
399         if (scale != framePixelWidth)
400             audioThumbCachePic.clear();
401         emit prepareAudioThumb(scale, path, startpixel, endpixel + 200, channels);//200 more for less missing parts before repaint after scrolling
402         int cropLeft = (int)((m_cropStart).frames(m_fps) * scale);
403         for (int startCache = startpixel - startpixel % 100; startCache < endpixel + 300;startCache += 100) {
404             if (audioThumbCachePic.contains(startCache) && !audioThumbCachePic[startCache].isNull())
405                 painter->drawPixmap((int)(roundRectPathUpper.united(roundRectPathLower).boundingRect().x() + startCache - cropLeft), (int)(path.boundingRect().y()), audioThumbCachePic[startCache]);
406         }
407     }
408
409     // draw markers
410     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
411     QList < CommentedTime >::Iterator it = markers.begin();
412     GenTime pos;
413     double framepos;
414     const int markerwidth = 4;
415     QBrush markerBrush;
416     markerBrush = QBrush(QColor(120, 120, 0, 100));
417     QPen pen = painter->pen();
418     pen.setColor(QColor(255, 255, 255, 200));
419     pen.setStyle(Qt::DotLine);
420     painter->setPen(pen);
421     for (; it != markers.end(); ++it) {
422         pos = (*it).time() - cropStart();
423         if (pos > GenTime()) {
424             if (pos > duration()) break;
425             framepos = scale * pos.frames(m_fps);
426             QLineF l(br.x() + framepos, br.y() + 5, br.x() + framepos, br.y() + br.height() - 5);
427             painter->drawLine(l);
428             if (KdenliveSettings::showmarkers()) {
429                 const QRectF txtBounding = painter->boundingRect(br.x() + framepos + 1, br.y() + 10, br.width() - framepos - 2, br.height() - 10, Qt::AlignLeft | Qt::AlignTop, " " + (*it).comment() + " ");
430                 QPainterPath path;
431                 path.addRoundedRect(txtBounding, 3, 3);
432                 painter->fillPath(path, markerBrush);
433                 painter->drawText(txtBounding, Qt::AlignCenter, (*it).comment());
434             }
435             //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
436         }
437     }
438     pen.setColor(Qt::black);
439     pen.setStyle(Qt::SolidLine);
440     painter->setPen(pen);
441
442     // draw start / end fades
443     QBrush fades;
444     if (isSelected()) {
445         fades = QBrush(QColor(200, 50, 50, 150));
446     } else fades = QBrush(QColor(200, 200, 200, 200));
447
448     if (m_startFade != 0) {
449         QPainterPath fadeInPath;
450         fadeInPath.moveTo(br.x() , br.y());
451         fadeInPath.lineTo(br.x() , br.bottom());
452         fadeInPath.lineTo(br.x() + m_startFade * scale, br.y());
453         fadeInPath.closeSubpath();
454         painter->fillPath(fadeInPath/*.intersected(resultClipPath)*/, fades);
455         if (isSelected()) {
456             QLineF l(br.x() + m_startFade * scale, br.y(), br.x(), br.bottom());
457             painter->drawLine(l);
458         }
459     }
460     if (m_endFade != 0) {
461         QPainterPath fadeOutPath;
462         fadeOutPath.moveTo(br.right(), br.y());
463         fadeOutPath.lineTo(br.right(), br.bottom());
464         fadeOutPath.lineTo(br.right() - m_endFade * scale, br.y());
465         fadeOutPath.closeSubpath();
466         painter->fillPath(fadeOutPath/*.intersected(resultClipPath)*/, fades);
467         if (isSelected()) {
468             QLineF l(br.right() - m_endFade * scale, br.y(), br.x() + br.width(), br.bottom());
469             painter->drawLine(l);
470         }
471     }
472
473     // Draw effects names
474     if (!m_effectNames.isEmpty() && br.width() > 30) {
475         QRectF txtBounding = painter->boundingRect(br, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
476         txtBounding.setRight(txtBounding.right() + 15);
477         painter->setPen(Qt::white);
478         QBrush markerBrush(Qt::SolidPattern);
479         if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
480             qreal value = m_timeLine->currentValue();
481             txtBounding.setWidth(txtBounding.width() * value);
482             markerBrush.setColor(QColor(50 + 200 * (1.0 - value), 50, 50, 100 + 50 * value));
483         } else markerBrush.setColor(QColor(50, 50, 50, 150));
484         QPainterPath path;
485         path.addRoundedRect(txtBounding, 4, 4);
486         painter->fillPath(path/*.intersected(resultClipPath)*/, markerBrush);
487         painter->drawText(txtBounding, Qt::AlignCenter, m_effectNames);
488         painter->setPen(Qt::black);
489     }
490
491     // Draw clip name
492     QRectF txtBounding = painter->boundingRect(br, Qt::AlignHCenter | Qt::AlignTop, " " + m_clipName + " ");
493     //painter->fillRect(txtBounding, QBrush(QColor(255, 255, 255, 150)));
494     painter->setPen(QColor(0, 0, 0, 180));
495     painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
496     txtBounding.translate(QPointF(1, 1));
497     painter->setPen(QColor(255, 255, 255, 255));
498     painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
499     // draw frame around clip
500     if (isSelected()) {
501         pen.setColor(Qt::red);
502         //pen.setWidth(2);
503     } else {
504         pen.setColor(Qt::black);
505         //pen.setWidth(1);
506     }
507
508
509     // draw effect or transition keyframes
510     if (br.width() > 20) drawKeyFrames(painter, option->exposedRect);
511
512     // draw clip border
513     painter->setClipRect(option->exposedRect);
514     painter->setPen(pen);
515     //painter->setClipRect(option->exposedRect);
516     painter->drawPath(resultClipPath);
517
518     if (m_hover && br.width() > 30) {
519         painter->setBrush(QColor(180, 180, 50, 180)); //gradient);
520
521         // draw transitions handles
522         QPainterPath transitionHandle;
523         const int handle_size = 4;
524         transitionHandle.moveTo(0, 0);
525         transitionHandle.lineTo(handle_size, handle_size);
526         transitionHandle.lineTo(handle_size * 2, 0);
527         transitionHandle.lineTo(handle_size * 3, handle_size);
528         transitionHandle.lineTo(handle_size * 2, handle_size * 2);
529         transitionHandle.lineTo(handle_size * 3, handle_size * 3);
530         transitionHandle.lineTo(0, handle_size * 3);
531         transitionHandle.closeSubpath();
532         int pointy = (int)(br.y() + br.height() / 2);
533         int pointx1 = (int)(br.x() + 10);
534         int pointx2 = (int)(br.x() + br.width() - (10 + handle_size * 3));
535 #if 0
536         painter->setPen(QPen(Qt::black));
537         painter->setBrush(QBrush(QColor(50, 50, 0)));
538 #else
539         /*QRadialGradient gradient(pointx1 + 5, pointy + 5 , 5, 2, 2);
540         gradient.setColorAt(0.2, Qt::white);
541         gradient.setColorAt(0.8, Qt::yellow);
542         gradient.setColorAt(1, Qt::black);*/
543
544 #endif
545         painter->translate(pointx1, pointy);
546         painter->drawPath(transitionHandle); //Ellipse(0, 0 , 10, 10);
547         painter->translate(-pointx1, -pointy);
548
549         /*        QRadialGradient gradient1(pointx2 + 5, pointy + 5 , 5, 2, 2);
550                 gradient1.setColorAt(0.2, Qt::white);
551                 gradient1.setColorAt(0.8, Qt::yellow);
552                 gradient1.setColorAt(1, Qt::black);
553                 painter->setBrush(gradient1);*/
554         painter->translate(pointx2, pointy);
555         QMatrix m;
556         m.scale(-1.0, 1.0);
557         //painter->setMatrix(m);
558         painter->drawPath(transitionHandle); // Ellipse(0, 0, 10, 10);
559         //painter->setMatrix(m);
560         painter->translate(- pointx2, -pointy);
561     }
562 }
563
564
565 OPERATIONTYPE ClipItem::operationMode(QPointF pos, double scale) {
566     if (isSelected()) {
567         m_editedKeyframe = mouseOverKeyFrames(pos);
568         if (m_editedKeyframe != -1) return KEYFRAME;
569     }
570     if (qAbs((int)(pos.x() - (rect().x() + scale * m_startFade))) < 6 && qAbs((int)(pos.y() - rect().y())) < 6) {
571         if (m_startFade == 0) setToolTip(i18n("Add audio fade"));
572         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_startFade, m_fps).seconds()));
573         return FADEIN;
574     } else if (qAbs((int)(pos.x() - rect().x())) < 6) {
575         setToolTip(i18n("Crop from start: %1s", cropStart().seconds()));
576         return RESIZESTART;
577     } else if (qAbs((int)(pos.x() - (rect().x() + rect().width() - scale * m_endFade))) < 6 && qAbs((int)(pos.y() - rect().y())) < 6) {
578         if (m_endFade == 0) setToolTip(i18n("Add audio fade"));
579         else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_endFade, m_fps).seconds()));
580         return FADEOUT;
581     } else if (qAbs((int)(pos.x() - (rect().x() + rect().width()))) < 6) {
582         setToolTip(i18n("Clip duration: %1s", duration().seconds()));
583         return RESIZEEND;
584     } else if (qAbs((int)(pos.x() - (rect().x() + 16))) < 10 && qAbs((int)(pos.y() - (rect().y() + rect().height() / 2 + 5))) < 8) {
585         setToolTip(i18n("Add transition"));
586         return TRANSITIONSTART;
587     } else if (qAbs((int)(pos.x() - (rect().x() + rect().width() - 21))) < 10 && qAbs((int)(pos.y() - (rect().y() + rect().height() / 2 + 5))) < 8) {
588         setToolTip(i18n("Add transition"));
589         return TRANSITIONEND;
590     }
591     setToolTip(QString());
592     return MOVE;
593 }
594
595 QList <GenTime> ClipItem::snapMarkers() const {
596     QList < GenTime > snaps;
597     QList < GenTime > markers = baseClip()->snapMarkers();
598     GenTime pos;
599     double framepos;
600
601     for (int i = 0; i < markers.size(); i++) {
602         pos = markers.at(i) - cropStart();
603         if (pos > GenTime()) {
604             if (pos > duration()) break;
605             else snaps.append(pos + startPos());
606         }
607     }
608     return snaps;
609 }
610
611 QList <CommentedTime> ClipItem::commentedSnapMarkers() const {
612     QList < CommentedTime > snaps;
613     QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
614     GenTime pos;
615     double framepos;
616
617     for (int i = 0; i < markers.size(); i++) {
618         pos = markers.at(i).time() - cropStart();
619         if (pos > GenTime()) {
620             if (pos > duration()) break;
621             else snaps.append(CommentedTime(pos + startPos(), markers.at(i).comment()));
622         }
623     }
624     return snaps;
625 }
626
627 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, QPainterPath path, int startpixel, int endpixel, int channels) {
628
629     QRectF re = path.boundingRect();
630     //kDebug() << "// PREP AUDIO THMB FRMO : " << startpixel << ", to: " << endpixel;
631     //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
632
633     for (int startCache = startpixel - startpixel % 100;startCache + 100 < endpixel ;startCache += 100) {
634         //kDebug() << "creating " << startCache;
635         //if (framePixelWidth!=pixelForOneFrame  ||
636         if (framePixelWidth == pixelForOneFrame && audioThumbCachePic.contains(startCache))
637             continue;
638         if (audioThumbCachePic[startCache].isNull() || framePixelWidth != pixelForOneFrame) {
639             audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
640             audioThumbCachePic[startCache].fill(QColor(200, 200, 200, 0));
641         }
642         bool fullAreaDraw = pixelForOneFrame < 10;
643         QMap<int, QPainterPath > positiveChannelPaths;
644         QMap<int, QPainterPath > negativeChannelPaths;
645         QPainter pixpainter(&audioThumbCachePic[startCache]);
646         QPen audiopen;
647         audiopen.setWidth(0);
648         pixpainter.setPen(audiopen);
649         //pixpainter.setRenderHint(QPainter::Antialiasing,true);
650         //pixpainter.drawLine(0,0,100,re.height());
651         int channelHeight = audioThumbCachePic[startCache].height() / channels;
652
653         for (int i = 0;i < channels;i++) {
654
655             positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
656             negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
657         }
658
659         for (int samples = 0;samples <= 100;samples++) {
660             double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
661             int sample = (int)((frame - (int)(frame)) * 20);   // AUDIO_FRAME_SIZE
662             if (frame < 0 || sample < 0 || sample > 19)
663                 continue;
664             QMap<int, QByteArray> frame_channel_data = baseClip()->audioFrameChache[(int)frame];
665
666             for (int channel = 0;channel < channels && frame_channel_data[channel].size() > 0;channel++) {
667
668                 int y = channelHeight * channel + channelHeight / 2;
669                 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2)  * channelHeight / 64;
670                 if (fullAreaDraw) {
671                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
672                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
673                 } else {
674                     positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
675                     negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
676                 }
677             }
678             for (int channel = 0;channel < channels ;channel++)
679                 if (fullAreaDraw && samples == 100) {
680                     positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
681                     negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
682                     positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
683                     negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
684                 }
685
686         }
687         if (m_clipType != AV) pixpainter.setBrush(QBrush(QColor(200, 200, 100)));
688         else {
689             pixpainter.setPen(QPen(QColor(0, 0, 0)));
690             pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
691         }
692         for (int i = 0;i < channels;i++) {
693             if (fullAreaDraw) {
694                 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
695                 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
696             } else
697                 pixpainter.drawPath(positiveChannelPaths[i]);
698         }
699     }
700     //audioThumbWasDrawn=true;
701     framePixelWidth = pixelForOneFrame;
702
703     //}
704 }
705
706 uint ClipItem::fadeIn() const {
707     return m_startFade;
708 }
709
710 uint ClipItem::fadeOut() const {
711     return m_endFade;
712 }
713
714
715 void ClipItem::setFadeIn(int pos, double scale) {
716     int oldIn = m_startFade;
717     if (pos < 0) pos = 0;
718     if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
719     m_startFade = pos;
720     update(rect().x(), rect().y(), qMax(oldIn, pos) * scale, rect().height());
721 }
722
723 void ClipItem::setFadeOut(int pos, double scale) {
724     int oldOut = m_endFade;
725     if (pos < 0) pos = 0;
726     if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
727     m_endFade = pos;
728     update(rect().x() + rect().width() - qMax(oldOut, pos) * scale, rect().y(), pos * scale, rect().height());
729
730 }
731
732 // virtual
733 void ClipItem::mousePressEvent(QGraphicsSceneMouseEvent * event) {
734     /*m_resizeMode = operationMode(event->pos());
735     if (m_resizeMode == MOVE) {
736       m_maxTrack = scene()->sceneRect().height();
737       m_grabPoint = (int) (event->pos().x() - rect().x());
738     }*/
739     QGraphicsRectItem::mousePressEvent(event);
740 }
741
742 // virtual
743 void ClipItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) {
744     m_resizeMode = NONE;
745     QGraphicsRectItem::mouseReleaseEvent(event);
746 }
747
748 //virtual
749 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *) {
750     m_hover = true;
751     QRectF r = boundingRect();
752     qreal width = qMin(25.0, r.width());
753     update(r.x(), r.y(), width, r.height());
754     update(r.right() - width, r.y(), width, r.height());
755 }
756
757 //virtual
758 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *) {
759     m_hover = false;
760     QRectF r = boundingRect();
761     qreal width = qMin(25.0, r.width());
762     update(r.x(), r.y(), width, r.height());
763     update(r.right() - width, r.y(), width, r.height());
764 }
765
766 void ClipItem::resizeStart(int posx, double scale) {
767     const int previous = cropStart().frames(m_fps);
768     AbstractClipItem::resizeStart(posx, scale);
769     checkEffectsKeyframesPos(previous, cropStart().frames(m_fps), true);
770     if (m_hasThumbs && KdenliveSettings::videothumbnails()) startThumbTimer->start(100);
771 }
772
773 void ClipItem::resizeEnd(int posx, double scale) {
774     const int previous = (cropStart() + duration()).frames(m_fps);
775     AbstractClipItem::resizeEnd(posx, scale);
776     checkEffectsKeyframesPos(previous, (cropStart() + duration()).frames(m_fps), false);
777     if (m_hasThumbs && KdenliveSettings::videothumbnails()) endThumbTimer->start(100);
778 }
779
780
781 void ClipItem::checkEffectsKeyframesPos(const int previous, const int current, bool fromStart) {
782     for (int i = 0; i < m_effectList.size(); i++) {
783         QDomElement effect = m_effectList.at(i);
784         QDomNodeList params = effect.elementsByTagName("parameter");
785         for (int j = 0; j < params.count(); j++) {
786             QDomElement e = params.item(i).toElement();
787             if (e.attribute("type") == "keyframe") {
788                 // parse keyframes and adjust values
789                 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
790                 QMap <int, double> kfr;
791                 foreach(const QString str, keyframes) {
792                     int pos = str.section(":", 0, 0).toInt();
793                     double val = str.section(":", 1, 1).toDouble();
794                     if (pos == previous) kfr[current] = val;
795                     else {
796                         if (fromStart && pos >= current) kfr[pos] = val;
797                         else if (!fromStart && pos <= current) kfr[pos] = val;
798                     }
799                 }
800                 QString newkfr;
801                 QMap<int, double>::const_iterator k = kfr.constBegin();
802                 while (k != kfr.constEnd()) {
803                     newkfr.append(QString::number(k.key()) + ":" + QString::number(k.value()) + ";");
804                     ++k;
805                 }
806                 e.setAttribute("keyframes", newkfr);
807                 break;
808             }
809         }
810     }
811     if (m_selectedEffect >= 0) setSelectedEffect(m_selectedEffect);
812 }
813
814
815 // virtual
816 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
817 }*/
818
819 int ClipItem::effectsCounter() {
820     return m_effectsCounter++;
821 }
822
823 int ClipItem::effectsCount() {
824     return m_effectList.size();
825 }
826
827 QStringList ClipItem::effectNames() {
828     return m_effectList.effectNames();
829 }
830
831 QDomElement ClipItem::effectAt(int ix) {
832     if (ix > m_effectList.count() - 1 || ix < 0) return QDomElement();
833     return m_effectList.at(ix);
834 }
835
836 void ClipItem::setEffectAt(int ix, QDomElement effect) {
837     kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
838     m_effectList.insert(ix, effect);
839     m_effectList.removeAt(ix + 1);
840     m_effectNames = m_effectList.effectNames().join(" / ");
841     if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fadeout") update(boundingRect());
842     else {
843         QRectF r = boundingRect();
844         r.setHeight(20);
845         update(r);
846     }
847 }
848
849 QMap <QString, QString> ClipItem::addEffect(QDomElement effect, bool animate) {
850     QMap <QString, QString> effectParams;
851     bool needRepaint = false;
852     /*QDomDocument doc;
853     doc.appendChild(doc.importNode(effect, true));
854     kDebug() << "///////  CLIP ADD EFFECT: "<< doc.toString();*/
855     m_effectList.append(effect);
856     effectParams["tag"] = effect.attribute("tag");
857     QString effectId = effect.attribute("id");
858     if (effectId.isEmpty()) effectId = effect.attribute("tag");
859     effectParams["id"] = effectId;
860     effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
861     QString state = effect.attribute("disabled");
862     if (!state.isEmpty()) effectParams["disabled"] = state;
863     QDomNodeList params = effect.elementsByTagName("parameter");
864     int fade = 0;
865     for (int i = 0; i < params.count(); i++) {
866         QDomElement e = params.item(i).toElement();
867         if (!e.isNull()) {
868             if (e.attribute("type") == "keyframe") {
869                 effectParams["keyframes"] = e.attribute("keyframes");
870                 effectParams["min"] = e.attribute("min");
871                 effectParams["max"] = e.attribute("max");
872                 effectParams["factor"] = e.attribute("factor", "1");
873                 effectParams["starttag"] = e.attribute("starttag", "start");
874                 effectParams["endtag"] = e.attribute("endtag", "end");
875             }
876
877             double f = e.attribute("factor", "1").toDouble();
878
879             if (f == 1) {
880                 effectParams[e.attribute("name")] = e.attribute("value");
881                 // check if it is a fade effect
882                 if (effectId == "fadein") {
883                     needRepaint = true;
884                     if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
885                     else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
886                 } else if (effectId == "fadeout") {
887                     needRepaint = true;
888                     if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
889                     else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
890                 }
891             } else {
892                 effectParams[e.attribute("name")] =  QString::number(effectParams[e.attribute("name")].toDouble() / f);
893             }
894         }
895     }
896     m_effectNames = m_effectList.effectNames().join(" / ");
897     if (fade > 0) m_startFade = fade;
898     else if (fade < 0) m_endFade = -fade;
899     if (needRepaint) update(boundingRect());
900     if (animate) {
901         flashClip();
902     } else if (!needRepaint) {
903         QRectF r = boundingRect();
904         r.setHeight(20);
905         update(r);
906     }
907     if (m_selectedEffect == -1) {
908         m_selectedEffect = 0;
909         setSelectedEffect(m_selectedEffect);
910     }
911     return effectParams;
912 }
913
914 QMap <QString, QString> ClipItem::getEffectArgs(QDomElement effect) {
915     QMap <QString, QString> effectParams;
916     effectParams["tag"] = effect.attribute("tag");
917     effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
918     effectParams["id"] = effect.attribute("id");
919     QString state = effect.attribute("disabled");
920     if (!state.isEmpty()) effectParams["disabled"] = state;
921     QDomNodeList params = effect.elementsByTagName("parameter");
922     for (int i = 0; i < params.count(); i++) {
923         QDomElement e = params.item(i).toElement();
924         kDebug() << "/ / / /SENDING EFFECT PARAM: " << e.attribute("type") << ", NAME_ " << e.attribute("tag");
925         if (e.attribute("type") == "keyframe") {
926             kDebug() << "/ / / /SENDING KEYFR EFFECT TYPE";
927             effectParams["keyframes"] = e.attribute("keyframes");
928             effectParams["max"] = e.attribute("max");
929             effectParams["min"] = e.attribute("min");
930             effectParams["factor"] = e.attribute("factor", "1");
931             effectParams["starttag"] = e.attribute("starttag", "start");
932             effectParams["endtag"] = e.attribute("endtag", "end");
933         } else if (e.attribute("namedesc").contains(";")) {
934             QString format = e.attribute("format");
935             QStringList separators = format.split("%d", QString::SkipEmptyParts);
936             QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
937             QString neu;
938             QTextStream txtNeu(&neu);
939             if (values.size() > 0)
940                 txtNeu << (int)values[0].toDouble();
941             for (int i = 0;i < separators.size() && i + 1 < values.size();i++) {
942                 txtNeu << separators[i];
943                 txtNeu << (int)(values[i+1].toDouble());
944             }
945             effectParams["start"] = neu;
946         } else {
947             if (e.attribute("factor", "1") != "1")
948                 effectParams[e.attribute("name")] =  QString::number(e.attribute("value").toDouble() / e.attribute("factor").toDouble());
949             else effectParams[e.attribute("name")] = e.attribute("value");
950         }
951     }
952     return effectParams;
953 }
954
955 void ClipItem::deleteEffect(QString index) {
956     bool needRepaint = false;
957     for (int i = 0; i < m_effectList.size(); ++i) {
958         if (m_effectList.at(i).attribute("kdenlive_ix") == index) {
959             if (m_effectList.at(i).attribute("id") == "fadein") {
960                 m_startFade = 0;
961                 needRepaint = true;
962             } else if (m_effectList.at(i).attribute("id") == "fadeout") {
963                 m_endFade = 0;
964                 needRepaint = true;
965             }
966             m_effectList.removeAt(i);
967             break;
968         }
969     }
970     m_effectNames = m_effectList.effectNames().join(" / ");
971     if (needRepaint) update(boundingRect());
972     flashClip();
973 }
974
975 double ClipItem::speed() const {
976     return m_speed;
977 }
978
979 void ClipItem::setSpeed(const double speed) {
980     m_speed = speed;
981     if (m_speed == 1.0) m_clipName = baseClip()->name();
982     else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + "%";
983     update();
984 }
985
986 //virtual
987 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event) {
988     QString effects = QString(event->mimeData()->data("kdenlive/effectslist"));
989     QDomDocument doc;
990     doc.setContent(effects, true);
991     QDomElement e = doc.documentElement();
992     CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
993     if (view) view->slotAddEffect(e, m_startPos, track());
994 }
995
996 //virtual
997 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
998     event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
999 }
1000
1001 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) {
1002     Q_UNUSED(event);
1003 }
1004 void ClipItem::addTransition(Transition* t) {
1005     m_transitionsList.append(t);
1006     CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1007     QDomDocument doc;
1008     QDomElement e = doc.documentElement();
1009     //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1010 }
1011 // virtual
1012 /*
1013 void CustomTrackView::mousePressEvent ( QMouseEvent * event )
1014 {
1015   int pos = event->x();
1016   if (event->modifiers() == Qt::ControlModifier)
1017     setDragMode(QGraphicsView::ScrollHandDrag);
1018   else if (event->modifiers() == Qt::ShiftModifier)
1019     setDragMode(QGraphicsView::RubberBandDrag);
1020   else {
1021     QGraphicsItem * item = itemAt(event->pos());
1022     if (item) {
1023     }
1024     else emit cursorMoved((int) mapToScene(event->x(), 0).x());
1025   }
1026   kDebug()<<pos;
1027   QGraphicsView::mousePressEvent(event);
1028 }
1029
1030 void CustomTrackView::mouseReleaseEvent ( QMouseEvent * event )
1031 {
1032   QGraphicsView::mouseReleaseEvent(event);
1033   setDragMode(QGraphicsView::NoDrag);
1034 }
1035 */
1036
1037 #include "clipitem.moc"