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