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