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