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