]> git.sesse.net Git - kdenlive/blob - src/trackview.cpp
Show icon on track header if track has effects applied
[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     //m_scene->addRect(QRectF(0, 0, 100, 100), QPen(), QBrush(Qt::red));
58
59     m_ruler = new CustomRuler(doc->timecode(), m_trackview);
60     connect(m_ruler, SIGNAL(zoneMoved(int, int)), this, SIGNAL(zoneMoved(int, int)));
61     connect(m_ruler, SIGNAL(adjustZoom(int)), this, SIGNAL(setZoom(int)));
62     QHBoxLayout *layout = new QHBoxLayout;
63     layout->setContentsMargins(m_trackview->frameWidth(), 0, 0, 0);
64     layout->setSpacing(0);
65     ruler_frame->setLayout(layout);
66     layout->addWidget(m_ruler);
67
68     QHBoxLayout *sizeLayout = new QHBoxLayout;
69     sizeLayout->setContentsMargins(0, 0, 0, 0);
70     sizeLayout->setSpacing(0);
71     size_frame->setLayout(sizeLayout);
72
73     QToolButton *butSmall = new QToolButton(this);
74     butSmall->setIcon(KIcon("kdenlive-zoom-small"));
75     butSmall->setToolTip(i18n("Smaller tracks"));
76     butSmall->setAutoRaise(true);
77     connect(butSmall, SIGNAL(clicked()), this, SLOT(slotVerticalZoomDown()));
78     sizeLayout->addWidget(butSmall);
79
80     QToolButton *butLarge = new QToolButton(this);
81     butLarge->setIcon(KIcon("kdenlive-zoom-large"));
82     butLarge->setToolTip(i18n("Bigger tracks"));
83     butLarge->setAutoRaise(true);
84     connect(butLarge, SIGNAL(clicked()), this, SLOT(slotVerticalZoomUp()));
85     sizeLayout->addWidget(butLarge);
86
87     QHBoxLayout *tracksLayout = new QHBoxLayout;
88     tracksLayout->setContentsMargins(0, 0, 0, 0);
89     tracksLayout->setSpacing(0);
90     tracks_frame->setLayout(tracksLayout);
91
92     headers_area->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
93     headers_area->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
94     headers_area->setFixedWidth(70);
95
96     QVBoxLayout *headersLayout = new QVBoxLayout;
97     headersLayout->setContentsMargins(0, m_trackview->frameWidth(), 0, 0);
98     headersLayout->setSpacing(0);
99     headers_container->setLayout(headersLayout);
100     connect(headers_area->verticalScrollBar(), SIGNAL(valueChanged(int)), m_trackview->verticalScrollBar(), SLOT(setValue(int)));
101
102     tracksLayout->addWidget(m_trackview);
103     connect(m_trackview->verticalScrollBar(), SIGNAL(valueChanged(int)), headers_area->verticalScrollBar(), SLOT(setValue(int)));
104     connect(m_trackview, SIGNAL(trackHeightChanged()), this, SLOT(slotRebuildTrackHeaders()));
105     connect(m_trackview, SIGNAL(tracksChanged()), this, SLOT(slotReloadTracks()));
106     connect(m_trackview, SIGNAL(updateTrackHeaders()), this, SLOT(slotRepaintTracks()));
107     connect(m_trackview, SIGNAL(showTrackEffects(int, TrackInfo)), this, SIGNAL(showTrackEffects(int, TrackInfo)));
108     connect(m_trackview, SIGNAL(updateTrackEffectState(int)), this, SLOT(slotUpdateTrackEffectState(int)));
109
110
111     parseDocument(m_doc->toXml());
112     if (m_doc->setSceneList() == -1) *ok = false;
113     else *ok = true;
114     connect(m_trackview, SIGNAL(cursorMoved(int, int)), m_ruler, SLOT(slotCursorMoved(int, int)));
115     connect(m_trackview->horizontalScrollBar(), SIGNAL(valueChanged(int)), m_ruler, SLOT(slotMoveRuler(int)));
116     connect(m_trackview->horizontalScrollBar(), SIGNAL(rangeChanged(int, int)), this, SLOT(slotUpdateVerticalScroll(int, int)));
117     connect(m_trackview, SIGNAL(mousePosition(int)), this, SIGNAL(mousePosition(int)));
118     connect(m_trackview, SIGNAL(doTrackLock(int, bool)), this, SLOT(slotChangeTrackLock(int, bool)));
119
120     slotChangeZoom(m_doc->zoom().x(), m_doc->zoom().y());
121     slotSetZone(m_doc->zone());
122 }
123
124 TrackView::~TrackView()
125 {
126     delete m_ruler;
127     delete m_trackview;
128 }
129
130 //virtual
131 void TrackView::keyPressEvent(QKeyEvent * event)
132 {
133     if (event->key() == Qt::Key_Up) {
134         m_trackview->slotTrackUp();
135         event->accept();
136     } else if (event->key() == Qt::Key_Down) {
137         m_trackview->slotTrackDown();
138         event->accept();
139     } else QWidget::keyPressEvent(event);
140 }
141
142 int TrackView::duration() const
143 {
144     return m_trackview->duration();
145 }
146
147 int TrackView::tracksNumber() const
148 {
149     return m_projectTracks - 1;
150 }
151
152 bool TrackView::checkProjectAudio() const
153 {
154     bool hasAudio = false;
155     const QList <TrackInfo> list = m_doc->tracksList();
156     int max = list.count();
157     for (int i = 0; i < max; i++) {
158         TrackInfo info = list.at(max - i - 1);
159         if (!info.isMute && m_trackview->hasAudio(i)) {
160             hasAudio = true;
161             break;
162         }
163     }
164     return hasAudio;
165 }
166
167 int TrackView::inPoint() const
168 {
169     return m_ruler->inPoint();
170 }
171
172 int TrackView::outPoint() const
173 {
174     return m_ruler->outPoint();
175 }
176
177 void TrackView::slotSetZone(QPoint p)
178 {
179     m_ruler->setZone(p);
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     QLayoutItem *child;
522     for (int i = 0; i < headers_container->layout()->count(); i++) {
523         child = headers_container->layout()->itemAt(i);
524         if (child->widget() && child->widget()->height() > 5) {
525             HeaderTrack *head = static_cast <HeaderTrack *>(child->widget());
526             if (head) head->setSelectedIndex(m_trackview->selectedTrack());
527         }
528     }
529 }
530
531 void TrackView::slotReloadTracks()
532 {
533     slotRebuildTrackHeaders();
534     emit updateTracksInfo();
535 }
536
537 void TrackView::slotRebuildTrackHeaders()
538 {
539     const QList <TrackInfo> list = m_doc->tracksList();
540     QLayoutItem *child;
541     while ((child = headers_container->layout()->takeAt(0)) != 0) {
542         QWidget *wid = child->widget();
543         delete child;
544         if (wid) wid->deleteLater();
545     }
546     int max = list.count();
547     int height = KdenliveSettings::trackheight() * m_scene->scale().y() - 1;
548     HeaderTrack *header = NULL;
549     QFrame *frame = NULL;
550     for (int i = 0; i < max; i++) {
551         frame = new QFrame(headers_container);
552         frame->setFixedHeight(1);
553         frame->setFrameStyle(QFrame::Plain);
554         frame->setFrameShape(QFrame::Box);
555         frame->setLineWidth(1);
556         headers_container->layout()->addWidget(frame);
557         TrackInfo info = list.at(max - i - 1);
558         header = new HeaderTrack(i, info, height, headers_container);
559         header->setSelectedIndex(m_trackview->selectedTrack());
560         connect(header, SIGNAL(switchTrackVideo(int)), m_trackview, SLOT(slotSwitchTrackVideo(int)));
561         connect(header, SIGNAL(switchTrackAudio(int)), m_trackview, SLOT(slotSwitchTrackAudio(int)));
562         connect(header, SIGNAL(switchTrackLock(int)), m_trackview, SLOT(slotSwitchTrackLock(int)));
563         connect(header, SIGNAL(selectTrack(int)), m_trackview, SLOT(slotSelectTrack(int)));
564         connect(header, SIGNAL(deleteTrack(int)), this, SIGNAL(deleteTrack(int)));
565         connect(header, SIGNAL(insertTrack(int)), this, SIGNAL(insertTrack(int)));
566         connect(header, SIGNAL(renameTrack(int, QString)), this, SLOT(slotRenameTrack(int, QString)));
567         connect(header, SIGNAL(configTrack(int)), this, SIGNAL(configTrack(int)));
568         connect(header, SIGNAL(addTrackInfo(const QDomElement, int)), m_trackview, SLOT(slotAddTrackEffect(const QDomElement, int)));
569         connect(header, SIGNAL(showTrackEffects(int)), this, SLOT(slotShowTrackEffects(int)));
570         headers_container->layout()->addWidget(header);
571     }
572     frame = new QFrame(this);
573     frame->setFixedHeight(1);
574     frame->setFrameStyle(QFrame::Plain);
575     frame->setFrameShape(QFrame::Box);
576     frame->setLineWidth(1);
577     headers_container->layout()->addWidget(frame);
578 }
579
580
581 void TrackView::adjustTrackHeaders()
582 {
583     int height = KdenliveSettings::trackheight() * m_scene->scale().y() - 1;
584     QLayoutItem *child;
585     for (int i = 0; i < headers_container->layout()->count(); i++) {
586         child = headers_container->layout()->itemAt(i);
587         if (child->widget() && child->widget()->height() > 5)(static_cast <HeaderTrack *>(child->widget()))->adjustSize(height);
588     }
589 }
590
591 int TrackView::slotAddProjectTrack(int ix, QDomElement xml, bool locked)
592 {
593     // parse track
594     int position = 0;
595     QDomNodeList children = xml.childNodes();
596     for (int nodeindex = 0; nodeindex < children.count(); nodeindex++) {
597         QDomNode n = children.item(nodeindex);
598         QDomElement elem = n.toElement();
599         if (elem.tagName() == "blank") {
600             position += elem.attribute("length").toInt();
601         } else if (elem.tagName() == "entry") {
602             // Found a clip
603             int in = elem.attribute("in").toInt();
604             int out = elem.attribute("out").toInt();
605             if (in > out || /*in == out ||*/ m_invalidProducers.contains(elem.attribute("producer"))) {
606                 m_documentErrors.append(i18n("Invalid clip removed from track %1 at %2\n", ix, position));
607                 xml.removeChild(children.at(nodeindex));
608                 nodeindex--;
609                 continue;
610             }
611             QString idString = elem.attribute("producer");
612             QString id = idString;
613             double speed = 1.0;
614             int strobe = 1;
615             if (idString.startsWith("slowmotion")) {
616                 id = idString.section(':', 1, 1);
617                 speed = idString.section(':', 2, 2).toDouble();
618                 strobe = idString.section(':', 3, 3).toInt();
619                 if (strobe == 0) strobe = 1;
620             } else id = id.section('_', 0, 0);
621             DocClipBase *clip = m_doc->clipManager()->getClipById(id);
622             if (clip == NULL) {
623                 // The clip in playlist was not listed in the kdenlive producers,
624                 // something went wrong, repair required.
625                 kWarning() << "CANNOT INSERT CLIP " << id;
626
627                 clip = getMissingProducer(id);
628                 if (!clip) {
629                     // We cannot find the producer, something is really wrong, add
630                     // placeholder color clip
631                     QDomDocument doc;
632                     QDomElement producerXml = doc.createElement("producer");
633                     doc.appendChild(producerXml);
634                     producerXml.setAttribute("colour", "0xff0000ff");
635                     producerXml.setAttribute("mlt_service", "colour");
636                     producerXml.setAttribute("length", "15000");
637                     producerXml.setAttribute("name", "INVALID");
638                     producerXml.setAttribute("type", COLOR);
639                     producerXml.setAttribute("id", id);
640                     clip = new DocClipBase(m_doc->clipManager(), doc.documentElement(), id);
641                     xml.insertBefore(producerXml, QDomNode());
642                     m_doc->clipManager()->addClip(clip);
643
644                     m_documentErrors.append(i18n("Broken clip producer %1", id) + '\n');
645                 } else {
646                     // Found correct producer
647                     m_documentErrors.append(i18n("Replaced wrong clip producer %1 with %2", id, clip->getId()) + '\n');
648                     elem.setAttribute("producer", clip->getId());
649                 }
650                 m_doc->setModified(true);
651             }
652
653             if (clip != NULL) {
654                 ItemInfo clipinfo;
655                 clipinfo.startPos = GenTime(position, m_doc->fps());
656                 clipinfo.endPos = clipinfo.startPos + GenTime(out - in + 1, m_doc->fps());
657                 clipinfo.cropStart = GenTime(in, m_doc->fps());
658                 clipinfo.cropDuration = clipinfo.endPos - clipinfo.startPos;
659
660                 clipinfo.track = ix;
661                 //kDebug() << "// INSERTING CLIP: " << in << "x" << out << ", track: " << ix << ", ID: " << id << ", SCALE: " << m_scale << ", FPS: " << m_doc->fps();
662                 ClipItem *item = new ClipItem(clip, clipinfo, m_doc->fps(), speed, strobe, false);
663                 if (idString.endsWith("_video")) item->setVideoOnly(true);
664                 else if (idString.endsWith("_audio")) item->setAudioOnly(true);
665                 m_scene->addItem(item);
666                 if (locked) item->setItemLocked(true);
667                 clip->addReference();
668                 position += (out - in + 1);
669                 if (speed != 1.0 || strobe > 1) {
670                     QDomElement speedeffect = MainWindow::videoEffects.getEffectByTag(QString(), "speed").cloneNode().toElement();
671                     EffectsList::setParameter(speedeffect, "speed", QString::number((int)(100 * speed + 0.5)));
672                     EffectsList::setParameter(speedeffect, "strobe", QString::number(strobe));
673                     item->addEffect(speedeffect, false);
674                     item->effectsCounter();
675                 }
676
677                 // parse clip effects
678                 QDomNodeList effects = elem.elementsByTagName("filter");
679                 slotAddProjectEffects(effects, elem, item, -1);
680             }
681         }
682     }
683     kDebug() << "*************  ADD DOC TRACK " << ix << ", DURATION: " << position;
684     return position;
685 }
686
687 void TrackView::slotAddProjectEffects(QDomNodeList effects, QDomElement parentNode, ClipItem *clip, int trackIndex)
688 {
689     for (int ix = 0; ix < effects.count(); ix++) {
690         bool disableeffect = false;
691         QDomElement effect = effects.at(ix).toElement();
692         if (effect.tagName() != "filter") continue;
693
694         // add effect to clip
695         QString effecttag;
696         QString effectid;
697         QString effectindex = QString::number(ix + 1);
698         QString ladspaEffectFile;
699         // Get effect tag & index
700         for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
701             // parse effect parameters
702             QDomElement effectparam = n3.toElement();
703             if (effectparam.attribute("name") == "tag") {
704                 effecttag = effectparam.text();
705             } else if (effectparam.attribute("name") == "kdenlive_id") {
706                 effectid = effectparam.text();
707             } else if (effectparam.attribute("name") == "disable" && effectparam.text().toInt() == 1) {
708                 // Fix effects index
709                 disableeffect = true;
710             } else if (effectparam.attribute("name") == "kdenlive_ix") {
711                 // Fix effects index
712                 effectparam.firstChild().setNodeValue(effectindex);
713             } else if (effectparam.attribute("name") == "src") {
714                 ladspaEffectFile = effectparam.text();
715                 if (!QFile::exists(ladspaEffectFile)) {
716                     // If the ladspa effect file is missing, recreate it
717                     kDebug() << "// MISSING LADSPA FILE: " << ladspaEffectFile;
718                     ladspaEffectFile = m_doc->getLadspaFile();
719                     effectparam.firstChild().setNodeValue(ladspaEffectFile);
720                     kDebug() << "// ... REPLACED WITH: " << ladspaEffectFile;
721                 }
722             }
723         }
724         //kDebug() << "+ + CLIP EFF FND: " << effecttag << ", " << effectid << ", " << effectindex;
725         // get effect standard tags
726         QDomElement clipeffect = MainWindow::customEffects.getEffectByTag(QString(), effectid);
727         if (clipeffect.isNull()) clipeffect = MainWindow::videoEffects.getEffectByTag(effecttag, effectid);
728         if (clipeffect.isNull()) clipeffect = MainWindow::audioEffects.getEffectByTag(effecttag, effectid);
729         if (clipeffect.isNull()) {
730             kDebug() << "///  WARNING, EFFECT: " << effecttag << ": " << effectid << " not found, removing it from project";
731             m_documentErrors.append(i18n("Effect %1:%2 not found in MLT, it was removed from this project\n", effecttag, effectid));
732             if (parentNode.removeChild(effects.at(ix)).isNull()) kDebug() << "///  PROBLEM REMOVING EFFECT: " << effecttag;
733             ix--;
734         } else {
735             QDomElement currenteffect = clipeffect.cloneNode().toElement();
736             currenteffect.setAttribute("kdenlive_ix", effectindex);
737             QDomNodeList clipeffectparams = currenteffect.childNodes();
738
739             if (MainWindow::videoEffects.hasKeyFrames(currenteffect)) {
740                 //kDebug() << " * * * * * * * * * * ** CLIP EFF WITH KFR FND  * * * * * * * * * * *";
741                 // effect is key-framable, read all effects to retrieve keyframes
742                 QString factor;
743                 QString starttag;
744                 QString endtag;
745                 QDomNodeList params = currenteffect.elementsByTagName("parameter");
746                 for (int i = 0; i < params.count(); i++) {
747                     QDomElement e = params.item(i).toElement();
748                     if (e.attribute("type") == "keyframe") {
749                         starttag = e.attribute("starttag", "start");
750                         endtag = e.attribute("endtag", "end");
751                         factor = e.attribute("factor", "1");
752                         break;
753                     }
754                 }
755                 QString keyframes;
756                 int effectin = effect.attribute("in").toInt();
757                 int effectout = effect.attribute("out").toInt();
758                 double startvalue = 0;
759                 double endvalue = 0;
760                 double fact;
761                 if (factor.isEmpty()) fact = 1;
762                 else if (factor.startsWith('%')) {
763                     fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
764                 } else fact = factor.toDouble();
765                 for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
766                     // parse effect parameters
767                     QDomElement effectparam = n3.toElement();
768                     if (effectparam.attribute("name") == starttag)
769                         startvalue = effectparam.text().toDouble() * fact;
770                     if (effectparam.attribute("name") == endtag)
771                         endvalue = effectparam.text().toDouble() * fact;
772                 }
773                 // add first keyframe
774                 if (effectout <= effectin) {
775                     // there is only one keyframe
776                     keyframes.append(QString::number(effectin) + ':' + QString::number(startvalue) + ';');
777                 } else keyframes.append(QString::number(effectin) + ':' + QString::number(startvalue) + ';' + QString::number(effectout) + ':' + QString::number(endvalue) + ';');
778                 QDomNode lastParsedEffect;
779                 ix++;
780                 QDomNode n2 = effects.at(ix);
781                 bool continueParsing = true;
782                 for (; !n2.isNull() && continueParsing; n2 = n2.nextSibling()) {
783                     // parse all effects
784                     QDomElement kfreffect = n2.toElement();
785                     int effectout = kfreffect.attribute("out").toInt();
786
787                     for (QDomNode n4 = kfreffect.firstChild(); !n4.isNull(); n4 = n4.nextSibling()) {
788                         // parse effect parameters
789                         QDomElement subeffectparam = n4.toElement();
790                         if (subeffectparam.attribute("name") == "kdenlive_ix" && subeffectparam.text() != effectindex) {
791                             //We are not in the same effect, stop parsing
792                             lastParsedEffect = n2.previousSibling();
793                             ix--;
794                             continueParsing = false;
795                             break;
796                         } else if (subeffectparam.attribute("name") == endtag) {
797                             endvalue = subeffectparam.text().toDouble() * fact;
798                             break;
799                         }
800                     }
801                     if (continueParsing) {
802                         keyframes.append(QString::number(effectout) + ':' + QString::number(endvalue) + ';');
803                         ix++;
804                     }
805                 }
806
807                 params = currenteffect.elementsByTagName("parameter");
808                 for (int i = 0; i < params.count(); i++) {
809                     QDomElement e = params.item(i).toElement();
810                     if (e.attribute("type") == "keyframe") e.setAttribute("keyframes", keyframes);
811                 }
812                 if (!continueParsing) {
813                     n2 = lastParsedEffect;
814                 }
815             } else {
816                 // Check if effect has in/out points
817                 if (effect.hasAttribute("in")) {
818                     EffectsList::setParameter(currenteffect, "in",  effect.attribute("in"));
819                 }
820                 if (effect.hasAttribute("out")) {
821                     EffectsList::setParameter(currenteffect, "out",  effect.attribute("out"));
822                 }
823             }
824
825             // adjust effect parameters
826             for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
827                 // parse effect parameters
828                 QDomElement effectparam = n3.toElement();
829                 QString paramname = effectparam.attribute("name");
830                 QString paramvalue = effectparam.text();
831
832                 // try to find this parameter in the effect xml
833                 QDomElement e;
834                 for (int k = 0; k < clipeffectparams.count(); k++) {
835                     e = clipeffectparams.item(k).toElement();
836                     if (!e.isNull() && e.tagName() == "parameter" && e.attribute("name") == paramname) {
837                         if (e.attribute("factor", "1") != "1") {
838                             QString factor = e.attribute("factor", "1");
839                             double fact;
840                             if (factor.startsWith('%')) {
841                                 fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
842                             } else fact = factor.toDouble();
843                             if (e.attribute("type") == "simplekeyframe") {
844                                 QStringList kfrs = paramvalue.split(";");
845                                 for (int l = 0; l < kfrs.count(); l++) {
846                                     QString fr = kfrs.at(l).section("=", 0, 0);
847                                     double val = kfrs.at(l).section("=", 1, 1).toDouble();
848                                     kfrs[l] = fr + ":" + QString::number((int)(val * fact));
849                                 }
850                                 e.setAttribute("keyframes", kfrs.join(";"));
851                             } else e.setAttribute("value", paramvalue.toDouble() * fact);
852                         } else e.setAttribute("value", paramvalue);
853                         break;
854                     }
855                 }
856             }
857             if (effecttag == "ladspa") {
858                 //QString ladspaEffectFile = EffectsList::parameter(effect, "src", "property");
859
860                 if (!QFile::exists(ladspaEffectFile)) {
861                     // If the ladspa effect file is missing, recreate it
862                     initEffects::ladspaEffectFile(ladspaEffectFile, currenteffect.attribute("ladspaid").toInt(), m_trackview->getLadspaParams(currenteffect));
863                 }
864                 currenteffect.setAttribute("src", ladspaEffectFile);
865             }
866             if (disableeffect) currenteffect.setAttribute("disable", "1");
867             if (clip) clip->addEffect(currenteffect, false);
868             else {
869                 kDebug() << "<< TRACK: " << trackIndex << ", adding effect";;
870                 m_doc->addTrackEffect(trackIndex, currenteffect);
871             }
872         }
873     }
874 }
875
876
877 DocClipBase *TrackView::getMissingProducer(const QString id) const
878 {
879     QDomElement missingXml;
880     QDomDocument doc = m_doc->toXml();
881     QString docRoot = doc.documentElement().attribute("root");
882     if (!docRoot.endsWith('/')) docRoot.append('/');
883     QDomNodeList prods = doc.elementsByTagName("producer");
884     int maxprod = prods.count();
885     for (int i = 0; i < maxprod; i++) {
886         QDomNode m = prods.at(i);
887         QString prodId = m.toElement().attribute("id");
888         if (prodId == id) {
889             missingXml =  m.toElement();
890             break;
891         }
892     }
893     if (missingXml == QDomElement()) return NULL;
894
895     QDomNodeList params = missingXml.childNodes();
896     QString resource;
897     for (int j = 0; j < params.count(); j++) {
898         QDomElement e = params.item(j).toElement();
899         if (e.attribute("name") == "resource") {
900             resource = e.firstChild().nodeValue();
901             break;
902         }
903     }
904     // prepend MLT XML document root if no path in clip resource and not a color clip
905     if (!resource.startsWith('/') && !resource.startsWith("0x")) resource.prepend(docRoot);
906     DocClipBase *missingClip = NULL;
907     if (!resource.isEmpty()) {
908         QList <DocClipBase *> list = m_doc->clipManager()->getClipByResource(resource);
909         if (!list.isEmpty()) missingClip = list.at(0);
910     }
911     return missingClip;
912 }
913
914 QGraphicsScene *TrackView::projectScene()
915 {
916     return m_scene;
917 }
918
919 CustomTrackView *TrackView::projectView()
920 {
921     return m_trackview;
922 }
923
924 void TrackView::setEditMode(const QString & editMode)
925 {
926     m_editMode = editMode;
927 }
928
929 const QString & TrackView::editMode() const
930 {
931     return m_editMode;
932 }
933
934 void TrackView::slotChangeTrackLock(int ix, bool lock)
935 {
936     QList<HeaderTrack *> widgets = findChildren<HeaderTrack *>();
937     widgets.at(ix)->setLock(lock);
938 }
939
940
941 void TrackView::slotVerticalZoomDown()
942 {
943     if (m_verticalZoom == 0) return;
944     m_verticalZoom--;
945     m_doc->setZoom(m_doc->zoom().x(), m_verticalZoom);
946     if (m_verticalZoom == 0)
947         m_trackview->setScale(m_scene->scale().x(), 0.5);
948     else
949         m_trackview->setScale(m_scene->scale().x(), 1);
950     adjustTrackHeaders();
951     m_trackview->verticalScrollBar()->setValue(headers_area->verticalScrollBar()->value());
952 }
953
954 void TrackView::slotVerticalZoomUp()
955 {
956     if (m_verticalZoom == 2) return;
957     m_verticalZoom++;
958     m_doc->setZoom(m_doc->zoom().x(), m_verticalZoom);
959     if (m_verticalZoom == 2)
960         m_trackview->setScale(m_scene->scale().x(), 2);
961     else
962         m_trackview->setScale(m_scene->scale().x(), 1);
963     adjustTrackHeaders();
964     m_trackview->verticalScrollBar()->setValue(headers_area->verticalScrollBar()->value());
965 }
966
967 void TrackView::updateProjectFps()
968 {
969     m_ruler->updateProjectFps(m_doc->timecode());
970     m_trackview->updateProjectFps();
971 }
972
973 void TrackView::slotRenameTrack(int ix, QString name)
974 {
975     int tracknumber = m_doc->tracksCount() - ix;
976     QList <TrackInfo> tracks = m_doc->tracksList();
977     tracks[tracknumber - 1].trackName = name;
978     ConfigTracksCommand *configTracks = new ConfigTracksCommand(m_trackview, m_doc->tracksList(), tracks);
979     m_doc->commandStack()->push(configTracks);
980     m_doc->setModified(true);
981 }
982
983 void TrackView::slotUpdateVerticalScroll(int /*min*/, int max)
984 {
985     int height = 0;
986     if (max > 0) height = m_trackview->horizontalScrollBar()->height() - 1;
987     headers_container->layout()->setContentsMargins(0, m_trackview->frameWidth(), 0, height);
988 }
989
990 void TrackView::updateRuler()
991 {
992     m_ruler->update();
993 }
994
995 void TrackView::slotShowTrackEffects(int ix)
996 {
997     m_trackview->clearSelection();
998     emit showTrackEffects(m_doc->tracksCount() - ix, m_doc->trackInfoAt(m_doc->tracksCount() - ix - 1));
999 }
1000
1001 void TrackView::slotUpdateTrackEffectState(int ix)
1002 {
1003     QList<HeaderTrack *> widgets = findChildren<HeaderTrack *>();
1004     if (ix >= widgets.count()) {
1005         kDebug() << "ERROR, Trying to access a non existant track: " << ix;
1006         return;
1007     }
1008     widgets.at(m_doc->tracksCount() - ix - 1)->updateEffectLabel(m_doc->trackInfoAt(ix).effectsList.effectNames());
1009 }
1010
1011 #include "trackview.moc"