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