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");
419 QDomNodeList guides = infoXml.elementsByTagName("guide");
420 for (int i = 0; i < guides.count(); i++) {
421 e = guides.item(i).toElement();
422 const QString comment = e.attribute("comment");
423 const GenTime pos = GenTime(e.attribute("time").toDouble());
424 m_trackview->addGuide(pos, comment);
428 QDomNodeList groups = infoXml.elementsByTagName("group");
429 m_trackview->loadGroups(groups);
430 m_trackview->setDuration(duration);
431 kDebug() << "/////////// TOTAL PROJECT DURATION: " << duration;
433 // Remove Kdenlive extra info from xml doc before sending it to MLT
434 mlt.removeChild(infoXml);
436 slotRebuildTrackHeaders();
437 if (!m_documentErrors.isNull()) KMessageBox::sorry(this, m_documentErrors);
438 if (infoXml.hasAttribute("upgraded") || infoXml.hasAttribute("modified")) {
439 // Our document was upgraded, create a backup copy just in case
440 QString baseFile = m_doc->url().path().section(".kdenlive", 0, 0);
442 QString backupFile = baseFile + "_backup" + QString::number(ct) + ".kdenlive";
443 while (QFile::exists(backupFile)) {
445 backupFile = baseFile + "_backup" + QString::number(ct) + ".kdenlive";
448 if (infoXml.hasAttribute("upgraded"))
449 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);
451 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);
452 if (KIO::NetAccess::file_copy(m_doc->url(), KUrl(backupFile), this))
453 KMessageBox::information(this, message);
455 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));
457 //m_trackview->setCursorPos(cursorPos);
458 //m_scrollBox->setGeometry(0, 0, 300 * zoomFactor(), m_scrollArea->height());
461 void TrackView::slotDeleteClip(const QString &clipId)
463 m_trackview->deleteClip(clipId);
466 void TrackView::setCursorPos(int pos)
468 m_trackview->setCursorPos(pos);
471 void TrackView::moveCursorPos(int pos)
473 m_trackview->setCursorPos(pos);
476 void TrackView::slotChangeZoom(int horizontal, int vertical)
478 m_ruler->setPixelPerMark(horizontal);
479 m_scale = (double) m_trackview->getFrameWidth() / m_ruler->comboScale[horizontal];
481 if (vertical == -1) {
483 m_doc->setZoom(horizontal, m_verticalZoom);
484 m_trackview->setScale(m_scale, m_scene->scale().y());
486 m_verticalZoom = vertical;
487 if (m_verticalZoom == 0)
488 m_trackview->setScale(m_scale, 0.5);
490 m_trackview->setScale(m_scale, m_verticalZoom);
491 adjustTrackHeaders();
495 int TrackView::fitZoom() const
497 int zoom = (int)((duration() + 20 / m_scale) * m_trackview->getFrameWidth() / m_trackview->width());
499 for (i = 0; i < 13; i++)
500 if (m_ruler->comboScale[i] > zoom) break;
504 KdenliveDoc *TrackView::document()
509 void TrackView::refresh()
511 m_trackview->viewport()->update();
514 void TrackView::slotRepaintTracks()
516 QList<HeaderTrack *> widgets = findChildren<HeaderTrack *>();
517 for (int i = 0; i < widgets.count(); i++) {
518 if (widgets.at(i)) widgets.at(i)->setSelectedIndex(m_trackview->selectedTrack());
522 void TrackView::slotReloadTracks()
524 slotRebuildTrackHeaders();
525 emit updateTracksInfo();
528 void TrackView::slotRebuildTrackHeaders()
530 const QList <TrackInfo> list = m_doc->tracksList();
532 while ((child = headers_container->layout()->takeAt(0)) != 0) {
533 QWidget *wid = child->widget();
535 if (wid) wid->deleteLater();
537 int max = list.count();
538 int height = KdenliveSettings::trackheight() * m_scene->scale().y() - 1;
539 HeaderTrack *header = NULL;
540 QFrame *frame = NULL;
544 for (int i = 0; i < max; i++) {
545 frame = new QFrame(headers_container);
546 frame->setFrameStyle(QFrame::HLine);
547 frame->setFixedHeight(1);
548 headers_container->layout()->addWidget(frame);
549 TrackInfo info = list.at(max - i - 1);
550 header = new HeaderTrack(i, info, height, m_trackActions, headers_container);
551 header->setSelectedIndex(m_trackview->selectedTrack());
552 connect(header, SIGNAL(switchTrackVideo(int)), m_trackview, SLOT(slotSwitchTrackVideo(int)));
553 connect(header, SIGNAL(switchTrackAudio(int)), m_trackview, SLOT(slotSwitchTrackAudio(int)));
554 connect(header, SIGNAL(switchTrackLock(int)), m_trackview, SLOT(slotSwitchTrackLock(int)));
555 connect(header, SIGNAL(selectTrack(int)), m_trackview, SLOT(slotSelectTrack(int)));
556 connect(header, SIGNAL(renameTrack(int, QString)), this, SLOT(slotRenameTrack(int, QString)));
557 connect(header, SIGNAL(configTrack(int)), this, SIGNAL(configTrack(int)));
558 connect(header, SIGNAL(addTrackEffect(const QDomElement, int)), m_trackview, SLOT(slotAddTrackEffect(const QDomElement, int)));
559 connect(header, SIGNAL(showTrackEffects(int)), this, SLOT(slotShowTrackEffects(int)));
560 headers_container->layout()->addWidget(header);
562 frame = new QFrame(this);
563 frame->setFrameStyle(QFrame::HLine);
564 frame->setFixedHeight(1);
565 headers_container->layout()->addWidget(frame);
569 void TrackView::updatePalette()
571 QPalette p = palette();
572 KColorScheme scheme(p.currentColorGroup(), KColorScheme::View, KSharedConfig::openConfig(KdenliveSettings::colortheme()));
573 QColor norm = scheme.shade(scheme.background(KColorScheme::ActiveBackground).color(), KColorScheme::MidShade);
574 p.setColor(QPalette::Button, norm);
575 QColor col = scheme.background().color();
576 QColor col2 = scheme.foreground().color();
577 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()));
578 m_trackview->updatePalette();
579 m_ruler->updatePalette();
583 void TrackView::adjustTrackHeaders()
585 int height = KdenliveSettings::trackheight() * m_scene->scale().y() - 1;
586 QList<HeaderTrack *> widgets = findChildren<HeaderTrack *>();
587 for (int i = 0; i < widgets.count(); i++) {
588 if (widgets.at(i)) widgets.at(i)->adjustSize(height);
592 int TrackView::slotAddProjectTrack(int ix, QDomElement xml, bool locked, QDomNodeList producers)
596 QMap <QString, QString> producerReplacementIds;
597 int frame_width = m_trackview->getFrameWidth();
598 QDomNodeList children = xml.childNodes();
599 for (int nodeindex = 0; nodeindex < children.count(); nodeindex++) {
600 QDomNode n = children.item(nodeindex);
601 QDomElement elem = n.toElement();
602 if (elem.tagName() == "blank") {
603 position += elem.attribute("length").toInt();
604 } else if (elem.tagName() == "entry") {
606 int in = elem.attribute("in").toInt();
607 int out = elem.attribute("out").toInt();
608 if (in > out || /*in == out ||*/ m_invalidProducers.contains(elem.attribute("producer"))) {
609 m_documentErrors.append(i18n("Invalid clip removed from track %1 at %2\n", ix, position));
610 xml.removeChild(children.at(nodeindex));
614 QString idString = elem.attribute("producer");
615 if (producerReplacementIds.contains(idString)) {
617 elem.setAttribute("producer", producerReplacementIds.value(idString));
618 idString = elem.attribute("producer");
620 QString id = idString;
623 if (idString.startsWith("slowmotion")) {
625 id = idString.section(':', 1, 1);
626 speed = locale.toDouble(idString.section(':', 2, 2));
627 strobe = idString.section(':', 3, 3).toInt();
628 if (strobe == 0) strobe = 1;
630 id = id.section('_', 0, 0);
631 DocClipBase *clip = m_doc->clipManager()->getClipById(id);
633 // The clip in playlist was not listed in the kdenlive producers,
634 // something went wrong, repair required.
635 kWarning() << "CANNOT INSERT CLIP " << id;
636 QString docRoot = m_doc->toXml().documentElement().attribute("root");
637 if (!docRoot.endsWith('/')) docRoot.append('/');
638 clip = getMissingProducer(idString);
640 // We found the original producer in Kdenlive's producers
641 // Found correct producer
642 m_documentErrors.append(i18n("Replaced wrong clip producer %1 with %2", id, clip->getId()) + '\n');
643 QString prodId = clip->getId();
644 if (clip->clipType() == PLAYLIST || clip->clipType() == AV || clip->clipType() == AUDIO) {
645 // We need producer for the track
646 prodId.append('_' + QString::number(ix));
648 elem.setAttribute("producer", prodId);
649 producerReplacementIds.insert(idString, prodId);
650 // now adjust the mlt producer
652 for (int i = 0; i < producers.count(); i++) {
653 QDomElement prod = producers.at(i).toElement();
654 if (prod.attribute("id") == prodId) {
655 // ok, producer already exists
661 for (int i = 0; i < producers.count(); i++) {
662 QDomElement prod = producers.at(i).toElement();
663 if (prod.attribute("id") == idString) {
664 prod.setAttribute("id", prodId);
665 m_replacementProducerIds.insert(idString, prodId);
672 // We didn't find the producer for this track, find producer for another track and duplicate
673 for (int i = 0; i < producers.count(); i++) {
674 QDomElement prod = producers.at(i).toElement();
675 QString mltProdId = prod.attribute("id");
676 if (mltProdId == prodId || mltProdId.startsWith(prodId + '_')) {
677 // Found parent producer, clone it
678 QDomElement clone = prod.cloneNode().toElement();
679 clone.setAttribute("id", prodId);
680 m_doc->toXml().documentElement().insertBefore(clone, xml);
687 // We cannot find the producer, something is really wrong, add
688 // placeholder color clip
690 QDomElement producerXml = doc.createElement("producer");
691 doc.appendChild(producerXml);
692 bool foundMltProd = false;
693 for (int i = 0; i < producers.count(); i++) {
694 QDomElement prod = producers.at(i).toElement();
695 if (prod.attribute("id") == id) {
696 QString service = EffectsList::property(prod, "mlt_service");
697 QString type = EffectsList::property(prod, "mlt_type");
698 QString resource = EffectsList::property(prod, "resource");
699 if (!resource.startsWith('/') && service != "colour") {
700 resource.prepend(docRoot);
701 kDebug()<<"******************\nADJUSTED 1\n*************************";
703 QString length = EffectsList::property(prod, "length");
704 producerXml.setAttribute("mlt_service", service);
705 producerXml.setAttribute("mlt_type", type);
706 producerXml.setAttribute("resource", resource);
707 producerXml.setAttribute("duration", length);
708 if (service == "colour") producerXml.setAttribute("type", COLOR);
709 else if (service == "qimage" || service == "pixbuf") producerXml.setAttribute("type", IMAGE);
710 else if (service == "kdenlivetitle") producerXml.setAttribute("type", TEXT);
711 else producerXml.setAttribute("type", AV);
712 clip = new DocClipBase(m_doc->clipManager(), doc.documentElement(), id);
713 m_doc->clipManager()->addClip(clip);
714 m_documentErrors.append(i18n("Broken clip producer %1, recreated base clip: %2", id, resource) + '\n');
720 // Cannot recover, replace with blank
721 int duration = elem.attribute("out").toInt() - elem.attribute("in").toInt();
722 elem.setAttribute("length", duration);
723 elem.setTagName("blank");
724 m_documentErrors.append(i18n("Broken clip producer %1, removed from project", id) + '\n');
727 m_doc->setModified(true);
732 clipinfo.startPos = GenTime(position, m_doc->fps());
733 clipinfo.endPos = clipinfo.startPos + GenTime(out - in + 1, m_doc->fps());
734 clipinfo.cropStart = GenTime(in, m_doc->fps());
735 clipinfo.cropDuration = clipinfo.endPos - clipinfo.startPos;
738 //kDebug() << "// INSERTING CLIP: " << in << "x" << out << ", track: " << ix << ", ID: " << id << ", SCALE: " << m_scale << ", FPS: " << m_doc->fps();
739 ClipItem *item = new ClipItem(clip, clipinfo, m_doc->fps(), speed, strobe, frame_width, false);
740 if (idString.endsWith("_video")) item->setVideoOnly(true);
741 else if (idString.endsWith("_audio")) item->setAudioOnly(true);
742 m_scene->addItem(item);
743 if (locked) item->setItemLocked(true);
744 clip->addReference();
745 position += (out - in + 1);
746 if (speed != 1.0 || strobe > 1) {
747 QDomElement speedeffect = MainWindow::videoEffects.getEffectByTag(QString(), "speed").cloneNode().toElement();
748 EffectsList::setParameter(speedeffect, "speed", QString::number((int)(100 * speed + 0.5)));
749 EffectsList::setParameter(speedeffect, "strobe", QString::number(strobe));
750 item->addEffect(speedeffect, false);
751 item->effectsCounter();
754 // parse clip effects
755 QDomNodeList effects = elem.elementsByTagName("filter");
756 slotAddProjectEffects(effects, elem, item, -1);
760 kDebug() << "************* ADD DOC TRACK " << ix << ", DURATION: " << position;
764 void TrackView::slotAddProjectEffects(QDomNodeList effects, QDomElement parentNode, ClipItem *clip, int trackIndex)
768 for (int ix = 0; ix < effects.count(); ix++) {
769 bool disableeffect = false;
770 QDomElement effect = effects.at(ix).toElement();
771 if (effect.tagName() != "filter") continue;
773 // add effect to clip
777 QString effectindex = QString::number(effectNb);
778 // Get effect tag & index
779 for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
780 // parse effect parameters
781 QDomElement effectparam = n3.toElement();
782 if (effectparam.attribute("name") == "tag") {
783 effecttag = effectparam.text();
784 } else if (effectparam.attribute("name") == "kdenlive_id") {
785 effectid = effectparam.text();
786 } else if (effectparam.attribute("name") == "kdenlive_info") {
787 effectinfo = effectparam.text();
788 } else if (effectparam.attribute("name") == "disable" && effectparam.text().toInt() == 1) {
790 disableeffect = true;
791 } else if (effectparam.attribute("name") == "kdenlive_ix") {
793 effectparam.firstChild().setNodeValue(effectindex);
796 //kDebug() << "+ + CLIP EFF FND: " << effecttag << ", " << effectid << ", " << effectindex;
797 // get effect standard tags
798 QDomElement clipeffect = getEffectByTag(effecttag, effectid);
799 if (clipeffect.isNull()) {
800 kDebug() << "/// WARNING, EFFECT: " << effecttag << ": " << effectid << " not found, removing it from project";
801 m_documentErrors.append(i18n("Effect %1:%2 not found in MLT, it was removed from this project\n", effecttag, effectid));
802 if (parentNode.removeChild(effects.at(ix)).isNull()) kDebug() << "/// PROBLEM REMOVING EFFECT: " << effecttag;
805 QDomElement currenteffect = clipeffect.cloneNode().toElement();
806 currenteffect.setAttribute("kdenlive_ix", effectindex);
807 currenteffect.setAttribute("kdenlive_info", effectinfo);
808 QDomNodeList clipeffectparams = currenteffect.childNodes();
810 if (MainWindow::videoEffects.hasKeyFrames(currenteffect)) {
811 //kDebug() << " * * * * * * * * * * ** CLIP EFF WITH KFR FND * * * * * * * * * * *";
812 // effect is key-framable, read all effects to retrieve keyframes
817 QDomNodeList params = currenteffect.elementsByTagName("parameter");
818 for (int i = 0; i < params.count(); i++) {
819 QDomElement e = params.item(i).toElement();
820 if (e.attribute("type") == "keyframe") {
821 starttag = e.attribute("starttag", "start");
822 endtag = e.attribute("endtag", "end");
823 factor = e.attribute("factor", "1");
824 offset = e.attribute("offset", "0").toDouble();
829 int effectin = effect.attribute("in").toInt();
830 int effectout = effect.attribute("out").toInt();
831 double startvalue = 0;
834 if (factor.contains('%')) {
835 fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
837 fact = factor.toDouble();
839 for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
840 // parse effect parameters
841 QDomElement effectparam = n3.toElement();
842 if (effectparam.attribute("name") == starttag)
843 startvalue = offset + effectparam.text().toDouble() * fact;
844 if (effectparam.attribute("name") == endtag)
845 endvalue = offset + effectparam.text().toDouble() * fact;
847 // add first keyframe
848 if (effectout <= effectin) {
849 // there is only one keyframe
850 keyframes.append(QString::number(effectin) + ':' + locale.toString(startvalue) + ';');
851 } else keyframes.append(QString::number(effectin) + ':' + locale.toString(startvalue) + ';' + QString::number(effectout) + ':' + QString::number(endvalue) + ';');
852 QDomNode lastParsedEffect;
854 QDomNode n2 = effects.at(ix);
855 bool continueParsing = true;
856 for (; !n2.isNull() && continueParsing; n2 = n2.nextSibling()) {
858 QDomElement kfreffect = n2.toElement();
859 int effectout = kfreffect.attribute("out").toInt();
861 for (QDomNode n4 = kfreffect.firstChild(); !n4.isNull(); n4 = n4.nextSibling()) {
862 // parse effect parameters
863 QDomElement subeffectparam = n4.toElement();
864 if (subeffectparam.attribute("name") == "kdenlive_ix" && subeffectparam.text() != effectindex) {
865 //We are not in the same effect, stop parsing
866 lastParsedEffect = n2.previousSibling();
868 continueParsing = false;
870 } else if (subeffectparam.attribute("name") == endtag) {
871 endvalue = offset + subeffectparam.text().toDouble() * fact;
875 if (continueParsing) {
876 keyframes.append(QString::number(effectout) + ':' + locale.toString(endvalue) + ';');
881 params = currenteffect.elementsByTagName("parameter");
882 for (int i = 0; i < params.count(); i++) {
883 QDomElement e = params.item(i).toElement();
884 if (e.attribute("type") == "keyframe") e.setAttribute("keyframes", keyframes);
886 if (!continueParsing) {
887 n2 = lastParsedEffect;
890 // Check if effect has in/out points
891 if (effect.hasAttribute("in")) {
892 EffectsList::setParameter(currenteffect, "in", effect.attribute("in"));
893 currenteffect.setAttribute("in", effect.attribute("in"));
894 currenteffect.setAttribute("_sync_in_out", "1");
896 if (effect.hasAttribute("out")) {
897 EffectsList::setParameter(currenteffect, "out", effect.attribute("out"));
898 currenteffect.setAttribute("out", effect.attribute("out"));
902 // Special case, region filter embeds other effects
903 bool regionFilter = effecttag == "region";
904 QMap <QString, QString> regionEffects;
906 // adjust effect parameters
907 for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
908 // parse effect parameters
909 QDomElement effectparam = n3.toElement();
910 QString paramname = effectparam.attribute("name");
911 QString paramvalue = effectparam.text();
913 if (regionFilter && paramname.startsWith("filter")) {
914 regionEffects.insert(paramname, paramvalue);
918 // try to find this parameter in the effect xml and set its value
919 adjustparameterValue(clipeffectparams, paramname, paramvalue);
923 if (regionFilter && !regionEffects.isEmpty()) {
924 // insert region sub-effects
926 while (regionEffects.contains(QString("filter%1").arg(i))) {
927 QString filterid = regionEffects.value(QString("filter%1.kdenlive_id").arg(i));
928 QString filtertag = regionEffects.value(QString("filter%1.tag").arg(i));
929 QDomElement subclipeffect = getEffectByTag(filtertag, filterid).cloneNode().toElement();
930 QDomNodeList subclipeffectparams = subclipeffect.childNodes();
931 subclipeffect.setAttribute("region_ix", i);
932 QMap<QString, QString>::const_iterator j = regionEffects.constBegin();
933 while (j != regionEffects.constEnd()) {
934 if (j.key().startsWith(QString("filter%1.").arg(i))) {
935 QString pname = j.key().section('.', 1, -1);
936 adjustparameterValue(subclipeffectparams, pname, j.value());
940 currenteffect.appendChild(currenteffect.ownerDocument().importNode(subclipeffect, true));
945 if (disableeffect) currenteffect.setAttribute("disable", "1");
947 clip->addEffect(currenteffect, false);
949 m_doc->addTrackEffect(trackIndex, currenteffect);
955 void TrackView::adjustparameterValue(QDomNodeList clipeffectparams, const QString ¶mname, const QString ¶mvalue)
959 for (int k = 0; k < clipeffectparams.count(); k++) {
960 e = clipeffectparams.item(k).toElement();
961 if (!e.isNull() && e.tagName() == "parameter" && e.attribute("name") == paramname) {
962 QString type = e.attribute("type");
963 QString factor = e.attribute("factor", "1");
965 if (factor.contains('%')) {
966 fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
968 fact = factor.toDouble();
970 double offset = e.attribute("offset", "0").toDouble();
971 if (type == "simplekeyframe") {
972 QStringList kfrs = paramvalue.split(";");
973 for (int l = 0; l < kfrs.count(); l++) {
974 QString fr = kfrs.at(l).section('=', 0, 0);
975 double val = locale.toDouble(kfrs.at(l).section('=', 1, 1));
976 //kfrs[l] = fr + ":" + locale.toString((int)(val * fact));
977 kfrs[l] = fr + ':' + QString::number((int) (offset + val * fact));
979 e.setAttribute("keyframes", kfrs.join(";"));
980 } else if (type == "double" || type == "constant") {
982 e.setAttribute("value", offset + locale.toDouble(paramvalue, &ok) * fact);
984 e.setAttribute("value", paramvalue);
986 e.setAttribute("value", paramvalue);
994 QDomElement TrackView::getEffectByTag(const QString &effecttag, const QString &effectid)
996 QDomElement clipeffect = MainWindow::customEffects.getEffectByTag(QString(), effectid);
997 if (clipeffect.isNull()) {
998 clipeffect = MainWindow::videoEffects.getEffectByTag(effecttag, effectid);
1000 if (clipeffect.isNull()) {
1001 clipeffect = MainWindow::audioEffects.getEffectByTag(effecttag, effectid);
1007 DocClipBase *TrackView::getMissingProducer(const QString id) const
1009 QDomElement missingXml;
1010 QDomDocument doc = m_doc->toXml();
1011 QString docRoot = doc.documentElement().attribute("root");
1012 if (!docRoot.endsWith('/')) docRoot.append('/');
1013 QDomNodeList prods = doc.elementsByTagName("producer");
1014 int maxprod = prods.count();
1015 bool slowmotionClip = false;
1016 for (int i = 0; i < maxprod; i++) {
1017 QDomNode m = prods.at(i);
1018 QString prodId = m.toElement().attribute("id");
1019 if (prodId.startsWith("slowmotion")) {
1020 slowmotionClip = true;
1021 prodId = prodId.section(':', 1, 1);
1023 prodId = prodId.section('_', 0, 0);
1025 missingXml = m.toElement();
1029 if (missingXml == QDomElement()) {
1030 // Check if producer id was replaced in another track
1031 if (m_replacementProducerIds.contains(id)) {
1032 QString newId = m_replacementProducerIds.value(id);
1033 slowmotionClip = false;
1034 for (int i = 0; i < maxprod; i++) {
1035 QDomNode m = prods.at(i);
1036 QString prodId = m.toElement().attribute("id");
1037 if (prodId.startsWith("slowmotion")) {
1038 slowmotionClip = true;
1039 prodId = prodId.section(':', 1, 1);
1041 prodId = prodId.section('_', 0, 0);
1043 missingXml = m.toElement();
1049 if (missingXml == QDomElement()) return NULL;
1050 QString resource = EffectsList::property(missingXml, "resource");
1051 QString service = EffectsList::property(missingXml, "mlt_service");
1053 if (slowmotionClip) resource = resource.section('?', 0, 0);
1054 // prepend MLT XML document root if no path in clip resource and not a color clip
1055 if (!resource.startsWith('/') && service != "colour") {
1056 resource.prepend(docRoot);
1057 kDebug()<<"******************\nADJUSTED 2\n*************************";
1059 DocClipBase *missingClip = NULL;
1060 if (!resource.isEmpty()) {
1061 QList <DocClipBase *> list = m_doc->clipManager()->getClipByResource(resource);
1062 if (!list.isEmpty()) missingClip = list.at(0);
1067 QGraphicsScene *TrackView::projectScene()
1072 CustomTrackView *TrackView::projectView()
1077 void TrackView::setEditMode(const QString & editMode)
1079 m_editMode = editMode;
1082 const QString & TrackView::editMode() const
1087 void TrackView::slotChangeTrackLock(int ix, bool lock)
1089 QList<HeaderTrack *> widgets = findChildren<HeaderTrack *>();
1090 widgets.at(ix)->setLock(lock);
1094 void TrackView::slotVerticalZoomDown()
1096 if (m_verticalZoom == 0) return;
1098 m_doc->setZoom(m_doc->zoom().x(), m_verticalZoom);
1099 if (m_verticalZoom == 0)
1100 m_trackview->setScale(m_scene->scale().x(), 0.5);
1102 m_trackview->setScale(m_scene->scale().x(), 1);
1103 adjustTrackHeaders();
1104 m_trackview->verticalScrollBar()->setValue(headers_area->verticalScrollBar()->value());
1107 void TrackView::slotVerticalZoomUp()
1109 if (m_verticalZoom == 2) return;
1111 m_doc->setZoom(m_doc->zoom().x(), m_verticalZoom);
1112 if (m_verticalZoom == 2)
1113 m_trackview->setScale(m_scene->scale().x(), 2);
1115 m_trackview->setScale(m_scene->scale().x(), 1);
1116 adjustTrackHeaders();
1117 m_trackview->verticalScrollBar()->setValue(headers_area->verticalScrollBar()->value());
1120 void TrackView::updateProjectFps()
1122 m_ruler->updateProjectFps(m_doc->timecode());
1123 m_trackview->updateProjectFps();
1126 void TrackView::slotRenameTrack(int ix, QString name)
1128 int tracknumber = m_doc->tracksCount() - ix;
1129 QList <TrackInfo> tracks = m_doc->tracksList();
1130 tracks[tracknumber - 1].trackName = name;
1131 ConfigTracksCommand *configTracks = new ConfigTracksCommand(m_trackview, m_doc->tracksList(), tracks);
1132 m_doc->commandStack()->push(configTracks);
1133 m_doc->setModified(true);
1136 void TrackView::slotUpdateVerticalScroll(int /*min*/, int max)
1139 if (max > 0) height = m_trackview->horizontalScrollBar()->height() - 1;
1140 headers_container->layout()->setContentsMargins(0, m_trackview->frameWidth(), 0, height);
1143 void TrackView::updateRuler()
1148 void TrackView::slotShowTrackEffects(int ix)
1150 m_trackview->clearSelection();
1151 emit showTrackEffects(m_doc->tracksCount() - ix, m_doc->trackInfoAt(m_doc->tracksCount() - ix - 1));
1154 void TrackView::slotUpdateTrackEffectState(int ix)
1156 QList<HeaderTrack *> widgets = findChildren<HeaderTrack *>();
1157 if (ix < 0 || ix >= widgets.count()) {
1158 kDebug() << "ERROR, Trying to access a non existant track: " << ix;
1161 widgets.at(m_doc->tracksCount() - ix - 1)->updateEffectLabel(m_doc->trackInfoAt(ix).effectsList.effectNames());
1164 void TrackView::slotSaveTimelinePreview(const QString path)
1166 QImage img(width(), height(), QImage::Format_ARGB32_Premultiplied);
1167 img.fill(palette().base().color().rgb());
1168 QPainter painter(&img);
1171 img = img.scaledToWidth(600, Qt::SmoothTransformation);
1175 void TrackView::updateProfile()
1177 m_ruler->updateFrameSize();
1178 m_trackview->updateSceneFrameWidth();
1179 slotChangeZoom(m_doc->zoom().x(), m_doc->zoom().y());
1180 slotSetZone(m_doc->zone(), false);
1183 void TrackView::checkTrackHeight()
1185 if (m_trackview->checkTrackHeight()) {
1186 m_doc->clipManager()->clearCache();
1187 m_ruler->updateFrameSize();
1188 m_trackview->updateSceneFrameWidth();
1189 slotChangeZoom(m_doc->zoom().x(), m_doc->zoom().y());
1190 slotSetZone(m_doc->zone(), false);
1194 #include "trackview.moc"