]> git.sesse.net Git - kdenlive/blob - src/trackview.cpp
c18b1678baf96c9b0b5fe3885d32271bde75bc45
[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 "definitions.h"
23 #include "headertrack.h"
24 #include "clipitem.h"
25 #include "transition.h"
26 #include "kdenlivesettings.h"
27 #include "clipmanager.h"
28 #include "customruler.h"
29 #include "kdenlivedoc.h"
30 #include "mainwindow.h"
31 #include "customtrackview.h"
32 #include "initeffects.h"
33 #include "profilesdialog.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
106     parseDocument(m_doc->toXml());
107     int error = m_doc->setSceneList();
108     if (error == -1) *ok = false;
109     else *ok = true;
110     connect(m_trackview, SIGNAL(cursorMoved(int, int)), m_ruler, SLOT(slotCursorMoved(int, int)));
111     connect(m_trackview->horizontalScrollBar(), SIGNAL(valueChanged(int)), m_ruler, SLOT(slotMoveRuler(int)));
112     connect(m_trackview, SIGNAL(mousePosition(int)), this, SIGNAL(mousePosition(int)));
113     connect(m_trackview, SIGNAL(doTrackLock(int, bool)), this, SLOT(slotChangeTrackLock(int, bool)));
114
115     slotChangeZoom(m_doc->zoom().x(), m_doc->zoom().y());
116     slotSetZone(m_doc->zone());
117 }
118
119 TrackView::~TrackView()
120 {
121     delete m_ruler;
122     delete m_trackview;
123 }
124
125 int TrackView::duration() const
126 {
127     return m_trackview->duration();
128 }
129
130 int TrackView::tracksNumber() const
131 {
132     return m_projectTracks - 1;
133 }
134
135 int TrackView::inPoint() const
136 {
137     return m_ruler->inPoint();
138 }
139
140 int TrackView::outPoint() const
141 {
142     return m_ruler->outPoint();
143 }
144
145 void TrackView::slotSetZone(QPoint p)
146 {
147     m_ruler->setZone(p);
148 }
149
150 void TrackView::setDuration(int dur)
151 {
152     m_trackview->setDuration(dur);
153     m_ruler->setDuration(dur);
154 }
155
156 void TrackView::parseDocument(QDomDocument doc)
157 {
158     //int cursorPos = 0;
159     m_documentErrors.clear();
160
161     //kDebug() << "//// DOCUMENT: " << doc.toString();
162     /*QDomNode props = doc.elementsByTagName("properties").item(0);
163     if (!props.isNull()) {
164         cursorPos = props.toElement().attribute("timeline_position").toInt();
165     }*/
166
167     // parse project tracks
168     QDomElement tractor = doc.elementsByTagName("tractor").item(0).toElement();
169     QDomNodeList tracks = doc.elementsByTagName("track");
170     QDomNodeList playlists = doc.elementsByTagName("playlist");
171     int duration = 300;
172     m_projectTracks = tracks.count();
173     int trackduration = 0;
174     QDomElement e;
175     QDomElement p;
176
177     int pos = m_projectTracks - 1;
178     m_invalidProducers.clear();
179     QDomNodeList producers = doc.elementsByTagName("producer");
180     for (int i = 0; i < producers.count(); i++) {
181         // Check for invalid producers
182         QDomNode n = producers.item(i);
183         e = n.toElement();
184
185         /*
186         // Check for invalid markup
187         QDomNodeList params = e.elementsByTagName("property");
188         for (int j = 0; j < params.count(); j++) {
189             QDomElement p = params.item(j).toElement();
190             if (p.attribute("name") == "markup") {
191          QString val = p.text().toUtf8().data();
192          kDebug()<<"//FOUND MARKUP, VAL: "<<val;
193          //e.setAttribute("value", value);
194          n.removeChild(params.item(j));
195          break;
196             }
197         }
198         */
199
200         if (e.hasAttribute("in") == false && e.hasAttribute("out") == false) continue;
201         int in = e.attribute("in").toInt();
202         int out = e.attribute("out").toInt();
203         if (in > out || in == out) {
204             // invalid producer, remove it
205             QString id = e.attribute("id");
206             m_invalidProducers.append(id);
207             m_documentErrors.append(i18n("Invalid clip producer %1\n", id));
208             doc.documentElement().removeChild(producers.at(i));
209             i--;
210         }
211     }
212
213     for (int i = 0; i < m_projectTracks; i++) {
214         e = tracks.item(i).toElement();
215         QString playlist_name = e.attribute("producer");
216         if (playlist_name != "black_track" && playlist_name != "playlistmain") {
217             // find playlist related to this track
218             p = QDomElement();
219             for (int j = 0; j < m_projectTracks; j++) {
220                 p = playlists.item(j).toElement();
221                 if (p.attribute("id") == playlist_name) break;
222             }
223             if (p.attribute("id") != playlist_name) { // then it didn't work.
224                 kDebug() << "NO PLAYLIST FOUND FOR TRACK " + pos;
225             }
226             if (e.attribute("hide") == "video") {
227                 m_doc->switchTrackVideo(i - 1, true);
228             } else if (e.attribute("hide") == "audio") {
229                 m_doc->switchTrackAudio(i - 1, true);
230             } else if (e.attribute("hide") == "both") {
231                 m_doc->switchTrackVideo(i - 1, true);
232                 m_doc->switchTrackAudio(i - 1, true);
233             }
234
235             trackduration = slotAddProjectTrack(pos, p, m_doc->isTrackLocked(i - 1));
236             pos--;
237             //kDebug() << " PRO DUR: " << trackduration << ", TRACK DUR: " << duration;
238             if (trackduration > duration) duration = trackduration;
239         } else {
240             // background black track
241             for (int j = 0; j < m_projectTracks; j++) {
242                 p = playlists.item(j).toElement();
243                 if (p.attribute("id") == playlist_name) break;
244             }
245             pos--;
246         }
247     }
248
249     // parse transitions
250     QDomNodeList transitions = doc.elementsByTagName("transition");
251
252     //kDebug() << "//////////// TIMELINE FOUND: " << projectTransitions << " transitions";
253     for (int i = 0; i < transitions.count(); i++) {
254         e = transitions.item(i).toElement();
255         QDomNodeList transitionparams = e.childNodes();
256         bool transitionAdd = true;
257         int a_track = 0;
258         int b_track = 0;
259         bool isAutomatic = false;
260         bool forceTrack = false;
261         QString mlt_geometry;
262         QString mlt_service;
263         QString transitionId;
264         for (int k = 0; k < transitionparams.count(); k++) {
265             p = transitionparams.item(k).toElement();
266             if (!p.isNull()) {
267                 QString paramName = p.attribute("name");
268                 // do not add audio mixing transitions
269                 if (paramName == "internal_added" && p.text() == "237") {
270                     transitionAdd = false;
271                     //kDebug() << "//  TRANSITRION " << i << " IS NOT VALID (INTERN ADDED)";
272                     //break;
273                 } else if (paramName == "a_track") a_track = p.text().toInt();
274                 else if (paramName == "b_track") b_track = p.text().toInt();
275                 else if (paramName == "mlt_service") mlt_service = p.text();
276                 else if (paramName == "kdenlive_id") transitionId = p.text();
277                 else if (paramName == "geometry") mlt_geometry = p.text();
278                 else if (paramName == "automatic" && p.text() == "1") isAutomatic = true;
279                 else if (paramName == "force_track" && p.text() == "1") forceTrack = true;
280             }
281         }
282         if (transitionAdd || mlt_service != "mix") {
283             // Transition should be added to the scene
284             ItemInfo transitionInfo;
285             if (mlt_service == "composite" && transitionId.isEmpty()) {
286                 // When adding composite transition, check if it is a wipe transition
287                 if (mlt_geometry.count(';') == 1) {
288                     mlt_geometry.remove(QChar('%'), Qt::CaseInsensitive);
289                     mlt_geometry.replace(QChar('x'), QChar(','), Qt::CaseInsensitive);
290                     QString start = mlt_geometry.section(';', 0, 0);
291                     start = start.section(':', 0, 1);
292                     start.replace(QChar(':'), QChar(','), Qt::CaseInsensitive);
293                     QString end = mlt_geometry.section('=', 1, 1);
294                     end = end.section(':', 0, 1);
295                     end.replace(QChar(':'), QChar(','), Qt::CaseInsensitive);
296                     start.append(',' + end);
297                     QStringList numbers = start.split(',', QString::SkipEmptyParts);
298                     bool isWipeTransition = true;
299                     int checkNumber;
300                     for (int i = 0; i < numbers.size(); ++i) {
301                         checkNumber = qAbs(numbers.at(i).toInt());
302                         if (checkNumber != 0 && checkNumber != 100) {
303                             isWipeTransition = false;
304                             break;
305                         }
306                     }
307                     if (isWipeTransition) transitionId = "slide";
308                 }
309             }
310             QDomElement base = MainWindow::transitions.getEffectByTag(mlt_service, transitionId).cloneNode().toElement();
311
312             for (int k = 0; k < transitionparams.count(); k++) {
313                 p = transitionparams.item(k).toElement();
314                 if (!p.isNull()) {
315                     QString paramName = p.attribute("name");
316                     QString paramValue = p.text();
317
318                     QDomNodeList params = base.elementsByTagName("parameter");
319                     if (paramName != "a_track" && paramName != "b_track") for (int i = 0; i < params.count(); i++) {
320                             QDomElement e = params.item(i).toElement();
321                             if (!e.isNull() && e.attribute("tag") == paramName) {
322                                 if (e.attribute("type") == "double") {
323                                     QString factor = e.attribute("factor", "1");
324                                     if (factor != "1") {
325                                         double fact;
326                                         if (factor.startsWith('%')) {
327                                             fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
328                                         } else fact = factor.toDouble();
329                                         double val = paramValue.toDouble() * fact;
330                                         paramValue = QString::number(val);
331                                     }
332                                 }
333                                 e.setAttribute("value", paramValue);
334                                 break;
335                             }
336                         }
337                 }
338             }
339
340             /*QDomDocument doc;
341             doc.appendChild(doc.importNode(base, true));
342             kDebug() << "///////  TRANSITION XML: "<< doc.toString();*/
343
344             transitionInfo.startPos = GenTime(e.attribute("in").toInt(), m_doc->fps());
345             transitionInfo.endPos = GenTime(e.attribute("out").toInt() + 1, m_doc->fps());
346             transitionInfo.track = m_projectTracks - 1 - b_track;
347
348             //kDebug() << "///////////////   +++++++++++  ADDING TRANSITION ON TRACK: " << b_track << ", TOTAL TRKA: " << m_projectTracks;
349             if (transitionInfo.startPos >= transitionInfo.endPos) {
350                 // invalid transition, remove it.
351                 m_documentErrors.append(i18n("Removed invalid transition: %1", e.attribute("id")) + '\n');
352                 kDebug() << "///// REMOVED INVALID TRANSITION: " << e.attribute("id");
353                 tractor.removeChild(transitions.item(i));
354                 i--;
355             } else {
356                 Transition *tr = new Transition(transitionInfo, a_track, m_doc->fps(), base, isAutomatic);
357                 if (forceTrack) tr->setForcedTrack(true, a_track);
358                 m_scene->addItem(tr);
359                 if (b_track > 0 && m_doc->isTrackLocked(b_track - 1)) {
360                     tr->setItemLocked(true);
361                 }
362             }
363         }
364     }
365
366     // Add guides
367     QDomNodeList guides = doc.elementsByTagName("guide");
368     for (int i = 0; i < guides.count(); i++) {
369         e = guides.item(i).toElement();
370         const QString comment = e.attribute("comment");
371         const GenTime pos = GenTime(e.attribute("time").toDouble());
372         m_trackview->addGuide(pos, comment);
373     }
374
375     // Rebuild groups
376     QDomNodeList groups = doc.elementsByTagName("group");
377     m_trackview->loadGroups(groups);
378     m_trackview->setDuration(duration);
379     kDebug() << "///////////  TOTAL PROJECT DURATION: " << duration;
380
381     // Remove Kdenlive extra info from xml doc before sending it to MLT
382     QDomElement mlt = doc.firstChildElement("mlt");
383     QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
384     mlt.removeChild(infoXml);
385
386     slotRebuildTrackHeaders();
387     if (!m_documentErrors.isNull()) KMessageBox::sorry(this, m_documentErrors);
388     if (infoXml.hasAttribute("upgraded")) {
389         // Our document was upgraded, create a backup copy just in case
390         QString baseFile = m_doc->url().path().section(".kdenlive", 0, 0);
391         int ct = 0;
392         QString backupFile = baseFile + "_backup" + QString::number(ct) + ".kdenlive";
393         while (QFile::exists(backupFile)) {
394             ct++;
395             backupFile = baseFile + "_backup" + QString::number(ct) + ".kdenlive";
396         }
397         if (KIO::NetAccess::file_copy(m_doc->url(), KUrl(backupFile), this)) KMessageBox::information(this, i18n("Your project file was upgraded to the latest Kdenlive document version.\n To make sure you don't loose data, a backup copy called: %1 was created.", backupFile));
398         else KMessageBox::information(this, i18n("Your project file was upgraded to the latest Kdenlive document version, it was not possible to create a backup copy.", backupFile));
399     }
400     //m_trackview->setCursorPos(cursorPos);
401     //m_scrollBox->setGeometry(0, 0, 300 * zoomFactor(), m_scrollArea->height());
402 }
403
404 void TrackView::slotDeleteClip(const QString &clipId)
405 {
406     m_trackview->deleteClip(clipId);
407 }
408
409 void TrackView::setCursorPos(int pos)
410 {
411     m_trackview->setCursorPos(pos);
412 }
413
414 void TrackView::moveCursorPos(int pos)
415 {
416     m_trackview->setCursorPos(pos, false);
417 }
418
419 void TrackView::slotChangeZoom(int horizontal, int vertical)
420 {
421     m_ruler->setPixelPerMark(horizontal);
422     m_scale = (double) FRAME_SIZE / m_ruler->comboScale[horizontal];
423
424     if (vertical == -1) {
425         // user called zoom
426         m_doc->setZoom(horizontal, m_verticalZoom);
427         m_trackview->setScale(m_scale, m_scene->scale().y());
428     } else {
429         m_verticalZoom = vertical;
430         if (m_verticalZoom == 0) m_trackview->setScale(m_scale, 0.5);
431         else m_trackview->setScale(m_scale, m_verticalZoom);
432         adjustTrackHeaders();
433     }
434 }
435
436 int TrackView::fitZoom() const
437 {
438     int zoom = (int)((duration() + 20 / m_scale) * FRAME_SIZE / m_trackview->width());
439     int i;
440     for (i = 0; i < 13; i++)
441         if (m_ruler->comboScale[i] > zoom) break;
442     return i;
443 }
444
445 KdenliveDoc *TrackView::document()
446 {
447     return m_doc;
448 }
449
450 void TrackView::refresh()
451 {
452     m_trackview->viewport()->update();
453 }
454
455 void TrackView::slotRebuildTrackHeaders()
456 {
457     const QList <TrackInfo> list = m_doc->tracksList();
458     QLayoutItem *child;
459     while ((child = headers_container->layout()->takeAt(0)) != 0) {
460         QWidget *wid = child->widget();
461         delete child;
462         if (wid) wid->deleteLater();
463     }
464     int max = list.count();
465     int height = KdenliveSettings::trackheight() * m_scene->scale().y() - 1;
466     HeaderTrack *header = NULL;
467     QFrame *frame = NULL;
468     for (int i = 0; i < max; i++) {
469         frame = new QFrame(headers_container);
470         frame->setFixedHeight(1);
471         frame->setFrameStyle(QFrame::Plain);
472         frame->setFrameShape(QFrame::Box);
473         frame->setLineWidth(1);
474         headers_container->layout()->addWidget(frame);
475         TrackInfo info = list.at(max - i - 1);
476         header = new HeaderTrack(i, info, height, headers_container);
477         connect(header, SIGNAL(switchTrackVideo(int)), m_trackview, SLOT(slotSwitchTrackVideo(int)));
478         connect(header, SIGNAL(switchTrackAudio(int)), m_trackview, SLOT(slotSwitchTrackAudio(int)));
479         connect(header, SIGNAL(switchTrackLock(int)), m_trackview, SLOT(slotSwitchTrackLock(int)));
480
481         connect(header, SIGNAL(deleteTrack(int)), this, SIGNAL(deleteTrack(int)));
482         connect(header, SIGNAL(insertTrack(int)), this, SIGNAL(insertTrack(int)));
483         connect(header, SIGNAL(changeTrack(int)), this, SIGNAL(changeTrack(int)));
484         connect(header, SIGNAL(renameTrack(int)), this, SLOT(slotRenameTrack(int)));
485         headers_container->layout()->addWidget(header);
486     }
487     frame = new QFrame(this);
488     frame->setFixedHeight(1);
489     frame->setFrameStyle(QFrame::Plain);
490     frame->setFrameShape(QFrame::Box);
491     frame->setLineWidth(1);
492     headers_container->layout()->addWidget(frame);
493 }
494
495
496 void TrackView::adjustTrackHeaders()
497 {
498     int height = KdenliveSettings::trackheight() * m_scene->scale().y() - 1;
499     QLayoutItem *child;
500     for (int i = 0; i < headers_container->layout()->count(); i++) {
501         child = headers_container->layout()->itemAt(i);
502         if (child->widget() && child->widget()->height() > 5)(static_cast <HeaderTrack *>(child->widget()))->adjustSize(height);
503     }
504 }
505
506 int TrackView::slotAddProjectTrack(int ix, QDomElement xml, bool locked)
507 {
508     // parse track
509     int position = 0;
510     QDomNodeList children = xml.childNodes();
511     for (int nodeindex = 0; nodeindex < children.count(); nodeindex++) {
512         QDomNode n = children.item(nodeindex);
513         QDomElement elem = n.toElement();
514         if (elem.tagName() == "blank") {
515             position += elem.attribute("length").toInt();
516         } else if (elem.tagName() == "entry") {
517             // Found a clip
518             int in = elem.attribute("in").toInt();
519             int out = elem.attribute("out").toInt();
520             if (in > out || /*in == out ||*/ m_invalidProducers.contains(elem.attribute("producer"))) {
521                 m_documentErrors.append(i18n("Invalid clip removed from track %1 at %2\n", ix, position));
522                 xml.removeChild(children.at(nodeindex));
523                 nodeindex--;
524                 continue;
525             }
526             QString idString = elem.attribute("producer");
527             QString id = idString;
528             double speed = 1.0;
529             int strobe = 1;
530             if (idString.startsWith("slowmotion")) {
531                 id = idString.section(':', 1, 1);
532                 speed = idString.section(':', 2, 2).toDouble();
533                 strobe = idString.section(':', 3, 3).toInt();
534                 if (strobe == 0) strobe = 1;
535             } else id = id.section('_', 0, 0);
536             DocClipBase *clip = m_doc->clipManager()->getClipById(id);
537             if (clip == NULL) {
538                 // The clip in playlist was not listed in the kdenlive producers,
539                 // something went wrong, repair required.
540                 kWarning() << "CANNOT INSERT CLIP " << id;
541
542                 clip = getMissingProducer(id);
543                 if (!clip) {
544                     // We cannot find the producer, something is really wrong, add
545                     // placeholder color clip
546                     QDomDocument doc;
547                     QDomElement producerXml = doc.createElement("producer");
548                     doc.appendChild(producerXml);
549                     producerXml.setAttribute("colour", "0xff0000ff");
550                     producerXml.setAttribute("mlt_service", "colour");
551                     producerXml.setAttribute("length", "15000");
552                     producerXml.setAttribute("name", "INVALID");
553                     producerXml.setAttribute("type", COLOR);
554                     producerXml.setAttribute("id", id);
555                     clip = new DocClipBase(m_doc->clipManager(), doc.documentElement(), id);
556                     xml.insertBefore(producerXml, QDomNode());
557                     m_doc->clipManager()->addClip(clip);
558
559                     m_documentErrors.append(i18n("Broken clip producer %1", id) + '\n');
560                 } else {
561                     // Found correct producer
562                     m_documentErrors.append(i18n("Replaced wrong clip producer %1 with %2", id, clip->getId()) + '\n');
563                     elem.setAttribute("producer", clip->getId());
564                 }
565                 m_doc->setModified(true);
566             }
567
568             if (clip != NULL) {
569                 ItemInfo clipinfo;
570                 clipinfo.startPos = GenTime(position, m_doc->fps());
571                 clipinfo.endPos = clipinfo.startPos + GenTime(out - in + 1, m_doc->fps());
572                 clipinfo.cropStart = GenTime(in, m_doc->fps());
573                 clipinfo.cropDuration = GenTime((int)((clipinfo.endPos - clipinfo.startPos).frames(m_doc->fps()) * speed + 0.5), m_doc->fps());
574                 clipinfo.originalcropStart = GenTime((int)((clipinfo.cropStart).frames(m_doc->fps()) * speed + 0.5), m_doc->fps());
575
576                 clipinfo.track = ix;
577                 //kDebug() << "// INSERTING CLIP: " << in << "x" << out << ", track: " << ix << ", ID: " << id << ", SCALE: " << m_scale << ", FPS: " << m_doc->fps();
578                 ClipItem *item = new ClipItem(clip, clipinfo, m_doc->fps(), speed, strobe, false);
579                 if (idString.endsWith("_video")) item->setVideoOnly(true);
580                 else if (idString.endsWith("_audio")) item->setAudioOnly(true);
581                 m_scene->addItem(item);
582                 if (locked) item->setItemLocked(true);
583                 clip->addReference();
584                 position += (out - in + 1);
585                 kDebug() << "/////////\n\n\n" << "CLIP SPEED: " << speed << ", " << strobe << "\n\n\n/////////////////////";
586                 if (speed != 1.0 || strobe > 1) {
587                     QDomElement speedeffect = MainWindow::videoEffects.getEffectByTag(QString(), "speed").cloneNode().toElement();
588                     EffectsList::setParameter(speedeffect, "speed", QString::number((int)(100 * speed + 0.5)));
589                     EffectsList::setParameter(speedeffect, "strobe", QString::number(strobe));
590                     item->addEffect(speedeffect, false);
591                     item->effectsCounter();
592                 }
593
594                 // parse clip effects
595                 QDomNodeList effects = elem.childNodes();
596                 for (int ix = 0; ix < effects.count(); ix++) {
597                     QDomElement effect = effects.at(ix).toElement();
598                     if (effect.tagName() == "filter") {
599                         // add effect to clip
600                         QString effecttag;
601                         QString effectid;
602                         QString effectindex;
603                         QString ladspaEffectFile;
604                         // Get effect tag & index
605                         for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
606                             // parse effect parameters
607                             QDomElement effectparam = n3.toElement();
608                             if (effectparam.attribute("name") == "tag") {
609                                 effecttag = effectparam.text();
610                             } else if (effectparam.attribute("name") == "kdenlive_id") {
611                                 effectid = effectparam.text();
612                             } else if (effectparam.attribute("name") == "kdenlive_ix") {
613                                 effectindex = effectparam.text();
614                             } else if (effectparam.attribute("name") == "src") {
615                                 ladspaEffectFile = effectparam.text();
616                                 if (!QFile::exists(ladspaEffectFile)) {
617                                     // If the ladspa effect file is missing, recreate it
618                                     kDebug() << "// MISSING LADSPA FILE: " << ladspaEffectFile;
619                                     ladspaEffectFile = m_doc->getLadspaFile();
620                                     effectparam.firstChild().setNodeValue(ladspaEffectFile);
621                                     kDebug() << "// ... REPLACED WITH: " << ladspaEffectFile;
622                                 }
623                             }
624                         }
625                         //kDebug() << "+ + CLIP EFF FND: " << effecttag << ", " << effectid << ", " << effectindex;
626                         // get effect standard tags
627                         QDomElement clipeffect = MainWindow::customEffects.getEffectByTag(QString(), effectid);
628                         if (clipeffect.isNull()) clipeffect = MainWindow::videoEffects.getEffectByTag(effecttag, effectid);
629                         if (clipeffect.isNull()) clipeffect = MainWindow::audioEffects.getEffectByTag(effecttag, effectid);
630                         if (clipeffect.isNull()) {
631                             kDebug() << "///  WARNING, EFFECT: " << effecttag << ": " << effectid << " not found, removing it from project";
632                             m_documentErrors.append(i18n("Effect %1:%2 not found in MLT, it was removed from this project\n", effecttag, effectid));
633                             elem.removeChild(effects.at(ix));
634                             ix--;
635                         } else {
636                             QDomElement currenteffect = clipeffect.cloneNode().toElement();
637                             currenteffect.setAttribute("kdenlive_ix", effectindex);
638                             QDomNodeList clipeffectparams = currenteffect.childNodes();
639
640                             if (MainWindow::videoEffects.hasKeyFrames(currenteffect)) {
641                                 //kDebug() << " * * * * * * * * * * ** CLIP EFF WITH KFR FND  * * * * * * * * * * *";
642                                 // effect is key-framable, read all effects to retrieve keyframes
643                                 QString factor;
644                                 QString starttag;
645                                 QString endtag;
646                                 QDomNodeList params = currenteffect.elementsByTagName("parameter");
647                                 for (int i = 0; i < params.count(); i++) {
648                                     QDomElement e = params.item(i).toElement();
649                                     if (e.attribute("type") == "keyframe") {
650                                         starttag = e.attribute("starttag", "start");
651                                         endtag = e.attribute("endtag", "end");
652                                         factor = e.attribute("factor", "1");
653                                         break;
654                                     }
655                                 }
656                                 QString keyframes;
657                                 int effectin = effect.attribute("in").toInt();
658                                 int effectout = effect.attribute("out").toInt();
659                                 double startvalue = 0;
660                                 double endvalue = 0;
661                                 double fact;
662                                 if (factor.isEmpty()) fact = 1;
663                                 else if (factor.startsWith('%')) {
664                                     fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
665                                 } else fact = factor.toDouble();
666                                 for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
667                                     // parse effect parameters
668                                     QDomElement effectparam = n3.toElement();
669                                     if (effectparam.attribute("name") == starttag)
670                                         startvalue = effectparam.text().toDouble() * fact;
671                                     if (effectparam.attribute("name") == endtag)
672                                         endvalue = effectparam.text().toDouble() * fact;
673                                 }
674                                 // add first keyframe
675                                 keyframes.append(QString::number(effectin) + ':' + QString::number(startvalue) + ';' + QString::number(effectout) + ':' + QString::number(endvalue) + ';');
676                                 QDomNode lastParsedEffect;
677                                 ix++;
678                                 QDomNode n2 = effects.at(ix);
679                                 bool continueParsing = true;
680                                 for (; !n2.isNull() && continueParsing; n2 = n2.nextSibling()) {
681                                     // parse all effects
682                                     QDomElement kfreffect = n2.toElement();
683                                     int effectout = kfreffect.attribute("out").toInt();
684
685                                     for (QDomNode n4 = kfreffect.firstChild(); !n4.isNull(); n4 = n4.nextSibling()) {
686                                         // parse effect parameters
687                                         QDomElement subeffectparam = n4.toElement();
688                                         if (subeffectparam.attribute("name") == "kdenlive_ix" && subeffectparam.text() != effectindex) {
689                                             //We are not in the same effect, stop parsing
690                                             lastParsedEffect = n2.previousSibling();
691                                             ix--;
692                                             continueParsing = false;
693                                             break;
694                                         } else if (subeffectparam.attribute("name") == endtag) {
695                                             endvalue = subeffectparam.text().toDouble() * fact;
696                                             break;
697                                         }
698                                     }
699                                     if (continueParsing) {
700                                         keyframes.append(QString::number(effectout) + ':' + QString::number(endvalue) + ';');
701                                         ix++;
702                                     }
703                                 }
704
705                                 params = currenteffect.elementsByTagName("parameter");
706                                 for (int i = 0; i < params.count(); i++) {
707                                     QDomElement e = params.item(i).toElement();
708                                     if (e.attribute("type") == "keyframe") e.setAttribute("keyframes", keyframes);
709                                 }
710                                 if (!continueParsing) {
711                                     n2 = lastParsedEffect;
712                                 }
713                             } else {
714                                 // Check if effect has in/out points
715                                 if (effect.hasAttribute("in")) {
716                                     EffectsList::setParameter(currenteffect, "in",  effect.attribute("in"));
717                                 }
718                                 if (effect.hasAttribute("out")) {
719                                     EffectsList::setParameter(currenteffect, "out",  effect.attribute("out"));
720                                 }
721                             }
722
723                             // adjust effect parameters
724                             for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
725                                 // parse effect parameters
726                                 QDomElement effectparam = n3.toElement();
727                                 QString paramname = effectparam.attribute("name");
728                                 QString paramvalue = effectparam.text();
729
730
731                                 // try to find this parameter in the effect xml
732                                 QDomElement e;
733                                 for (int k = 0; k < clipeffectparams.count(); k++) {
734                                     e = clipeffectparams.item(k).toElement();
735                                     if (!e.isNull() && e.tagName() == "parameter" && e.attribute("name") == paramname) {
736                                         if (e.attribute("factor", "1") != "1") {
737                                             QString factor = e.attribute("factor", "1");
738                                             double fact;
739                                             if (factor.startsWith('%')) {
740                                                 fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
741                                             } else fact = factor.toDouble();
742                                             e.setAttribute("value", paramvalue.toDouble() * fact);
743                                         } else e.setAttribute("value", paramvalue);
744                                         break;
745                                     }
746                                 }
747                             }
748                             if (effecttag == "ladspa") {
749                                 //QString ladspaEffectFile = EffectsList::parameter(effect, "src", "property");
750
751                                 if (!QFile::exists(ladspaEffectFile)) {
752                                     // If the ladspa effect file is missing, recreate it
753                                     initEffects::ladspaEffectFile(ladspaEffectFile, currenteffect.attribute("ladspaid").toInt(), m_trackview->getLadspaParams(currenteffect));
754                                 }
755                                 currenteffect.setAttribute("src", ladspaEffectFile);
756                             }
757                             item->addEffect(currenteffect, false);
758                             item->effectsCounter();
759                         }
760                     }
761                 }
762             }
763             //m_clipList.append(clip);
764         }
765     }
766     //m_trackDuration = position;
767
768
769     //documentTracks.insert(ix, track);
770     kDebug() << "*************  ADD DOC TRACK " << ix << ", DURATION: " << position;
771     return position;
772     //track->show();
773 }
774
775 DocClipBase *TrackView::getMissingProducer(const QString id) const
776 {
777     QDomElement missingXml;
778     QDomDocument doc = m_doc->toXml();
779     QString docRoot = doc.documentElement().attribute("root");
780     if (!docRoot.endsWith('/')) docRoot.append('/');
781     QDomNodeList prods = doc.elementsByTagName("producer");
782     int maxprod = prods.count();
783     for (int i = 0; i < maxprod; i++) {
784         QDomNode m = prods.at(i);
785         QString prodId = m.toElement().attribute("id");
786         if (prodId == id) {
787             missingXml =  m.toElement();
788             break;
789         }
790     }
791     if (missingXml == QDomElement()) return NULL;
792
793     QDomNodeList params = missingXml.childNodes();
794     QString resource;
795     for (int j = 0; j < params.count(); j++) {
796         QDomElement e = params.item(j).toElement();
797         if (e.attribute("name") == "resource") {
798             resource = e.firstChild().nodeValue();
799             break;
800         }
801     }
802     // prepend MLT XML document root if no path in clip resource and not a color clip
803     if (!resource.startsWith('/') && !resource.startsWith("0x")) resource.prepend(docRoot);
804     DocClipBase *missingClip = NULL;
805     if (!resource.isEmpty()) {
806         QList <DocClipBase *> list = m_doc->clipManager()->getClipByResource(resource);
807         if (!list.isEmpty()) missingClip = list.at(0);
808     }
809     return missingClip;
810 }
811
812 QGraphicsScene *TrackView::projectScene()
813 {
814     return m_scene;
815 }
816
817 CustomTrackView *TrackView::projectView()
818 {
819     return m_trackview;
820 }
821
822 void TrackView::setEditMode(const QString & editMode)
823 {
824     m_editMode = editMode;
825 }
826
827 const QString & TrackView::editMode() const
828 {
829     return m_editMode;
830 }
831
832 void TrackView::slotChangeTrackLock(int ix, bool lock)
833 {
834     QList<HeaderTrack *> widgets = findChildren<HeaderTrack *>();
835     widgets.at(ix)->setLock(lock);
836 }
837
838
839 void TrackView::slotVerticalZoomDown()
840 {
841     if (m_verticalZoom == 0) return;
842     m_verticalZoom--;
843     m_doc->setZoom(m_doc->zoom().x(), m_verticalZoom);
844     if (m_verticalZoom == 0) m_trackview->setScale(m_scene->scale().x(), 0.5);
845     else m_trackview->setScale(m_scene->scale().x(), 1);
846     adjustTrackHeaders();
847     m_trackview->verticalScrollBar()->setValue(headers_area->verticalScrollBar()->value());
848 }
849
850 void TrackView::slotVerticalZoomUp()
851 {
852     if (m_verticalZoom == 2) return;
853     m_verticalZoom++;
854     m_doc->setZoom(m_doc->zoom().x(), m_verticalZoom);
855     if (m_verticalZoom == 2) m_trackview->setScale(m_scene->scale().x(), 2);
856     else m_trackview->setScale(m_scene->scale().x(), 1);
857     adjustTrackHeaders();
858     m_trackview->verticalScrollBar()->setValue(headers_area->verticalScrollBar()->value());
859 }
860
861 void TrackView::updateProjectFps()
862 {
863     m_ruler->updateProjectFps(m_doc->timecode());
864     m_trackview->updateProjectFps();
865 }
866
867 void TrackView::slotRenameTrack(int ix)
868 {
869     int tracknumber = m_doc->tracksCount() - ix;
870     TrackInfo info = m_doc->trackInfoAt(tracknumber - 1);
871     bool ok;
872     QString newName = QInputDialog::getText(this, i18n("New Track Name"), i18n("Enter new name"), QLineEdit::Normal, info.trackName, &ok);
873     if (ok) {
874         info.trackName = newName;
875         m_doc->setTrackType(tracknumber - 1, info);
876         QTimer::singleShot(300, this, SLOT(slotRebuildTrackHeaders()));
877         m_doc->setModified(true);
878     }
879 }
880
881
882 #include "trackview.moc"