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), 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 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);
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);
602 QRectF txtBounding = painter->boundingRect(mapped, Qt::AlignHCenter | Qt::AlignTop, " " + m_clipName + " ");
603 //painter->fillRect(txtBounding, QBrush(QColor(255, 255, 255, 150)));
604 painter->setPen(QColor(0, 0, 0, 180));
605 painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
606 txtBounding.translate(QPointF(1, 1));
607 painter->setPen(QColor(255, 255, 255, 255));
608 painter->drawText(txtBounding, Qt::AlignCenter, m_clipName);
611 // draw transition handles on hover
612 if (m_hover && itemWidth * scale > 40) {
613 QPainterPath transitionHandle;
614 const int handle_size = 4;
615 QPointF p1 = painter->matrix().map(QPointF(0, itemHeight / 2)) + QPointF(10, 0);
616 painter->drawPixmap(p1, projectScene()->m_transitionPixmap);
617 p1 = painter->matrix().map(QPointF(itemWidth, itemHeight / 2)) - QPointF(10 + handle_size * 3, 0);
618 painter->drawPixmap(p1, projectScene()->m_transitionPixmap);
622 // draw frame around clip
624 pen.setColor(Qt::red);
627 pen.setColor(Qt::black);
631 // draw effect or transition keyframes
632 if (itemWidth > 20) drawKeyFrames(painter, exposed);
634 painter->setMatrixEnabled(true);
638 //kDebug()<<"/// ITEM PAINTING:: exposed="<<exposed<<", RECT = "<<rect();
640 exposed.setRight(exposed.right() + 1);
641 exposed.setBottom(exposed.bottom() + 1);
642 painter->setClipRect(exposed);
643 //painter->setClipping(false);
644 //painter->fillRect(exposed, Qt::blue);
645 painter->setPen(pen);
646 painter->drawRect(br);
650 OPERATIONTYPE ClipItem::operationMode(QPointF pos) {
652 m_editedKeyframe = mouseOverKeyFrames(pos);
653 if (m_editedKeyframe != -1) return KEYFRAME;
655 QRectF rect = sceneBoundingRect();
656 const double scale = projectScene()->scale();
657 double maximumOffset;
658 if (scale > 3) maximumOffset = 25 / scale;
659 else maximumOffset = 6 / scale;
661 matrix.scale(scale, 0);
662 //kDebug()<<"// Item rect: "<<rect.x()<<". pos. "<<pos.x()<<", scale: "<<scale<<", ratio: "<<qAbs((int)(pos.x() - rect.x())) / scale;
664 if (qAbs((int)(pos.x() - (rect.x() + m_startFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
665 if (m_startFade == 0) setToolTip(i18n("Add audio fade"));
666 else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_startFade, m_fps).seconds()));
668 } else if (pos.x() - rect.x() < maximumOffset) {
669 setToolTip(i18n("Crop from start: %1s", cropStart().seconds()));
671 } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - m_endFade))) < maximumOffset && qAbs((int)(pos.y() - rect.y())) < 6) {
672 if (m_endFade == 0) setToolTip(i18n("Add audio fade"));
673 else setToolTip(i18n("Audio fade duration: %1s", GenTime(m_endFade, m_fps).seconds()));
675 } else if (qAbs((int)(pos.x() - (rect.x() + rect.width()))) < maximumOffset) {
676 setToolTip(i18n("Clip duration: %1s", duration().seconds()));
678 } else if (qAbs((int)(pos.x() - (rect.x() + 16))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 5))) < 6) {
679 setToolTip(i18n("Add transition"));
680 return TRANSITIONSTART;
681 } else if (qAbs((int)(pos.x() - (rect.x() + rect.width() - 21))) < maximumOffset && qAbs((int)(pos.y() - (rect.y() + rect.height() / 2 + 5))) < 6) {
682 setToolTip(i18n("Add transition"));
683 return TRANSITIONEND;
685 setToolTip(QString());
689 QList <GenTime> ClipItem::snapMarkers() const {
690 QList < GenTime > snaps;
691 QList < GenTime > markers = baseClip()->snapMarkers();
695 for (int i = 0; i < markers.size(); i++) {
696 pos = markers.at(i) - cropStart();
697 if (pos > GenTime()) {
698 if (pos > duration()) break;
699 else snaps.append(pos + startPos());
705 QList <CommentedTime> ClipItem::commentedSnapMarkers() const {
706 QList < CommentedTime > snaps;
707 QList < CommentedTime > markers = baseClip()->commentedSnapMarkers();
711 for (int i = 0; i < markers.size(); i++) {
712 pos = markers.at(i).time() - cropStart();
713 if (pos > GenTime()) {
714 if (pos > duration()) break;
715 else snaps.append(CommentedTime(pos + startPos(), markers.at(i).comment()));
721 void ClipItem::slotPrepareAudioThumb(double pixelForOneFrame, int startpixel, int endpixel, int channels) {
723 QRectF re = sceneBoundingRect();
724 if (m_clipType == AV) re.setTop(re.y() + re.height() / 2);
726 //kDebug() << "// PREP AUDIO THMB FRMO : scale:" << pixelForOneFrame<< ", from: " << startpixel << ", to: " << endpixel;
727 //if ( (!audioThumbWasDrawn || framePixelWidth!=pixelForOneFrame ) && !baseClip()->audioFrameChache.isEmpty()){
729 for (int startCache = startpixel - startpixel % 100;startCache < endpixel;startCache += 100) {
730 //kDebug() << "creating " << startCache;
731 //if (framePixelWidth!=pixelForOneFrame ||
732 if (framePixelWidth == pixelForOneFrame && audioThumbCachePic.contains(startCache))
734 if (audioThumbCachePic[startCache].isNull() || framePixelWidth != pixelForOneFrame) {
735 audioThumbCachePic[startCache] = QPixmap(100, (int)(re.height()));
736 audioThumbCachePic[startCache].fill(QColor(180, 180, 200, 140));
738 bool fullAreaDraw = pixelForOneFrame < 10;
739 QMap<int, QPainterPath > positiveChannelPaths;
740 QMap<int, QPainterPath > negativeChannelPaths;
741 QPainter pixpainter(&audioThumbCachePic[startCache]);
743 audiopen.setWidth(0);
744 pixpainter.setPen(audiopen);
745 //pixpainter.setRenderHint(QPainter::Antialiasing,true);
746 //pixpainter.drawLine(0,0,100,re.height());
747 int channelHeight = audioThumbCachePic[startCache].height() / channels;
749 for (int i = 0;i < channels;i++) {
751 positiveChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
752 negativeChannelPaths[i].moveTo(0, channelHeight*i + channelHeight / 2);
755 for (int samples = 0;samples <= 100;samples++) {
756 double frame = (double)(samples + startCache - 0) / pixelForOneFrame;
757 int sample = (int)((frame - (int)(frame)) * 20); // AUDIO_FRAME_SIZE
758 if (frame < 0 || sample < 0 || sample > 19)
760 QMap<int, QByteArray> frame_channel_data = baseClip()->audioFrameChache[(int)frame];
762 for (int channel = 0;channel < channels && frame_channel_data[channel].size() > 0;channel++) {
764 int y = channelHeight * channel + channelHeight / 2;
765 int delta = (int)(frame_channel_data[channel][sample] - 127 / 2) * channelHeight / 64;
767 positiveChannelPaths[channel].lineTo(samples, 0.1 + y + qAbs(delta));
768 negativeChannelPaths[channel].lineTo(samples, 0.1 + y - qAbs(delta));
770 positiveChannelPaths[channel].lineTo(samples, 0.1 + y + delta);
771 negativeChannelPaths[channel].lineTo(samples, 0.1 + y - delta);
774 for (int channel = 0;channel < channels ;channel++)
775 if (fullAreaDraw && samples == 100) {
776 positiveChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
777 negativeChannelPaths[channel].lineTo(samples, channelHeight*channel + channelHeight / 2);
778 positiveChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
779 negativeChannelPaths[channel].lineTo(0, channelHeight*channel + channelHeight / 2);
783 if (m_clipType != AV) pixpainter.setBrush(QBrush(QColor(200, 200, 100)));
785 pixpainter.setPen(QPen(QColor(0, 0, 0)));
786 pixpainter.setBrush(QBrush(QColor(60, 60, 60)));
788 for (int i = 0;i < channels;i++) {
790 //pixpainter.fillPath(positiveChannelPaths[i].united(negativeChannelPaths[i]),QBrush(Qt::SolidPattern));//or singleif looks better
791 pixpainter.drawPath(positiveChannelPaths[i].united(negativeChannelPaths[i]));//or singleif looks better
793 pixpainter.drawPath(positiveChannelPaths[i]);
796 //audioThumbWasDrawn=true;
797 framePixelWidth = pixelForOneFrame;
802 uint ClipItem::fadeIn() const {
806 uint ClipItem::fadeOut() const {
811 void ClipItem::setFadeIn(int pos) {
812 int oldIn = m_startFade;
813 if (pos < 0) pos = 0;
814 if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
816 QRectF rect = boundingRect();
817 update(rect.x(), rect.y(), qMax(oldIn, pos), rect.height());
820 void ClipItem::setFadeOut(int pos) {
821 int oldOut = m_endFade;
822 if (pos < 0) pos = 0;
823 if (pos > m_cropDuration.frames(m_fps)) pos = (int)(m_cropDuration.frames(m_fps) / 2);
825 QRectF rect = boundingRect();
826 update(rect.x() + rect.width() - qMax(oldOut, pos), rect.y(), pos, rect.height());
831 void ClipItem::mousePressEvent(QGraphicsSceneMouseEvent * event) {
832 /*m_resizeMode = operationMode(event->pos());
833 if (m_resizeMode == MOVE) {
834 m_maxTrack = scene()->sceneRect().height();
835 m_grabPoint = (int) (event->pos().x() - rect().x());
837 QGraphicsRectItem::mousePressEvent(event);
841 void ClipItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) {
843 QGraphicsRectItem::mouseReleaseEvent(event);
847 void ClipItem::hoverEnterEvent(QGraphicsSceneHoverEvent *e) {
848 //if (e->pos().x() < 20) m_hover = true;
850 QRectF r = boundingRect();
851 double width = 35 / projectScene()->scale();
852 double height = r.height() / 2;
853 //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
854 update(r.x(), r.y() + height, width, height);
855 update(r.right() - width, r.y() + height, width, height);
859 void ClipItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *) {
861 QRectF r = boundingRect();
862 double width = 35 / projectScene()->scale();
863 double height = r.height() / 2;
864 //WARNING: seems like it generates a full repaint of the clip, maybe not so good...
865 update(r.x(), r.y() + height, width, height);
866 update(r.right() - width, r.y() + height, width, height);
869 void ClipItem::resizeStart(int posx) {
870 const int min = (startPos() - cropStart()).frames(m_fps);
871 if (posx < min) posx = min;
872 if (posx == startPos().frames(m_fps)) return;
873 const int previous = cropStart().frames(m_fps);
874 AbstractClipItem::resizeStart(posx);
875 checkEffectsKeyframesPos(previous, cropStart().frames(m_fps), true);
876 if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
877 /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
878 startThumbTimer->start(100);
882 void ClipItem::resizeEnd(int posx) {
883 const int max = (startPos() - cropStart() + maxDuration()).frames(m_fps) + 1;
884 if (posx > max) posx = max;
885 if (posx == endPos().frames(m_fps)) return;
886 const int previous = (cropStart() + duration()).frames(m_fps);
887 AbstractClipItem::resizeEnd(posx);
888 checkEffectsKeyframesPos(previous, (cropStart() + duration()).frames(m_fps), false);
889 if (m_hasThumbs && KdenliveSettings::videothumbnails()) {
890 /*connect(m_clip->thumbProducer(), SIGNAL(thumbReady(int, QPixmap)), this, SLOT(slotThumbReady(int, QPixmap)));*/
891 endThumbTimer->start(100);
896 void ClipItem::checkEffectsKeyframesPos(const int previous, const int current, bool fromStart) {
897 for (int i = 0; i < m_effectList.size(); i++) {
898 QDomElement effect = m_effectList.at(i);
899 QDomNodeList params = effect.elementsByTagName("parameter");
900 for (int j = 0; j < params.count(); j++) {
901 QDomElement e = params.item(i).toElement();
902 if (e.attribute("type") == "keyframe") {
903 // parse keyframes and adjust values
904 const QStringList keyframes = e.attribute("keyframes").split(";", QString::SkipEmptyParts);
905 QMap <int, double> kfr;
906 foreach(const QString str, keyframes) {
907 int pos = str.section(":", 0, 0).toInt();
908 double val = str.section(":", 1, 1).toDouble();
909 if (pos == previous) kfr[current] = val;
911 if (fromStart && pos >= current) kfr[pos] = val;
912 else if (!fromStart && pos <= current) kfr[pos] = val;
916 QMap<int, double>::const_iterator k = kfr.constBegin();
917 while (k != kfr.constEnd()) {
918 newkfr.append(QString::number(k.key()) + ":" + QString::number(k.value()) + ";");
921 e.setAttribute("keyframes", newkfr);
926 if (m_selectedEffect >= 0) setSelectedEffect(m_selectedEffect);
931 QVariant ClipItem::itemChange(GraphicsItemChange change, const QVariant &value) {
932 if (change == ItemPositionChange && scene()) {
933 // calculate new position.
934 if (group() != 0) return pos();
935 QPointF newPos = value.toPointF();
936 //kDebug() << "/// MOVING CLIP ITEM.------------";
937 int xpos = projectScene()->getSnapPointForPos((int) newPos.x(), KdenliveSettings::snaptopoints());
938 xpos = qMax(xpos, 0);
940 int newTrack = (newPos.y() + KdenliveSettings::trackheight() / 2) / KdenliveSettings::trackheight();
941 newTrack = qMin(newTrack, projectScene()->tracksCount() - 1);
942 newTrack = qMax(newTrack, 0);
943 newPos.setY((int)(newTrack * KdenliveSettings::trackheight() + 1));
944 // Only one clip is moving
945 QRectF sceneShape = rect();
946 sceneShape.translate(newPos);
947 QList<QGraphicsItem*> items = scene()->items(sceneShape, Qt::IntersectsItemShape);
948 items.removeAll(this);
950 if (!items.isEmpty()) {
951 for (int i = 0; i < items.count(); i++) {
952 if (items.at(i)->type() == type()) {
954 QPointF otherPos = items.at(i)->pos();
955 if ((int) otherPos.y() != (int) pos().y()) return pos();
956 if (pos().x() < otherPos.x()) {
957 // move clip just before colliding clip
958 int npos = (static_cast < AbstractClipItem* >(items.at(i))->startPos() - m_cropDuration).frames(m_fps);
959 // check we don't run into another clip
962 sceneShape.translate(newPos);
963 QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
964 items.removeAll(this);
965 for (int j = 0; j < subitems.count(); j++) {
966 if (subitems.at(j)->type() == type()) return pos();
969 // get pos just after colliding clip
970 int npos = static_cast < AbstractClipItem* >(items.at(i))->endPos().frames(m_fps);
971 // check we don't run into another clip
974 sceneShape.translate(newPos);
975 QList<QGraphicsItem*> subitems = scene()->items(sceneShape, Qt::IntersectsItemShape);
976 items.removeAll(this);
977 for (int j = 0; j < subitems.count(); j++) {
978 if (subitems.at(j)->type() == type()) return pos();
982 m_startPos = GenTime((int) newPos.x(), m_fps);
988 m_startPos = GenTime((int) newPos.x(), m_fps);
989 //kDebug()<<"// ITEM NEW POS: "<<newPos.x()<<", mapped: "<<mapToScene(newPos.x(), 0).x();
992 return QGraphicsItem::itemChange(change, value);
996 /*void ClipItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event) {
999 int ClipItem::effectsCounter() {
1000 return m_effectsCounter++;
1003 int ClipItem::effectsCount() {
1004 return m_effectList.size();
1007 int ClipItem::hasEffect(const QString &tag, const QString &id) const {
1008 return m_effectList.hasEffect(tag, id);
1011 QStringList ClipItem::effectNames() {
1012 return m_effectList.effectNames();
1015 QDomElement ClipItem::effectAt(int ix) {
1016 if (ix > m_effectList.count() - 1 || ix < 0) return QDomElement();
1017 return m_effectList.at(ix);
1020 void ClipItem::setEffectAt(int ix, QDomElement effect) {
1021 kDebug() << "CHange EFFECT AT: " << ix << ", CURR: " << m_effectList.at(ix).attribute("tag") << ", NEW: " << effect.attribute("tag");
1022 m_effectList.insert(ix, effect);
1023 m_effectList.removeAt(ix + 1);
1024 m_effectNames = m_effectList.effectNames().join(" / ");
1025 if (effect.attribute("id") == "fadein" || effect.attribute("id") == "fadeout") update(boundingRect());
1027 QRectF r = boundingRect();
1033 QHash <QString, QString> ClipItem::addEffect(QDomElement effect, bool animate) {
1034 QHash <QString, QString> effectParams;
1035 bool needRepaint = false;
1037 doc.appendChild(doc.importNode(effect, true));
1038 kDebug() << "/////// CLIP ADD EFFECT: "<< doc.toString();*/
1039 m_effectList.append(effect);
1040 effectParams["tag"] = effect.attribute("tag");
1041 QString effectId = effect.attribute("id");
1042 if (effectId.isEmpty()) effectId = effect.attribute("tag");
1043 effectParams["id"] = effectId;
1044 effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
1045 QString state = effect.attribute("disabled");
1046 if (!state.isEmpty()) effectParams["disabled"] = state;
1047 QDomNodeList params = effect.elementsByTagName("parameter");
1049 for (int i = 0; i < params.count(); i++) {
1050 QDomElement e = params.item(i).toElement();
1052 if (e.attribute("type") == "keyframe") {
1053 effectParams["keyframes"] = e.attribute("keyframes");
1054 effectParams["min"] = e.attribute("min");
1055 effectParams["max"] = e.attribute("max");
1056 effectParams["factor"] = e.attribute("factor", "1");
1057 effectParams["starttag"] = e.attribute("starttag", "start");
1058 effectParams["endtag"] = e.attribute("endtag", "end");
1061 double f = e.attribute("factor", "1").toDouble();
1064 effectParams[e.attribute("name")] = e.attribute("value");
1065 // check if it is a fade effect
1066 if (effectId == "fadein") {
1068 if (e.attribute("name") == "out") fade += e.attribute("value").toInt();
1069 else if (e.attribute("name") == "in") fade -= e.attribute("value").toInt();
1070 } else if (effectId == "fadeout") {
1072 if (e.attribute("name") == "out") fade -= e.attribute("value").toInt();
1073 else if (e.attribute("name") == "in") fade += e.attribute("value").toInt();
1076 effectParams[e.attribute("name")] = QString::number(effectParams[e.attribute("name")].toDouble() / f);
1080 m_effectNames = m_effectList.effectNames().join(" / ");
1081 if (fade > 0) m_startFade = fade;
1082 else if (fade < 0) m_endFade = -fade;
1083 if (needRepaint) update(boundingRect());
1086 } else if (!needRepaint) {
1087 QRectF r = boundingRect();
1091 if (m_selectedEffect == -1) {
1092 m_selectedEffect = 0;
1093 setSelectedEffect(m_selectedEffect);
1095 return effectParams;
1098 QHash <QString, QString> ClipItem::getEffectArgs(QDomElement effect) {
1099 QHash <QString, QString> effectParams;
1100 effectParams["tag"] = effect.attribute("tag");
1101 effectParams["kdenlive_ix"] = effect.attribute("kdenlive_ix");
1102 effectParams["id"] = effect.attribute("id");
1103 QString state = effect.attribute("disabled");
1104 if (!state.isEmpty()) effectParams["disabled"] = state;
1105 QDomNodeList params = effect.elementsByTagName("parameter");
1106 for (int i = 0; i < params.count(); i++) {
1107 QDomElement e = params.item(i).toElement();
1108 //kDebug() << "/ / / /SENDING EFFECT PARAM: " << e.attribute("type") << ", NAME_ " << e.attribute("tag");
1109 if (e.attribute("type") == "keyframe") {
1110 kDebug() << "/ / / /SENDING KEYFR EFFECT TYPE";
1111 effectParams["keyframes"] = e.attribute("keyframes");
1112 effectParams["max"] = e.attribute("max");
1113 effectParams["min"] = e.attribute("min");
1114 effectParams["factor"] = e.attribute("factor", "1");
1115 effectParams["starttag"] = e.attribute("starttag", "start");
1116 effectParams["endtag"] = e.attribute("endtag", "end");
1117 } else if (e.attribute("namedesc").contains(";")) {
1118 QString format = e.attribute("format");
1119 QStringList separators = format.split("%d", QString::SkipEmptyParts);
1120 QStringList values = e.attribute("value").split(QRegExp("[,:;x]"));
1122 QTextStream txtNeu(&neu);
1123 if (values.size() > 0)
1124 txtNeu << (int)values[0].toDouble();
1125 for (int i = 0;i < separators.size() && i + 1 < values.size();i++) {
1126 txtNeu << separators[i];
1127 txtNeu << (int)(values[i+1].toDouble());
1129 effectParams["start"] = neu;
1131 if (e.attribute("factor", "1") != "1")
1132 effectParams[e.attribute("name")] = QString::number(e.attribute("value").toDouble() / e.attribute("factor").toDouble());
1133 else effectParams[e.attribute("name")] = e.attribute("value");
1136 return effectParams;
1139 void ClipItem::deleteEffect(QString index) {
1140 bool needRepaint = false;
1141 for (int i = 0; i < m_effectList.size(); ++i) {
1142 if (m_effectList.at(i).attribute("kdenlive_ix") == index) {
1143 if (m_effectList.at(i).attribute("id") == "fadein") {
1146 } else if (m_effectList.at(i).attribute("id") == "fadeout") {
1150 m_effectList.removeAt(i);
1154 m_effectNames = m_effectList.effectNames().join(" / ");
1155 if (needRepaint) update(boundingRect());
1159 double ClipItem::speed() const {
1163 void ClipItem::setSpeed(const double speed) {
1165 if (m_speed == 1.0) m_clipName = baseClip()->name();
1166 else m_clipName = baseClip()->name() + " - " + QString::number(speed * 100, 'f', 0) + "%";
1170 GenTime ClipItem::maxDuration() const {
1171 return m_maxDuration / m_speed;
1175 void ClipItem::dropEvent(QGraphicsSceneDragDropEvent * event) {
1176 QString effects = QString(event->mimeData()->data("kdenlive/effectslist"));
1178 doc.setContent(effects, true);
1179 QDomElement e = doc.documentElement();
1180 CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1181 if (view) view->slotAddEffect(e, m_startPos, track());
1185 void ClipItem::dragEnterEvent(QGraphicsSceneDragDropEvent *event) {
1186 event->setAccepted(event->mimeData()->hasFormat("kdenlive/effectslist"));
1189 void ClipItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) {
1192 void ClipItem::addTransition(Transition* t) {
1193 m_transitionsList.append(t);
1194 CustomTrackView *view = (CustomTrackView *) scene()->views()[0];
1196 QDomElement e = doc.documentElement();
1197 //if (view) view->slotAddTransition(this, t->toXML() , t->startPos(), track());
1201 void CustomTrackView::mousePressEvent ( QMouseEvent * event )
1203 int pos = event->x();
1204 if (event->modifiers() == Qt::ControlModifier)
1205 setDragMode(QGraphicsView::ScrollHandDrag);
1206 else if (event->modifiers() == Qt::ShiftModifier)
1207 setDragMode(QGraphicsView::RubberBandDrag);
1209 QGraphicsItem * item = itemAt(event->pos());
1212 else emit cursorMoved((int) mapToScene(event->x(), 0).x());
1215 QGraphicsView::mousePressEvent(event);
1218 void CustomTrackView::mouseReleaseEvent ( QMouseEvent * event )
1220 QGraphicsView::mouseReleaseEvent(event);
1221 setDragMode(QGraphicsView::NoDrag);
1225 #include "clipitem.moc"