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 QRectF mapped = painter->matrix().mapRect(br);
421 const double itemWidth = br.width();
422 const double itemHeight = br.height();
423 const double scale = option->matrix.m11();
427 //painter->setRenderHints(QPainter::Antialiasing);
429 //QPainterPath roundRectPathUpper = upperRectPart(br), roundRectPathLower = lowerRectPart(br);
430 painter->setClipRect(exposed);
432 // build path around clip
433 //QPainterPath resultClipPath = roundRectPathUpper.united(roundRectPathLower);
434 //painter->fillPath(resultClipPath, paintColor);
435 painter->fillRect(br, paintColor);
437 //painter->setClipPath(resultClipPath, Qt::IntersectClip);
440 painter->setMatrixEnabled(false);
442 if (KdenliveSettings::videothumbnails()) {
443 QPen pen = painter->pen();
444 pen.setStyle(Qt::DotLine);
445 pen.setColor(Qt::white);
446 painter->setPen(pen);
447 if (m_clipType == IMAGE && !m_startPix.isNull()) {
448 QPointF p1 = painter->matrix().map(QPointF(itemWidth, 0)) - QPointF(m_startPix.width(), 0);
449 QPointF p2 = painter->matrix().map(QPointF(itemWidth, itemHeight)) - QPointF(m_startPix.width(), 0);
450 painter->drawPixmap(p1, m_startPix);
452 painter->drawLine(l);
453 } else if (!m_endPix.isNull()) {
454 QPointF p1 = painter->matrix().map(QPointF(itemWidth, 0)) - QPointF(m_endPix.width(), 0);
455 QPointF p2 = painter->matrix().map(QPointF(itemWidth, itemHeight)) - QPointF(m_endPix.width(), 0);
456 painter->drawPixmap(p1, m_endPix);
458 painter->drawLine(l);
460 if (!m_startPix.isNull()) {
461 QPointF p1 = painter->matrix().map(QPointF(0, 0));
462 QPointF p2 = painter->matrix().map(QPointF(0, itemHeight));
463 painter->drawPixmap(p1, m_startPix);
464 QLineF l2(p1.x() + m_startPix.width(), p1.y(), p2.x() + m_startPix.width(), p2.y());
465 painter->drawLine(l2);
467 painter->setPen(Qt::black);
470 // draw audio thumbnails
471 if (KdenliveSettings::audiothumbnails() && ((m_clipType == AV && exposed.bottom() > (itemHeight / 2)) || m_clipType == AUDIO) && audioThumbReady) {
473 double startpixel = exposed.left();
476 double endpixel = exposed.right();
479 //kDebug()<<"/// REPAINTING AUDIO THMBS ZONE: "<<startpixel<<"x"<<endpixel;
481 /*QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;*/
483 if (m_clipType == AV) {
485 re.setTop(re.y() + re.height() / 2);
486 mappedRect = painter->matrix().mapRect(re);
487 //painter->fillRect(mappedRect, QBrush(QColor(200, 200, 200, 140)));
488 } else mappedRect = mapped;
490 int channels = baseClip()->getProperty("channels").toInt();
491 if (scale != framePixelWidth)
492 audioThumbCachePic.clear();
493 double cropLeft = m_cropStart.frames(m_fps);
494 const int clipStart = mappedRect.x();
495 const int mappedStartPixel = painter->matrix().map(QPointF(startpixel + cropLeft, 0)).x() - clipStart;
496 const int mappedEndPixel = painter->matrix().map(QPointF(endpixel + cropLeft, 0)).x() - clipStart;
497 cropLeft = cropLeft * scale;
499 emit prepareAudioThumb(scale, mappedStartPixel, mappedEndPixel, channels);
501 for (int startCache = mappedStartPixel - (mappedStartPixel) % 100; startCache < mappedEndPixel; startCache += 100) {
502 if (audioThumbCachePic.contains(startCache) && !audioThumbCachePic[startCache].isNull())
503 painter->drawPixmap(clipStart + startCache - cropLeft, mappedRect.y(), audioThumbCachePic[startCache]);
508 QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
509 QList < CommentedTime >::Iterator it = markers.begin();
512 const int markerwidth = 4;
514 markerBrush = QBrush(QColor(120, 120, 0, 140));
515 QPen pen = painter->pen();
516 pen.setColor(QColor(255, 255, 255, 200));
517 pen.setStyle(Qt::DotLine);
518 painter->setPen(pen);
519 for (; it != markers.end(); ++it) {
520 pos = (*it).time() - cropStart();
521 if (pos > GenTime()) {
522 if (pos > duration()) break;
523 QLineF l(br.x() + pos.frames(m_fps), br.y() + 5, br.x() + pos.frames(m_fps), br.bottom() - 5);
524 QLineF l2 = painter->matrix().map(l);
525 //framepos = scale * pos.frames(m_fps);
526 //QLineF l(framepos, 5, framepos, itemHeight - 5);
527 painter->drawLine(l2);
528 if (KdenliveSettings::showmarkers()) {
529 framepos = br.x() + pos.frames(m_fps);
530 const QRectF r1(framepos + 0.04, 10, itemWidth - framepos - 2, itemHeight - 10);
531 const QRectF r2 = painter->matrix().mapRect(r1);
532 const QRectF txtBounding = painter->boundingRect(r2, Qt::AlignLeft | Qt::AlignTop, " " + (*it).comment() + " ");
535 path.addRoundedRect(txtBounding, 3, 3);
536 painter->fillPath(path, markerBrush);
537 painter->drawText(txtBounding, Qt::AlignCenter, (*it).comment());
539 //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
542 pen.setColor(Qt::black);
543 pen.setStyle(Qt::SolidLine);
544 painter->setPen(pen);
546 // draw start / end fades
549 fades = QBrush(QColor(200, 50, 50, 150));
550 } else fades = QBrush(QColor(200, 200, 200, 200));
552 if (m_startFade != 0) {
553 QPainterPath fadeInPath;
554 fadeInPath.moveTo(0, 0);
555 fadeInPath.lineTo(0, itemHeight);
556 fadeInPath.lineTo(m_startFade, 0);
557 fadeInPath.closeSubpath();
558 QPainterPath f1 = painter->matrix().map(fadeInPath);
559 painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
560 /*if (isSelected()) {
561 QLineF l(m_startFade * scale, 0, 0, itemHeight);
562 painter->drawLine(l);
565 if (m_endFade != 0) {
566 QPainterPath fadeOutPath;
567 fadeOutPath.moveTo(itemWidth, 0);
568 fadeOutPath.lineTo(itemWidth, itemHeight);
569 fadeOutPath.lineTo(itemWidth - m_endFade, 0);
570 fadeOutPath.closeSubpath();
571 QPainterPath f1 = painter->matrix().map(fadeOutPath);
572 painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
573 /*if (isSelected()) {
574 QLineF l(itemWidth - m_endFade * scale, 0, itemWidth, itemHeight);
575 painter->drawLine(l);
579 // Draw effects names
580 if (!m_effectNames.isEmpty() && itemWidth * scale > 40) {
581 QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
582 txtBounding.setRight(txtBounding.right() + 15);
583 painter->setPen(Qt::white);
584 QBrush markerBrush(Qt::SolidPattern);
585 if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
586 qreal value = m_timeLine->currentValue();
587 txtBounding.setWidth(txtBounding.width() * value);
588 markerBrush.setColor(QColor(50 + 200 * (1.0 - value), 50, 50, 100 + 50 * value));
589 } else markerBrush.setColor(QColor(50, 50, 50, 150));
591 path.addRoundedRect(txtBounding, 4, 4);
592 painter->fillPath(path/*.intersected(resultClipPath)*/, markerBrush);
593 painter->drawText(txtBounding, Qt::AlignCenter, m_effectNames);
594 painter->setPen(Qt::black);
599 QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignHCenter | Qt::AlignTop, " " + m_clipName + " ");
600 //painter->fillRect(txtBounding, QBrush(QColor(255, 255, 255, 150)));
601 painter->setPen(QColor(0, 0, 0, 180));
602 painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
603 txtBounding.translate(QPointF(1, 1));
604 painter->setPen(QColor(255, 255, 255, 255));
605 painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
608 // draw transition handles on hover
609 if (m_hover && itemWidth * scale > 40) {
610 QPainterPath transitionHandle;
611 const int handle_size = 4;
612 QPointF p1 = painter->matrix().map(QPointF(0, itemHeight / 2)) + QPointF(10, 0);
613 painter->drawPixmap(p1, projectScene()->m_transitionPixmap);
614 p1 = painter->matrix().map(QPointF(itemWidth, itemHeight / 2)) - QPointF(10 + handle_size * 3, 0);
615 painter->drawPixmap(p1, projectScene()->m_transitionPixmap);
619 // draw frame around clip
621 pen.setColor(Qt::red);
624 pen.setColor(Qt::black);
628 // draw effect or transition keyframes
629 if (itemWidth > 20) drawKeyFrames(painter, exposed);
631 painter->setMatrixEnabled(true);
635 //kDebug()<<"/// ITEM PAINTING:: exposed="<<exposed<<", RECT = "<<rect();
637 exposed.setRight(exposed.right() + 1);
638 exposed.setBottom(exposed.bottom() + 1);
639 painter->setClipRect(exposed);
640 //painter->setClipping(false);
641 //painter->fillRect(exposed, Qt::blue);
642 painter->setPen(pen);
643 painter->drawRect(br);
647 OPERATIONTYPE ClipItem::operationMode(QPointF pos) {
649 m_editedKeyframe = mouseOverKeyFrames(pos);
650 if (m_editedKeyframe != -1) return KEYFRAME;
652 QRectF rect = sceneBoundingRect();
653 const double scale = projectScene()->scale();
654 double maximumOffset;
655 if (scale > 3) maximumOffset = 25 / scale;
656 else maximumOffset = 6 / scale;
658 matrix.scale(scale, 0);
659 //kDebug()<<"// Item rect: "<<rect.x()<<". pos. "<<pos.x()<<", scale: "<<scale<<", ratio: "<<qAbs((int)(pos.x() - rect.x())) / scale;
661 if (qAbs((int)(pos.x() - (rect.x() + m_startFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
662 if (m_startFade == 0) setToolTip(i18n("Add audio fade"));
663 else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_startFade, m_fps).seconds()));
665 } else if (pos.x() - rect.x() < maximumOffset) {
666 setToolTip(i18n("Crop from start: %1s", cropStart().seconds()));
668 } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - m_endFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
669 if (m_endFade == 0) setToolTip(i18n("Add audio fade"));
670 else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_endFade, m_fps).seconds()));
672 } else if (qAbs((int)(pos.x() - (rect.x() + rect.width()))) < maximumOffset) {
673 setToolTip(i18n("Clip duration: %1s", duration().seconds()));
675 } else if (qAbs((int)(pos.x() - (rect.x() + 16))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 5))) < 6) {
676 setToolTip(i18n("Add transition"));
677 return TRANSITIONSTART;
678 } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - 21))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 5))) < 6) {
679 setToolTip(i18n("Add transition"));
680 return TRANSITIONEND;
682 setToolTip(QString());
686 QList <GenTime> ClipItem::snapMarkers() const {
687 QList < GenTime > snaps;
688 QList < GenTime > markers = baseClip()->snapMarkers();
692 for (int i = 0; i < markers.size(); i++) {
693 pos = markers.at(i) - cropStart();
694 if (pos > GenTime()) {
695 if (pos > duration()) break;
696 else snaps.append(pos + startPos());
702 QList <CommentedTime> ClipItem::commentedSnapMarkers() const {
703 QList < CommentedTime > snaps;
704 QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
708 for (int i = 0; i < markers.size(); i++) {
709 pos = markers.at(i).time() - cropStart();
710 if (pos > GenTime()) {
711 if (pos > duration()) break;
712 else snaps.append(CommentedTime(pos + startPos(), markers.at(i).comment()));
718 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, int startpixel, int endpixel, int channels) {
720 QRectF re = sceneBoundingRect();
721 if (m_clipType == AV) re.setTop(re.y() + re.height() / 2);
723 //kDebug() << "// PREP AUDIO THMB FRMO : scale:" << pixelForOneFrame<< ", from: " << startpixel << ", to: " << endpixel;
724 //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
726 for (int startCache = startpixel - startpixel % 100;startCache < endpixel;startCache += 100) {
727 //kDebug() << "creating " << startCache;
728 //if (framePixelWidth!=pixelForOneFrame ||
729 if (framePixelWidth == pixelForOneFrame && audioThumbCachePic.contains(startCache))
731 if (audioThumbCachePic[startCache].isNull() || framePixelWidth != pixelForOneFrame) {
732 audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
733 audioThumbCachePic[startCache].fill(QColor(180, 180, 200, 140));
735 bool fullAreaDraw = pixelForOneFrame < 10;
736 QMap<int, QPainterPath > positiveChannelPaths;
737 QMap<int, QPainterPath > negativeChannelPaths;
738 QPainter pixpainter(&audioThumbCachePic[startCache]);
740 audiopen.setWidth(0);
741 pixpainter.setPen(audiopen);
742 //pixpainter.setRenderHint(QPainter::Antialiasing,true);
743 //pixpainter.drawLine(0,0,100,re.height());
744 int channelHeight = audioThumbCachePic[startCache].height() / channels;
746 for (int i = 0;i < channels;i++) {
748 positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
749 negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
752 for (int samples = 0;samples <= 100;samples++) {
753 double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
754 int sample = (int)((frame - (int)(frame)) * 20); // AUDIO_FRAME_SIZE
755 if (frame < 0 || sample < 0 || sample > 19)
757 QMap<int, QByteArray> frame_channel_data = baseClip()->audioFrameChache[(int)frame];
759 for (int channel = 0;channel < channels && frame_channel_data[channel].size() > 0;channel++) {
761 int y = channelHeight * channel + channelHeight / 2;
762 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2) * channelHeight / 64;
764 positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
765 negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
767 positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
768 negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
771 for (int channel = 0;channel < channels ;channel++)
772 if (fullAreaDraw && samples == 100) {
773 positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
774 negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
775 positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
776 negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
780 if (m_clipType != AV) pixpainter.setBrush(QBrush(QColor(200, 200, 100)));
782 pixpainter.setPen(QPen(QColor(0, 0, 0)));
783 pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
785 for (int i = 0;i < channels;i++) {
787 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
788 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
790 pixpainter.drawPath(positiveChannelPaths[i]);
793 //audioThumbWasDrawn=true;
794 framePixelWidth = pixelForOneFrame;
799 uint ClipItem::fadeIn() const {
803 uint ClipItem::fadeOut() const {
808 void ClipItem::setFadeIn(int pos) {
809 int oldIn = m_startFade;
810 if (pos < 0) pos = 0;
811 if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
813 QRectF rect = boundingRect();
814 update(rect.x(), rect.y(), qMax(oldIn, pos), rect.height());
817 void ClipItem::setFadeOut(int pos) {
818 int oldOut = m_endFade;
819 if (pos < 0) pos = 0;
820 if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
822 QRectF rect = boundingRect();
823 update(rect.x() + rect.width() - qMax(oldOut, pos), rect.y(), pos, rect.height());
828 void ClipItem::mousePressEvent(QGraphicsSceneMouseEvent * event) {
829 /*m_resizeMode = operationMode(event->pos());
830 if (m_resizeMode == MOVE) {
831 m_maxTrack = scene()->sceneRect().height();
832 m_grabPoint = (int) (event->pos().x() - rect().x());
834 QGraphicsRectItem::mousePressEvent(event);
838 void ClipItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) {
840 QGraphicsRectItem::mouseReleaseEvent(event);
844 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e) {
845 //if (e->pos().x() < 20) m_hover = true;
847 QRectF r = boundingRect();
848 double width = 35 / projectScene()->scale();
849 double height = r.height() / 2;
850 //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
851 update(r.x(), r.y() + height, width, height);
852 update(r.right() - width, r.y() + height, width, height);
856 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *) {
858 QRectF r = boundingRect();
859 double width = 35 / projectScene()->scale();
860 double height = r.height() / 2;
861 //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
862 update(r.x(), r.y() + height, width, height);
863 update(r.right() - width, r.y() + height, width, height);
866 void ClipItem::resizeStart(int posx) {
867 const int min = (startPos() - cropStart()).frames(m_fps);
868 if (posx < min) posx = min;
869 if (posx == startPos().frames(m_fps)) return;
870 const int previous = cropStart().frames(m_fps);
871 AbstractClipItem::resizeStart(posx);
872 checkEffectsKeyframesPos(previous, cropStart().frames(m_fps), true);
873 if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
874 /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
875 startThumbTimer->start(100);
879 void ClipItem::resizeEnd(int posx) {
880 const int max = (startPos() - cropStart() + maxDuration()).frames(m_fps) + 1;
881 if (posx > max) posx = max;
882 if (posx == endPos().frames(m_fps)) return;
883 const int previous = (cropStart() + duration()).frames(m_fps);
884 AbstractClipItem::resizeEnd(posx);
885 checkEffectsKeyframesPos(previous, (cropStart() + duration()).frames(m_fps), false);
886 if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
887 /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
888 endThumbTimer->start(100);
893 void ClipItem::checkEffectsKeyframesPos(const int previous, const int current, bool fromStart) {
894 for (int i = 0; i < m_effectList.size(); i++) {
895 QDomElement effect = m_effectList.at(i);
896 QDomNodeList params = effect.elementsByTagName("parameter");
897 for (int j = 0; j < params.count(); j++) {
898 QDomElement e = params.item(i).toElement();
899 if (e.attribute("type") == "keyframe") {
900 // parse keyframes and adjust values
901 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
902 QMap <int, double> kfr;
903 foreach(const QString str, keyframes) {
904 int pos = str.section(":", 0, 0).toInt();
905 double val = str.section(":", 1, 1).toDouble();
906 if (pos == previous) kfr[current] = val;
908 if (fromStart && pos >= current) kfr[pos] = val;
909 else if (!fromStart && pos <= current) kfr[pos] = val;
913 QMap<int, double>::const_iterator k = kfr.constBegin();
914 while (k != kfr.constEnd()) {
915 newkfr.append(QString::number(k.key()) + ":" + QString::number(k.value()) + ";");
918 e.setAttribute("keyframes", newkfr);
923 if (m_selectedEffect >= 0) setSelectedEffect(m_selectedEffect);
928 QVariant ClipItem::itemChange(GraphicsItemChange change, const QVariant &value) {
929 if (change == ItemPositionChange && scene()) {
930 // calculate new position.
931 if (group() != 0) return pos();
932 QPointF newPos = value.toPointF();
933 kDebug() << "/// MOVING CLIP ITEM.------------";
934 int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
935 xpos = qMax(xpos, 0);
937 int newTrack = (newPos.y() + KdenliveSettings::trackheight() / 2) / KdenliveSettings::trackheight();
938 newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
939 newTrack = qMax(newTrack, 0);
940 newPos.setY((int)(newTrack * KdenliveSettings::trackheight() + 1));
941 // Only one clip is moving
942 QRectF sceneShape = rect();
943 sceneShape.translate(newPos);
944 QList<QGraphicsItem*> items = scene()->items(sceneShape, Qt::IntersectsItemShape);
945 items.removeAll(this);
947 if (!items.isEmpty()) {
948 for (int i = 0; i < items.count(); i++) {
949 if (items.at(i)->type() == type()) {
951 QPointF otherPos = items.at(i)->pos();
952 if ((int) otherPos.y() != (int) pos().y()) return pos();
953 if (pos().x() < otherPos.x()) {
954 // move clip just before colliding clip
955 int npos = (static_cast < AbstractClipItem* >(items.at(i))->startPos() - m_cropDuration).frames(m_fps);
956 // check we don't run into another clip
959 sceneShape.translate(newPos);
960 QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
961 items.removeAll(this);
962 for (int j = 0; j < subitems.count(); i++) {
963 if (subitems.at(j)->type() == type()) return pos();
966 // get pos just after colliding clip
967 int npos = static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps);
968 // check we don't run into another clip
971 sceneShape.translate(newPos);
972 QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
973 items.removeAll(this);
974 for (int j = 0; j < subitems.count(); i++) {
975 if (subitems.at(j)->type() == type()) return pos();
979 m_startPos = GenTime((int) newPos.x(), m_fps);
985 m_startPos = GenTime((int) newPos.x(), m_fps);
986 //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
989 return QGraphicsItem::itemChange(change, value);
993 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
996 int ClipItem::effectsCounter() {
997 return m_effectsCounter++;
1000 int ClipItem::effectsCount() {
1001 return m_effectList.size();
1004 QStringList ClipItem::effectNames() {
1005 return m_effectList.effectNames();
1008 QDomElement ClipItem::effectAt(int ix) {
1009 if (ix > m_effectList.count() - 1 || ix < 0) return QDomElement();
1010 return m_effectList.at(ix);
1013 void ClipItem::setEffectAt(int ix, QDomElement effect) {
1014 kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1015 m_effectList.insert(ix, effect);
1016 m_effectList.removeAt(ix + 1);
1017 m_effectNames = m_effectList.effectNames().join(" / ");
1018 if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fadeout") update(boundingRect());
1020 QRectF r = boundingRect();
1026 QHash <QString, QString> ClipItem::addEffect(QDomElement effect, bool animate) {
1027 QHash <QString, QString> effectParams;
1028 bool needRepaint = false;
1030 doc.appendChild(doc.importNode(effect, true));
1031 kDebug() << "/////// CLIP ADD EFFECT: "<< doc.toString();*/
1032 m_effectList.append(effect);
1033 effectParams["tag"] = effect.attribute("tag");
1034 QString effectId = effect.attribute("id");
1035 if (effectId.isEmpty()) effectId = effect.attribute("tag");
1036 effectParams["id"] = effectId;
1037 effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
1038 QString state = effect.attribute("disabled");
1039 if (!state.isEmpty()) effectParams["disabled"] = state;
1040 QDomNodeList params = effect.elementsByTagName("parameter");
1042 for (int i = 0; i < params.count(); i++) {
1043 QDomElement e = params.item(i).toElement();
1045 if (e.attribute("type") == "keyframe") {
1046 effectParams["keyframes"] = e.attribute("keyframes");
1047 effectParams["min"] = e.attribute("min");
1048 effectParams["max"] = e.attribute("max");
1049 effectParams["factor"] = e.attribute("factor", "1");
1050 effectParams["starttag"] = e.attribute("starttag", "start");
1051 effectParams["endtag"] = e.attribute("endtag", "end");
1054 double f = e.attribute("factor", "1").toDouble();
1057 effectParams[e.attribute("name")] = e.attribute("value");
1058 // check if it is a fade effect
1059 if (effectId == "fadein") {
1061 if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1062 else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1063 } else if (effectId == "fadeout") {
1065 if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1066 else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1069 effectParams[e.attribute("name")] = QString::number(effectParams[e.attribute("name")].toDouble() / f);
1073 m_effectNames = m_effectList.effectNames().join(" / ");
1074 if (fade > 0) m_startFade = fade;
1075 else if (fade < 0) m_endFade = -fade;
1076 if (needRepaint) update(boundingRect());
1079 } else if (!needRepaint) {
1080 QRectF r = boundingRect();
1084 if (m_selectedEffect == -1) {
1085 m_selectedEffect = 0;
1086 setSelectedEffect(m_selectedEffect);
1088 return effectParams;
1091 QHash <QString, QString> ClipItem::getEffectArgs(QDomElement effect) {
1092 QHash <QString, QString> effectParams;
1093 effectParams["tag"] = effect.attribute("tag");
1094 effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
1095 effectParams["id"] = effect.attribute("id");
1096 QString state = effect.attribute("disabled");
1097 if (!state.isEmpty()) effectParams["disabled"] = state;
1098 QDomNodeList params = effect.elementsByTagName("parameter");
1099 for (int i = 0; i < params.count(); i++) {
1100 QDomElement e = params.item(i).toElement();
1101 //kDebug() << "/ / / /SENDING EFFECT PARAM: " << e.attribute("type") << ", NAME_ " << e.attribute("tag");
1102 if (e.attribute("type") == "keyframe") {
1103 kDebug() << "/ / / /SENDING KEYFR EFFECT TYPE";
1104 effectParams["keyframes"] = e.attribute("keyframes");
1105 effectParams["max"] = e.attribute("max");
1106 effectParams["min"] = e.attribute("min");
1107 effectParams["factor"] = e.attribute("factor", "1");
1108 effectParams["starttag"] = e.attribute("starttag", "start");
1109 effectParams["endtag"] = e.attribute("endtag", "end");
1110 } else if (e.attribute("namedesc").contains(";")) {
1111 QString format = e.attribute("format");
1112 QStringList separators = format.split("%d", QString::SkipEmptyParts);
1113 QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
1115 QTextStream txtNeu(&neu);
1116 if (values.size() > 0)
1117 txtNeu << (int)values[0].toDouble();
1118 for (int i = 0;i < separators.size() && i + 1 < values.size();i++) {
1119 txtNeu << separators[i];
1120 txtNeu << (int)(values[i+1].toDouble());
1122 effectParams["start"] = neu;
1124 if (e.attribute("factor", "1") != "1")
1125 effectParams[e.attribute("name")] = QString::number(e.attribute("value").toDouble() / e.attribute("factor").toDouble());
1126 else effectParams[e.attribute("name")] = e.attribute("value");
1129 return effectParams;
1132 void ClipItem::deleteEffect(QString index) {
1133 bool needRepaint = false;
1134 for (int i = 0; i < m_effectList.size(); ++i) {
1135 if (m_effectList.at(i).attribute("kdenlive_ix") == index) {
1136 if (m_effectList.at(i).attribute("id") == "fadein") {
1139 } else if (m_effectList.at(i).attribute("id") == "fadeout") {
1143 m_effectList.removeAt(i);
1147 m_effectNames = m_effectList.effectNames().join(" / ");
1148 if (needRepaint) update(boundingRect());
1152 double ClipItem::speed() const {
1156 void ClipItem::setSpeed(const double speed) {
1158 if (m_speed == 1.0) m_clipName = baseClip()->name();
1159 else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + "%";
1163 GenTime ClipItem::maxDuration() const {
1164 return m_maxDuration / m_speed;
1168 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event) {
1169 QString effects = QString(event->mimeData()->data("kdenlive/effectslist"));
1171 doc.setContent(effects, true);
1172 QDomElement e = doc.documentElement();
1173 CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1174 if (view) view->slotAddEffect(e, m_startPos, track());
1178 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
1179 event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
1182 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) {
1185 void ClipItem::addTransition(Transition* t) {
1186 m_transitionsList.append(t);
1187 CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1189 QDomElement e = doc.documentElement();
1190 //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1194 void CustomTrackView::mousePressEvent ( QMouseEvent * event )
1196 int pos = event->x();
1197 if (event->modifiers() == Qt::ControlModifier)
1198 setDragMode(QGraphicsView::ScrollHandDrag);
1199 else if (event->modifiers() == Qt::ShiftModifier)
1200 setDragMode(QGraphicsView::RubberBandDrag);
1202 QGraphicsItem * item = itemAt(event->pos());
1205 else emit cursorMoved((int) mapToScene(event->x(), 0).x());
1208 QGraphicsView::mousePressEvent(event);
1211 void CustomTrackView::mouseReleaseEvent ( QMouseEvent * event )
1213 QGraphicsView::mouseReleaseEvent(event);
1214 setDragMode(QGraphicsView::NoDrag);
1218 #include "clipitem.moc"