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, bool generateThumbs)
44 : AbstractClipItem(info, QRectF(), fps), m_clip(clip), m_resizeMode(NONE), m_grabPoint(0), m_maxTrack(0), m_hasThumbs(false), startThumbTimer(NULL), endThumbTimer(NULL), 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), m_startPix(QPixmap()), m_endPix(QPixmap()) {
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(this, SIGNAL(getThumb(int, int)), clip->thumbProducer(), SLOT(getVideoThumbs(int, int)));
82 connect(clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));
83 connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
84 if (generateThumbs) QTimer::singleShot(200, this, SLOT(slotFetchThumbs()));
86 /*if (m_clip->producer()) {
87 videoThumbProducer.init(this, m_clip->producer(), KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio(), KdenliveSettings::trackheight());
90 } else if (m_clipType == COLOR) {
91 QString colour = clip->getProperty("colour");
92 colour = colour.replace(0, 2, "#");
93 setBrush(QColor(colour.left(7)));
94 } else if (m_clipType == IMAGE || m_clipType == TEXT) {
95 m_startPix = KThumb::getImage(KUrl(clip->getProperty("resource")), (int)(KdenliveSettings::trackheight() * KdenliveSettings::project_display_ratio()), KdenliveSettings::trackheight());
96 m_endPix = m_startPix;
97 } else if (m_clipType == AUDIO) {
98 connect(clip, SIGNAL(gotAudioData()), this, SLOT(slotGotAudioData()));
103 ClipItem::~ClipItem() {
104 if (startThumbTimer) delete startThumbTimer;
105 if (endThumbTimer) delete endThumbTimer;
106 if (m_timeLine) m_timeLine;
109 ClipItem *ClipItem::clone(ItemInfo info) const {
110 ClipItem *duplicate = new ClipItem(m_clip, info, m_fps);
111 if (info.cropStart == cropStart()) duplicate->slotSetStartThumb(m_startPix);
112 if (info.cropStart + (info.endPos - info.startPos) == m_cropStart + m_cropDuration) duplicate->slotSetEndThumb(m_endPix);
113 kDebug() << "// CLoning clip: " << (info.cropStart + (info.endPos - info.startPos)).frames(m_fps) << ", CURRENT end: " << (cropStart() + duration()).frames(m_fps);
114 duplicate->setEffectList(m_effectList.clone());
115 duplicate->setSpeed(m_speed);
119 void ClipItem::setEffectList(const EffectsList effectList) {
120 m_effectList = effectList;
121 m_effectNames = m_effectList.effectNames().join(" / ");
124 const EffectsList ClipItem::effectList() {
128 int ClipItem::selectedEffectIndex() const {
129 return m_selectedEffect;
132 void ClipItem::initEffect(QDomElement effect) {
133 // the kdenlive_ix int is used to identify an effect in mlt's playlist, should
135 if (effect.attribute("kdenlive_ix").toInt() == 0)
136 effect.setAttribute("kdenlive_ix", QString::number(effectsCounter()));
137 // init keyframes if required
138 QDomNodeList params = effect.elementsByTagName("parameter");
139 for (int i = 0; i < params.count(); i++) {
140 QDomElement e = params.item(i).toElement();
141 if (!e.isNull() && e.attribute("type") == "keyframe") {
142 QString def = e.attribute("default");
143 // Effect has a keyframe type parameter, we need to set the values
144 if (e.attribute("keyframes").isEmpty()) {
145 e.setAttribute("keyframes", QString::number(m_cropStart.frames(m_fps)) + ":" + def + ";" + QString::number((m_cropStart + m_cropDuration).frames(m_fps)) + ":" + def);
146 //kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
153 void ClipItem::setKeyframes(const int ix, const QString keyframes) {
154 QDomElement effect = effectAt(ix);
155 if (effect.attribute("disabled") == "1") return;
156 QDomNodeList params = effect.elementsByTagName("parameter");
157 for (int i = 0; i < params.count(); i++) {
158 QDomElement e = params.item(i).toElement();
159 if (!e.isNull() && e.attribute("type") == "keyframe") {
160 e.setAttribute("keyframes", keyframes);
161 if (ix == m_selectedEffect) {
163 double max = e.attribute("max").toDouble();
164 double min = e.attribute("min").toDouble();
165 m_keyframeFactor = 100.0 / (max - min);
166 m_keyframeDefault = e.attribute("default").toDouble();
168 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
169 foreach(const QString str, keyframes) {
170 int pos = str.section(":", 0, 0).toInt();
171 double val = str.section(":", 1, 1).toDouble();
172 m_keyframes[pos] = val;
183 void ClipItem::setSelectedEffect(const int ix) {
184 m_selectedEffect = ix;
185 QDomElement effect = effectAt(m_selectedEffect);
186 QDomNodeList params = effect.elementsByTagName("parameter");
187 if (effect.attribute("disabled") != "1")
188 for (int i = 0; i < params.count(); i++) {
189 QDomElement e = params.item(i).toElement();
190 if (!e.isNull() && e.attribute("type") == "keyframe") {
192 double max = e.attribute("max").toDouble();
193 double min = e.attribute("min").toDouble();
194 m_keyframeFactor = 100.0 / (max - min);
195 m_keyframeDefault = e.attribute("default").toDouble();
197 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
198 foreach(const QString str, keyframes) {
199 int pos = str.section(":", 0, 0).toInt();
200 double val = str.section(":", 1, 1).toDouble();
201 m_keyframes[pos] = val;
207 if (!m_keyframes.isEmpty()) {
213 QString ClipItem::keyframes(const int index) {
215 QDomElement effect = effectAt(index);
216 QDomNodeList params = effect.elementsByTagName("parameter");
218 for (int i = 0; i < params.count(); i++) {
219 QDomElement e = params.item(i).toElement();
220 if (!e.isNull() && e.attribute("type") == "keyframe") {
221 result = e.attribute("keyframes");
228 void ClipItem::updateKeyframeEffect() {
229 // regenerate xml parameter from the clip keyframes
230 QDomElement effect = effectAt(m_selectedEffect);
231 if (effect.attribute("disabled") == "1") return;
232 QDomNodeList params = effect.elementsByTagName("parameter");
234 for (int i = 0; i < params.count(); i++) {
235 QDomElement e = params.item(i).toElement();
236 if (!e.isNull() && e.attribute("type") == "keyframe") {
238 if (m_keyframes.count() > 1) {
239 QMap<int, double>::const_iterator i = m_keyframes.constBegin();
242 while (i != m_keyframes.constEnd()) {
243 keyframes.append(QString::number(i.key()) + ":" + QString::number(i.value()) + ";");
247 // Effect has a keyframe type parameter, we need to set the values
248 //kDebug() << "::::::::::::::: SETTING EFFECT KEYFRAMES: " << keyframes;
249 e.setAttribute("keyframes", keyframes);
255 QDomElement ClipItem::selectedEffect() {
256 if (m_selectedEffect == -1 || m_effectList.isEmpty()) return QDomElement();
257 return effectAt(m_selectedEffect);
260 void ClipItem::resetThumbs() {
261 m_startPix = QPixmap();
262 m_endPix = QPixmap();
264 audioThumbCachePic.clear();
268 void ClipItem::refreshClip() {
269 m_maxDuration = m_clip->maxDuration();
270 if (m_clipType == COLOR) {
271 QString colour = m_clip->getProperty("colour");
272 colour = colour.replace(0, 2, "#");
273 setBrush(QColor(colour.left(7)));
274 } else slotFetchThumbs();
277 void ClipItem::slotFetchThumbs() {
278 if (m_endPix.isNull() && m_startPix.isNull()) {
279 m_startThumbRequested = true;
280 m_endThumbRequested = true;
281 emit getThumb((int)m_cropStart.frames(m_fps), (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1);
283 if (m_endPix.isNull()) {
286 if (m_startPix.isNull()) {
292 if (m_endPix.isNull() && m_startPix.isNull()) {
293 int frame1 = (int)m_cropStart.frames(m_fps);
294 int frame2 = (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1;
295 //videoThumbProducer.setThumbFrames(m_clip->producer(), frame1, frame2);
296 //videoThumbProducer.start(QThread::LowestPriority);
298 if (m_endPix.isNull()) slotGetEndThumb();
299 else slotGetStartThumb();
302 } else if (m_startPix.isNull()) slotGetStartThumb();*/
305 void ClipItem::slotGetStartThumb() {
306 m_startThumbRequested = true;
307 emit getThumb((int)m_cropStart.frames(m_fps), -1);
308 //videoThumbProducer.setThumbFrames(m_clip->producer(), (int)m_cropStart.frames(m_fps), - 1);
309 //videoThumbProducer.start(QThread::LowestPriority);
312 void ClipItem::slotGetEndThumb() {
313 m_endThumbRequested = true;
314 emit getThumb(-1, (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1);
315 //videoThumbProducer.setThumbFrames(m_clip->producer(), -1, (int)(m_cropStart + m_cropDuration).frames(m_fps) - 1);
316 //videoThumbProducer.start(QThread::LowestPriority);
320 void ClipItem::slotSetStartThumb(QImage img) {
321 if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
322 QPixmap pix = QPixmap::fromImage(img);
324 QRectF r = sceneBoundingRect();
325 r.setRight(pix.width() + 2);
330 void ClipItem::slotSetEndThumb(QImage img) {
331 if (!img.isNull() && img.format() == QImage::Format_ARGB32) {
332 QPixmap pix = QPixmap::fromImage(img);
334 QRectF r = sceneBoundingRect();
335 r.setLeft(r.right() - pix.width() - 2);
340 void ClipItem::slotThumbReady(int frame, QPixmap pix) {
341 if (scene() == NULL) return;
342 QRectF r = sceneBoundingRect();
343 double width = m_startPix.width() / projectScene()->scale();
344 if (m_startThumbRequested && frame == m_cropStart.frames(m_fps)) {
346 m_startThumbRequested = false;
347 double height = r.height();
348 update(r.x(), r.y(), width, height);
349 } else if (m_endThumbRequested && frame == (m_cropStart + m_cropDuration).frames(m_fps) - 1) {
351 m_endThumbRequested = false;
352 double height = r.height();
353 update(r.right() - width, r.y(), width, height);
357 void ClipItem::slotSetStartThumb(QPixmap pix) {
361 void ClipItem::slotSetEndThumb(QPixmap pix) {
365 void ClipItem::slotGotAudioData() {
366 audioThumbReady = true;
367 if (m_clipType == AV) {
368 QRectF r = boundingRect();
369 r.setTop(r.top() + r.height() / 2 - 1);
374 int ClipItem::type() const {
378 DocClipBase *ClipItem::baseClip() const {
382 QDomElement ClipItem::xml() const {
383 return m_clip->toXML();
386 int ClipItem::clipType() const {
390 QString ClipItem::clipName() const {
394 const QString &ClipItem::clipProducer() const {
398 void ClipItem::flashClip() {
399 if (m_timeLine == 0) {
400 m_timeLine = new QTimeLine(750, this);
401 m_timeLine->setCurveShape(QTimeLine::EaseInOutCurve);
402 connect(m_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(animate(qreal)));
407 void ClipItem::animate(qreal value) {
408 QRectF r = boundingRect();
414 void ClipItem::paint(QPainter *painter,
415 const QStyleOptionGraphicsItem *option,
417 painter->setOpacity(m_opacity);
418 QBrush paintColor = brush();
419 if (isSelected()) paintColor = QBrush(QColor(79, 93, 121));
421 QRectF exposed = option->exposedRect;
422 QRectF mapped = painter->matrix().mapRect(br);
424 const double itemWidth = br.width();
425 const double itemHeight = br.height();
426 const double scale = option->matrix.m11();
430 //painter->setRenderHints(QPainter::Antialiasing);
432 //QPainterPath roundRectPathUpper = upperRectPart(br), roundRectPathLower = lowerRectPart(br);
433 painter->setClipRect(exposed);
435 // build path around clip
436 //QPainterPath resultClipPath = roundRectPathUpper.united(roundRectPathLower);
437 //painter->fillPath(resultClipPath, paintColor);
438 painter->fillRect(br, paintColor);
440 //painter->setClipPath(resultClipPath, Qt::IntersectClip);
443 painter->setMatrixEnabled(false);
445 if (KdenliveSettings::videothumbnails()) {
446 QPen pen = painter->pen();
447 pen.setStyle(Qt::DotLine);
448 pen.setColor(Qt::white);
449 painter->setPen(pen);
450 if (m_clipType == IMAGE && !m_startPix.isNull()) {
451 QPointF p1 = painter->matrix().map(QPointF(itemWidth, 0)) - QPointF(m_startPix.width(), 0);
452 QPointF p2 = painter->matrix().map(QPointF(itemWidth, itemHeight)) - QPointF(m_startPix.width(), 0);
453 painter->drawPixmap(p1, m_startPix);
455 painter->drawLine(l);
456 } else if (!m_endPix.isNull()) {
457 QPointF p1 = painter->matrix().map(QPointF(itemWidth, 0)) - QPointF(m_endPix.width(), 0);
458 QPointF p2 = painter->matrix().map(QPointF(itemWidth, itemHeight)) - QPointF(m_endPix.width(), 0);
459 painter->drawPixmap(p1, m_endPix);
461 painter->drawLine(l);
463 if (!m_startPix.isNull()) {
464 QPointF p1 = painter->matrix().map(QPointF(0, 0));
465 QPointF p2 = painter->matrix().map(QPointF(0, itemHeight));
466 painter->drawPixmap(p1, m_startPix);
467 QLineF l2(p1.x() + m_startPix.width(), p1.y(), p2.x() + m_startPix.width(), p2.y());
468 painter->drawLine(l2);
470 painter->setPen(Qt::black);
473 // draw audio thumbnails
474 if (KdenliveSettings::audiothumbnails() && ((m_clipType == AV && exposed.bottom() > (itemHeight / 2)) || m_clipType == AUDIO) && audioThumbReady) {
476 double startpixel = exposed.left();
479 double endpixel = exposed.right();
482 //kDebug()<<"/// REPAINTING AUDIO THMBS ZONE: "<<startpixel<<"x"<<endpixel;
484 /*QPainterPath path = m_clipType == AV ? roundRectPathLower : resultClipPath;*/
486 if (m_clipType == AV) {
488 re.setTop(re.y() + re.height() / 2);
489 mappedRect = painter->matrix().mapRect(re);
490 //painter->fillRect(mappedRect, QBrush(QColor(200, 200, 200, 140)));
491 } else mappedRect = mapped;
493 int channels = baseClip()->getProperty("channels").toInt();
494 if (scale != framePixelWidth)
495 audioThumbCachePic.clear();
496 double cropLeft = m_cropStart.frames(m_fps);
497 const int clipStart = mappedRect.x();
498 const int mappedStartPixel = painter->matrix().map(QPointF(startpixel + cropLeft, 0)).x() - clipStart;
499 const int mappedEndPixel = painter->matrix().map(QPointF(endpixel + cropLeft, 0)).x() - clipStart;
500 cropLeft = cropLeft * scale;
502 emit prepareAudioThumb(scale, mappedStartPixel, mappedEndPixel, channels);
504 for (int startCache = mappedStartPixel - (mappedStartPixel) % 100; startCache < mappedEndPixel; startCache += 100) {
505 if (audioThumbCachePic.contains(startCache) && !audioThumbCachePic[startCache].isNull())
506 painter->drawPixmap(clipStart + startCache - cropLeft, mappedRect.y(), audioThumbCachePic[startCache]);
511 QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
512 QList < CommentedTime >::Iterator it = markers.begin();
515 const int markerwidth = 4;
517 markerBrush = QBrush(QColor(120, 120, 0, 140));
518 QPen pen = painter->pen();
519 pen.setColor(QColor(255, 255, 255, 200));
520 pen.setStyle(Qt::DotLine);
521 painter->setPen(pen);
522 for (; it != markers.end(); ++it) {
523 pos = (*it).time() - cropStart();
524 if (pos > GenTime()) {
525 if (pos > duration()) break;
526 QLineF l(br.x() + pos.frames(m_fps), br.y() + 5, br.x() + pos.frames(m_fps), br.bottom() - 5);
527 QLineF l2 = painter->matrix().map(l);
528 //framepos = scale * pos.frames(m_fps);
529 //QLineF l(framepos, 5, framepos, itemHeight - 5);
530 painter->drawLine(l2);
531 if (KdenliveSettings::showmarkers()) {
532 framepos = br.x() + pos.frames(m_fps);
533 const QRectF r1(framepos + 0.04, 10, itemWidth - framepos - 2, itemHeight - 10);
534 const QRectF r2 = painter->matrix().mapRect(r1);
535 const QRectF txtBounding = painter->boundingRect(r2, Qt::AlignLeft | Qt::AlignTop, " " + (*it).comment() + " ");
538 path.addRoundedRect(txtBounding, 3, 3);
539 painter->fillPath(path, markerBrush);
540 painter->drawText(txtBounding, Qt::AlignCenter, (*it).comment());
542 //painter->fillRect(QRect(br.x() + framepos, br.y(), 10, br.height()), QBrush(QColor(0, 0, 0, 150)));
545 pen.setColor(Qt::black);
546 pen.setStyle(Qt::SolidLine);
547 painter->setPen(pen);
549 // draw start / end fades
552 fades = QBrush(QColor(200, 50, 50, 150));
553 } else fades = QBrush(QColor(200, 200, 200, 200));
555 if (m_startFade != 0) {
556 QPainterPath fadeInPath;
557 fadeInPath.moveTo(0, 0);
558 fadeInPath.lineTo(0, itemHeight);
559 fadeInPath.lineTo(m_startFade, 0);
560 fadeInPath.closeSubpath();
561 QPainterPath f1 = painter->matrix().map(fadeInPath);
562 painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
563 /*if (isSelected()) {
564 QLineF l(m_startFade * scale, 0, 0, itemHeight);
565 painter->drawLine(l);
568 if (m_endFade != 0) {
569 QPainterPath fadeOutPath;
570 fadeOutPath.moveTo(itemWidth, 0);
571 fadeOutPath.lineTo(itemWidth, itemHeight);
572 fadeOutPath.lineTo(itemWidth - m_endFade, 0);
573 fadeOutPath.closeSubpath();
574 QPainterPath f1 = painter->matrix().map(fadeOutPath);
575 painter->fillPath(f1/*.intersected(resultClipPath)*/, fades);
576 /*if (isSelected()) {
577 QLineF l(itemWidth - m_endFade * scale, 0, itemWidth, itemHeight);
578 painter->drawLine(l);
582 // Draw effects names
583 if (!m_effectNames.isEmpty() && itemWidth * scale > 40) {
584 QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignLeft | Qt::AlignTop, m_effectNames);
585 txtBounding.setRight(txtBounding.right() + 15);
586 painter->setPen(Qt::white);
587 QBrush markerBrush(Qt::SolidPattern);
588 if (m_timeLine && m_timeLine->state() == QTimeLine::Running) {
589 qreal value = m_timeLine->currentValue();
590 txtBounding.setWidth(txtBounding.width() * value);
591 markerBrush.setColor(QColor(50 + 200 * (1.0 - value), 50, 50, 100 + 50 * value));
592 } else markerBrush.setColor(QColor(50, 50, 50, 150));
594 path.addRoundedRect(txtBounding, 4, 4);
595 painter->fillPath(path/*.intersected(resultClipPath)*/, markerBrush);
596 painter->drawText(txtBounding, Qt::AlignCenter, m_effectNames);
597 painter->setPen(Qt::black);
601 QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignHCenter | Qt::AlignVCenter, " " + m_clipName + " ");
602 painter->fillRect(txtBounding, QBrush(QColor(0, 0, 0, 150)));
603 //painter->setPen(QColor(0, 0, 0, 180));
604 //painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
605 txtBounding.translate(QPointF(1, 1));
606 painter->setPen(QColor(255, 255, 255, 255));
607 painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
610 // draw transition handles on hover
611 if (m_hover && itemWidth * scale > 40) {
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(22, 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 / scale))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 9))) < 6) {
676 setToolTip(i18n("Add transition"));
677 return TRANSITIONSTART;
678 } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - 21 / scale))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 9))) < 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) {
719 QRectF re = sceneBoundingRect();
720 if (m_clipType == AV) re.setTop(re.y() + re.height() / 2);
722 //kDebug() << "// PREP AUDIO THMB FRMO : scale:" << pixelForOneFrame<< ", from: " << startpixel << ", to: " << endpixel;
723 //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
725 for (int startCache = startpixel - startpixel % 100;startCache < endpixel;startCache += 100) {
726 //kDebug() << "creating " << startCache;
727 //if (framePixelWidth!=pixelForOneFrame ||
728 if (framePixelWidth == pixelForOneFrame && audioThumbCachePic.contains(startCache))
730 if (audioThumbCachePic[startCache].isNull() || framePixelWidth != pixelForOneFrame) {
731 audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
732 audioThumbCachePic[startCache].fill(QColor(180, 180, 200, 140));
734 bool fullAreaDraw = pixelForOneFrame < 10;
735 QMap<int, QPainterPath > positiveChannelPaths;
736 QMap<int, QPainterPath > negativeChannelPaths;
737 QPainter pixpainter(&audioThumbCachePic[startCache]);
739 audiopen.setWidth(0);
740 pixpainter.setPen(audiopen);
741 //pixpainter.setRenderHint(QPainter::Antialiasing,true);
742 //pixpainter.drawLine(0,0,100,re.height());
743 int channelHeight = audioThumbCachePic[startCache].height() / channels;
745 for (int i = 0;i < channels;i++) {
747 positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
748 negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
751 for (int samples = 0;samples <= 100;samples++) {
752 double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
753 int sample = (int)((frame - (int)(frame)) * 20); // AUDIO_FRAME_SIZE
754 if (frame < 0 || sample < 0 || sample > 19)
756 QMap<int, QByteArray> frame_channel_data = baseClip()->audioFrameChache[(int)frame];
758 for (int channel = 0;channel < channels && frame_channel_data[channel].size() > 0;channel++) {
760 int y = channelHeight * channel + channelHeight / 2;
761 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2) * channelHeight / 64;
763 positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
764 negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
766 positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
767 negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
770 for (int channel = 0;channel < channels ;channel++)
771 if (fullAreaDraw && samples == 100) {
772 positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
773 negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
774 positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
775 negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
779 if (m_clipType != AV) pixpainter.setBrush(QBrush(QColor(200, 200, 100)));
781 pixpainter.setPen(QPen(QColor(0, 0, 0)));
782 pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
784 for (int i = 0;i < channels;i++) {
786 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
787 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
789 pixpainter.drawPath(positiveChannelPaths[i]);
792 //audioThumbWasDrawn=true;
793 framePixelWidth = pixelForOneFrame;
798 uint ClipItem::fadeIn() const {
802 uint ClipItem::fadeOut() const {
807 void ClipItem::setFadeIn(int pos) {
808 int oldIn = m_startFade;
809 if (pos < 0) pos = 0;
810 if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
812 QRectF rect = boundingRect();
813 update(rect.x(), rect.y(), qMax(oldIn, pos), rect.height());
816 void ClipItem::setFadeOut(int pos) {
817 int oldOut = m_endFade;
818 if (pos < 0) pos = 0;
819 if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
821 QRectF rect = boundingRect();
822 update(rect.x() + rect.width() - qMax(oldOut, pos), rect.y(), pos, rect.height());
827 void ClipItem::mousePressEvent(QGraphicsSceneMouseEvent * event) {
828 /*m_resizeMode = operationMode(event->pos());
829 if (m_resizeMode == MOVE) {
830 m_maxTrack = scene()->sceneRect().height();
831 m_grabPoint = (int) (event->pos().x() - rect().x());
833 QGraphicsRectItem::mousePressEvent(event);
837 void ClipItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) {
839 QGraphicsRectItem::mouseReleaseEvent(event);
843 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e) {
844 //if (e->pos().x() < 20) m_hover = true;
846 QRectF r = boundingRect();
847 double width = 35 / projectScene()->scale();
848 double height = r.height() / 2;
849 //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
850 update(r.x(), r.y() + height, width, height);
851 update(r.right() - width, r.y() + height, width, height);
855 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *) {
857 QRectF r = boundingRect();
858 double width = 35 / projectScene()->scale();
859 double height = r.height() / 2;
860 //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
861 update(r.x(), r.y() + height, width, height);
862 update(r.right() - width, r.y() + height, width, height);
865 void ClipItem::resizeStart(int posx) {
866 const int min = (startPos() - cropStart()).frames(m_fps);
867 if (posx < min) posx = min;
868 if (posx == startPos().frames(m_fps)) return;
869 const int previous = cropStart().frames(m_fps);
870 AbstractClipItem::resizeStart(posx);
871 checkEffectsKeyframesPos(previous, cropStart().frames(m_fps), true);
872 if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
873 /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
874 startThumbTimer->start(100);
878 void ClipItem::resizeEnd(int posx) {
879 const int max = (startPos() - cropStart() + maxDuration()).frames(m_fps) + 1;
880 if (posx > max) posx = max;
881 if (posx == endPos().frames(m_fps)) return;
882 const int previous = (cropStart() + duration()).frames(m_fps);
883 AbstractClipItem::resizeEnd(posx);
884 checkEffectsKeyframesPos(previous, (cropStart() + duration()).frames(m_fps), false);
885 if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
886 /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
887 endThumbTimer->start(100);
892 void ClipItem::checkEffectsKeyframesPos(const int previous, const int current, bool fromStart) {
893 for (int i = 0; i < m_effectList.size(); i++) {
894 QDomElement effect = m_effectList.at(i);
895 QDomNodeList params = effect.elementsByTagName("parameter");
896 for (int j = 0; j < params.count(); j++) {
897 QDomElement e = params.item(i).toElement();
898 if (e.attribute("type") == "keyframe") {
899 // parse keyframes and adjust values
900 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
901 QMap <int, double> kfr;
902 foreach(const QString str, keyframes) {
903 int pos = str.section(":", 0, 0).toInt();
904 double val = str.section(":", 1, 1).toDouble();
905 if (pos == previous) kfr[current] = val;
907 if (fromStart && pos >= current) kfr[pos] = val;
908 else if (!fromStart && pos <= current) kfr[pos] = val;
912 QMap<int, double>::const_iterator k = kfr.constBegin();
913 while (k != kfr.constEnd()) {
914 newkfr.append(QString::number(k.key()) + ":" + QString::number(k.value()) + ";");
917 e.setAttribute("keyframes", newkfr);
922 if (m_selectedEffect >= 0) setSelectedEffect(m_selectedEffect);
927 QVariant ClipItem::itemChange(GraphicsItemChange change, const QVariant &value) {
928 if (change == ItemPositionChange && scene()) {
929 // calculate new position.
930 if (group() != 0) return pos();
931 QPointF newPos = value.toPointF();
932 //kDebug() << "/// MOVING CLIP ITEM.------------";
933 int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
934 xpos = qMax(xpos, 0);
936 int newTrack = (newPos.y() + KdenliveSettings::trackheight() / 2) / KdenliveSettings::trackheight();
937 newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
938 newTrack = qMax(newTrack, 0);
939 newPos.setY((int)(newTrack * KdenliveSettings::trackheight() + 1));
940 // Only one clip is moving
941 QRectF sceneShape = rect();
942 sceneShape.translate(newPos);
943 QList<QGraphicsItem*> items = scene()->items(sceneShape, Qt::IntersectsItemShape);
944 items.removeAll(this);
946 if (!items.isEmpty()) {
947 for (int i = 0; i < items.count(); i++) {
948 if (items.at(i)->type() == type()) {
950 QPointF otherPos = items.at(i)->pos();
951 if ((int) otherPos.y() != (int) pos().y()) return pos();
952 if (pos().x() < otherPos.x()) {
953 // move clip just before colliding clip
954 int npos = (static_cast < AbstractClipItem* >(items.at(i))->startPos() - m_cropDuration).frames(m_fps);
955 // check we don't run into another clip
958 sceneShape.translate(newPos);
959 QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
960 items.removeAll(this);
961 for (int j = 0; j < subitems.count(); j++) {
962 if (subitems.at(j)->type() == type()) return pos();
965 // get pos just after colliding clip
966 int npos = static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps);
967 // check we don't run into another clip
970 sceneShape.translate(newPos);
971 QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
972 items.removeAll(this);
973 for (int j = 0; j < subitems.count(); j++) {
974 if (subitems.at(j)->type() == type()) return pos();
978 m_startPos = GenTime((int) newPos.x(), m_fps);
984 m_startPos = GenTime((int) newPos.x(), m_fps);
985 //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
988 return QGraphicsItem::itemChange(change, value);
992 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
995 int ClipItem::effectsCounter() {
996 return effectsCount() + 1;
999 int ClipItem::effectsCount() {
1000 return m_effectList.size();
1003 int ClipItem::hasEffect(const QString &tag, const QString &id) const {
1004 return m_effectList.hasEffect(tag, id);
1007 QStringList ClipItem::effectNames() {
1008 return m_effectList.effectNames();
1011 QDomElement ClipItem::effectAt(int ix) {
1012 if (ix > m_effectList.count() - 1 || ix < 0) return QDomElement();
1013 return m_effectList.at(ix);
1016 void ClipItem::setEffectAt(int ix, QDomElement effect) {
1017 kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1018 effect.setAttribute("kdenlive_ix", ix + 1);
1019 m_effectList.insert(ix, effect);
1020 m_effectList.removeAt(ix + 1);
1021 m_effectNames = m_effectList.effectNames().join(" / ");
1022 if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fadeout") update(boundingRect());
1024 QRectF r = boundingRect();
1030 QHash <QString, QString> ClipItem::addEffect(QDomElement effect, bool animate) {
1031 QHash <QString, QString> effectParams;
1032 bool needRepaint = false;
1034 doc.appendChild(doc.importNode(effect, true));
1035 kDebug() << "/////// CLIP ADD EFFECT: " << doc.toString();*/
1036 m_effectList.append(effect);
1037 effectParams["tag"] = effect.attribute("tag");
1038 QString effectId = effect.attribute("id");
1039 if (effectId.isEmpty()) effectId = effect.attribute("tag");
1040 effectParams["id"] = effectId;
1041 effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
1042 QString state = effect.attribute("disabled");
1043 if (!state.isEmpty()) effectParams["disabled"] = state;
1044 QDomNodeList params = effect.elementsByTagName("parameter");
1046 for (int i = 0; i < params.count(); i++) {
1047 QDomElement e = params.item(i).toElement();
1049 if (e.attribute("type") == "keyframe") {
1050 effectParams["keyframes"] = e.attribute("keyframes");
1051 effectParams["min"] = e.attribute("min");
1052 effectParams["max"] = e.attribute("max");
1053 effectParams["factor"] = e.attribute("factor", "1");
1054 effectParams["starttag"] = e.attribute("starttag", "start");
1055 effectParams["endtag"] = e.attribute("endtag", "end");
1058 double f = e.attribute("factor", "1").toDouble();
1061 effectParams[e.attribute("name")] = e.attribute("value");
1062 // check if it is a fade effect
1063 if (effectId == "fadein") {
1065 if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1066 else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1067 } else if (effectId == "fadeout") {
1069 if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1070 else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1073 effectParams[e.attribute("name")] = QString::number(e.attribute("value").toDouble() / f);
1077 m_effectNames = m_effectList.effectNames().join(" / ");
1078 if (fade > 0) m_startFade = fade;
1079 else if (fade < 0) m_endFade = -fade;
1080 if (needRepaint) update(boundingRect());
1083 } else if (!needRepaint) {
1084 QRectF r = boundingRect();
1088 if (m_selectedEffect == -1) {
1089 m_selectedEffect = 0;
1090 setSelectedEffect(m_selectedEffect);
1092 return effectParams;
1095 QHash <QString, QString> ClipItem::getEffectArgs(QDomElement effect) {
1096 QHash <QString, QString> effectParams;
1097 effectParams["tag"] = effect.attribute("tag");
1098 effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
1099 effectParams["id"] = effect.attribute("id");
1100 QString state = effect.attribute("disabled");
1101 if (!state.isEmpty()) effectParams["disabled"] = state;
1102 QDomNodeList params = effect.elementsByTagName("parameter");
1103 for (int i = 0; i < params.count(); i++) {
1104 QDomElement e = params.item(i).toElement();
1105 //kDebug() << "/ / / /SENDING EFFECT PARAM: " << e.attribute("type") << ", NAME_ " << e.attribute("tag");
1106 if (e.attribute("type") == "keyframe") {
1107 kDebug() << "/ / / /SENDING KEYFR EFFECT TYPE";
1108 effectParams["keyframes"] = e.attribute("keyframes");
1109 effectParams["max"] = e.attribute("max");
1110 effectParams["min"] = e.attribute("min");
1111 effectParams["factor"] = e.attribute("factor", "1");
1112 effectParams["starttag"] = e.attribute("starttag", "start");
1113 effectParams["endtag"] = e.attribute("endtag", "end");
1114 } else if (e.attribute("namedesc").contains(";")) {
1115 QString format = e.attribute("format");
1116 QStringList separators = format.split("%d", QString::SkipEmptyParts);
1117 QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
1119 QTextStream txtNeu(&neu);
1120 if (values.size() > 0)
1121 txtNeu << (int)values[0].toDouble();
1122 for (int i = 0;i < separators.size() && i + 1 < values.size();i++) {
1123 txtNeu << separators[i];
1124 txtNeu << (int)(values[i+1].toDouble());
1126 effectParams["start"] = neu;
1128 if (e.attribute("factor", "1") != "1")
1129 effectParams[e.attribute("name")] = QString::number(e.attribute("value").toDouble() / e.attribute("factor").toDouble());
1130 else effectParams[e.attribute("name")] = e.attribute("value");
1133 return effectParams;
1136 void ClipItem::deleteEffect(QString index) {
1137 bool needRepaint = false;
1139 for (int i = 0; i < m_effectList.size(); ++i) {
1140 ix = m_effectList.at(i).attribute("kdenlive_ix");
1142 if (m_effectList.at(i).attribute("id") == "fadein") {
1145 } else if (m_effectList.at(i).attribute("id") == "fadeout") {
1149 m_effectList.removeAt(i);
1150 } else if (ix.toInt() > index.toInt()) m_effectList[i].setAttribute("kdenlive_ix", ix.toInt() - 1);
1152 m_effectNames = m_effectList.effectNames().join(" / ");
1153 if (needRepaint) update(boundingRect());
1157 double ClipItem::speed() const {
1161 void ClipItem::setSpeed(const double speed) {
1163 if (m_speed == 1.0) m_clipName = baseClip()->name();
1164 else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + "%";
1168 GenTime ClipItem::maxDuration() const {
1169 return m_maxDuration / m_speed;
1173 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event) {
1174 QString effects = QString(event->mimeData()->data("kdenlive/effectslist"));
1176 doc.setContent(effects, true);
1177 QDomElement e = doc.documentElement();
1178 CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1179 if (view) view->slotAddEffect(e, m_startPos, track());
1183 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
1184 event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
1187 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) {
1190 void ClipItem::addTransition(Transition* t) {
1191 m_transitionsList.append(t);
1192 CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1194 QDomElement e = doc.documentElement();
1195 //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1199 void CustomTrackView::mousePressEvent ( QMouseEvent * event )
1201 int pos = event->x();
1202 if (event->modifiers() == Qt::ControlModifier)
1203 setDragMode(QGraphicsView::ScrollHandDrag);
1204 else if (event->modifiers() == Qt::ShiftModifier)
1205 setDragMode(QGraphicsView::RubberBandDrag);
1207 QGraphicsItem * item = itemAt(event->pos());
1210 else emit cursorMoved((int) mapToScene(event->x(), 0).x());
1213 QGraphicsView::mousePressEvent(event);
1216 void CustomTrackView::mouseReleaseEvent ( QMouseEvent * event )
1218 QGraphicsView::mouseReleaseEvent(event);
1219 setDragMode(QGraphicsView::NoDrag);
1223 #include "clipitem.moc"