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