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