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