]> git.sesse.net Git - kdenlive/blob - src/trackview.cpp
Fix crash and corruption caused by bad index in effects
[kdenlive] / src / trackview.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *                                                                         *
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.                                   *
8  *                                                                         *
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.                          *
13  *                                                                         *
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  ***************************************************************************/
19
20
21 #include "trackview.h"
22 #include "definitions.h"
23 #include "headertrack.h"
24 #include "clipitem.h"
25 #include "transition.h"
26 #include "kdenlivesettings.h"
27 #include "clipmanager.h"
28 #include "customruler.h"
29 #include "kdenlivedoc.h"
30 #include "mainwindow.h"
31 #include "customtrackview.h"
32 #include "initeffects.h"
33 #include "profilesdialog.h"
34
35 #include <KDebug>
36 #include <KMessageBox>
37 #include <KIO/NetAccess>
38
39 #include <QScrollBar>
40 #include <QInputDialog>
41
42 TrackView::TrackView(KdenliveDoc *doc, bool *ok, QWidget *parent) :
43         QWidget(parent),
44         m_scale(1.0),
45         m_projectTracks(0),
46         m_doc(doc),
47         m_verticalZoom(1)
48 {
49
50     setupUi(this);
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);
57     //m_scene->addRect(QRectF(0, 0, 100, 100), QPen(), QBrush(Qt::red));
58
59     m_ruler = new CustomRuler(doc->timecode(), m_trackview);
60     connect(m_ruler, SIGNAL(zoneMoved(int, int)), this, SIGNAL(zoneMoved(int, int)));
61     connect(m_ruler, SIGNAL(adjustZoom(int)), this, SIGNAL(setZoom(int)));
62     QHBoxLayout *layout = new QHBoxLayout;
63     layout->setContentsMargins(m_trackview->frameWidth(), 0, 0, 0);
64     layout->setSpacing(0);
65     ruler_frame->setLayout(layout);
66     layout->addWidget(m_ruler);
67
68     QHBoxLayout *sizeLayout = new QHBoxLayout;
69     sizeLayout->setContentsMargins(0, 0, 0, 0);
70     sizeLayout->setSpacing(0);
71     size_frame->setLayout(sizeLayout);
72
73     QToolButton *butSmall = new QToolButton(this);
74     butSmall->setIcon(KIcon("kdenlive-zoom-small"));
75     butSmall->setToolTip(i18n("Smaller tracks"));
76     butSmall->setAutoRaise(true);
77     connect(butSmall, SIGNAL(clicked()), this, SLOT(slotVerticalZoomDown()));
78     sizeLayout->addWidget(butSmall);
79
80     QToolButton *butLarge = new QToolButton(this);
81     butLarge->setIcon(KIcon("kdenlive-zoom-large"));
82     butLarge->setToolTip(i18n("Bigger tracks"));
83     butLarge->setAutoRaise(true);
84     connect(butLarge, SIGNAL(clicked()), this, SLOT(slotVerticalZoomUp()));
85     sizeLayout->addWidget(butLarge);
86
87     QHBoxLayout *tracksLayout = new QHBoxLayout;
88     tracksLayout->setContentsMargins(0, 0, 0, 0);
89     tracksLayout->setSpacing(0);
90     tracks_frame->setLayout(tracksLayout);
91
92     headers_area->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
93     headers_area->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
94     headers_area->setFixedWidth(70);
95
96     QVBoxLayout *headersLayout = new QVBoxLayout;
97     headersLayout->setContentsMargins(0, m_trackview->frameWidth(), 0, 0);
98     headersLayout->setSpacing(0);
99     headers_container->setLayout(headersLayout);
100     connect(headers_area->verticalScrollBar(), SIGNAL(valueChanged(int)), m_trackview->verticalScrollBar(), SLOT(setValue(int)));
101
102     tracksLayout->addWidget(m_trackview);
103     connect(m_trackview->verticalScrollBar(), SIGNAL(valueChanged(int)), headers_area->verticalScrollBar(), SLOT(setValue(int)));
104     connect(m_trackview, SIGNAL(trackHeightChanged()), this, SLOT(slotRebuildTrackHeaders()));
105     connect(m_trackview, SIGNAL(tracksChanged()), this, SLOT(slotReloadTracks()));
106     connect(m_trackview, SIGNAL(updateTrackHeaders()), this, SLOT(slotRepaintTracks()));
107
108     parseDocument(m_doc->toXml());
109     if (m_doc->setSceneList() == -1) *ok = false;
110     else *ok = true;
111     connect(m_trackview, SIGNAL(cursorMoved(int, int)), m_ruler, SLOT(slotCursorMoved(int, int)));
112     connect(m_trackview->horizontalScrollBar(), SIGNAL(valueChanged(int)), m_ruler, SLOT(slotMoveRuler(int)));
113     connect(m_trackview, SIGNAL(mousePosition(int)), this, SIGNAL(mousePosition(int)));
114     connect(m_trackview, SIGNAL(doTrackLock(int, bool)), this, SLOT(slotChangeTrackLock(int, bool)));
115
116     slotChangeZoom(m_doc->zoom().x(), m_doc->zoom().y());
117     slotSetZone(m_doc->zone());
118 }
119
120 TrackView::~TrackView()
121 {
122     delete m_ruler;
123     delete m_trackview;
124 }
125
126 //virtual
127 void TrackView::keyPressEvent(QKeyEvent * event)
128 {
129     if (event->key() == Qt::Key_Up) {
130         m_trackview->slotTrackUp();
131         event->accept();
132     } else if (event->key() == Qt::Key_Down) {
133         m_trackview->slotTrackDown();
134         event->accept();
135     } else QWidget::keyPressEvent(event);
136 }
137
138 int TrackView::duration() const
139 {
140     return m_trackview->duration();
141 }
142
143 int TrackView::tracksNumber() const
144 {
145     return m_projectTracks - 1;
146 }
147
148 int TrackView::inPoint() const
149 {
150     return m_ruler->inPoint();
151 }
152
153 int TrackView::outPoint() const
154 {
155     return m_ruler->outPoint();
156 }
157
158 void TrackView::slotSetZone(QPoint p)
159 {
160     m_ruler->setZone(p);
161 }
162
163 void TrackView::setDuration(int dur)
164 {
165     m_trackview->setDuration(dur);
166     m_ruler->setDuration(dur);
167 }
168
169 void TrackView::parseDocument(QDomDocument doc)
170 {
171     //int cursorPos = 0;
172     m_documentErrors.clear();
173
174     //kDebug() << "//// DOCUMENT: " << doc.toString();
175     /*QDomNode props = doc.elementsByTagName("properties").item(0);
176     if (!props.isNull()) {
177         cursorPos = props.toElement().attribute("timeline_position").toInt();
178     }*/
179
180     // parse project tracks
181     QDomElement tractor = doc.elementsByTagName("tractor").item(0).toElement();
182     QDomNodeList tracks = doc.elementsByTagName("track");
183     QDomNodeList playlists = doc.elementsByTagName("playlist");
184     int duration = 300;
185     m_projectTracks = tracks.count();
186     int trackduration = 0;
187     QDomElement e;
188     QDomElement p;
189
190     int pos = m_projectTracks - 1;
191     m_invalidProducers.clear();
192     QDomNodeList producers = doc.elementsByTagName("producer");
193     for (int i = 0; i < producers.count(); i++) {
194         // Check for invalid producers
195         QDomNode n = producers.item(i);
196         e = n.toElement();
197
198         /*
199         // Check for invalid markup
200         QDomNodeList params = e.elementsByTagName("property");
201         for (int j = 0; j < params.count(); j++) {
202             QDomElement p = params.item(j).toElement();
203             if (p.attribute("name") == "markup") {
204          QString val = p.text().toUtf8().data();
205          kDebug()<<"//FOUND MARKUP, VAL: "<<val;
206          //e.setAttribute("value", value);
207          n.removeChild(params.item(j));
208          break;
209             }
210         }
211         */
212
213         if (e.hasAttribute("in") == false && e.hasAttribute("out") == false) continue;
214         int in = e.attribute("in").toInt();
215         int out = e.attribute("out").toInt();
216         if (in > out || in == out) {
217             // invalid producer, remove it
218             QString id = e.attribute("id");
219             m_invalidProducers.append(id);
220             m_documentErrors.append(i18n("Invalid clip producer %1\n", id));
221             doc.documentElement().removeChild(producers.at(i));
222             i--;
223         }
224     }
225
226     for (int i = 0; i < m_projectTracks; i++) {
227         e = tracks.item(i).toElement();
228         QString playlist_name = e.attribute("producer");
229         if (playlist_name != "black_track" && playlist_name != "playlistmain") {
230             // find playlist related to this track
231             p = QDomElement();
232             for (int j = 0; j < m_projectTracks; j++) {
233                 p = playlists.item(j).toElement();
234                 if (p.attribute("id") == playlist_name) break;
235             }
236             if (p.attribute("id") != playlist_name) { // then it didn't work.
237                 kDebug() << "NO PLAYLIST FOUND FOR TRACK " + pos;
238             }
239             if (e.attribute("hide") == "video") {
240                 m_doc->switchTrackVideo(i - 1, true);
241             } else if (e.attribute("hide") == "audio") {
242                 m_doc->switchTrackAudio(i - 1, true);
243             } else if (e.attribute("hide") == "both") {
244                 m_doc->switchTrackVideo(i - 1, true);
245                 m_doc->switchTrackAudio(i - 1, true);
246             }
247
248             trackduration = slotAddProjectTrack(pos, p, m_doc->isTrackLocked(i - 1));
249             pos--;
250             //kDebug() << " PRO DUR: " << trackduration << ", TRACK DUR: " << duration;
251             if (trackduration > duration) duration = trackduration;
252         } else {
253             // background black track
254             for (int j = 0; j < m_projectTracks; j++) {
255                 p = playlists.item(j).toElement();
256                 if (p.attribute("id") == playlist_name) break;
257             }
258             pos--;
259         }
260     }
261
262     // parse transitions
263     QDomNodeList transitions = doc.elementsByTagName("transition");
264
265     //kDebug() << "//////////// TIMELINE FOUND: " << projectTransitions << " transitions";
266     for (int i = 0; i < transitions.count(); i++) {
267         e = transitions.item(i).toElement();
268         QDomNodeList transitionparams = e.childNodes();
269         bool transitionAdd = true;
270         int a_track = 0;
271         int b_track = 0;
272         bool isAutomatic = false;
273         bool forceTrack = false;
274         QString mlt_geometry;
275         QString mlt_service;
276         QString transitionId;
277         for (int k = 0; k < transitionparams.count(); k++) {
278             p = transitionparams.item(k).toElement();
279             if (!p.isNull()) {
280                 QString paramName = p.attribute("name");
281                 // do not add audio mixing transitions
282                 if (paramName == "internal_added" && p.text() == "237") {
283                     transitionAdd = false;
284                     //kDebug() << "//  TRANSITRION " << i << " IS NOT VALID (INTERN ADDED)";
285                     //break;
286                 } else if (paramName == "a_track") {
287                     a_track = qMax(0, p.text().toInt());
288                     a_track = qMin(m_projectTracks - 1, a_track);
289                     if (a_track != p.text().toInt()) {
290                         // the transition track was out of bounds
291                         m_documentErrors.append(i18n("Transition %1 had an invalid track: %2 > %3", e.attribute("id"), p.text().toInt(), a_track) + '\n');
292                         EffectsList::setProperty(e, "a_track", QString::number(a_track));
293                     }
294                 } else if (paramName == "b_track") {
295                     b_track = qMax(0, p.text().toInt());
296                     b_track = qMin(m_projectTracks - 1, b_track);
297                     if (b_track != p.text().toInt()) {
298                         // the transition track was out of bounds
299                         m_documentErrors.append(i18n("Transition %1 had an invalid track: %2 > %3", e.attribute("id"), p.text().toInt(), b_track) + '\n');
300                         EffectsList::setProperty(e, "b_track", QString::number(b_track));
301                     }
302                 } else if (paramName == "mlt_service") mlt_service = p.text();
303                 else if (paramName == "kdenlive_id") transitionId = p.text();
304                 else if (paramName == "geometry") mlt_geometry = p.text();
305                 else if (paramName == "automatic" && p.text() == "1") isAutomatic = true;
306                 else if (paramName == "force_track" && p.text() == "1") forceTrack = true;
307             }
308         }
309         if (a_track == b_track || b_track == 0) {
310             // invalid transition, remove it
311             m_documentErrors.append(i18n("Removed invalid transition: %1", e.attribute("id")) + '\n');
312             tractor.removeChild(transitions.item(i));
313             i--;
314             continue;
315         }
316         if (transitionAdd || mlt_service != "mix") {
317             // Transition should be added to the scene
318             ItemInfo transitionInfo;
319             if (mlt_service == "composite" && transitionId.isEmpty()) {
320                 // When adding composite transition, check if it is a wipe transition
321                 if (mlt_geometry.count(';') == 1) {
322                     mlt_geometry.remove(QChar('%'), Qt::CaseInsensitive);
323                     mlt_geometry.replace(QChar('x'), QChar(','), Qt::CaseInsensitive);
324                     QString start = mlt_geometry.section(';', 0, 0);
325                     start = start.section(':', 0, 1);
326                     start.replace(QChar(':'), QChar(','), Qt::CaseInsensitive);
327                     QString end = mlt_geometry.section('=', 1, 1);
328                     end = end.section(':', 0, 1);
329                     end.replace(QChar(':'), QChar(','), Qt::CaseInsensitive);
330                     start.append(',' + end);
331                     QStringList numbers = start.split(',', QString::SkipEmptyParts);
332                     bool isWipeTransition = true;
333                     int checkNumber;
334                     for (int i = 0; i < numbers.size(); ++i) {
335                         checkNumber = qAbs(numbers.at(i).toInt());
336                         if (checkNumber != 0 && checkNumber != 100) {
337                             isWipeTransition = false;
338                             break;
339                         }
340                     }
341                     if (isWipeTransition) transitionId = "slide";
342                 }
343             }
344             QDomElement base = MainWindow::transitions.getEffectByTag(mlt_service, transitionId).cloneNode().toElement();
345
346             for (int k = 0; k < transitionparams.count(); k++) {
347                 p = transitionparams.item(k).toElement();
348                 if (!p.isNull()) {
349                     QString paramName = p.attribute("name");
350                     QString paramValue = p.text();
351
352                     QDomNodeList params = base.elementsByTagName("parameter");
353                     if (paramName != "a_track" && paramName != "b_track") for (int i = 0; i < params.count(); i++) {
354                             QDomElement e = params.item(i).toElement();
355                             if (!e.isNull() && e.attribute("tag") == paramName) {
356                                 if (e.attribute("type") == "double") {
357                                     QString factor = e.attribute("factor", "1");
358                                     if (factor != "1") {
359                                         double fact;
360                                         if (factor.startsWith('%')) {
361                                             fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
362                                         } else fact = factor.toDouble();
363                                         double val = paramValue.toDouble() * fact;
364                                         paramValue = QString::number(val);
365                                     }
366                                 }
367                                 e.setAttribute("value", paramValue);
368                                 break;
369                             }
370                         }
371                 }
372             }
373
374             /*QDomDocument doc;
375             doc.appendChild(doc.importNode(base, true));
376             kDebug() << "///////  TRANSITION XML: "<< doc.toString();*/
377
378             transitionInfo.startPos = GenTime(e.attribute("in").toInt(), m_doc->fps());
379             transitionInfo.endPos = GenTime(e.attribute("out").toInt() + 1, m_doc->fps());
380             transitionInfo.track = m_projectTracks - 1 - b_track;
381
382             //kDebug() << "///////////////   +++++++++++  ADDING TRANSITION ON TRACK: " << b_track << ", TOTAL TRKA: " << m_projectTracks;
383             if (transitionInfo.startPos >= transitionInfo.endPos) {
384                 // invalid transition, remove it.
385                 m_documentErrors.append(i18n("Removed invalid transition: %1", e.attribute("id")) + '\n');
386                 kDebug() << "///// REMOVED INVALID TRANSITION: " << e.attribute("id");
387                 tractor.removeChild(transitions.item(i));
388                 i--;
389             } else {
390                 Transition *tr = new Transition(transitionInfo, a_track, m_doc->fps(), base, isAutomatic);
391                 if (forceTrack) tr->setForcedTrack(true, a_track);
392                 m_scene->addItem(tr);
393                 if (b_track > 0 && m_doc->isTrackLocked(b_track - 1)) {
394                     tr->setItemLocked(true);
395                 }
396             }
397         }
398     }
399
400     // Add guides
401     QDomNodeList guides = doc.elementsByTagName("guide");
402     for (int i = 0; i < guides.count(); i++) {
403         e = guides.item(i).toElement();
404         const QString comment = e.attribute("comment");
405         const GenTime pos = GenTime(e.attribute("time").toDouble());
406         m_trackview->addGuide(pos, comment);
407     }
408
409     // Rebuild groups
410     QDomNodeList groups = doc.elementsByTagName("group");
411     m_trackview->loadGroups(groups);
412     m_trackview->setDuration(duration);
413     kDebug() << "///////////  TOTAL PROJECT DURATION: " << duration;
414
415     // Remove Kdenlive extra info from xml doc before sending it to MLT
416     QDomElement mlt = doc.firstChildElement("mlt");
417     QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
418     mlt.removeChild(infoXml);
419
420     slotRebuildTrackHeaders();
421     if (!m_documentErrors.isNull()) KMessageBox::sorry(this, m_documentErrors);
422     if (infoXml.hasAttribute("upgraded")) {
423         // Our document was upgraded, create a backup copy just in case
424         QString baseFile = m_doc->url().path().section(".kdenlive", 0, 0);
425         int ct = 0;
426         QString backupFile = baseFile + "_backup" + QString::number(ct) + ".kdenlive";
427         while (QFile::exists(backupFile)) {
428             ct++;
429             backupFile = baseFile + "_backup" + QString::number(ct) + ".kdenlive";
430         }
431         if (KIO::NetAccess::file_copy(m_doc->url(), KUrl(backupFile), this)) KMessageBox::information(this, i18n("Your project file was upgraded to the latest Kdenlive document version.\n To make sure you don't lose data, a backup copy called %1 was created.", backupFile));
432         else KMessageBox::information(this, i18n("Your project file was upgraded to the latest Kdenlive document version, it was not possible to create a backup copy.", backupFile));
433     }
434     //m_trackview->setCursorPos(cursorPos);
435     //m_scrollBox->setGeometry(0, 0, 300 * zoomFactor(), m_scrollArea->height());
436 }
437
438 void TrackView::slotDeleteClip(const QString &clipId)
439 {
440     m_trackview->deleteClip(clipId);
441 }
442
443 void TrackView::setCursorPos(int pos)
444 {
445     m_trackview->setCursorPos(pos);
446 }
447
448 void TrackView::moveCursorPos(int pos)
449 {
450     m_trackview->setCursorPos(pos, false);
451 }
452
453 void TrackView::slotChangeZoom(int horizontal, int vertical)
454 {
455     m_ruler->setPixelPerMark(horizontal);
456     m_scale = (double) FRAME_SIZE / m_ruler->comboScale[horizontal];
457
458     if (vertical == -1) {
459         // user called zoom
460         m_doc->setZoom(horizontal, m_verticalZoom);
461         m_trackview->setScale(m_scale, m_scene->scale().y());
462     } else {
463         m_verticalZoom = vertical;
464         if (m_verticalZoom == 0) m_trackview->setScale(m_scale, 0.5);
465         else m_trackview->setScale(m_scale, m_verticalZoom);
466         adjustTrackHeaders();
467     }
468 }
469
470 int TrackView::fitZoom() const
471 {
472     int zoom = (int)((duration() + 20 / m_scale) * FRAME_SIZE / m_trackview->width());
473     int i;
474     for (i = 0; i < 13; i++)
475         if (m_ruler->comboScale[i] > zoom) break;
476     return i;
477 }
478
479 KdenliveDoc *TrackView::document()
480 {
481     return m_doc;
482 }
483
484 void TrackView::refresh()
485 {
486     m_trackview->viewport()->update();
487 }
488
489 void TrackView::slotRepaintTracks()
490 {
491     QLayoutItem *child;
492     for (int i = 0; i < headers_container->layout()->count(); i++) {
493         child = headers_container->layout()->itemAt(i);
494         if (child->widget() && child->widget()->height() > 5) {
495             HeaderTrack *head = static_cast <HeaderTrack *>(child->widget());
496             if (head) head->setSelectedIndex(m_trackview->selectedTrack());
497         }
498     }
499 }
500
501 void TrackView::slotReloadTracks()
502 {
503     slotRebuildTrackHeaders();
504     emit updateTracksInfo();
505 }
506
507 void TrackView::slotRebuildTrackHeaders()
508 {
509     const QList <TrackInfo> list = m_doc->tracksList();
510     QLayoutItem *child;
511     while ((child = headers_container->layout()->takeAt(0)) != 0) {
512         QWidget *wid = child->widget();
513         delete child;
514         if (wid) wid->deleteLater();
515     }
516     int max = list.count();
517     int height = KdenliveSettings::trackheight() * m_scene->scale().y() - 1;
518     HeaderTrack *header = NULL;
519     QFrame *frame = NULL;
520     for (int i = 0; i < max; i++) {
521         frame = new QFrame(headers_container);
522         frame->setFixedHeight(1);
523         frame->setFrameStyle(QFrame::Plain);
524         frame->setFrameShape(QFrame::Box);
525         frame->setLineWidth(1);
526         headers_container->layout()->addWidget(frame);
527         TrackInfo info = list.at(max - i - 1);
528         header = new HeaderTrack(i, info, height, headers_container);
529         header->setSelectedIndex(m_trackview->selectedTrack());
530         connect(header, SIGNAL(switchTrackVideo(int)), m_trackview, SLOT(slotSwitchTrackVideo(int)));
531         connect(header, SIGNAL(switchTrackAudio(int)), m_trackview, SLOT(slotSwitchTrackAudio(int)));
532         connect(header, SIGNAL(switchTrackLock(int)), m_trackview, SLOT(slotSwitchTrackLock(int)));
533         connect(header, SIGNAL(selectTrack(int)), m_trackview, SLOT(slotSelectTrack(int)));
534         connect(header, SIGNAL(deleteTrack(int)), this, SIGNAL(deleteTrack(int)));
535         connect(header, SIGNAL(insertTrack(int)), this, SIGNAL(insertTrack(int)));
536         connect(header, SIGNAL(changeTrack(int)), this, SIGNAL(changeTrack(int)));
537         connect(header, SIGNAL(renameTrack(int)), this, SLOT(slotRenameTrack(int)));
538         headers_container->layout()->addWidget(header);
539     }
540     frame = new QFrame(this);
541     frame->setFixedHeight(1);
542     frame->setFrameStyle(QFrame::Plain);
543     frame->setFrameShape(QFrame::Box);
544     frame->setLineWidth(1);
545     headers_container->layout()->addWidget(frame);
546 }
547
548
549 void TrackView::adjustTrackHeaders()
550 {
551     int height = KdenliveSettings::trackheight() * m_scene->scale().y() - 1;
552     QLayoutItem *child;
553     for (int i = 0; i < headers_container->layout()->count(); i++) {
554         child = headers_container->layout()->itemAt(i);
555         if (child->widget() && child->widget()->height() > 5)(static_cast <HeaderTrack *>(child->widget()))->adjustSize(height);
556     }
557 }
558
559 int TrackView::slotAddProjectTrack(int ix, QDomElement xml, bool locked)
560 {
561     // parse track
562     int position = 0;
563     QDomNodeList children = xml.childNodes();
564     for (int nodeindex = 0; nodeindex < children.count(); nodeindex++) {
565         QDomNode n = children.item(nodeindex);
566         QDomElement elem = n.toElement();
567         if (elem.tagName() == "blank") {
568             position += elem.attribute("length").toInt();
569         } else if (elem.tagName() == "entry") {
570             // Found a clip
571             int in = elem.attribute("in").toInt();
572             int out = elem.attribute("out").toInt();
573             if (in > out || /*in == out ||*/ m_invalidProducers.contains(elem.attribute("producer"))) {
574                 m_documentErrors.append(i18n("Invalid clip removed from track %1 at %2\n", ix, position));
575                 xml.removeChild(children.at(nodeindex));
576                 nodeindex--;
577                 continue;
578             }
579             QString idString = elem.attribute("producer");
580             QString id = idString;
581             double speed = 1.0;
582             int strobe = 1;
583             if (idString.startsWith("slowmotion")) {
584                 id = idString.section(':', 1, 1);
585                 speed = idString.section(':', 2, 2).toDouble();
586                 strobe = idString.section(':', 3, 3).toInt();
587                 if (strobe == 0) strobe = 1;
588             } else id = id.section('_', 0, 0);
589             DocClipBase *clip = m_doc->clipManager()->getClipById(id);
590             if (clip == NULL) {
591                 // The clip in playlist was not listed in the kdenlive producers,
592                 // something went wrong, repair required.
593                 kWarning() << "CANNOT INSERT CLIP " << id;
594
595                 clip = getMissingProducer(id);
596                 if (!clip) {
597                     // We cannot find the producer, something is really wrong, add
598                     // placeholder color clip
599                     QDomDocument doc;
600                     QDomElement producerXml = doc.createElement("producer");
601                     doc.appendChild(producerXml);
602                     producerXml.setAttribute("colour", "0xff0000ff");
603                     producerXml.setAttribute("mlt_service", "colour");
604                     producerXml.setAttribute("length", "15000");
605                     producerXml.setAttribute("name", "INVALID");
606                     producerXml.setAttribute("type", COLOR);
607                     producerXml.setAttribute("id", id);
608                     clip = new DocClipBase(m_doc->clipManager(), doc.documentElement(), id);
609                     xml.insertBefore(producerXml, QDomNode());
610                     m_doc->clipManager()->addClip(clip);
611
612                     m_documentErrors.append(i18n("Broken clip producer %1", id) + '\n');
613                 } else {
614                     // Found correct producer
615                     m_documentErrors.append(i18n("Replaced wrong clip producer %1 with %2", id, clip->getId()) + '\n');
616                     elem.setAttribute("producer", clip->getId());
617                 }
618                 m_doc->setModified(true);
619             }
620
621             if (clip != NULL) {
622                 ItemInfo clipinfo;
623                 clipinfo.startPos = GenTime(position, m_doc->fps());
624                 clipinfo.endPos = clipinfo.startPos + GenTime(out - in + 1, m_doc->fps());
625                 clipinfo.cropStart = GenTime(in, m_doc->fps());
626                 clipinfo.cropDuration = clipinfo.endPos - clipinfo.startPos;
627
628                 clipinfo.track = ix;
629                 //kDebug() << "// INSERTING CLIP: " << in << "x" << out << ", track: " << ix << ", ID: " << id << ", SCALE: " << m_scale << ", FPS: " << m_doc->fps();
630                 ClipItem *item = new ClipItem(clip, clipinfo, m_doc->fps(), speed, strobe, false);
631                 if (idString.endsWith("_video")) item->setVideoOnly(true);
632                 else if (idString.endsWith("_audio")) item->setAudioOnly(true);
633                 m_scene->addItem(item);
634                 if (locked) item->setItemLocked(true);
635                 clip->addReference();
636                 position += (out - in + 1);
637                 if (speed != 1.0 || strobe > 1) {
638                     QDomElement speedeffect = MainWindow::videoEffects.getEffectByTag(QString(), "speed").cloneNode().toElement();
639                     EffectsList::setParameter(speedeffect, "speed", QString::number((int)(100 * speed + 0.5)));
640                     EffectsList::setParameter(speedeffect, "strobe", QString::number(strobe));
641                     item->addEffect(speedeffect, false);
642                     item->effectsCounter();
643                 }
644
645                 // parse clip effects
646                 QDomNodeList effects = elem.childNodes();
647                 for (int ix = 0; ix < effects.count(); ix++) {
648                     QDomElement effect = effects.at(ix).toElement();
649                     if (effect.tagName() == "filter") {
650                         // add effect to clip
651                         QString effecttag;
652                         QString effectid;
653                         QString effectindex = QString::number(ix + 1);
654                         QString ladspaEffectFile;
655                         // Get effect tag & index
656                         for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
657                             // parse effect parameters
658                             QDomElement effectparam = n3.toElement();
659                             if (effectparam.attribute("name") == "tag") {
660                                 effecttag = effectparam.text();
661                             } else if (effectparam.attribute("name") == "kdenlive_id") {
662                                 effectid = effectparam.text();
663                             } else if (effectparam.attribute("name") == "kdenlive_ix") {
664                                 // Fix effects index
665                                 effectparam.firstChild().setNodeValue(effectindex);
666                             } else if (effectparam.attribute("name") == "src") {
667                                 ladspaEffectFile = effectparam.text();
668                                 if (!QFile::exists(ladspaEffectFile)) {
669                                     // If the ladspa effect file is missing, recreate it
670                                     kDebug() << "// MISSING LADSPA FILE: " << ladspaEffectFile;
671                                     ladspaEffectFile = m_doc->getLadspaFile();
672                                     effectparam.firstChild().setNodeValue(ladspaEffectFile);
673                                     kDebug() << "// ... REPLACED WITH: " << ladspaEffectFile;
674                                 }
675                             }
676                         }
677                         //kDebug() << "+ + CLIP EFF FND: " << effecttag << ", " << effectid << ", " << effectindex;
678                         // get effect standard tags
679                         QDomElement clipeffect = MainWindow::customEffects.getEffectByTag(QString(), effectid);
680                         if (clipeffect.isNull()) clipeffect = MainWindow::videoEffects.getEffectByTag(effecttag, effectid);
681                         if (clipeffect.isNull()) clipeffect = MainWindow::audioEffects.getEffectByTag(effecttag, effectid);
682                         if (clipeffect.isNull()) {
683                             kDebug() << "///  WARNING, EFFECT: " << effecttag << ": " << effectid << " not found, removing it from project";
684                             m_documentErrors.append(i18n("Effect %1:%2 not found in MLT, it was removed from this project\n", effecttag, effectid));
685                             elem.removeChild(effects.at(ix));
686                             ix--;
687                         } else {
688                             QDomElement currenteffect = clipeffect.cloneNode().toElement();
689                             currenteffect.setAttribute("kdenlive_ix", effectindex);
690                             QDomNodeList clipeffectparams = currenteffect.childNodes();
691
692                             if (MainWindow::videoEffects.hasKeyFrames(currenteffect)) {
693                                 //kDebug() << " * * * * * * * * * * ** CLIP EFF WITH KFR FND  * * * * * * * * * * *";
694                                 // effect is key-framable, read all effects to retrieve keyframes
695                                 QString factor;
696                                 QString starttag;
697                                 QString endtag;
698                                 QDomNodeList params = currenteffect.elementsByTagName("parameter");
699                                 for (int i = 0; i < params.count(); i++) {
700                                     QDomElement e = params.item(i).toElement();
701                                     if (e.attribute("type") == "keyframe") {
702                                         starttag = e.attribute("starttag", "start");
703                                         endtag = e.attribute("endtag", "end");
704                                         factor = e.attribute("factor", "1");
705                                         break;
706                                     }
707                                 }
708                                 QString keyframes;
709                                 int effectin = effect.attribute("in").toInt();
710                                 int effectout = effect.attribute("out").toInt();
711                                 double startvalue = 0;
712                                 double endvalue = 0;
713                                 double fact;
714                                 if (factor.isEmpty()) fact = 1;
715                                 else if (factor.startsWith('%')) {
716                                     fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
717                                 } else fact = factor.toDouble();
718                                 for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
719                                     // parse effect parameters
720                                     QDomElement effectparam = n3.toElement();
721                                     if (effectparam.attribute("name") == starttag)
722                                         startvalue = effectparam.text().toDouble() * fact;
723                                     if (effectparam.attribute("name") == endtag)
724                                         endvalue = effectparam.text().toDouble() * fact;
725                                 }
726                                 // add first keyframe
727                                 keyframes.append(QString::number(effectin) + ':' + QString::number(startvalue) + ';' + QString::number(effectout) + ':' + QString::number(endvalue) + ';');
728                                 QDomNode lastParsedEffect;
729                                 ix++;
730                                 QDomNode n2 = effects.at(ix);
731                                 bool continueParsing = true;
732                                 for (; !n2.isNull() && continueParsing; n2 = n2.nextSibling()) {
733                                     // parse all effects
734                                     QDomElement kfreffect = n2.toElement();
735                                     int effectout = kfreffect.attribute("out").toInt();
736
737                                     for (QDomNode n4 = kfreffect.firstChild(); !n4.isNull(); n4 = n4.nextSibling()) {
738                                         // parse effect parameters
739                                         QDomElement subeffectparam = n4.toElement();
740                                         if (subeffectparam.attribute("name") == "kdenlive_ix" && subeffectparam.text() != effectindex) {
741                                             //We are not in the same effect, stop parsing
742                                             lastParsedEffect = n2.previousSibling();
743                                             ix--;
744                                             continueParsing = false;
745                                             break;
746                                         } else if (subeffectparam.attribute("name") == endtag) {
747                                             endvalue = subeffectparam.text().toDouble() * fact;
748                                             break;
749                                         }
750                                     }
751                                     if (continueParsing) {
752                                         keyframes.append(QString::number(effectout) + ':' + QString::number(endvalue) + ';');
753                                         ix++;
754                                     }
755                                 }
756
757                                 params = currenteffect.elementsByTagName("parameter");
758                                 for (int i = 0; i < params.count(); i++) {
759                                     QDomElement e = params.item(i).toElement();
760                                     if (e.attribute("type") == "keyframe") e.setAttribute("keyframes", keyframes);
761                                 }
762                                 if (!continueParsing) {
763                                     n2 = lastParsedEffect;
764                                 }
765                             } else {
766                                 // Check if effect has in/out points
767                                 if (effect.hasAttribute("in")) {
768                                     EffectsList::setParameter(currenteffect, "in",  effect.attribute("in"));
769                                 }
770                                 if (effect.hasAttribute("out")) {
771                                     EffectsList::setParameter(currenteffect, "out",  effect.attribute("out"));
772                                 }
773                             }
774
775                             // adjust effect parameters
776                             for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
777                                 // parse effect parameters
778                                 QDomElement effectparam = n3.toElement();
779                                 QString paramname = effectparam.attribute("name");
780                                 QString paramvalue = effectparam.text();
781
782
783                                 // try to find this parameter in the effect xml
784                                 QDomElement e;
785                                 for (int k = 0; k < clipeffectparams.count(); k++) {
786                                     e = clipeffectparams.item(k).toElement();
787                                     if (!e.isNull() && e.tagName() == "parameter" && e.attribute("name") == paramname) {
788                                         if (e.attribute("factor", "1") != "1") {
789                                             QString factor = e.attribute("factor", "1");
790                                             double fact;
791                                             if (factor.startsWith('%')) {
792                                                 fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
793                                             } else fact = factor.toDouble();
794                                             if (e.attribute("type") == "simplekeyframe") {
795                                                 QStringList kfrs = paramvalue.split(";");
796                                                 for (int l = 0; l < kfrs.count(); l++) {
797                                                     QString fr = kfrs.at(l).section("=", 0, 0);
798                                                     double val = kfrs.at(l).section("=", 1, 1).toDouble();
799                                                     kfrs[l] = fr + ":" + QString::number((int)(val * fact));
800                                                 }
801                                                 e.setAttribute("keyframes", kfrs.join(";"));
802                                             } else e.setAttribute("value", paramvalue.toDouble() * fact);
803                                         } else e.setAttribute("value", paramvalue);
804                                         break;
805                                     }
806                                 }
807                             }
808                             if (effecttag == "ladspa") {
809                                 //QString ladspaEffectFile = EffectsList::parameter(effect, "src", "property");
810
811                                 if (!QFile::exists(ladspaEffectFile)) {
812                                     // If the ladspa effect file is missing, recreate it
813                                     initEffects::ladspaEffectFile(ladspaEffectFile, currenteffect.attribute("ladspaid").toInt(), m_trackview->getLadspaParams(currenteffect));
814                                 }
815                                 currenteffect.setAttribute("src", ladspaEffectFile);
816                             }
817                             item->addEffect(currenteffect, false);
818                         }
819                     }
820                 }
821             }
822             //m_clipList.append(clip);
823         }
824     }
825     //m_trackDuration = position;
826
827
828     //documentTracks.insert(ix, track);
829     kDebug() << "*************  ADD DOC TRACK " << ix << ", DURATION: " << position;
830     return position;
831     //track->show();
832 }
833
834 DocClipBase *TrackView::getMissingProducer(const QString id) const
835 {
836     QDomElement missingXml;
837     QDomDocument doc = m_doc->toXml();
838     QString docRoot = doc.documentElement().attribute("root");
839     if (!docRoot.endsWith('/')) docRoot.append('/');
840     QDomNodeList prods = doc.elementsByTagName("producer");
841     int maxprod = prods.count();
842     for (int i = 0; i < maxprod; i++) {
843         QDomNode m = prods.at(i);
844         QString prodId = m.toElement().attribute("id");
845         if (prodId == id) {
846             missingXml =  m.toElement();
847             break;
848         }
849     }
850     if (missingXml == QDomElement()) return NULL;
851
852     QDomNodeList params = missingXml.childNodes();
853     QString resource;
854     for (int j = 0; j < params.count(); j++) {
855         QDomElement e = params.item(j).toElement();
856         if (e.attribute("name") == "resource") {
857             resource = e.firstChild().nodeValue();
858             break;
859         }
860     }
861     // prepend MLT XML document root if no path in clip resource and not a color clip
862     if (!resource.startsWith('/') && !resource.startsWith("0x")) resource.prepend(docRoot);
863     DocClipBase *missingClip = NULL;
864     if (!resource.isEmpty()) {
865         QList <DocClipBase *> list = m_doc->clipManager()->getClipByResource(resource);
866         if (!list.isEmpty()) missingClip = list.at(0);
867     }
868     return missingClip;
869 }
870
871 QGraphicsScene *TrackView::projectScene()
872 {
873     return m_scene;
874 }
875
876 CustomTrackView *TrackView::projectView()
877 {
878     return m_trackview;
879 }
880
881 void TrackView::setEditMode(const QString & editMode)
882 {
883     m_editMode = editMode;
884 }
885
886 const QString & TrackView::editMode() const
887 {
888     return m_editMode;
889 }
890
891 void TrackView::slotChangeTrackLock(int ix, bool lock)
892 {
893     QList<HeaderTrack *> widgets = findChildren<HeaderTrack *>();
894     widgets.at(ix)->setLock(lock);
895 }
896
897
898 void TrackView::slotVerticalZoomDown()
899 {
900     if (m_verticalZoom == 0) return;
901     m_verticalZoom--;
902     m_doc->setZoom(m_doc->zoom().x(), m_verticalZoom);
903     if (m_verticalZoom == 0) m_trackview->setScale(m_scene->scale().x(), 0.5);
904     else m_trackview->setScale(m_scene->scale().x(), 1);
905     adjustTrackHeaders();
906     m_trackview->verticalScrollBar()->setValue(headers_area->verticalScrollBar()->value());
907 }
908
909 void TrackView::slotVerticalZoomUp()
910 {
911     if (m_verticalZoom == 2) return;
912     m_verticalZoom++;
913     m_doc->setZoom(m_doc->zoom().x(), m_verticalZoom);
914     if (m_verticalZoom == 2) m_trackview->setScale(m_scene->scale().x(), 2);
915     else m_trackview->setScale(m_scene->scale().x(), 1);
916     adjustTrackHeaders();
917     m_trackview->verticalScrollBar()->setValue(headers_area->verticalScrollBar()->value());
918 }
919
920 void TrackView::updateProjectFps()
921 {
922     m_ruler->updateProjectFps(m_doc->timecode());
923     m_trackview->updateProjectFps();
924 }
925
926 void TrackView::slotRenameTrack(int ix)
927 {
928     int tracknumber = m_doc->tracksCount() - ix;
929     TrackInfo info = m_doc->trackInfoAt(tracknumber - 1);
930     bool ok;
931     QString newName = QInputDialog::getText(this, i18n("New Track Name"), i18n("Enter new name"), QLineEdit::Normal, info.trackName, &ok);
932     if (ok) {
933         info.trackName = newName;
934         m_doc->setTrackType(tracknumber - 1, info);
935         QTimer::singleShot(300, this, SLOT(slotReloadTracks()));
936         m_doc->setModified(true);
937     }
938 }
939
940
941 #include "trackview.moc"