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