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