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