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