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