1 /***************************************************************************
2 * Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org) *
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. *
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. *
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 ***************************************************************************/
24 #include <QStyleOptionGraphicsItem>
25 #include <QGraphicsScene>
26 #include <QGraphicsView>
29 #include <QApplication>
34 #include "customtrackview.h"
35 #include "customtrackscene.h"
37 #include "docclipbase.h"
38 #include "transition.h"
39 #include "kdenlivesettings.h"
43 ClipItem::ClipItem(DocClipBase *clip, ItemInfo info, double fps)
44 : 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_startThumbRequested(false), m_endThumbRequested(false), m_startFade(0), m_endFade(0), m_hover(false), m_selectedEffect(-1), m_speed(1.0), framePixelWidth(0) {
45 setRect(0, 0, (info.endPos - info.startPos).frames(fps) - 0.02, (qreal)(KdenliveSettings::trackheight() - 2));
46 setPos((qreal) info.startPos.frames(fps), (qreal)(info.track * KdenliveSettings::trackheight()) + 1);
48 m_clipName = clip->name();
49 m_producer = clip->getId();
50 m_clipType = clip->clipType();
51 m_cropStart = info.cropStart;
52 m_maxDuration = clip->maxDuration();
54 audioThumbReady = clip->audioThumbCreated();
57 m_cropStart = xml.attribute("in", 0).toInt();
58 m_maxDuration = xml.attribute("duration", 0).toInt();
59 if (m_maxDuration == 0) m_maxDuration = xml.attribute("out", 0).toInt() - m_cropStart;
61 if (duration != -1) m_cropDuration = duration;
62 else m_cropDuration = m_maxDuration;*/
65 setFlags(QGraphicsItem::ItemClipsToShape | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
66 setAcceptsHoverEvents(true);
67 connect(this , SIGNAL(prepareAudioThumb(double, int, int, int)) , this, SLOT(slotPrepareAudioThumb(double, int, int, int)));
69 setBrush(QColor(141, 166, 215));
70 if (m_clipType == VIDEO || m_clipType == AV || m_clipType == SLIDESHOW || m_clipType == PLAYLIST) {
72 startThumbTimer = new QTimer(this);
73 startThumbTimer->setSingleShot(true);
74 connect(startThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetStartThumb()));
75 endThumbTimer = new QTimer(this);
76 endThumbTimer->setSingleShot(true);
77 connect(endThumbTimer, SIGNAL(timeout()), this, SLOT(slotGetEndThumb()));
79 connect(this, SIGNAL(getThumb(int, int)), clip->thumbProducer(), SLOT(extractImage(int, int)));
80 connect(clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));
81 connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
82 QTimer::singleShot(200, this, SLOT(slotFetchThumbs()));
84 /*if (m_clip->producer()) {
85 videoThumbProducer.init(this, m_clip->producer(), KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio(), KdenliveSettings::trackheight());
88 } else if (m_clipType == COLOR) {
89 QString colour = clip->getProperty("colour");
90 colour = colour.replace(0, 2, "#");
91 setBrush(QColor(colour.left(7)));
92 } else if (m_clipType == IMAGE || m_clipType == TEXT) {
93 m_startPix = KThumb::getImage(KUrl(clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
94 m_endPix = m_startPix;
95 } else if (m_clipType == AUDIO) {
96 connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
101 ClipItem::~ClipItem() {
102 if (startThumbTimer) delete startThumbTimer;
103 if (endThumbTimer) delete endThumbTimer;
104 if (m_timeLine) m_timeLine;
107 ClipItem *ClipItem::clone(ItemInfo info) const {
108 ClipItem *duplicate = new ClipItem(m_clip, info, m_fps);
109 if (info.cropStart == cropStart()) duplicate->slotSetStartThumb(m_startPix);
110 if (info.cropStart + (info.endPos - info.startPos) == m_cropStart + m_cropDuration) duplicate->slotSetEndThumb(m_endPix);
111 kDebug() << "// CLoning clip: " << (info.cropStart + (info.endPos - info.startPos)).frames(m_fps) << ", CURRENT end: " << (cropStart() + duration()).frames(m_fps);
112 duplicate->setEffectList(m_effectList);
113 duplicate->setSpeed(m_speed);
117 void ClipItem::setEffectList(const EffectsList effectList) {
118 m_effectList = effectList;
119 m_effectNames = m_effectList.effectNames().join(" / ");
122 const EffectsList ClipItem::effectList() {
126 int ClipItem::selectedEffectIndex() const {
127 return m_selectedEffect;
130 void ClipItem::initEffect(QDomElement effect) {
131 // the kdenlive_ix int is used to identify an effect in mlt's playlist, should
133 if (effect.attribute("kdenlive_ix").toInt() == 0)
134 effect.setAttribute("kdenlive_ix", QString::number(effectsCounter()));
135 // init keyframes if required
136 QDomNodeList params = effect.elementsByTagName("parameter");
137 for (int i = 0; i < params.count(); i++) {
138 QDomElement e = params.item(i).toElement();
139 if (!e.isNull() && e.attribute("type") == "keyframe") {
140 QString def = e.attribute("default");
141 // Effect has a keyframe type parameter, we need to set the values
142 if (e.attribute("keyframes").isEmpty()) {
143 e.setAttribute("keyframes", QString::number(m_cropStart.frames(m_fps)) + ":" + def + ";" + QString::number((m_cropStart + m_cropDuration).frames(m_fps)) + ":" + def);
144 //kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
151 void ClipItem::setKeyframes(const int ix, const QString keyframes) {
152 QDomElement effect = effectAt(ix);
153 if (effect.attribute("disabled") == "1") return;
154 QDomNodeList params = effect.elementsByTagName("parameter");
155 for (int i = 0; i < params.count(); i++) {
156 QDomElement e = params.item(i).toElement();
157 if (!e.isNull() && e.attribute("type") == "keyframe") {
158 e.setAttribute("keyframes", keyframes);
159 if (ix == m_selectedEffect) {
161 double max = e.attribute("max").toDouble();
162 double min = e.attribute("min").toDouble();
163 m_keyframeFactor = 100.0 / (max - min);
164 m_keyframeDefault = e.attribute("default").toDouble();
166 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
167 foreach(const QString str, keyframes) {
168 int pos = str.section(":", 0, 0).toInt();
169 double val = str.section(":", 1, 1).toDouble();
170 m_keyframes[pos] = val;
181 void ClipItem::setSelectedEffect(const int ix) {
182 m_selectedEffect = ix;
183 QDomElement effect = effectAt(m_selectedEffect);
184 QDomNodeList params = effect.elementsByTagName("parameter");
185 if (effect.attribute("disabled") != "1")
186 for (int i = 0; i < params.count(); i++) {
187 QDomElement e = params.item(i).toElement();
188 if (!e.isNull() && e.attribute("type") == "keyframe") {
190 double max = e.attribute("max").toDouble();
191 double min = e.attribute("min").toDouble();
192 m_keyframeFactor = 100.0 / (max - min);
193 m_keyframeDefault = e.attribute("default").toDouble();
195 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
196 foreach(const QString str, keyframes) {
197 int pos = str.section(":", 0, 0).toInt();
198 double val = str.section(":", 1, 1).toDouble();
199 m_keyframes[pos] = val;
205 if (!m_keyframes.isEmpty()) {
211 QString ClipItem::keyframes(const int index) {
213 QDomElement effect = effectAt(index);
214 QDomNodeList params = effect.elementsByTagName("parameter");
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 result = e.attribute("keyframes");
226 void ClipItem::updateKeyframeEffect() {
227 // regenerate xml parameter from the clip keyframes
228 QDomElement effect = effectAt(m_selectedEffect);
229 if (effect.attribute("disabled") == "1") return;
230 QDomNodeList params = effect.elementsByTagName("parameter");
232 for (int i = 0; i < params.count(); i++) {
233 QDomElement e = params.item(i).toElement();
234 if (!e.isNull() && e.attribute("type") == "keyframe") {
236 if (m_keyframes.count() > 1) {
237 QMap<int, double>::const_iterator i = m_keyframes.constBegin();
240 while (i != m_keyframes.constEnd()) {
241 keyframes.append(QString::number(i.key()) + ":" + QString::number(i.value()) + ";");
245 // Effect has a keyframe type parameter, we need to set the values
246 //kDebug() << "::::::::::::::: SETTING EFFECT KEYFRAMES: " << keyframes;
247 e.setAttribute("keyframes", keyframes);
253 QDomElement ClipItem::selectedEffect() {
254 if (m_selectedEffect == -1 || m_effectList.isEmpty()) return QDomElement();
255 return effectAt(m_selectedEffect);
258 void ClipItem::resetThumbs() {
259 m_startPix = QPixmap();
260 m_endPix = QPixmap();
262 audioThumbCachePic.clear();
266 void ClipItem::refreshClip() {
267 m_maxDuration = m_clip->maxDuration();
268 if (m_clipType == COLOR) {
269 QString colour = m_clip->getProperty("colour");
270 colour = colour.replace(0, 2, "#");
271 setBrush(QColor(colour.left(7)));
272 } else slotFetchThumbs();
275 void ClipItem::slotFetchThumbs() {
276 if (m_endPix.isNull() && m_startPix.isNull()) {
277 m_startThumbRequested = true;
278 m_endThumbRequested = true;
279 emit getThumb((int)m_cropStart.frames(m_fps), (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1);
281 if (m_endPix.isNull()) {
284 if (m_startPix.isNull()) {
290 if (m_endPix.isNull() && m_startPix.isNull()) {
291 int frame1 = (int)m_cropStart.frames(m_fps);
292 int frame2 = (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1;
293 //videoThumbProducer.setThumbFrames(m_clip->producer(), frame1, frame2);
294 //videoThumbProducer.start(QThread::LowestPriority);
296 if (m_endPix.isNull()) slotGetEndThumb();
297 else slotGetStartThumb();
300 } else if (m_startPix.isNull()) slotGetStartThumb();*/
303 void ClipItem::slotGetStartThumb() {
304 m_startThumbRequested = true;
305 emit getThumb((int)m_cropStart.frames(m_fps), -1);
306 //videoThumbProducer.setThumbFrames(m_clip->producer(), (int)m_cropStart.frames(m_fps), - 1);
307 //videoThumbProducer.start(QThread::LowestPriority);
310 void ClipItem::slotGetEndThumb() {
311 m_endThumbRequested = true;
312 emit getThumb(-1, (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1);
313 //videoThumbProducer.setThumbFrames(m_clip->producer(), -1, (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1);
314 //videoThumbProducer.start(QThread::LowestPriority);
318 void ClipItem::slotSetStartThumb(QImage img) {
319 if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
320 QPixmap pix = QPixmap::fromImage(img);
322 QRectF r = sceneBoundingRect();
323 r.setRight(pix.width() + 2);
328 void ClipItem::slotSetEndThumb(QImage img) {
329 if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
330 QPixmap pix = QPixmap::fromImage(img);
332 QRectF r = sceneBoundingRect();
333 r.setLeft(r.right() - pix.width() - 2);
338 void ClipItem::slotThumbReady(int frame, QPixmap pix) {
339 QRectF r = sceneBoundingRect();
340 double width = m_startPix.width() / projectScene()->scale();
341 if (m_startThumbRequested && frame == m_cropStart.frames(m_fps)) {
343 m_startThumbRequested = false;
344 double height = r.height();
345 update(r.x(), r.y(), width, height);
346 } else if (m_endThumbRequested && frame == (m_cropStart + m_cropDuration).frames(m_fps) - 1) {
348 m_endThumbRequested = false;
349 double height = r.height();
350 update(r.right() - width, r.y(), width, height);
354 void ClipItem::slotSetStartThumb(QPixmap pix) {
358 void ClipItem::slotSetEndThumb(QPixmap pix) {
362 void ClipItem::slotGotAudioData() {
363 audioThumbReady = true;
364 if (m_clipType == AV) {
365 QRectF r = boundingRect();
366 r.setTop(r.top() + r.height() / 2 - 1);
371 int ClipItem::type() const {
375 DocClipBase *ClipItem::baseClip() const {
379 QDomElement ClipItem::xml() const {
380 return m_clip->toXML();
383 int ClipItem::clipType() const {
387 QString ClipItem::clipName() const {
391 const QString &ClipItem::clipProducer() const {
395 void ClipItem::flashClip() {
396 if (m_timeLine == 0) {
397 m_timeLine = new QTimeLine(750, this);
398 m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
399 connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
404 void ClipItem::animate(qreal value) {
405 QRectF r = boundingRect();
411 void ClipItem::paint(QPainter *painter,
412 const QStyleOptionGraphicsItem *option,
414 painter->setOpacity(m_opacity);
415 QBrush paintColor = brush();
416 if (isSelected()) paintColor = QBrush(QColor(79, 93, 121));
418 QRectF exposed = option->exposedRect;
419 const double itemWidth = br.width();
420 const double itemHeight = br.height();
421 //kDebug() << "/// ITEM RECT: " << br << ", EPXOSED: " << option->exposedRect;
422 const double scale = option->matrix.m11();
424 // kDebug()<<"/// EXPOSED RECT: "<<option->exposedRect.x()<<" X "<<option->exposedRect.right();
426 //painter->setRenderHints(QPainter::Antialiasing);
428 //QPainterPath roundRectPathUpper = upperRectPart(br), roundRectPathLower = lowerRectPart(br);
429 painter->setClipRect(exposed);
431 // build path around clip
432 //QPainterPath resultClipPath = roundRectPathUpper.united(roundRectPathLower);
433 //painter->fillPath(resultClipPath, paintColor);
434 painter->fillRect(br, paintColor);
436 //painter->setClipPath(resultClipPath, Qt::IntersectClip);
439 painter->setMatrixEnabled(false);
441 if (KdenliveSettings::videothumbnails()) {
442 QPen pen = painter->pen();
443 pen.setStyle(Qt::DotLine);
444 pen.setColor(Qt::white);
445 painter->setPen(pen);
446 if (m_clipType == IMAGE && !m_startPix.isNull()) {
447 QPointF p1 = painter->matrix().map(QPointF(itemWidth, 0)) - QPointF(m_startPix.width(), 0);
448 QPointF p2 = painter->matrix().map(QPointF(itemWidth, itemHeight)) - QPointF(m_startPix.width(), 0);
449 painter->drawPixmap(p1, m_startPix);
451 painter->drawLine(l);
452 } else if (!m_endPix.isNull()) {
453 QPointF p1 = painter->matrix().map(QPointF(itemWidth, 0)) - QPointF(m_endPix.width(), 0);
454 QPointF p2 = painter->matrix().map(QPointF(itemWidth, itemHeight)) - QPointF(m_endPix.width(), 0);
455 painter->drawPixmap(p1, m_endPix);
457 painter->drawLine(l);
459 if (!m_startPix.isNull()) {
460 QPointF p1 = painter->matrix().map(QPointF(0, 0));
461 QPointF p2 = painter->matrix().map(QPointF(0, itemHeight));
462 painter->drawPixmap(p1, m_startPix);
463 QLineF l2(p1.x() + m_startPix.width(), p1.y(), p2.x() + m_startPix.width(), p2.y());
464 painter->drawLine(l2);
466 painter->setPen(Qt::black);
469 // draw audio thumbnails
470 if (KdenliveSettings::audiothumbnails() && ((m_clipType == AV && option->exposedRect.bottom() > (itemHeight / 2)) || m_clipType == AUDIO) && audioThumbReady) {
472 double startpixel = option->exposedRect.left(); // - pos().x();
475 double endpixel = option->exposedRect.right();
478 //kDebug()<<"/// REPAINTING AUDIO THMBS ZONE: "<<startpixel<<"x"<<endpixel;
480 /*QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;*/
483 if (m_clipType == AV) {
484 re.setTop(re.y() + re.height() / 2);
485 mappedRect = painter->matrix().mapRect(re);
486 painter->fillRect(mappedRect, QBrush(QColor(200, 200, 200, 140)));
487 } else mappedRect = painter->matrix().mapRect(re);
489 int channels = baseClip()->getProperty("channels").toInt();
490 if (scale != framePixelWidth)
491 audioThumbCachePic.clear();
492 double cropLeft = m_cropStart.frames(m_fps);
493 emit prepareAudioThumb(scale, startpixel + cropLeft, endpixel + cropLeft, channels);//200 more for less missing parts before repaint after scrolling
494 int newstart = startpixel + cropLeft;
495 const int clipStart = mappedRect.x();
496 for (int startCache = newstart - (newstart) % 100; startCache < endpixel + cropLeft; startCache += 100) {
497 if (audioThumbCachePic.contains(startCache) && !audioThumbCachePic[startCache].isNull())
498 //painter->drawPixmap((int)(startCache - cropLeft), (int)(path.boundingRect().y()), audioThumbCachePic[startCache]);
499 painter->drawPixmap(clipStart + startCache, mappedRect.y(), audioThumbCachePic[startCache]);
504 QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
505 QList < CommentedTime >::Iterator it = markers.begin();
508 const int markerwidth = 4;
510 markerBrush = QBrush(QColor(120, 120, 0, 100));
511 QPen pen = painter->pen();
512 pen.setColor(QColor(255, 255, 255, 200));
513 pen.setStyle(Qt::DotLine);
514 painter->setPen(pen);
515 for (; it != markers.end(); ++it) {
516 pos = (*it).time() - cropStart();
517 if (pos > GenTime()) {
518 if (pos > duration()) break;
519 QLineF l(br.x() + pos.frames(m_fps), br.y() + 5, br.x() + pos.frames(m_fps), br.bottom() - 5);
520 QLineF l2 = painter->matrix().map(l);
521 //framepos = scale * pos.frames(m_fps);
522 //QLineF l(framepos, 5, framepos, itemHeight - 5);
523 painter->drawLine(l2);
524 if (KdenliveSettings::showmarkers()) {
525 framepos = br.x() + pos.frames(m_fps);
526 const QRectF r1(framepos + 0.04, 10, itemWidth - framepos - 2, itemHeight - 10);
527 const QRectF r2 = painter->matrix().map(r1).boundingRect();
528 const QRectF txtBounding = painter->boundingRect(r2, Qt::AlignLeft | Qt::AlignTop, " " + (*it).comment() + " ");
531 path.addRoundedRect(txtBounding, 3, 3);
532 painter->fillPath(path, markerBrush);
533 painter->drawText(txtBounding, Qt::AlignCenter, (*it).comment());
535 //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
538 pen.setColor(Qt::black);
539 pen.setStyle(Qt::SolidLine);
540 painter->setPen(pen);
542 // draw start / end fades
545 fades = QBrush(QColor(200, 50, 50, 150));
546 } else fades = QBrush(QColor(200, 200, 200, 200));
548 if (m_startFade != 0) {
549 QPainterPath fadeInPath;
550 fadeInPath.moveTo(0, 0);
551 fadeInPath.lineTo(0, itemHeight);
552 fadeInPath.lineTo(m_startFade, 0);
553 fadeInPath.closeSubpath();
554 QPainterPath f1 = painter->matrix().map(fadeInPath);
555 painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
556 /*if (isSelected()) {
557 QLineF l(m_startFade * scale, 0, 0, itemHeight);
558 painter->drawLine(l);
561 if (m_endFade != 0) {
562 QPainterPath fadeOutPath;
563 fadeOutPath.moveTo(itemWidth, 0);
564 fadeOutPath.lineTo(itemWidth, itemHeight);
565 fadeOutPath.lineTo(itemWidth - m_endFade, 0);
566 fadeOutPath.closeSubpath();
567 QPainterPath f1 = painter->matrix().map(fadeOutPath);
568 painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
569 /*if (isSelected()) {
570 QLineF l(itemWidth - m_endFade * scale, 0, itemWidth, itemHeight);
571 painter->drawLine(l);
575 // Draw effects names
576 if (!m_effectNames.isEmpty() && itemWidth * scale > 40) {
577 QRectF txtBounding = painter->boundingRect(painter->matrix().map(br).boundingRect(), Qt::AlignLeft | Qt::AlignTop, m_effectNames);
578 txtBounding.setRight(txtBounding.right() + 15);
579 painter->setPen(Qt::white);
580 QBrush markerBrush(Qt::SolidPattern);
581 if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
582 qreal value = m_timeLine->currentValue();
583 txtBounding.setWidth(txtBounding.width() * value);
584 markerBrush.setColor(QColor(50 + 200 * (1.0 - value), 50, 50, 100 + 50 * value));
585 } else markerBrush.setColor(QColor(50, 50, 50, 150));
587 path.addRoundedRect(txtBounding, 4, 4);
588 painter->fillPath(path/*.intersected(resultClipPath)*/, markerBrush);
589 painter->drawText(txtBounding, Qt::AlignCenter, m_effectNames);
590 painter->setPen(Qt::black);
595 QRectF txtBounding = painter->boundingRect(painter->matrix().map(br).boundingRect(), Qt::AlignHCenter | Qt::AlignTop, " " + m_clipName + " ");
596 //painter->fillRect(txtBounding, QBrush(QColor(255, 255, 255, 150)));
597 painter->setPen(QColor(0, 0, 0, 180));
598 painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
599 txtBounding.translate(QPointF(1, 1));
600 painter->setPen(QColor(255, 255, 255, 255));
601 painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
604 // draw transition handles on hover
605 if (m_hover && itemWidth * scale > 40) {
606 QPainterPath transitionHandle;
607 const int handle_size = 4;
608 QPointF p1 = painter->matrix().map(QPointF(0, itemHeight / 2)) + QPointF(10, 0);
609 painter->drawPixmap(p1, projectScene()->m_transitionPixmap);
610 p1 = painter->matrix().map(QPointF(itemWidth, itemHeight / 2)) - QPointF(10 + handle_size * 3, 0);
611 painter->drawPixmap(p1, projectScene()->m_transitionPixmap);
615 // draw frame around clip
617 pen.setColor(Qt::red);
620 pen.setColor(Qt::black);
624 // draw effect or transition keyframes
625 if (itemWidth > 20) drawKeyFrames(painter, option->exposedRect);
627 painter->setMatrixEnabled(true);
631 //kDebug()<<"/// ITEM PAINTING:: exposed="<<exposed<<", RECT = "<<rect();
633 exposed.setRight(exposed.right() + 1);
634 exposed.setBottom(exposed.bottom() + 1);
635 painter->setClipRect(exposed);
636 //painter->setClipping(false);
637 //painter->fillRect(exposed, Qt::blue);
638 painter->setPen(pen);
639 painter->drawRect(br);
643 OPERATIONTYPE ClipItem::operationMode(QPointF pos) {
645 m_editedKeyframe = mouseOverKeyFrames(pos);
646 if (m_editedKeyframe != -1) return KEYFRAME;
648 QRectF rect = sceneBoundingRect();
649 const double scale = projectScene()->scale();
650 double maximumOffset;
651 if (scale > 3) maximumOffset = 25 / scale;
652 else maximumOffset = 6 / scale;
654 matrix.scale(scale, 0);
655 //kDebug()<<"// Item rect: "<<rect.x()<<". pos. "<<pos.x()<<", scale: "<<scale<<", ratio: "<<qAbs((int)(pos.x() - rect.x())) / scale;
657 if (qAbs((int)(pos.x() - (rect.x() + m_startFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
658 if (m_startFade == 0) setToolTip(i18n("Add audio fade"));
659 else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_startFade, m_fps).seconds()));
661 } else if (pos.x() - rect.x() < maximumOffset) {
662 setToolTip(i18n("Crop from start: %1s", cropStart().seconds()));
664 } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - m_endFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
665 if (m_endFade == 0) setToolTip(i18n("Add audio fade"));
666 else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_endFade, m_fps).seconds()));
668 } else if (qAbs((int)(pos.x() - (rect.x() + rect.width()))) < maximumOffset) {
669 setToolTip(i18n("Clip duration: %1s", duration().seconds()));
671 } else if (qAbs((int)(pos.x() - (rect.x() + 16))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 5))) < 6) {
672 setToolTip(i18n("Add transition"));
673 return TRANSITIONSTART;
674 } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - 21))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 5))) < 6) {
675 setToolTip(i18n("Add transition"));
676 return TRANSITIONEND;
678 setToolTip(QString());
682 QList <GenTime> ClipItem::snapMarkers() const {
683 QList < GenTime > snaps;
684 QList < GenTime > markers = baseClip()->snapMarkers();
688 for (int i = 0; i < markers.size(); i++) {
689 pos = markers.at(i) - cropStart();
690 if (pos > GenTime()) {
691 if (pos > duration()) break;
692 else snaps.append(pos + startPos());
698 QList <CommentedTime> ClipItem::commentedSnapMarkers() const {
699 QList < CommentedTime > snaps;
700 QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
704 for (int i = 0; i < markers.size(); i++) {
705 pos = markers.at(i).time() - cropStart();
706 if (pos > GenTime()) {
707 if (pos > duration()) break;
708 else snaps.append(CommentedTime(pos + startPos(), markers.at(i).comment()));
714 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, int startpixel, int endpixel, int channels) {
716 //QRectF re = path.boundingRect();
718 if (m_clipType == AV) re.setTop(re.y() + re.height() / 2);
720 //QRectF re = rect(); //path.boundingRect();
721 //kDebug() << "// PREP AUDIO THMB FRMO : " << startpixel << ", to: " << endpixel;
722 //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
724 for (int startCache = startpixel - startpixel % 100;startCache + 100 < endpixel + 100;startCache += 100) {
725 //kDebug() << "creating " << startCache;
726 //if (framePixelWidth!=pixelForOneFrame ||
727 if (framePixelWidth == pixelForOneFrame && audioThumbCachePic.contains(startCache))
729 if (audioThumbCachePic[startCache].isNull() || framePixelWidth != pixelForOneFrame) {
730 audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
731 audioThumbCachePic[startCache].fill(QColor(200, 200, 200, 0));
733 bool fullAreaDraw = pixelForOneFrame < 10;
734 QMap<int, QPainterPath > positiveChannelPaths;
735 QMap<int, QPainterPath > negativeChannelPaths;
736 QPainter pixpainter(&audioThumbCachePic[startCache]);
738 audiopen.setWidth(0);
739 pixpainter.setPen(audiopen);
740 //pixpainter.setRenderHint(QPainter::Antialiasing,true);
741 //pixpainter.drawLine(0,0,100,re.height());
742 int channelHeight = audioThumbCachePic[startCache].height() / channels;
744 for (int i = 0;i < channels;i++) {
746 positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
747 negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
750 for (int samples = 0;samples <= 100;samples++) {
751 double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
752 int sample = (int)((frame - (int)(frame)) * 20); // AUDIO_FRAME_SIZE
753 if (frame < 0 || sample < 0 || sample > 19)
755 QMap<int, QByteArray> frame_channel_data = baseClip()->audioFrameChache[(int)frame];
757 for (int channel = 0;channel < channels && frame_channel_data[channel].size() > 0;channel++) {
759 int y = channelHeight * channel + channelHeight / 2;
760 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2) * channelHeight / 64;
762 positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
763 negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
765 positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
766 negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
769 for (int channel = 0;channel < channels ;channel++)
770 if (fullAreaDraw && samples == 100) {
771 positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
772 negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
773 positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
774 negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
778 if (m_clipType != AV) pixpainter.setBrush(QBrush(QColor(200, 200, 100)));
780 pixpainter.setPen(QPen(QColor(0, 0, 0)));
781 pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
783 for (int i = 0;i < channels;i++) {
785 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
786 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
788 pixpainter.drawPath(positiveChannelPaths[i]);
791 //audioThumbWasDrawn=true;
792 framePixelWidth = pixelForOneFrame;
797 uint ClipItem::fadeIn() const {
801 uint ClipItem::fadeOut() const {
806 void ClipItem::setFadeIn(int pos) {
807 int oldIn = m_startFade;
808 if (pos < 0) pos = 0;
809 if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
811 QRectF rect = boundingRect();
812 update(rect.x(), rect.y(), qMax(oldIn, pos), rect.height());
815 void ClipItem::setFadeOut(int pos) {
816 int oldOut = m_endFade;
817 if (pos < 0) pos = 0;
818 if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
820 QRectF rect = boundingRect();
821 update(rect.x() + rect.width() - qMax(oldOut, pos), rect.y(), pos, rect.height());
826 void ClipItem::mousePressEvent(QGraphicsSceneMouseEvent * event) {
827 /*m_resizeMode = operationMode(event->pos());
828 if (m_resizeMode == MOVE) {
829 m_maxTrack = scene()->sceneRect().height();
830 m_grabPoint = (int) (event->pos().x() - rect().x());
832 QGraphicsRectItem::mousePressEvent(event);
836 void ClipItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) {
838 QGraphicsRectItem::mouseReleaseEvent(event);
842 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e) {
843 //if (e->pos().x() < 20) m_hover = true;
845 QRectF r = boundingRect();
846 double width = 35 / projectScene()->scale();
847 double height = r.height() / 2;
848 update(r.x(), r.y() + height, width, height);
849 update(r.right() - width, r.y() + height, width, height);
853 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *) {
855 QRectF r = boundingRect();
856 double width = 35 / projectScene()->scale();
857 double height = r.height() / 2;
858 update(r.x(), r.y() + height, width, height);
859 update(r.right() - width, r.y() + height, width, height);
862 void ClipItem::resizeStart(int posx) {
863 const int min = (startPos() - cropStart()).frames(m_fps);
864 if (posx < min) posx = min;
865 if (posx == startPos().frames(m_fps)) return;
866 const int previous = cropStart().frames(m_fps);
867 AbstractClipItem::resizeStart(posx);
868 checkEffectsKeyframesPos(previous, cropStart().frames(m_fps), true);
869 if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
870 /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
871 startThumbTimer->start(100);
875 void ClipItem::resizeEnd(int posx) {
876 const int max = (startPos() - cropStart() + maxDuration()).frames(m_fps) + 1;
877 if (posx > max) posx = max;
878 if (posx == endPos().frames(m_fps)) return;
879 const int previous = (cropStart() + duration()).frames(m_fps);
880 AbstractClipItem::resizeEnd(posx);
881 checkEffectsKeyframesPos(previous, (cropStart() + duration()).frames(m_fps), false);
882 if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
883 /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
884 endThumbTimer->start(100);
889 void ClipItem::checkEffectsKeyframesPos(const int previous, const int current, bool fromStart) {
890 for (int i = 0; i < m_effectList.size(); i++) {
891 QDomElement effect = m_effectList.at(i);
892 QDomNodeList params = effect.elementsByTagName("parameter");
893 for (int j = 0; j < params.count(); j++) {
894 QDomElement e = params.item(i).toElement();
895 if (e.attribute("type") == "keyframe") {
896 // parse keyframes and adjust values
897 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
898 QMap <int, double> kfr;
899 foreach(const QString str, keyframes) {
900 int pos = str.section(":", 0, 0).toInt();
901 double val = str.section(":", 1, 1).toDouble();
902 if (pos == previous) kfr[current] = val;
904 if (fromStart && pos >= current) kfr[pos] = val;
905 else if (!fromStart && pos <= current) kfr[pos] = val;
909 QMap<int, double>::const_iterator k = kfr.constBegin();
910 while (k != kfr.constEnd()) {
911 newkfr.append(QString::number(k.key()) + ":" + QString::number(k.value()) + ";");
914 e.setAttribute("keyframes", newkfr);
919 if (m_selectedEffect >= 0) setSelectedEffect(m_selectedEffect);
924 QVariant ClipItem::itemChange(GraphicsItemChange change, const QVariant &value) {
925 if (change == ItemPositionChange && scene()) {
926 // calculate new position.
927 if (group() != 0) return pos();
928 QPointF newPos = value.toPointF();
929 kDebug() << "/// MOVING CLIP ITEM.------------";
930 int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
931 xpos = qMax(xpos, 0);
933 int newTrack = (newPos.y() + KdenliveSettings::trackheight() / 2) / KdenliveSettings::trackheight();
934 newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
935 newTrack = qMax(newTrack, 0);
936 newPos.setY((int)(newTrack * KdenliveSettings::trackheight() + 1));
937 // Only one clip is moving
938 QRectF sceneShape = rect();
939 sceneShape.translate(newPos);
940 QList<QGraphicsItem*> items = scene()->items(sceneShape, Qt::IntersectsItemShape);
941 items.removeAll(this);
943 if (!items.isEmpty()) {
944 for (int i = 0; i < items.count(); i++) {
945 if (items.at(i)->type() == type()) {
947 QPointF otherPos = items.at(i)->pos();
948 if ((int) otherPos.y() != (int) pos().y()) return pos();
949 if (pos().x() < otherPos.x()) {
950 // move clip just before colliding clip
951 int npos = (static_cast < AbstractClipItem* >(items.at(i))->startPos() - m_cropDuration).frames(m_fps);
952 // check we don't run into another clip
955 sceneShape.translate(newPos);
956 QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
957 items.removeAll(this);
958 for (int j = 0; j < subitems.count(); i++) {
959 if (subitems.at(j)->type() == type()) return pos();
962 // get pos just after colliding clip
963 int npos = static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps);
964 // check we don't run into another clip
967 sceneShape.translate(newPos);
968 QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
969 items.removeAll(this);
970 for (int j = 0; j < subitems.count(); i++) {
971 if (subitems.at(j)->type() == type()) return pos();
975 m_startPos = GenTime((int) newPos.x(), m_fps);
981 m_startPos = GenTime((int) newPos.x(), m_fps);
982 //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
985 return QGraphicsItem::itemChange(change, value);
989 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
992 int ClipItem::effectsCounter() {
993 return m_effectsCounter++;
996 int ClipItem::effectsCount() {
997 return m_effectList.size();
1000 QStringList ClipItem::effectNames() {
1001 return m_effectList.effectNames();
1004 QDomElement ClipItem::effectAt(int ix) {
1005 if (ix > m_effectList.count() - 1 || ix < 0) return QDomElement();
1006 return m_effectList.at(ix);
1009 void ClipItem::setEffectAt(int ix, QDomElement effect) {
1010 kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1011 m_effectList.insert(ix, effect);
1012 m_effectList.removeAt(ix + 1);
1013 m_effectNames = m_effectList.effectNames().join(" / ");
1014 if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fadeout") update(boundingRect());
1016 QRectF r = boundingRect();
1022 QHash <QString, QString> ClipItem::addEffect(QDomElement effect, bool animate) {
1023 QHash <QString, QString> effectParams;
1024 bool needRepaint = false;
1026 doc.appendChild(doc.importNode(effect, true));
1027 kDebug() << "/////// CLIP ADD EFFECT: "<< doc.toString();*/
1028 m_effectList.append(effect);
1029 effectParams["tag"] = effect.attribute("tag");
1030 QString effectId = effect.attribute("id");
1031 if (effectId.isEmpty()) effectId = effect.attribute("tag");
1032 effectParams["id"] = effectId;
1033 effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
1034 QString state = effect.attribute("disabled");
1035 if (!state.isEmpty()) effectParams["disabled"] = state;
1036 QDomNodeList params = effect.elementsByTagName("parameter");
1038 for (int i = 0; i < params.count(); i++) {
1039 QDomElement e = params.item(i).toElement();
1041 if (e.attribute("type") == "keyframe") {
1042 effectParams["keyframes"] = e.attribute("keyframes");
1043 effectParams["min"] = e.attribute("min");
1044 effectParams["max"] = e.attribute("max");
1045 effectParams["factor"] = e.attribute("factor", "1");
1046 effectParams["starttag"] = e.attribute("starttag", "start");
1047 effectParams["endtag"] = e.attribute("endtag", "end");
1050 double f = e.attribute("factor", "1").toDouble();
1053 effectParams[e.attribute("name")] = e.attribute("value");
1054 // check if it is a fade effect
1055 if (effectId == "fadein") {
1057 if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1058 else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1059 } else if (effectId == "fadeout") {
1061 if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1062 else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1065 effectParams[e.attribute("name")] = QString::number(effectParams[e.attribute("name")].toDouble() / f);
1069 m_effectNames = m_effectList.effectNames().join(" / ");
1070 if (fade > 0) m_startFade = fade;
1071 else if (fade < 0) m_endFade = -fade;
1072 if (needRepaint) update(boundingRect());
1075 } else if (!needRepaint) {
1076 QRectF r = boundingRect();
1080 if (m_selectedEffect == -1) {
1081 m_selectedEffect = 0;
1082 setSelectedEffect(m_selectedEffect);
1084 return effectParams;
1087 QHash <QString, QString> ClipItem::getEffectArgs(QDomElement effect) {
1088 QHash <QString, QString> effectParams;
1089 effectParams["tag"] = effect.attribute("tag");
1090 effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
1091 effectParams["id"] = effect.attribute("id");
1092 QString state = effect.attribute("disabled");
1093 if (!state.isEmpty()) effectParams["disabled"] = state;
1094 QDomNodeList params = effect.elementsByTagName("parameter");
1095 for (int i = 0; i < params.count(); i++) {
1096 QDomElement e = params.item(i).toElement();
1097 //kDebug() << "/ / / /SENDING EFFECT PARAM: " << e.attribute("type") << ", NAME_ " << e.attribute("tag");
1098 if (e.attribute("type") == "keyframe") {
1099 kDebug() << "/ / / /SENDING KEYFR EFFECT TYPE";
1100 effectParams["keyframes"] = e.attribute("keyframes");
1101 effectParams["max"] = e.attribute("max");
1102 effectParams["min"] = e.attribute("min");
1103 effectParams["factor"] = e.attribute("factor", "1");
1104 effectParams["starttag"] = e.attribute("starttag", "start");
1105 effectParams["endtag"] = e.attribute("endtag", "end");
1106 } else if (e.attribute("namedesc").contains(";")) {
1107 QString format = e.attribute("format");
1108 QStringList separators = format.split("%d", QString::SkipEmptyParts);
1109 QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
1111 QTextStream txtNeu(&neu);
1112 if (values.size() > 0)
1113 txtNeu << (int)values[0].toDouble();
1114 for (int i = 0;i < separators.size() && i + 1 < values.size();i++) {
1115 txtNeu << separators[i];
1116 txtNeu << (int)(values[i+1].toDouble());
1118 effectParams["start"] = neu;
1120 if (e.attribute("factor", "1") != "1")
1121 effectParams[e.attribute("name")] = QString::number(e.attribute("value").toDouble() / e.attribute("factor").toDouble());
1122 else effectParams[e.attribute("name")] = e.attribute("value");
1125 return effectParams;
1128 void ClipItem::deleteEffect(QString index) {
1129 bool needRepaint = false;
1130 for (int i = 0; i < m_effectList.size(); ++i) {
1131 if (m_effectList.at(i).attribute("kdenlive_ix") == index) {
1132 if (m_effectList.at(i).attribute("id") == "fadein") {
1135 } else if (m_effectList.at(i).attribute("id") == "fadeout") {
1139 m_effectList.removeAt(i);
1143 m_effectNames = m_effectList.effectNames().join(" / ");
1144 if (needRepaint) update(boundingRect());
1148 double ClipItem::speed() const {
1152 void ClipItem::setSpeed(const double speed) {
1154 if (m_speed == 1.0) m_clipName = baseClip()->name();
1155 else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + "%";
1159 GenTime ClipItem::maxDuration() const {
1160 return m_maxDuration / m_speed;
1164 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event) {
1165 QString effects = QString(event->mimeData()->data("kdenlive/effectslist"));
1167 doc.setContent(effects, true);
1168 QDomElement e = doc.documentElement();
1169 CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1170 if (view) view->slotAddEffect(e, m_startPos, track());
1174 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
1175 event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
1178 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) {
1181 void ClipItem::addTransition(Transition* t) {
1182 m_transitionsList.append(t);
1183 CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1185 QDomElement e = doc.documentElement();
1186 //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1190 void CustomTrackView::mousePressEvent ( QMouseEvent * event )
1192 int pos = event->x();
1193 if (event->modifiers() == Qt::ControlModifier)
1194 setDragMode(QGraphicsView::ScrollHandDrag);
1195 else if (event->modifiers() == Qt::ShiftModifier)
1196 setDragMode(QGraphicsView::RubberBandDrag);
1198 QGraphicsItem * item = itemAt(event->pos());
1201 else emit cursorMoved((int) mapToScene(event->x(), 0).x());
1204 QGraphicsView::mousePressEvent(event);
1207 void CustomTrackView::mouseReleaseEvent ( QMouseEvent * event )
1209 QGraphicsView::mouseReleaseEvent(event);
1210 setDragMode(QGraphicsView::NoDrag);
1214 #include "clipitem.moc"