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