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