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