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