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