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