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