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