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 ***************************************************************************/
21 #include "trackview.h"
22 #include "headertrack.h"
24 #include "transition.h"
25 #include "kdenlivesettings.h"
26 #include "clipmanager.h"
27 #include "customruler.h"
28 #include "kdenlivedoc.h"
29 #include "mainwindow.h"
30 #include "customtrackview.h"
31 #include "initeffects.h"
32 #include "profilesdialog.h"
33 #include "commands/configtrackscommand.h"
36 #include <KMessageBox>
37 #include <KIO/NetAccess>
40 #include <QInputDialog>
42 TrackView::TrackView(KdenliveDoc *doc, QList <QAction*> actions, bool *ok, QWidget *parent) :
49 m_trackActions << actions;
51 // ruler_frame->setMaximumHeight();
52 // size_frame->setMaximumHeight();
53 m_scene = new CustomTrackScene(doc);
54 m_trackview = new CustomTrackView(doc, m_scene, parent);
55 m_trackview->scale(1, 1);
56 m_trackview->setAlignment(Qt::AlignLeft | Qt::AlignTop);
58 m_ruler = new CustomRuler(doc->timecode(), m_trackview);
59 connect(m_ruler, SIGNAL(zoneMoved(int, int)), this, SIGNAL(zoneMoved(int, int)));
60 connect(m_ruler, SIGNAL(adjustZoom(int)), this, SIGNAL(setZoom(int)));
61 QHBoxLayout *layout = new QHBoxLayout;
62 layout->setContentsMargins(m_trackview->frameWidth(), 0, 0, 0);
63 layout->setSpacing(0);
64 ruler_frame->setLayout(layout);
65 ruler_frame->setMaximumHeight(m_ruler->height());
66 layout->addWidget(m_ruler);
68 QHBoxLayout *sizeLayout = new QHBoxLayout;
69 sizeLayout->setContentsMargins(0, 0, 0, 0);
70 sizeLayout->setSpacing(0);
71 size_frame->setLayout(sizeLayout);
72 size_frame->setMaximumHeight(m_ruler->height());
74 QToolButton *butSmall = new QToolButton(this);
75 butSmall->setIcon(KIcon("kdenlive-zoom-small"));
76 butSmall->setToolTip(i18n("Smaller tracks"));
77 butSmall->setAutoRaise(true);
78 connect(butSmall, SIGNAL(clicked()), this, SLOT(slotVerticalZoomDown()));
79 sizeLayout->addWidget(butSmall);
81 QToolButton *butLarge = new QToolButton(this);
82 butLarge->setIcon(KIcon("kdenlive-zoom-large"));
83 butLarge->setToolTip(i18n("Bigger tracks"));
84 butLarge->setAutoRaise(true);
85 connect(butLarge, SIGNAL(clicked()), this, SLOT(slotVerticalZoomUp()));
86 sizeLayout->addWidget(butLarge);
88 QHBoxLayout *tracksLayout = new QHBoxLayout;
89 tracksLayout->setContentsMargins(0, 0, 0, 0);
90 tracksLayout->setSpacing(0);
91 tracks_frame->setLayout(tracksLayout);
93 headers_area->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
94 headers_area->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
95 headers_area->setFixedWidth(70);
97 QVBoxLayout *headersLayout = new QVBoxLayout;
98 headersLayout->setContentsMargins(0, m_trackview->frameWidth(), 0, 0);
99 headersLayout->setSpacing(0);
100 headers_container->setLayout(headersLayout);
101 connect(headers_area->verticalScrollBar(), SIGNAL(valueChanged(int)), m_trackview->verticalScrollBar(), SLOT(setValue(int)));
103 tracksLayout->addWidget(m_trackview);
104 connect(m_trackview->verticalScrollBar(), SIGNAL(valueChanged(int)), headers_area->verticalScrollBar(), SLOT(setValue(int)));
105 connect(m_trackview, SIGNAL(trackHeightChanged()), this, SLOT(slotRebuildTrackHeaders()));
106 connect(m_trackview, SIGNAL(tracksChanged()), this, SLOT(slotReloadTracks()));
107 connect(m_trackview, SIGNAL(updateTrackHeaders()), this, SLOT(slotRepaintTracks()));
108 connect(m_trackview, SIGNAL(showTrackEffects(int, TrackInfo)), this, SIGNAL(showTrackEffects(int, TrackInfo)));
109 connect(m_trackview, SIGNAL(updateTrackEffectState(int)), this, SLOT(slotUpdateTrackEffectState(int)));
112 parseDocument(m_doc->toXml());
113 if (m_doc->setSceneList() == -1) *ok = false;
115 connect(m_trackview, SIGNAL(cursorMoved(int, int)), m_ruler, SLOT(slotCursorMoved(int, int)));
116 connect(m_trackview, SIGNAL(updateRuler()), m_ruler, SLOT(updateRuler()));
118 connect(m_trackview->horizontalScrollBar(), SIGNAL(valueChanged(int)), m_ruler, SLOT(slotMoveRuler(int)));
119 connect(m_trackview->horizontalScrollBar(), SIGNAL(rangeChanged(int, int)), this, SLOT(slotUpdateVerticalScroll(int, int)));
120 connect(m_trackview, SIGNAL(mousePosition(int)), this, SIGNAL(mousePosition(int)));
121 connect(m_trackview, SIGNAL(doTrackLock(int, bool)), this, SLOT(slotChangeTrackLock(int, bool)));
123 slotChangeZoom(m_doc->zoom().x(), m_doc->zoom().y());
124 slotSetZone(m_doc->zone(), false);
127 TrackView::~TrackView()
135 void TrackView::keyPressEvent(QKeyEvent * event)
137 if (event->key() == Qt::Key_Up) {
138 m_trackview->slotTrackUp();
140 } else if (event->key() == Qt::Key_Down) {
141 m_trackview->slotTrackDown();
143 } else QWidget::keyPressEvent(event);
146 int TrackView::duration() const
148 return m_trackview->duration();
151 int TrackView::tracksNumber() const
153 return m_projectTracks - 1;
156 bool TrackView::checkProjectAudio() const
158 bool hasAudio = false;
159 const QList <TrackInfo> list = m_doc->tracksList();
160 int max = list.count();
161 for (int i = 0; i < max; i++) {
162 TrackInfo info = list.at(max - i - 1);
163 if (!info.isMute && m_trackview->hasAudio(i)) {
171 int TrackView::inPoint() const
173 return m_ruler->inPoint();
176 int TrackView::outPoint() const
178 return m_ruler->outPoint();
181 void TrackView::slotSetZone(QPoint p, bool updateDocumentProperties)
184 if (updateDocumentProperties) m_doc->setZone(p.x(), p.y());
187 void TrackView::setDuration(int dur)
189 m_trackview->setDuration(dur);
190 m_ruler->setDuration(dur);
193 void TrackView::parseDocument(QDomDocument doc)
196 m_documentErrors.clear();
197 m_replacementProducerIds.clear();
199 // parse project tracks
200 QDomElement mlt = doc.firstChildElement("mlt");
201 QDomElement tractor = mlt.firstChildElement("tractor");
202 QDomNodeList tracks = tractor.elementsByTagName("track");
203 QDomNodeList playlists = doc.elementsByTagName("playlist");
205 m_projectTracks = tracks.count();
206 int trackduration = 0;
210 int pos = m_projectTracks - 1;
211 m_invalidProducers.clear();
212 QDomNodeList producers = doc.elementsByTagName("producer");
213 for (int i = 0; i < producers.count(); i++) {
214 // Check for invalid producers
215 QDomNode n = producers.item(i);
218 if (e.hasAttribute("in") == false && e.hasAttribute("out") == false) continue;
219 int in = e.attribute("in").toInt();
220 int out = e.attribute("out").toInt();
222 // invalid producer, remove it
223 QString id = e.attribute("id");
224 m_invalidProducers.append(id);
225 m_documentErrors.append(i18n("Invalid clip producer %1\n", id));
226 doc.documentElement().removeChild(producers.at(i));
232 for (int i = 0; i < m_projectTracks; i++) {
233 e = tracks.item(i).toElement();
234 QString playlist_name = e.attribute("producer");
235 if (playlist_name != "black_track" && playlist_name != "playlistmain") {
236 // find playlist related to this track
238 for (int j = 0; j < m_projectTracks; j++) {
239 p = playlists.item(j).toElement();
240 if (p.attribute("id") == playlist_name) {
241 // playlist found, check track effects
242 QDomNodeList trackEffects = p.childNodes();
243 slotAddProjectEffects(trackEffects, p, NULL, trackIndex++);
247 if (p.attribute("id") != playlist_name) { // then it didn't work.
248 kDebug() << "NO PLAYLIST FOUND FOR TRACK " + pos;
250 if (e.attribute("hide") == "video") {
251 m_doc->switchTrackVideo(i - 1, true);
252 } else if (e.attribute("hide") == "audio") {
253 m_doc->switchTrackAudio(i - 1, true);
254 } else if (e.attribute("hide") == "both") {
255 m_doc->switchTrackVideo(i - 1, true);
256 m_doc->switchTrackAudio(i - 1, true);
259 trackduration = slotAddProjectTrack(pos, p, m_doc->isTrackLocked(i - 1), producers);
261 //kDebug() << " PRO DUR: " << trackduration << ", TRACK DUR: " << duration;
262 if (trackduration > duration) duration = trackduration;
264 // background black track
265 for (int j = 0; j < m_projectTracks; j++) {
266 p = playlists.item(j).toElement();
267 if (p.attribute("id") == playlist_name) break;
274 QDomNodeList transitions = tractor.elementsByTagName("transition");
276 //kDebug() << "//////////// TIMELINE FOUND: " << projectTransitions << " transitions";
277 for (int i = 0; i < transitions.count(); i++) {
278 e = transitions.item(i).toElement();
279 QDomNodeList transitionparams = e.childNodes();
280 bool transitionAdd = true;
283 bool isAutomatic = false;
284 bool forceTrack = false;
285 QString mlt_geometry;
287 QString transitionId;
288 for (int k = 0; k < transitionparams.count(); k++) {
289 p = transitionparams.item(k).toElement();
291 QString paramName = p.attribute("name");
292 // do not add audio mixing transitions
293 if (paramName == "internal_added" && p.text() == "237") {
294 transitionAdd = false;
295 //kDebug() << "// TRANSITRION " << i << " IS NOT VALID (INTERN ADDED)";
297 } else if (paramName == "a_track") {
298 a_track = qMax(0, p.text().toInt());
299 a_track = qMin(m_projectTracks - 1, a_track);
300 if (a_track != p.text().toInt()) {
301 // the transition track was out of bounds
302 m_documentErrors.append(i18n("Transition %1 had an invalid track: %2 > %3", e.attribute("id"), p.text().toInt(), a_track) + '\n');
303 EffectsList::setProperty(e, "a_track", QString::number(a_track));
305 } else if (paramName == "b_track") {
306 b_track = qMax(0, p.text().toInt());
307 b_track = qMin(m_projectTracks - 1, b_track);
308 if (b_track != p.text().toInt()) {
309 // the transition track was out of bounds
310 m_documentErrors.append(i18n("Transition %1 had an invalid track: %2 > %3", e.attribute("id"), p.text().toInt(), b_track) + '\n');
311 EffectsList::setProperty(e, "b_track", QString::number(b_track));
313 } else if (paramName == "mlt_service") mlt_service = p.text();
314 else if (paramName == "kdenlive_id") transitionId = p.text();
315 else if (paramName == "geometry") mlt_geometry = p.text();
316 else if (paramName == "automatic" && p.text() == "1") isAutomatic = true;
317 else if (paramName == "force_track" && p.text() == "1") forceTrack = true;
320 if (a_track == b_track || b_track == 0) {
321 // invalid transition, remove it
322 m_documentErrors.append(i18n("Removed invalid transition: %1", e.attribute("id")) + '\n');
323 tractor.removeChild(transitions.item(i));
327 if (transitionAdd || mlt_service != "mix") {
328 // Transition should be added to the scene
329 ItemInfo transitionInfo;
330 if (mlt_service == "composite" && transitionId.isEmpty()) {
331 // When adding composite transition, check if it is a wipe transition
332 if (mlt_geometry.count(';') == 1) {
333 mlt_geometry.remove(QChar('%'), Qt::CaseInsensitive);
334 mlt_geometry.replace(QChar('x'), QChar(':'), Qt::CaseInsensitive);
335 mlt_geometry.replace(QChar(','), QChar(':'), Qt::CaseInsensitive);
336 mlt_geometry.replace(QChar('/'), QChar(':'), Qt::CaseInsensitive);
338 QString start = mlt_geometry.section('=', 0, 0).section(':', 0, -2) + ':';
339 start.append(mlt_geometry.section('=', 1, 1).section(':', 0, -2));
340 QStringList numbers = start.split(':', QString::SkipEmptyParts);
341 bool isWipeTransition = true;
343 for (int i = 0; i < numbers.size(); ++i) {
344 checkNumber = qAbs(numbers.at(i).toInt());
345 if (checkNumber != 0 && checkNumber != 100) {
346 isWipeTransition = false;
350 if (isWipeTransition) transitionId = "slide";
354 QDomElement base = MainWindow::transitions.getEffectByTag(mlt_service, transitionId).cloneNode().toElement();
356 if (!base.isNull()) for (int k = 0; k < transitionparams.count(); k++) {
357 p = transitionparams.item(k).toElement();
359 QString paramName = p.attribute("name");
360 QString paramValue = p.text();
362 QDomNodeList params = base.elementsByTagName("parameter");
363 if (paramName != "a_track" && paramName != "b_track") for (int i = 0; i < params.count(); i++) {
364 QDomElement e = params.item(i).toElement();
365 if (!e.isNull() && e.attribute("tag") == paramName) {
366 if (e.attribute("type") == "double") {
367 QString factor = e.attribute("factor", "1");
368 double offset = e.attribute("offset", "0").toDouble();
369 if (factor != "1" || offset != 0) {
371 if (factor.contains('%')) {
372 fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
374 fact = factor.toDouble();
376 paramValue = QLocale().toString(offset + paramValue.toDouble() * fact);
379 e.setAttribute("value", paramValue);
387 doc.appendChild(doc.importNode(base, true));
388 kDebug() << "/////// TRANSITION XML: "<< doc.toString();*/
390 transitionInfo.startPos = GenTime(e.attribute("in").toInt(), m_doc->fps());
391 transitionInfo.endPos = GenTime(e.attribute("out").toInt() + 1, m_doc->fps());
392 transitionInfo.track = m_projectTracks - 1 - b_track;
394 //kDebug() << "/////////////// +++++++++++ ADDING TRANSITION ON TRACK: " << b_track << ", TOTAL TRKA: " << m_projectTracks;
395 if (transitionInfo.startPos >= transitionInfo.endPos || base.isNull()) {
396 // invalid transition, remove it.
397 m_documentErrors.append(i18n("Removed invalid transition: (%1, %2, %3)", e.attribute("id"), mlt_service, transitionId) + '\n');
398 kDebug() << "///// REMOVED INVALID TRANSITION: " << e.attribute("id");
399 tractor.removeChild(transitions.item(i));
401 } else if (m_trackview->canBePastedTo(transitionInfo, TRANSITIONWIDGET)) {
402 Transition *tr = new Transition(transitionInfo, a_track, m_doc->fps(), base, isAutomatic);
403 if (forceTrack) tr->setForcedTrack(true, a_track);
404 m_scene->addItem(tr);
405 if (b_track > 0 && m_doc->isTrackLocked(b_track - 1)) {
406 tr->setItemLocked(true);
410 m_documentErrors.append(i18n("Removed overlapping transition: (%1, %2, %3)", e.attribute("id"), mlt_service, transitionId) + '\n');
411 tractor.removeChild(transitions.item(i));
416 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
418 QDomElement propsXml = infoXml.firstChildElement("documentproperties");
420 int currentPos = propsXml.attribute("position").toInt();
421 if (currentPos > 0) m_trackview->initCursorPos(currentPos);
425 QDomNodeList guides = infoXml.elementsByTagName("guide");
426 for (int i = 0; i < guides.count(); i++) {
427 e = guides.item(i).toElement();
428 const QString comment = e.attribute("comment");
429 const GenTime pos = GenTime(e.attribute("time").toDouble());
430 m_trackview->addGuide(pos, comment);
434 QDomNodeList groups = infoXml.elementsByTagName("group");
435 m_trackview->loadGroups(groups);
436 m_trackview->setDuration(duration);
437 kDebug() << "/////////// TOTAL PROJECT DURATION: " << duration;
439 // Remove Kdenlive extra info from xml doc before sending it to MLT
440 mlt.removeChild(infoXml);
442 slotRebuildTrackHeaders();
443 if (!m_documentErrors.isNull()) KMessageBox::sorry(this, m_documentErrors);
444 if (infoXml.hasAttribute("upgraded") || infoXml.hasAttribute("modified")) {
445 // Our document was upgraded, create a backup copy just in case
446 QString baseFile = m_doc->url().path().section(".kdenlive", 0, 0);
448 QString backupFile = baseFile + "_backup" + QString::number(ct) + ".kdenlive";
449 while (QFile::exists(backupFile)) {
451 backupFile = baseFile + "_backup" + QString::number(ct) + ".kdenlive";
454 if (infoXml.hasAttribute("upgraded"))
455 message = i18n("Your project file was upgraded to the latest Kdenlive document version.\nTo make sure you don't lose data, a backup copy called %1 was created.", backupFile);
457 message = i18n("Your project file was modified by Kdenlive.\nTo make sure you don't lose data, a backup copy called %1 was created.", backupFile);
458 if (KIO::NetAccess::file_copy(m_doc->url(), KUrl(backupFile), this))
459 KMessageBox::information(this, message);
461 KMessageBox::information(this, i18n("Your project file was upgraded to the latest Kdenlive document version, but it was not possible to create a backup copy.", backupFile));
463 //m_trackview->setCursorPos(cursorPos);
464 //m_scrollBox->setGeometry(0, 0, 300 * zoomFactor(), m_scrollArea->height());
467 void TrackView::slotDeleteClip(const QString &clipId)
469 m_trackview->deleteClip(clipId);
472 void TrackView::setCursorPos(int pos)
474 m_trackview->setCursorPos(pos);
477 void TrackView::moveCursorPos(int pos)
479 m_trackview->setCursorPos(pos);
482 void TrackView::slotChangeZoom(int horizontal, int vertical)
484 m_ruler->setPixelPerMark(horizontal);
485 m_scale = (double) m_trackview->getFrameWidth() / m_ruler->comboScale[horizontal];
487 if (vertical == -1) {
489 m_doc->setZoom(horizontal, m_verticalZoom);
490 m_trackview->setScale(m_scale, m_scene->scale().y());
492 m_verticalZoom = vertical;
493 if (m_verticalZoom == 0)
494 m_trackview->setScale(m_scale, 0.5);
496 m_trackview->setScale(m_scale, m_verticalZoom);
497 adjustTrackHeaders();
501 int TrackView::fitZoom() const
503 int zoom = (int)((duration() + 20 / m_scale) * m_trackview->getFrameWidth() / m_trackview->width());
505 for (i = 0; i < 13; i++)
506 if (m_ruler->comboScale[i] > zoom) break;
510 KdenliveDoc *TrackView::document()
515 void TrackView::refresh()
517 m_trackview->viewport()->update();
520 void TrackView::slotRepaintTracks()
522 QList<HeaderTrack *> widgets = findChildren<HeaderTrack *>();
523 for (int i = 0; i < widgets.count(); i++) {
524 if (widgets.at(i)) widgets.at(i)->setSelectedIndex(m_trackview->selectedTrack());
528 void TrackView::slotReloadTracks()
530 slotRebuildTrackHeaders();
531 emit updateTracksInfo();
534 void TrackView::slotRebuildTrackHeaders()
536 const QList <TrackInfo> list = m_doc->tracksList();
538 while ((child = headers_container->layout()->takeAt(0)) != 0) {
539 QWidget *wid = child->widget();
541 if (wid) wid->deleteLater();
543 int max = list.count();
544 int height = KdenliveSettings::trackheight() * m_scene->scale().y() - 1;
545 HeaderTrack *header = NULL;
546 QFrame *frame = NULL;
550 for (int i = 0; i < max; i++) {
551 frame = new QFrame(headers_container);
552 frame->setFrameStyle(QFrame::HLine);
553 frame->setFixedHeight(1);
554 headers_container->layout()->addWidget(frame);
555 TrackInfo info = list.at(max - i - 1);
556 header = new HeaderTrack(i, info, height, m_trackActions, headers_container);
557 header->setSelectedIndex(m_trackview->selectedTrack());
558 connect(header, SIGNAL(switchTrackVideo(int)), m_trackview, SLOT(slotSwitchTrackVideo(int)));
559 connect(header, SIGNAL(switchTrackAudio(int)), m_trackview, SLOT(slotSwitchTrackAudio(int)));
560 connect(header, SIGNAL(switchTrackLock(int)), m_trackview, SLOT(slotSwitchTrackLock(int)));
561 connect(header, SIGNAL(selectTrack(int)), m_trackview, SLOT(slotSelectTrack(int)));
562 connect(header, SIGNAL(renameTrack(int, QString)), this, SLOT(slotRenameTrack(int, QString)));
563 connect(header, SIGNAL(configTrack(int)), this, SIGNAL(configTrack(int)));
564 connect(header, SIGNAL(addTrackEffect(const QDomElement, int)), m_trackview, SLOT(slotAddTrackEffect(const QDomElement, int)));
565 connect(header, SIGNAL(showTrackEffects(int)), this, SLOT(slotShowTrackEffects(int)));
566 headers_container->layout()->addWidget(header);
568 frame = new QFrame(this);
569 frame->setFrameStyle(QFrame::HLine);
570 frame->setFixedHeight(1);
571 headers_container->layout()->addWidget(frame);
575 void TrackView::updatePalette()
577 QPalette p = palette();
578 KColorScheme scheme(p.currentColorGroup(), KColorScheme::View, KSharedConfig::openConfig(KdenliveSettings::colortheme()));
579 QColor norm = scheme.shade(scheme.background(KColorScheme::ActiveBackground).color(), KColorScheme::MidShade);
580 p.setColor(QPalette::Button, norm);
581 QColor col = scheme.background().color();
582 QColor col2 = scheme.foreground().color();
583 headers_container->setStyleSheet(QString("QLineEdit { background-color: transparent;color: %1;} QLineEdit:hover{ background-color: %2;} QLineEdit:focus { background-color: %2;}").arg(col2.name()).arg(col.name()));
584 m_trackview->updatePalette();
585 m_ruler->updatePalette();
589 void TrackView::adjustTrackHeaders()
591 int height = KdenliveSettings::trackheight() * m_scene->scale().y() - 1;
592 QList<HeaderTrack *> widgets = findChildren<HeaderTrack *>();
593 for (int i = 0; i < widgets.count(); i++) {
594 if (widgets.at(i)) widgets.at(i)->adjustSize(height);
598 int TrackView::slotAddProjectTrack(int ix, QDomElement xml, bool locked, QDomNodeList producers)
602 QMap <QString, QString> producerReplacementIds;
603 int frame_width = m_trackview->getFrameWidth();
604 QDomNodeList children = xml.childNodes();
605 for (int nodeindex = 0; nodeindex < children.count(); nodeindex++) {
606 QDomNode n = children.item(nodeindex);
607 QDomElement elem = n.toElement();
608 if (elem.tagName() == "blank") {
609 position += elem.attribute("length").toInt();
610 } else if (elem.tagName() == "entry") {
612 int in = elem.attribute("in").toInt();
613 int out = elem.attribute("out").toInt();
614 if (in > out || /*in == out ||*/ m_invalidProducers.contains(elem.attribute("producer"))) {
615 m_documentErrors.append(i18n("Invalid clip removed from track %1 at %2\n", ix, position));
616 xml.removeChild(children.at(nodeindex));
620 QString idString = elem.attribute("producer");
621 if (producerReplacementIds.contains(idString)) {
623 elem.setAttribute("producer", producerReplacementIds.value(idString));
624 idString = elem.attribute("producer");
626 QString id = idString;
629 if (idString.startsWith("slowmotion")) {
631 id = idString.section(':', 1, 1);
632 speed = locale.toDouble(idString.section(':', 2, 2));
633 strobe = idString.section(':', 3, 3).toInt();
634 if (strobe == 0) strobe = 1;
636 id = id.section('_', 0, 0);
637 DocClipBase *clip = m_doc->clipManager()->getClipById(id);
639 // The clip in playlist was not listed in the kdenlive producers,
640 // something went wrong, repair required.
641 kWarning() << "CANNOT INSERT CLIP " << id;
642 QString docRoot = m_doc->toXml().documentElement().attribute("root");
643 if (!docRoot.endsWith('/')) docRoot.append('/');
644 clip = getMissingProducer(idString);
646 // We found the original producer in Kdenlive's producers
647 // Found correct producer
648 m_documentErrors.append(i18n("Replaced wrong clip producer %1 with %2", id, clip->getId()) + '\n');
649 QString prodId = clip->getId();
650 if (clip->clipType() == PLAYLIST || clip->clipType() == AV || clip->clipType() == AUDIO) {
651 // We need producer for the track
652 prodId.append('_' + QString::number(ix));
654 elem.setAttribute("producer", prodId);
655 producerReplacementIds.insert(idString, prodId);
656 // now adjust the mlt producer
658 for (int i = 0; i < producers.count(); i++) {
659 QDomElement prod = producers.at(i).toElement();
660 if (prod.attribute("id") == prodId) {
661 // ok, producer already exists
667 for (int i = 0; i < producers.count(); i++) {
668 QDomElement prod = producers.at(i).toElement();
669 if (prod.attribute("id") == idString) {
670 prod.setAttribute("id", prodId);
671 m_replacementProducerIds.insert(idString, prodId);
678 // We didn't find the producer for this track, find producer for another track and duplicate
679 for (int i = 0; i < producers.count(); i++) {
680 QDomElement prod = producers.at(i).toElement();
681 QString mltProdId = prod.attribute("id");
682 if (mltProdId == prodId || mltProdId.startsWith(prodId + '_')) {
683 // Found parent producer, clone it
684 QDomElement clone = prod.cloneNode().toElement();
685 clone.setAttribute("id", prodId);
686 m_doc->toXml().documentElement().insertBefore(clone, xml);
693 // We cannot find the producer, something is really wrong, add
694 // placeholder color clip
696 QDomElement producerXml = doc.createElement("producer");
697 doc.appendChild(producerXml);
698 bool foundMltProd = false;
699 for (int i = 0; i < producers.count(); i++) {
700 QDomElement prod = producers.at(i).toElement();
701 if (prod.attribute("id") == id) {
702 QString service = EffectsList::property(prod, "mlt_service");
703 QString type = EffectsList::property(prod, "mlt_type");
704 QString resource = EffectsList::property(prod, "resource");
705 if (!resource.startsWith('/') && service != "colour") {
706 resource.prepend(docRoot);
707 kDebug()<<"******************\nADJUSTED 1\n*************************";
709 QString length = EffectsList::property(prod, "length");
710 producerXml.setAttribute("mlt_service", service);
711 producerXml.setAttribute("mlt_type", type);
712 producerXml.setAttribute("resource", resource);
713 producerXml.setAttribute("duration", length);
714 if (service == "colour") producerXml.setAttribute("type", COLOR);
715 else if (service == "qimage" || service == "pixbuf") producerXml.setAttribute("type", IMAGE);
716 else if (service == "kdenlivetitle") producerXml.setAttribute("type", TEXT);
717 else producerXml.setAttribute("type", AV);
718 clip = new DocClipBase(m_doc->clipManager(), doc.documentElement(), id);
719 m_doc->clipManager()->addClip(clip);
720 m_documentErrors.append(i18n("Broken clip producer %1, recreated base clip: %2", id, resource) + '\n');
726 // Cannot recover, replace with blank
727 int duration = elem.attribute("out").toInt() - elem.attribute("in").toInt();
728 elem.setAttribute("length", duration);
729 elem.setTagName("blank");
730 m_documentErrors.append(i18n("Broken clip producer %1, removed from project", id) + '\n');
733 m_doc->setModified(true);
738 clipinfo.startPos = GenTime(position, m_doc->fps());
739 clipinfo.endPos = clipinfo.startPos + GenTime(out - in + 1, m_doc->fps());
740 clipinfo.cropStart = GenTime(in, m_doc->fps());
741 clipinfo.cropDuration = clipinfo.endPos - clipinfo.startPos;
744 //kDebug() << "// INSERTING CLIP: " << in << "x" << out << ", track: " << ix << ", ID: " << id << ", SCALE: " << m_scale << ", FPS: " << m_doc->fps();
745 ClipItem *item = new ClipItem(clip, clipinfo, m_doc->fps(), speed, strobe, frame_width, false);
746 if (idString.endsWith("_video")) item->setVideoOnly(true);
747 else if (idString.endsWith("_audio")) item->setAudioOnly(true);
748 m_scene->addItem(item);
749 if (locked) item->setItemLocked(true);
750 clip->addReference();
751 position += (out - in + 1);
752 if (speed != 1.0 || strobe > 1) {
753 QDomElement speedeffect = MainWindow::videoEffects.getEffectByTag(QString(), "speed").cloneNode().toElement();
754 EffectsList::setParameter(speedeffect, "speed", QString::number((int)(100 * speed + 0.5)));
755 EffectsList::setParameter(speedeffect, "strobe", QString::number(strobe));
756 item->addEffect(speedeffect, false);
757 item->effectsCounter();
760 // parse clip effects
761 QDomNodeList effects = elem.elementsByTagName("filter");
762 slotAddProjectEffects(effects, elem, item, -1);
766 kDebug() << "************* ADD DOC TRACK " << ix << ", DURATION: " << position;
770 void TrackView::slotAddProjectEffects(QDomNodeList effects, QDomElement parentNode, ClipItem *clip, int trackIndex)
774 for (int ix = 0; ix < effects.count(); ix++) {
775 bool disableeffect = false;
776 QDomElement effect = effects.at(ix).toElement();
777 if (effect.tagName() != "filter") continue;
779 // add effect to clip
783 QString effectindex = QString::number(effectNb);
784 // Get effect tag & index
785 for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
786 // parse effect parameters
787 QDomElement effectparam = n3.toElement();
788 if (effectparam.attribute("name") == "tag") {
789 effecttag = effectparam.text();
790 } else if (effectparam.attribute("name") == "kdenlive_id") {
791 effectid = effectparam.text();
792 } else if (effectparam.attribute("name") == "kdenlive_info") {
793 effectinfo = effectparam.text();
794 } else if (effectparam.attribute("name") == "disable" && effectparam.text().toInt() == 1) {
796 disableeffect = true;
797 } else if (effectparam.attribute("name") == "kdenlive_ix") {
799 effectparam.firstChild().setNodeValue(effectindex);
802 //kDebug() << "+ + CLIP EFF FND: " << effecttag << ", " << effectid << ", " << effectindex;
803 // get effect standard tags
804 QDomElement clipeffect = getEffectByTag(effecttag, effectid);
805 if (clipeffect.isNull()) {
806 kDebug() << "/// WARNING, EFFECT: " << effecttag << ": " << effectid << " not found, removing it from project";
807 m_documentErrors.append(i18n("Effect %1:%2 not found in MLT, it was removed from this project\n", effecttag, effectid));
808 if (parentNode.removeChild(effects.at(ix)).isNull()) kDebug() << "/// PROBLEM REMOVING EFFECT: " << effecttag;
811 QDomElement currenteffect = clipeffect.cloneNode().toElement();
812 currenteffect.setAttribute("kdenlive_ix", effectindex);
813 currenteffect.setAttribute("kdenlive_info", effectinfo);
814 QDomNodeList clipeffectparams = currenteffect.childNodes();
816 if (MainWindow::videoEffects.hasKeyFrames(currenteffect)) {
817 //kDebug() << " * * * * * * * * * * ** CLIP EFF WITH KFR FND * * * * * * * * * * *";
818 // effect is key-framable, read all effects to retrieve keyframes
823 QDomNodeList params = currenteffect.elementsByTagName("parameter");
824 for (int i = 0; i < params.count(); i++) {
825 QDomElement e = params.item(i).toElement();
826 if (e.attribute("type") == "keyframe") {
827 starttag = e.attribute("starttag", "start");
828 endtag = e.attribute("endtag", "end");
829 factor = e.attribute("factor", "1");
830 offset = e.attribute("offset", "0").toDouble();
835 int effectin = effect.attribute("in").toInt();
836 int effectout = effect.attribute("out").toInt();
837 double startvalue = 0;
840 if (factor.contains('%')) {
841 fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
843 fact = factor.toDouble();
845 for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
846 // parse effect parameters
847 QDomElement effectparam = n3.toElement();
848 if (effectparam.attribute("name") == starttag)
849 startvalue = offset + effectparam.text().toDouble() * fact;
850 if (effectparam.attribute("name") == endtag)
851 endvalue = offset + effectparam.text().toDouble() * fact;
853 // add first keyframe
854 if (effectout <= effectin) {
855 // there is only one keyframe
856 keyframes.append(QString::number(effectin) + ':' + locale.toString(startvalue) + ';');
857 } else keyframes.append(QString::number(effectin) + ':' + locale.toString(startvalue) + ';' + QString::number(effectout) + ':' + QString::number(endvalue) + ';');
858 QDomNode lastParsedEffect;
860 QDomNode n2 = effects.at(ix);
861 bool continueParsing = true;
862 for (; !n2.isNull() && continueParsing; n2 = n2.nextSibling()) {
864 QDomElement kfreffect = n2.toElement();
865 int effectout = kfreffect.attribute("out").toInt();
867 for (QDomNode n4 = kfreffect.firstChild(); !n4.isNull(); n4 = n4.nextSibling()) {
868 // parse effect parameters
869 QDomElement subeffectparam = n4.toElement();
870 if (subeffectparam.attribute("name") == "kdenlive_ix" && subeffectparam.text() != effectindex) {
871 //We are not in the same effect, stop parsing
872 lastParsedEffect = n2.previousSibling();
874 continueParsing = false;
876 } else if (subeffectparam.attribute("name") == endtag) {
877 endvalue = offset + subeffectparam.text().toDouble() * fact;
881 if (continueParsing) {
882 keyframes.append(QString::number(effectout) + ':' + locale.toString(endvalue) + ';');
887 params = currenteffect.elementsByTagName("parameter");
888 for (int i = 0; i < params.count(); i++) {
889 QDomElement e = params.item(i).toElement();
890 if (e.attribute("type") == "keyframe") e.setAttribute("keyframes", keyframes);
892 if (!continueParsing) {
893 n2 = lastParsedEffect;
896 // Check if effect has in/out points
897 if (effect.hasAttribute("in")) {
898 EffectsList::setParameter(currenteffect, "in", effect.attribute("in"));
899 currenteffect.setAttribute("in", effect.attribute("in"));
900 currenteffect.setAttribute("_sync_in_out", "1");
902 if (effect.hasAttribute("out")) {
903 EffectsList::setParameter(currenteffect, "out", effect.attribute("out"));
904 currenteffect.setAttribute("out", effect.attribute("out"));
908 // Special case, region filter embeds other effects
909 bool regionFilter = effecttag == "region";
910 QMap <QString, QString> regionEffects;
912 // adjust effect parameters
913 for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
914 // parse effect parameters
915 QDomElement effectparam = n3.toElement();
916 QString paramname = effectparam.attribute("name");
917 QString paramvalue = effectparam.text();
919 if (regionFilter && paramname.startsWith("filter")) {
920 regionEffects.insert(paramname, paramvalue);
924 // try to find this parameter in the effect xml and set its value
925 adjustparameterValue(clipeffectparams, paramname, paramvalue);
929 if (regionFilter && !regionEffects.isEmpty()) {
930 // insert region sub-effects
932 while (regionEffects.contains(QString("filter%1").arg(i))) {
933 QString filterid = regionEffects.value(QString("filter%1.kdenlive_id").arg(i));
934 QString filtertag = regionEffects.value(QString("filter%1.tag").arg(i));
935 QDomElement subclipeffect = getEffectByTag(filtertag, filterid).cloneNode().toElement();
936 QDomNodeList subclipeffectparams = subclipeffect.childNodes();
937 subclipeffect.setAttribute("region_ix", i);
938 QMap<QString, QString>::const_iterator j = regionEffects.constBegin();
939 while (j != regionEffects.constEnd()) {
940 if (j.key().startsWith(QString("filter%1.").arg(i))) {
941 QString pname = j.key().section('.', 1, -1);
942 adjustparameterValue(subclipeffectparams, pname, j.value());
946 currenteffect.appendChild(currenteffect.ownerDocument().importNode(subclipeffect, true));
951 if (disableeffect) currenteffect.setAttribute("disable", "1");
953 clip->addEffect(currenteffect, false);
955 m_doc->addTrackEffect(trackIndex, currenteffect);
961 void TrackView::adjustparameterValue(QDomNodeList clipeffectparams, const QString ¶mname, const QString ¶mvalue)
965 for (int k = 0; k < clipeffectparams.count(); k++) {
966 e = clipeffectparams.item(k).toElement();
967 if (!e.isNull() && e.tagName() == "parameter" && e.attribute("name") == paramname) {
968 QString type = e.attribute("type");
969 QString factor = e.attribute("factor", "1");
971 if (factor.contains('%')) {
972 fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
974 fact = factor.toDouble();
976 double offset = e.attribute("offset", "0").toDouble();
977 if (type == "simplekeyframe") {
978 QStringList kfrs = paramvalue.split(";");
979 for (int l = 0; l < kfrs.count(); l++) {
980 QString fr = kfrs.at(l).section('=', 0, 0);
981 double val = locale.toDouble(kfrs.at(l).section('=', 1, 1));
982 //kfrs[l] = fr + ":" + locale.toString((int)(val * fact));
983 kfrs[l] = fr + ':' + QString::number((int) (offset + val * fact));
985 e.setAttribute("keyframes", kfrs.join(";"));
986 } else if (type == "double" || type == "constant") {
988 e.setAttribute("value", offset + locale.toDouble(paramvalue, &ok) * fact);
990 e.setAttribute("value", paramvalue);
992 e.setAttribute("value", paramvalue);
1000 QDomElement TrackView::getEffectByTag(const QString &effecttag, const QString &effectid)
1002 QDomElement clipeffect = MainWindow::customEffects.getEffectByTag(QString(), effectid);
1003 if (clipeffect.isNull()) {
1004 clipeffect = MainWindow::videoEffects.getEffectByTag(effecttag, effectid);
1006 if (clipeffect.isNull()) {
1007 clipeffect = MainWindow::audioEffects.getEffectByTag(effecttag, effectid);
1013 DocClipBase *TrackView::getMissingProducer(const QString id) const
1015 QDomElement missingXml;
1016 QDomDocument doc = m_doc->toXml();
1017 QString docRoot = doc.documentElement().attribute("root");
1018 if (!docRoot.endsWith('/')) docRoot.append('/');
1019 QDomNodeList prods = doc.elementsByTagName("producer");
1020 int maxprod = prods.count();
1021 bool slowmotionClip = false;
1022 for (int i = 0; i < maxprod; i++) {
1023 QDomNode m = prods.at(i);
1024 QString prodId = m.toElement().attribute("id");
1025 if (prodId.startsWith("slowmotion")) {
1026 slowmotionClip = true;
1027 prodId = prodId.section(':', 1, 1);
1029 prodId = prodId.section('_', 0, 0);
1031 missingXml = m.toElement();
1035 if (missingXml == QDomElement()) {
1036 // Check if producer id was replaced in another track
1037 if (m_replacementProducerIds.contains(id)) {
1038 QString newId = m_replacementProducerIds.value(id);
1039 slowmotionClip = false;
1040 for (int i = 0; i < maxprod; i++) {
1041 QDomNode m = prods.at(i);
1042 QString prodId = m.toElement().attribute("id");
1043 if (prodId.startsWith("slowmotion")) {
1044 slowmotionClip = true;
1045 prodId = prodId.section(':', 1, 1);
1047 prodId = prodId.section('_', 0, 0);
1049 missingXml = m.toElement();
1055 if (missingXml == QDomElement()) return NULL;
1056 QString resource = EffectsList::property(missingXml, "resource");
1057 QString service = EffectsList::property(missingXml, "mlt_service");
1059 if (slowmotionClip) resource = resource.section('?', 0, 0);
1060 // prepend MLT XML document root if no path in clip resource and not a color clip
1061 if (!resource.startsWith('/') && service != "colour") {
1062 resource.prepend(docRoot);
1063 kDebug()<<"******************\nADJUSTED 2\n*************************";
1065 DocClipBase *missingClip = NULL;
1066 if (!resource.isEmpty()) {
1067 QList <DocClipBase *> list = m_doc->clipManager()->getClipByResource(resource);
1068 if (!list.isEmpty()) missingClip = list.at(0);
1073 QGraphicsScene *TrackView::projectScene()
1078 CustomTrackView *TrackView::projectView()
1083 void TrackView::setEditMode(const QString & editMode)
1085 m_editMode = editMode;
1088 const QString & TrackView::editMode() const
1093 void TrackView::slotChangeTrackLock(int ix, bool lock)
1095 QList<HeaderTrack *> widgets = findChildren<HeaderTrack *>();
1096 widgets.at(ix)->setLock(lock);
1100 void TrackView::slotVerticalZoomDown()
1102 if (m_verticalZoom == 0) return;
1104 m_doc->setZoom(m_doc->zoom().x(), m_verticalZoom);
1105 if (m_verticalZoom == 0)
1106 m_trackview->setScale(m_scene->scale().x(), 0.5);
1108 m_trackview->setScale(m_scene->scale().x(), 1);
1109 adjustTrackHeaders();
1110 m_trackview->verticalScrollBar()->setValue(headers_area->verticalScrollBar()->value());
1113 void TrackView::slotVerticalZoomUp()
1115 if (m_verticalZoom == 2) return;
1117 m_doc->setZoom(m_doc->zoom().x(), m_verticalZoom);
1118 if (m_verticalZoom == 2)
1119 m_trackview->setScale(m_scene->scale().x(), 2);
1121 m_trackview->setScale(m_scene->scale().x(), 1);
1122 adjustTrackHeaders();
1123 m_trackview->verticalScrollBar()->setValue(headers_area->verticalScrollBar()->value());
1126 void TrackView::updateProjectFps()
1128 m_ruler->updateProjectFps(m_doc->timecode());
1129 m_trackview->updateProjectFps();
1132 void TrackView::slotRenameTrack(int ix, QString name)
1134 int tracknumber = m_doc->tracksCount() - ix;
1135 QList <TrackInfo> tracks = m_doc->tracksList();
1136 tracks[tracknumber - 1].trackName = name;
1137 ConfigTracksCommand *configTracks = new ConfigTracksCommand(m_trackview, m_doc->tracksList(), tracks);
1138 m_doc->commandStack()->push(configTracks);
1139 m_doc->setModified(true);
1142 void TrackView::slotUpdateVerticalScroll(int /*min*/, int max)
1145 if (max > 0) height = m_trackview->horizontalScrollBar()->height() - 1;
1146 headers_container->layout()->setContentsMargins(0, m_trackview->frameWidth(), 0, height);
1149 void TrackView::updateRuler()
1154 void TrackView::slotShowTrackEffects(int ix)
1156 m_trackview->clearSelection();
1157 emit showTrackEffects(m_doc->tracksCount() - ix, m_doc->trackInfoAt(m_doc->tracksCount() - ix - 1));
1160 void TrackView::slotUpdateTrackEffectState(int ix)
1162 QList<HeaderTrack *> widgets = findChildren<HeaderTrack *>();
1163 if (ix < 0 || ix >= widgets.count()) {
1164 kDebug() << "ERROR, Trying to access a non existant track: " << ix;
1167 widgets.at(m_doc->tracksCount() - ix - 1)->updateEffectLabel(m_doc->trackInfoAt(ix).effectsList.effectNames());
1170 void TrackView::slotSaveTimelinePreview(const QString path)
1172 QImage img(width(), height(), QImage::Format_ARGB32_Premultiplied);
1173 img.fill(palette().base().color().rgb());
1174 QPainter painter(&img);
1177 img = img.scaledToWidth(600, Qt::SmoothTransformation);
1181 void TrackView::updateProfile()
1183 m_ruler->updateFrameSize();
1184 m_trackview->updateSceneFrameWidth();
1185 slotChangeZoom(m_doc->zoom().x(), m_doc->zoom().y());
1186 slotSetZone(m_doc->zone(), false);
1189 void TrackView::checkTrackHeight()
1191 if (m_trackview->checkTrackHeight()) {
1192 m_doc->clipManager()->clearCache();
1193 m_ruler->updateFrameSize();
1194 m_trackview->updateSceneFrameWidth();
1195 slotChangeZoom(m_doc->zoom().x(), m_doc->zoom().y());
1196 slotSetZone(m_doc->zone(), false);
1200 #include "trackview.moc"