]> git.sesse.net Git - kdenlive/blob - src/trackview.cpp
reindent + nice (working) progress bar for document loading
[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
38 #include <QScrollBar>
39 #include <QInputDialog>
40
41 TrackView::TrackView(KdenliveDoc *doc, bool *ok, QWidget *parent) :
42         QWidget(parent),
43         m_scale(1.0),
44         m_projectTracks(0),
45         m_doc(doc),
46         m_verticalZoom(1)
47 {
48
49     setupUi(this);
50 //    ruler_frame->setMaximumHeight();
51 //    size_frame->setMaximumHeight();
52     m_scene = new CustomTrackScene(doc);
53     m_trackview = new CustomTrackView(doc, m_scene, parent);
54     m_trackview->scale(1, 1);
55     m_trackview->setAlignment(Qt::AlignLeft | Qt::AlignTop);
56     //m_scene->addRect(QRectF(0, 0, 100, 100), QPen(), QBrush(Qt::red));
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
105     parseDocument(m_doc->toXml());
106     int error = m_doc->setSceneList();
107     if (error == -1) *ok = false;
108     else *ok = true;
109     connect(m_trackview, SIGNAL(cursorMoved(int, int)), m_ruler, SLOT(slotCursorMoved(int, int)));
110     connect(m_trackview->horizontalScrollBar(), SIGNAL(valueChanged(int)), m_ruler, SLOT(slotMoveRuler(int)));
111     connect(m_trackview, SIGNAL(mousePosition(int)), this, SIGNAL(mousePosition(int)));
112     connect(m_trackview, SIGNAL(doTrackLock(int, bool)), this, SLOT(slotChangeTrackLock(int, bool)));
113
114     slotChangeZoom(m_doc->zoom().x(), m_doc->zoom().y());
115     slotSetZone(m_doc->zone());
116 }
117
118 TrackView::~TrackView()
119 {
120     delete m_ruler;
121     delete m_trackview;
122 }
123
124 int TrackView::duration() const
125 {
126     return m_trackview->duration();
127 }
128
129 int TrackView::tracksNumber() const
130 {
131     return m_projectTracks - 1;
132 }
133
134 int TrackView::inPoint() const
135 {
136     return m_ruler->inPoint();
137 }
138
139 int TrackView::outPoint() const
140 {
141     return m_ruler->outPoint();
142 }
143
144 void TrackView::slotSetZone(QPoint p)
145 {
146     m_ruler->setZone(p);
147 }
148
149 void TrackView::setDuration(int dur)
150 {
151     m_trackview->setDuration(dur);
152     m_ruler->setDuration(dur);
153 }
154
155 void TrackView::parseDocument(QDomDocument doc)
156 {
157     //int cursorPos = 0;
158     m_documentErrors.clear();
159
160     //kDebug() << "//// DOCUMENT: " << doc.toString();
161     /*QDomNode props = doc.elementsByTagName("properties").item(0);
162     if (!props.isNull()) {
163         cursorPos = props.toElement().attribute("timeline_position").toInt();
164     }*/
165
166     // parse project tracks
167     QDomElement tractor = doc.elementsByTagName("tractor").item(0).toElement();
168     QDomNodeList tracks = doc.elementsByTagName("track");
169     QDomNodeList playlists = doc.elementsByTagName("playlist");
170     int duration = 300;
171     m_projectTracks = tracks.count();
172     int trackduration = 0;
173     QDomElement e;
174     QDomElement p;
175
176     int pos = m_projectTracks - 1;
177     m_invalidProducers.clear();
178     QDomNodeList producers = doc.elementsByTagName("producer");
179     for (int i = 0; i < producers.count(); i++) {
180         // Check for invalid producers
181         QDomNode n = producers.item(i);
182         e = n.toElement();
183
184         /*
185         // Check for invalid markup
186         QDomNodeList params = e.elementsByTagName("property");
187         for (int j = 0; j < params.count(); j++) {
188             QDomElement p = params.item(j).toElement();
189             if (p.attribute("name") == "markup") {
190          QString val = p.text().toUtf8().data();
191          kDebug()<<"//FOUND MARKUP, VAL: "<<val;
192          //e.setAttribute("value", value);
193          n.removeChild(params.item(j));
194          break;
195             }
196         }
197         */
198
199         if (e.hasAttribute("in") == false && e.hasAttribute("out") == false) continue;
200         int in = e.attribute("in").toInt();
201         int out = e.attribute("out").toInt();
202         if (in > out || in == out) {
203             // invalid producer, remove it
204             QString id = e.attribute("id");
205             m_invalidProducers.append(id);
206             m_documentErrors.append(i18n("Invalid clip producer %1\n", id));
207             doc.documentElement().removeChild(producers.at(i));
208             i--;
209         }
210     }
211
212     for (int i = 0; i < m_projectTracks; i++) {
213         e = tracks.item(i).toElement();
214         QString playlist_name = e.attribute("producer");
215         if (playlist_name != "black_track" && playlist_name != "playlistmain") {
216             // find playlist related to this track
217             p = QDomElement();
218             for (int j = 0; j < m_projectTracks; j++) {
219                 p = playlists.item(j).toElement();
220                 if (p.attribute("id") == playlist_name) break;
221             }
222             if (p.attribute("id") != playlist_name) { // then it didn't work.
223                 kDebug() << "NO PLAYLIST FOUND FOR TRACK " + pos;
224             }
225             if (e.attribute("hide") == "video") {
226                 m_doc->switchTrackVideo(i - 1, true);
227             } else if (e.attribute("hide") == "audio") {
228                 m_doc->switchTrackAudio(i - 1, true);
229             } else if (e.attribute("hide") == "both") {
230                 m_doc->switchTrackVideo(i - 1, true);
231                 m_doc->switchTrackAudio(i - 1, true);
232             }
233
234             trackduration = slotAddProjectTrack(pos, p, m_doc->isTrackLocked(i - 1));
235             pos--;
236             //kDebug() << " PRO DUR: " << trackduration << ", TRACK DUR: " << duration;
237             if (trackduration > duration) duration = trackduration;
238         } else {
239             // background black track
240             for (int j = 0; j < m_projectTracks; j++) {
241                 p = playlists.item(j).toElement();
242                 if (p.attribute("id") == playlist_name) break;
243             }
244             int black_clips = p.childNodes().count();
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     //m_trackview->setCursorPos(cursorPos);
389     //m_scrollBox->setGeometry(0, 0, 300 * zoomFactor(), m_scrollArea->height());
390 }
391
392 void TrackView::slotDeleteClip(const QString &clipId)
393 {
394     m_trackview->deleteClip(clipId);
395 }
396
397 void TrackView::setCursorPos(int pos)
398 {
399     m_trackview->setCursorPos(pos);
400 }
401
402 void TrackView::moveCursorPos(int pos)
403 {
404     m_trackview->setCursorPos(pos, false);
405 }
406
407 void TrackView::slotChangeZoom(int horizontal, int vertical)
408 {
409     m_ruler->setPixelPerMark(horizontal);
410     m_scale = (double) FRAME_SIZE / m_ruler->comboScale[horizontal];
411
412     if (vertical == -1) {
413         // user called zoom
414         m_doc->setZoom(horizontal, m_verticalZoom);
415         m_trackview->setScale(m_scale, m_scene->scale().y());
416     } else {
417         m_verticalZoom = vertical;
418         if (m_verticalZoom == 0) m_trackview->setScale(m_scale, 0.5);
419         else m_trackview->setScale(m_scale, m_verticalZoom);
420         adjustTrackHeaders();
421     }
422 }
423
424 int TrackView::fitZoom() const
425 {
426     int zoom = (int)((duration() + 20 / m_scale) * FRAME_SIZE / m_trackview->width());
427     int i;
428     for (i = 0; i < 13; i++)
429         if (m_ruler->comboScale[i] > zoom) break;
430     return i;
431 }
432
433 KdenliveDoc *TrackView::document()
434 {
435     return m_doc;
436 }
437
438 void TrackView::refresh()
439 {
440     m_trackview->viewport()->update();
441 }
442
443 void TrackView::slotRebuildTrackHeaders()
444 {
445     const QList <TrackInfo> list = m_doc->tracksList();
446     QLayoutItem *child;
447     while ((child = headers_container->layout()->takeAt(0)) != 0) {
448         QWidget *wid = child->widget();
449         delete child;
450         if (wid) wid->deleteLater();
451     }
452     int max = list.count();
453     int height = KdenliveSettings::trackheight() * m_scene->scale().y() - 1;
454     HeaderTrack *header = NULL;
455     QFrame *frame = NULL;
456     for (int i = 0; i < max; i++) {
457         frame = new QFrame(headers_container);
458         frame->setFixedHeight(1);
459         frame->setFrameStyle(QFrame::Plain);
460         frame->setFrameShape(QFrame::Box);
461         frame->setLineWidth(1);
462         headers_container->layout()->addWidget(frame);
463         TrackInfo info = list.at(max - i - 1);
464         header = new HeaderTrack(i, info, height, headers_container);
465         connect(header, SIGNAL(switchTrackVideo(int)), m_trackview, SLOT(slotSwitchTrackVideo(int)));
466         connect(header, SIGNAL(switchTrackAudio(int)), m_trackview, SLOT(slotSwitchTrackAudio(int)));
467         connect(header, SIGNAL(switchTrackLock(int)), m_trackview, SLOT(slotSwitchTrackLock(int)));
468
469         connect(header, SIGNAL(deleteTrack(int)), this, SIGNAL(deleteTrack(int)));
470         connect(header, SIGNAL(insertTrack(int)), this, SIGNAL(insertTrack(int)));
471         connect(header, SIGNAL(changeTrack(int)), this, SIGNAL(changeTrack(int)));
472         connect(header, SIGNAL(renameTrack(int)), this, SLOT(slotRenameTrack(int)));
473         headers_container->layout()->addWidget(header);
474     }
475     frame = new QFrame(this);
476     frame->setFixedHeight(1);
477     frame->setFrameStyle(QFrame::Plain);
478     frame->setFrameShape(QFrame::Box);
479     frame->setLineWidth(1);
480     headers_container->layout()->addWidget(frame);
481 }
482
483
484 void TrackView::adjustTrackHeaders()
485 {
486     int height = KdenliveSettings::trackheight() * m_scene->scale().y() - 1;
487     QLayoutItem *child;
488     for (int i = 0; i < headers_container->layout()->count(); i++) {
489         child = headers_container->layout()->itemAt(i);
490         if (child->widget() && child->widget()->height() > 5)(static_cast <HeaderTrack *>(child->widget()))->adjustSize(height);
491     }
492 }
493
494 int TrackView::slotAddProjectTrack(int ix, QDomElement xml, bool locked)
495 {
496     // parse track
497     int position = 0;
498     QDomNodeList children = xml.childNodes();
499     for (int nodeindex = 0; nodeindex < children.count(); nodeindex++) {
500         QDomNode n = children.item(nodeindex);
501         QDomElement elem = n.toElement();
502         if (elem.tagName() == "blank") {
503             position += elem.attribute("length").toInt();
504         } else if (elem.tagName() == "entry") {
505             // Found a clip
506             int in = elem.attribute("in").toInt();
507             int out = elem.attribute("out").toInt();
508             if (in > out || /*in == out ||*/ m_invalidProducers.contains(elem.attribute("producer"))) {
509                 m_documentErrors.append(i18n("Invalid clip removed from track %1 at %2\n", ix, position));
510                 xml.removeChild(children.at(nodeindex));
511                 nodeindex--;
512                 continue;
513             }
514             QString idString = elem.attribute("producer");
515             QString id = idString;
516             double speed = 1.0;
517             int strobe = 1;
518             if (idString.startsWith("slowmotion")) {
519                 id = idString.section(':', 1, 1);
520                 speed = idString.section(':', 2, 2).toDouble();
521                 strobe = idString.section(':', 3, 3).toInt();
522                 if (strobe == 0) strobe = 1;
523             } else id = id.section('_', 0, 0);
524             DocClipBase *clip = m_doc->clipManager()->getClipById(id);
525             if (clip == NULL) {
526                 // The clip in playlist was not listed in the kdenlive producers,
527                 // something went wrong, repair required.
528                 kWarning() << "CANNOT INSERT CLIP " << id;
529
530                 clip = getMissingProducer(id);
531                 if (!clip) {
532                     // We cannot find the producer, something is really wrong, add
533                     // placeholder color clip
534                     QDomDocument doc;
535                     QDomElement producerXml = doc.createElement("producer");
536                     doc.appendChild(producerXml);
537                     producerXml.setAttribute("colour", "0xff0000ff");
538                     producerXml.setAttribute("mlt_service", "colour");
539                     producerXml.setAttribute("length", "15000");
540                     producerXml.setAttribute("name", "INVALID");
541                     producerXml.setAttribute("type", COLOR);
542                     producerXml.setAttribute("id", id);
543                     clip = new DocClipBase(m_doc->clipManager(), doc.documentElement(), id);
544                     xml.insertBefore(producerXml, QDomNode());
545                     m_doc->clipManager()->addClip(clip);
546
547                     m_documentErrors.append(i18n("Broken clip producer %1", id) + '\n');
548                 } else {
549                     // Found correct producer
550                     m_documentErrors.append(i18n("Replaced wrong clip producer %1 with %2", id, clip->getId()) + '\n');
551                     elem.setAttribute("producer", clip->getId());
552                 }
553                 m_doc->setModified(true);
554             }
555
556             if (clip != NULL) {
557                 ItemInfo clipinfo;
558                 clipinfo.startPos = GenTime(position, m_doc->fps());
559                 clipinfo.endPos = clipinfo.startPos + GenTime(out - in + 1, m_doc->fps());
560                 clipinfo.cropStart = GenTime(in, m_doc->fps());
561                 clipinfo.cropDuration = GenTime((int)((clipinfo.endPos - clipinfo.startPos).frames(m_doc->fps()) * speed + 0.5), m_doc->fps());
562                 clipinfo.originalcropStart = GenTime((int)((clipinfo.cropStart).frames(m_doc->fps()) * speed + 0.5), m_doc->fps());
563
564                 clipinfo.track = ix;
565                 //kDebug() << "// INSERTING CLIP: " << in << "x" << out << ", track: " << ix << ", ID: " << id << ", SCALE: " << m_scale << ", FPS: " << m_doc->fps();
566                 ClipItem *item = new ClipItem(clip, clipinfo, m_doc->fps(), speed, strobe, false);
567                 if (idString.endsWith("_video")) item->setVideoOnly(true);
568                 else if (idString.endsWith("_audio")) item->setAudioOnly(true);
569                 m_scene->addItem(item);
570                 if (locked) item->setItemLocked(true);
571                 clip->addReference();
572                 position += (out - in + 1);
573                 kDebug() << "/////////\n\n\n" << "CLIP SPEED: " << speed << ", " << strobe << "\n\n\n/////////////////////";
574                 if (speed != 1.0 || strobe > 1) {
575                     QDomElement speedeffect = MainWindow::videoEffects.getEffectByTag(QString(), "speed").cloneNode().toElement();
576                     EffectsList::setParameter(speedeffect, "speed", QString::number((int)(100 * speed + 0.5)));
577                     EffectsList::setParameter(speedeffect, "strobe", QString::number(strobe));
578                     item->addEffect(speedeffect, false);
579                     item->effectsCounter();
580                 }
581
582                 // parse clip effects
583                 QDomNodeList effects = elem.childNodes();
584                 for (int ix = 0; ix < effects.count(); ix++) {
585                     QDomElement effect = effects.at(ix).toElement();
586                     if (effect.tagName() == "filter") {
587                         // add effect to clip
588                         QString effecttag;
589                         QString effectid;
590                         QString effectindex;
591                         QString ladspaEffectFile;
592                         // Get effect tag & index
593                         for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
594                             // parse effect parameters
595                             QDomElement effectparam = n3.toElement();
596                             if (effectparam.attribute("name") == "tag") {
597                                 effecttag = effectparam.text();
598                             } else if (effectparam.attribute("name") == "kdenlive_id") {
599                                 effectid = effectparam.text();
600                             } else if (effectparam.attribute("name") == "kdenlive_ix") {
601                                 effectindex = effectparam.text();
602                             } else if (effectparam.attribute("name") == "src") {
603                                 ladspaEffectFile = effectparam.text();
604                                 if (!QFile::exists(ladspaEffectFile)) {
605                                     // If the ladspa effect file is missing, recreate it
606                                     kDebug() << "// MISSING LADSPA FILE: " << ladspaEffectFile;
607                                     ladspaEffectFile = m_doc->getLadspaFile();
608                                     effectparam.firstChild().setNodeValue(ladspaEffectFile);
609                                     kDebug() << "// ... REPLACED WITH: " << ladspaEffectFile;
610                                 }
611                             }
612                         }
613                         //kDebug() << "+ + CLIP EFF FND: " << effecttag << ", " << effectid << ", " << effectindex;
614                         // get effect standard tags
615                         QDomElement clipeffect = MainWindow::customEffects.getEffectByTag(QString(), effectid);
616                         if (clipeffect.isNull()) clipeffect = MainWindow::videoEffects.getEffectByTag(effecttag, effectid);
617                         if (clipeffect.isNull()) clipeffect = MainWindow::audioEffects.getEffectByTag(effecttag, effectid);
618                         if (clipeffect.isNull()) {
619                             kDebug() << "///  WARNING, EFFECT: " << effecttag << ": " << effectid << " not found, removing it from project";
620                             m_documentErrors.append(i18n("Effect %1:%2 not found in MLT, it was removed from this project\n", effecttag, effectid));
621                             elem.removeChild(effects.at(ix));
622                             ix--;
623                         } else {
624                             QDomElement currenteffect = clipeffect.cloneNode().toElement();
625                             currenteffect.setAttribute("kdenlive_ix", effectindex);
626                             QDomNodeList clipeffectparams = currenteffect.childNodes();
627
628                             if (MainWindow::videoEffects.hasKeyFrames(currenteffect)) {
629                                 //kDebug() << " * * * * * * * * * * ** CLIP EFF WITH KFR FND  * * * * * * * * * * *";
630                                 // effect is key-framable, read all effects to retrieve keyframes
631                                 QString factor;
632                                 QString starttag;
633                                 QString endtag;
634                                 QDomNodeList params = currenteffect.elementsByTagName("parameter");
635                                 for (int i = 0; i < params.count(); i++) {
636                                     QDomElement e = params.item(i).toElement();
637                                     if (e.attribute("type") == "keyframe") {
638                                         starttag = e.attribute("starttag", "start");
639                                         endtag = e.attribute("endtag", "end");
640                                         factor = e.attribute("factor", "1");
641                                         break;
642                                     }
643                                 }
644                                 QString keyframes;
645                                 int effectin = effect.attribute("in").toInt();
646                                 int effectout = effect.attribute("out").toInt();
647                                 double startvalue = 0;
648                                 double endvalue = 0;
649                                 double fact;
650                                 if (factor.isEmpty()) fact = 1;
651                                 else if (factor.startsWith('%')) {
652                                     fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
653                                 } else fact = factor.toDouble();
654                                 for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
655                                     // parse effect parameters
656                                     QDomElement effectparam = n3.toElement();
657                                     if (effectparam.attribute("name") == starttag)
658                                         startvalue = effectparam.text().toDouble() * fact;
659                                     if (effectparam.attribute("name") == endtag)
660                                         endvalue = effectparam.text().toDouble() * fact;
661                                 }
662                                 // add first keyframe
663                                 keyframes.append(QString::number(effectin) + ':' + QString::number(startvalue) + ';' + QString::number(effectout) + ':' + QString::number(endvalue) + ';');
664                                 QDomNode lastParsedEffect;
665                                 ix++;
666                                 QDomNode n2 = effects.at(ix);
667                                 bool continueParsing = true;
668                                 for (; !n2.isNull() && continueParsing; n2 = n2.nextSibling()) {
669                                     // parse all effects
670                                     QDomElement kfreffect = n2.toElement();
671                                     int effectout = kfreffect.attribute("out").toInt();
672
673                                     for (QDomNode n4 = kfreffect.firstChild(); !n4.isNull(); n4 = n4.nextSibling()) {
674                                         // parse effect parameters
675                                         QDomElement subeffectparam = n4.toElement();
676                                         if (subeffectparam.attribute("name") == "kdenlive_ix" && subeffectparam.text() != effectindex) {
677                                             //We are not in the same effect, stop parsing
678                                             lastParsedEffect = n2.previousSibling();
679                                             ix--;
680                                             continueParsing = false;
681                                             break;
682                                         } else if (subeffectparam.attribute("name") == endtag) {
683                                             endvalue = subeffectparam.text().toDouble() * fact;
684                                             break;
685                                         }
686                                     }
687                                     if (continueParsing) {
688                                         keyframes.append(QString::number(effectout) + ':' + QString::number(endvalue) + ';');
689                                         ix++;
690                                     }
691                                 }
692
693                                 params = currenteffect.elementsByTagName("parameter");
694                                 for (int i = 0; i < params.count(); i++) {
695                                     QDomElement e = params.item(i).toElement();
696                                     if (e.attribute("type") == "keyframe") e.setAttribute("keyframes", keyframes);
697                                 }
698                                 if (!continueParsing) {
699                                     n2 = lastParsedEffect;
700                                 }
701                             } else {
702                                 // Check if effect has in/out points
703                                 if (effect.hasAttribute("in")) {
704                                     EffectsList::setParameter(currenteffect, "in",  effect.attribute("in"));
705                                 }
706                                 if (effect.hasAttribute("out")) {
707                                     EffectsList::setParameter(currenteffect, "out",  effect.attribute("out"));
708                                 }
709                             }
710
711                             // adjust effect parameters
712                             for (QDomNode n3 = effect.firstChild(); !n3.isNull(); n3 = n3.nextSibling()) {
713                                 // parse effect parameters
714                                 QDomElement effectparam = n3.toElement();
715                                 QString paramname = effectparam.attribute("name");
716                                 QString paramvalue = effectparam.text();
717
718
719                                 // try to find this parameter in the effect xml
720                                 QDomElement e;
721                                 for (int k = 0; k < clipeffectparams.count(); k++) {
722                                     e = clipeffectparams.item(k).toElement();
723                                     if (!e.isNull() && e.tagName() == "parameter" && e.attribute("name") == paramname) {
724                                         if (e.attribute("factor", "1") != "1") {
725                                             QString factor = e.attribute("factor", "1");
726                                             double fact;
727                                             if (factor.startsWith('%')) {
728                                                 fact = ProfilesDialog::getStringEval(m_doc->mltProfile(), factor);
729                                             } else fact = factor.toDouble();
730                                             e.setAttribute("value", paramvalue.toDouble() * fact);
731                                         } else e.setAttribute("value", paramvalue);
732                                         break;
733                                     }
734                                 }
735                             }
736                             if (effecttag == "ladspa") {
737                                 //QString ladspaEffectFile = EffectsList::parameter(effect, "src", "property");
738
739                                 if (!QFile::exists(ladspaEffectFile)) {
740                                     // If the ladspa effect file is missing, recreate it
741                                     initEffects::ladspaEffectFile(ladspaEffectFile, currenteffect.attribute("ladspaid").toInt(), m_trackview->getLadspaParams(currenteffect));
742                                 }
743                                 currenteffect.setAttribute("src", ladspaEffectFile);
744                             }
745                             item->addEffect(currenteffect, false);
746                             item->effectsCounter();
747                         }
748                     }
749                 }
750             }
751             //m_clipList.append(clip);
752         }
753     }
754     //m_trackDuration = position;
755
756
757     //documentTracks.insert(ix, track);
758     kDebug() << "*************  ADD DOC TRACK " << ix << ", DURATION: " << position;
759     return position;
760     //track->show();
761 }
762
763 DocClipBase *TrackView::getMissingProducer(const QString id) const
764 {
765     QDomElement missingXml;
766     QDomDocument doc = m_doc->toXml();
767     QString docRoot = doc.documentElement().attribute("root");
768     if (!docRoot.endsWith('/')) docRoot.append('/');
769     QDomNodeList prods = doc.elementsByTagName("producer");
770     int maxprod = prods.count();
771     for (int i = 0; i < maxprod; i++) {
772         QDomNode m = prods.at(i);
773         QString prodId = m.toElement().attribute("id");
774         if (prodId == id) {
775             missingXml =  m.toElement();
776             break;
777         }
778     }
779     if (missingXml == QDomElement()) return NULL;
780
781     QDomNodeList params = missingXml.childNodes();
782     QString resource;
783     for (int j = 0; j < params.count(); j++) {
784         QDomElement e = params.item(j).toElement();
785         if (e.attribute("name") == "resource") {
786             resource = e.firstChild().nodeValue();
787             break;
788         }
789     }
790     // prepend MLT XML document root if no path in clip resource and not a color clip
791     if (!resource.startsWith('/') && !resource.startsWith("0x")) resource.prepend(docRoot);
792     DocClipBase *missingClip = NULL;
793     if (!resource.isEmpty()) {
794         QList <DocClipBase *> list = m_doc->clipManager()->getClipByResource(resource);
795         if (!list.isEmpty()) missingClip = list.at(0);
796     }
797     return missingClip;
798 }
799
800 QGraphicsScene *TrackView::projectScene()
801 {
802     return m_scene;
803 }
804
805 CustomTrackView *TrackView::projectView()
806 {
807     return m_trackview;
808 }
809
810 void TrackView::setEditMode(const QString & editMode)
811 {
812     m_editMode = editMode;
813 }
814
815 const QString & TrackView::editMode() const
816 {
817     return m_editMode;
818 }
819
820 void TrackView::slotChangeTrackLock(int ix, bool lock)
821 {
822     QList<HeaderTrack *> widgets = findChildren<HeaderTrack *>();
823     widgets.at(ix)->setLock(lock);
824 }
825
826
827 void TrackView::slotVerticalZoomDown()
828 {
829     if (m_verticalZoom == 0) return;
830     m_verticalZoom--;
831     m_doc->setZoom(m_doc->zoom().x(), m_verticalZoom);
832     if (m_verticalZoom == 0) m_trackview->setScale(m_scene->scale().x(), 0.5);
833     else m_trackview->setScale(m_scene->scale().x(), 1);
834     adjustTrackHeaders();
835     m_trackview->verticalScrollBar()->setValue(headers_area->verticalScrollBar()->value());
836 }
837
838 void TrackView::slotVerticalZoomUp()
839 {
840     if (m_verticalZoom == 2) return;
841     m_verticalZoom++;
842     m_doc->setZoom(m_doc->zoom().x(), m_verticalZoom);
843     if (m_verticalZoom == 2) m_trackview->setScale(m_scene->scale().x(), 2);
844     else m_trackview->setScale(m_scene->scale().x(), 1);
845     adjustTrackHeaders();
846     m_trackview->verticalScrollBar()->setValue(headers_area->verticalScrollBar()->value());
847 }
848
849 void TrackView::updateProjectFps()
850 {
851     m_ruler->updateProjectFps(m_doc->timecode());
852     m_trackview->updateProjectFps();
853 }
854
855 void TrackView::slotRenameTrack(int ix)
856 {
857     int tracknumber = m_doc->tracksCount() - ix;
858     TrackInfo info = m_doc->trackInfoAt(tracknumber - 1);
859     bool ok;
860     QString newName = QInputDialog::getText(this, i18n("New Track Name"), i18n("Enter new name"), QLineEdit::Normal, info.trackName, &ok);
861     if (ok) {
862         info.trackName = newName;
863         m_doc->setTrackType(tracknumber - 1, info);
864         QTimer::singleShot(300, this, SLOT(slotRebuildTrackHeaders()));
865         m_doc->setModified(true);
866     }
867 }
868
869
870 #include "trackview.moc"