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