]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
Fix display of clip duration in project tree + some cleanup + indent fixes
[kdenlive] / src / kdenlivedoc.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 "kdenlivedoc.h"
22 #include "docclipbase.h"
23 #include "profilesdialog.h"
24 #include "kdenlivesettings.h"
25 #include "renderer.h"
26 #include "clipmanager.h"
27 #include "titlewidget.h"
28 #include "mainwindow.h"
29
30 #include <KDebug>
31 #include <KStandardDirs>
32 #include <KMessageBox>
33 #include <KLocale>
34 #include <KFileDialog>
35 #include <KIO/NetAccess>
36 #include <KIO/CopyJob>
37 #include <KApplication>
38
39 #include <QCryptographicHash>
40 #include <QFile>
41
42 #include <mlt++/Mlt.h>
43
44
45 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, const QString &profileName, const QPoint tracks, Render *render, MainWindow *parent): QObject(parent), m_render(render), m_url(url), m_projectFolder(projectFolder), m_commandStack(new QUndoStack(undoGroup)), m_modified(false), m_documentLoadingProgress(0), m_documentLoadingStep(0.0), m_startPos(0), m_zoom(7), m_autosave(NULL), m_zoneStart(0), m_zoneEnd(100), m_abortLoading(false) {
46     m_clipManager = new ClipManager(this);
47     m_autoSaveTimer = new QTimer(this);
48     m_autoSaveTimer->setSingleShot(true);
49     if (!url.isEmpty()) {
50         QString tmpFile;
51         if (KIO::NetAccess::download(url.path(), tmpFile, parent)) {
52             QFile file(tmpFile);
53             m_document.setContent(&file, false);
54             file.close();
55             QDomNode infoXmlNode = m_document.elementsByTagName("kdenlivedoc").at(0);
56             QDomNode westley = m_document.elementsByTagName("westley").at(0);
57             if (!infoXmlNode.isNull()) {
58                 QDomElement infoXml = infoXmlNode.toElement();
59                 double version = infoXml.attribute("version").toDouble();
60
61                 // Upgrade old Kdenlive documents to current version
62                 if (!convertDocument(version)) {
63                     KMessageBox::sorry(parent, i18n("This project type is unsupported and can't be loaded."), i18n("Unable to open project"));
64                     m_document = createEmptyDocument(tracks.x(), tracks.y());
65                     setProfilePath(profileName);
66                 } else {
67                     /*
68                      * read again <kdenlivedoc> and <westley> to get all the new
69                      * stuff (convertDocument() can now do anything without breaking
70                      * document loading)
71                      */
72                     infoXmlNode = m_document.elementsByTagName("kdenlivedoc").at(0);
73                     infoXml = infoXmlNode.toElement();
74                     version = infoXml.attribute("version").toDouble();
75                     westley = m_document.elementsByTagName("westley").at(0);
76
77                     QString profilePath = infoXml.attribute("profile");
78                     QString projectFolderPath = infoXml.attribute("projectfolder");
79                     if (!projectFolderPath.isEmpty()) m_projectFolder = KUrl(projectFolderPath);
80
81                     if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
82                         // Make sure the project folder is usable
83                         KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
84                         m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
85                     }
86                     m_startPos = infoXml.attribute("position").toInt();
87                     m_zoom = infoXml.attribute("zoom", "7").toInt();
88                     m_zoneEnd = infoXml.attribute("zoneout", "100").toInt();
89                     setProfilePath(profilePath);
90
91                     // Build tracks
92                     QDomElement e;
93                     QDomNode tracksinfo = m_document.elementsByTagName("tracksinfo").at(0);
94                     TrackInfo projectTrack;
95                     if (!tracksinfo.isNull()) {
96                         QDomNodeList trackslist = tracksinfo.childNodes();
97                         int maxchild = trackslist.count();
98                         for (int k = 0; k < maxchild; k++) {
99                             e = trackslist.at(k).toElement();
100                             if (e.tagName() == "trackinfo") {
101                                 if (e.attribute("type") == "audio") projectTrack.type = AUDIOTRACK;
102                                 else projectTrack.type = VIDEOTRACK;
103                                 projectTrack.isMute = e.attribute("mute").toInt();
104                                 projectTrack.isBlind = e.attribute("blind").toInt();
105                                 projectTrack.isLocked = e.attribute("locked").toInt();
106                                 m_tracksList.append(projectTrack);
107                             }
108                         }
109                         westley.removeChild(tracksinfo);
110                     }
111
112                     QDomNodeList producers = m_document.elementsByTagName("producer");
113                     QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
114                     const int max = producers.count();
115                     const int infomax = infoproducers.count();
116
117                     QDomNodeList folders = m_document.elementsByTagName("folder");
118                     for (int i = 0; i < folders.count(); i++) {
119                         e = folders.item(i).cloneNode().toElement();
120                         m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
121                     }
122
123                     if (max > 0) {
124                         m_documentLoadingStep = 100.0 / (max + infomax + m_document.elementsByTagName("entry").count());
125                         parent->slotGotProgressInfo(i18n("Loading project clips"), (int) m_documentLoadingProgress);
126                     }
127
128
129                     for (int i = 0; i < infomax && !m_abortLoading; i++) {
130                         e = infoproducers.item(i).cloneNode().toElement();
131                         if (m_documentLoadingStep > 0) {
132                             m_documentLoadingProgress += m_documentLoadingStep;
133                             parent->slotGotProgressInfo(QString(), (int) m_documentLoadingProgress);
134                             //qApp->processEvents();
135                         }
136                         QString prodId = e.attribute("id");
137                         if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion") && !m_abortLoading) {
138                             e.setTagName("producer");
139                             // Get MLT's original producer properties
140                             QDomElement orig;
141                             for (int j = 0; j < max; j++) {
142                                 QDomElement o = producers.item(j).cloneNode().toElement();
143                                 QString origId = o.attribute("id").section('_', 0, 0);
144                                 if (origId == prodId) {
145                                     orig = o;
146                                     break;
147                                 }
148                             }
149                             addClipInfo(e, orig, prodId);
150                             kDebug() << "// NLIVE PROD: " << prodId;
151                         }
152                     }
153                     if (m_abortLoading) {
154                         //parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
155                         emit resetProjectList();
156                         m_startPos = 0;
157                         m_url = KUrl();
158                         m_tracksList.clear();
159                         kWarning() << "Aborted loading of: " << url.path();
160                         m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
161                         setProfilePath(KdenliveSettings::default_profile());
162                         m_clipManager->clear();
163                     } else {
164                         QDomNode markers = m_document.elementsByTagName("markers").at(0);
165                         if (!markers.isNull()) {
166                             QDomNodeList markerslist = markers.childNodes();
167                             int maxchild = markerslist.count();
168                             for (int k = 0; k < maxchild; k++) {
169                                 e = markerslist.at(k).toElement();
170                                 if (e.tagName() == "marker") {
171                                     m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
172                                 }
173                             }
174                             westley.removeChild(markers);
175                         }
176                         m_document.removeChild(infoXmlNode);
177                         kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
178                     }
179                 }
180             } else {
181                 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
182                 kWarning() << "  NO KDENLIVE INFO FOUND IN FILE: " << url.path();
183                 m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
184                 m_url = KUrl();
185                 setProfilePath(KdenliveSettings::default_profile());
186             }
187             KIO::NetAccess::removeTempFile(tmpFile);
188         } else {
189             KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
190             parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
191             m_url = KUrl();
192             m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
193             setProfilePath(KdenliveSettings::default_profile());
194         }
195     } else {
196         m_document = createEmptyDocument(tracks.x(), tracks.y());
197         setProfilePath(profileName);
198     }
199     if (m_projectFolder.isEmpty()) m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
200
201     // make sure that the necessary folders exist
202     KStandardDirs::makeDir(m_projectFolder.path() + "/titles/");
203     KStandardDirs::makeDir(m_projectFolder.path() + "/thumbs/");
204     KStandardDirs::makeDir(m_projectFolder.path() + "/ladspa/");
205
206     kDebug() << "KDEnlive document, init timecode: " << m_fps;
207     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
208     else m_timecode.setFormat((int) m_fps);
209
210     //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
211     connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
212
213 }
214
215 KdenliveDoc::~KdenliveDoc() {
216     delete m_commandStack;
217     delete m_clipManager;
218     delete m_autoSaveTimer;
219     if (m_autosave) {
220         m_autosave->remove();
221         delete m_autosave;
222     }
223 }
224
225 void KdenliveDoc::setSceneList() {
226     m_render->setSceneList(m_document.toString(), m_startPos);
227     checkProjectClips();
228 }
229
230 QDomDocument KdenliveDoc::createEmptyDocument(const int videotracks, const int audiotracks) {
231     // Creating new document
232     QDomDocument doc;
233     QDomElement westley = doc.createElement("westley");
234     doc.appendChild(westley);
235
236
237     TrackInfo videoTrack;
238     videoTrack.type = VIDEOTRACK;
239     videoTrack.isMute = false;
240     videoTrack.isBlind = false;
241     videoTrack.isLocked = false;
242
243     TrackInfo audioTrack;
244     audioTrack.type = AUDIOTRACK;
245     audioTrack.isMute = false;
246     audioTrack.isBlind = true;
247     audioTrack.isLocked = false;
248
249     QDomElement tractor = doc.createElement("tractor");
250     tractor.setAttribute("id", "maintractor");
251     QDomElement multitrack = doc.createElement("multitrack");
252     QDomElement playlist = doc.createElement("playlist");
253     playlist.setAttribute("id", "black_track");
254     westley.appendChild(playlist);
255
256
257     // create playlists
258     int total = audiotracks + videotracks + 1;
259
260     for (int i = 1; i < total; i++) {
261         QDomElement playlist = doc.createElement("playlist");
262         playlist.setAttribute("id", "playlist" + QString::number(i));
263         westley.appendChild(playlist);
264     }
265
266     QDomElement track0 = doc.createElement("track");
267     track0.setAttribute("producer", "black_track");
268     tractor.appendChild(track0);
269
270     // create audio tracks
271     for (int i = 1; i < audiotracks + 1; i++) {
272         QDomElement track = doc.createElement("track");
273         track.setAttribute("producer", "playlist" + QString::number(i));
274         track.setAttribute("hide", "video");
275         tractor.appendChild(track);
276         m_tracksList.append(audioTrack);
277     }
278
279     // create video tracks
280     for (int i = audiotracks + 1; i < total; i++) {
281         QDomElement track = doc.createElement("track");
282         track.setAttribute("producer", "playlist" + QString::number(i));
283         tractor.appendChild(track);
284         m_tracksList.append(videoTrack);
285     }
286
287     for (uint i = 2; i < total ; i++) {
288         QDomElement transition = doc.createElement("transition");
289         transition.setAttribute("always_active", "1");
290
291         QDomElement property = doc.createElement("property");
292         property.setAttribute("name", "a_track");
293         QDomText value = doc.createTextNode(QString::number(1));
294         property.appendChild(value);
295         transition.appendChild(property);
296
297         property = doc.createElement("property");
298         property.setAttribute("name", "b_track");
299         value = doc.createTextNode(QString::number(i));
300         property.appendChild(value);
301         transition.appendChild(property);
302
303         property = doc.createElement("property");
304         property.setAttribute("name", "mlt_service");
305         value = doc.createTextNode("mix");
306         property.appendChild(value);
307         transition.appendChild(property);
308
309         property = doc.createElement("property");
310         property.setAttribute("name", "combine");
311         value = doc.createTextNode("1");
312         property.appendChild(value);
313         transition.appendChild(property);
314
315         property = doc.createElement("property");
316         property.setAttribute("name", "internal_added");
317         value = doc.createTextNode("237");
318         property.appendChild(value);
319         transition.appendChild(property);
320         tractor.appendChild(transition);
321     }
322     westley.appendChild(tractor);
323     return doc;
324 }
325
326
327 void KdenliveDoc::syncGuides(QList <Guide *> guides) {
328     QDomDocument doc;
329     QDomElement e;
330     m_guidesXml.clear();
331     m_guidesXml = doc.createElement("guides");
332
333     for (int i = 0; i < guides.count(); i++) {
334         e = doc.createElement("guide");
335         e.setAttribute("time", guides.at(i)->position().ms() / 1000);
336         e.setAttribute("comment", guides.at(i)->label());
337         m_guidesXml.appendChild(e);
338     }
339     emit guidesUpdated();
340 }
341
342 QDomElement KdenliveDoc::guidesXml() const {
343     return m_guidesXml;
344 }
345
346 void KdenliveDoc::slotAutoSave() {
347     if (m_render && m_autosave) {
348         if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
349             // show error: could not open the autosave file
350             kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
351         }
352         kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
353         QString doc;
354         if (KdenliveSettings::dropbframes()) {
355             KdenliveSettings::setDropbframes(false);
356             m_clipManager->updatePreviewSettings();
357             doc = m_render->sceneList();
358             KdenliveSettings::setDropbframes(true);
359             m_clipManager->updatePreviewSettings();
360         } else doc = m_render->sceneList();
361         saveSceneList(m_autosave->fileName(), doc);
362     }
363 }
364
365 void KdenliveDoc::setZoom(int factor) {
366     m_zoom = factor;
367 }
368
369 int KdenliveDoc::zoom() const {
370     return m_zoom;
371 }
372
373 bool KdenliveDoc::convertDocument(double version) {
374     kDebug() << "Opening a document with version " << version;
375
376     if (version == 0.82) return true;
377
378     if (version == 0.81) {
379         // Add correct tracks info
380         QDomNode kdenlivedoc = m_document.elementsByTagName("kdenlivedoc").at(0);
381         QDomElement infoXml = kdenlivedoc.toElement();
382         QString currentTrackOrder = infoXml.attribute("tracks");
383         QDomElement tracksinfo = m_document.createElement("tracksinfo");
384         for (int i = 0; i < currentTrackOrder.size(); i++) {
385             QDomElement trackinfo = m_document.createElement("trackinfo");
386             if (currentTrackOrder.data()[i] == 'a') {
387                 trackinfo.setAttribute("type", "audio");
388                 trackinfo.setAttribute("blind", true);
389             } else trackinfo.setAttribute("blind", false);
390             trackinfo.setAttribute("mute", false);
391             trackinfo.setAttribute("locked", false);
392             tracksinfo.appendChild(trackinfo);
393         }
394         infoXml.appendChild(tracksinfo);
395         return true;
396     }
397
398     // Opening a old Kdenlive document
399     if (version == 0.5 || version == 0.7 || version > 0.81) {
400         kDebug() << "Unable to open document with version " << version;
401         // TODO: convert 0.7 (0.5?) files to the new document format.
402         return false;
403     }
404
405     if (version == 0.8) {
406         // Add the tracks information
407         QDomNodeList tracks = m_document.elementsByTagName("track");
408         int max = tracks.count();
409
410         QDomNode kdenlivedoc = m_document.elementsByTagName("kdenlivedoc").at(0);
411         QDomElement infoXml = kdenlivedoc.toElement();
412         QDomElement tracksinfo = m_document.createElement("tracksinfo");
413
414         for (int i = 0; i < max; i++) {
415             QDomElement trackinfo = m_document.createElement("trackinfo");
416             QDomElement t = tracks.at(i).toElement();
417             if (t.attribute("hide") == "video") {
418                 trackinfo.setAttribute("type", "audio");
419                 trackinfo.setAttribute("blind", true);
420             } else trackinfo.setAttribute("blind", false);
421             trackinfo.setAttribute("mute", false);
422             trackinfo.setAttribute("locked", false);
423             if (t.attribute("producer") != "black_track") tracksinfo.appendChild(trackinfo);
424         }
425         infoXml.appendChild(tracksinfo);
426         return true;
427     }
428
429     QDomNode westley = m_document.elementsByTagName("westley").at(1);
430     QDomNode tractor = m_document.elementsByTagName("tractor").at(0);
431     QDomNode kdenlivedoc = m_document.elementsByTagName("kdenlivedoc").at(0);
432     QDomElement kdenlivedoc_old = kdenlivedoc.cloneNode(true).toElement(); // Needed for folders
433     QDomNode multitrack = m_document.elementsByTagName("multitrack").at(0);
434     QDomNodeList playlists = m_document.elementsByTagName("playlist");
435
436     QDomNode props = m_document.elementsByTagName("properties").at(0).toElement();
437     QString profile = props.toElement().attribute("videoprofile");
438     m_startPos = props.toElement().attribute("timeline_position").toInt();
439     if (profile == "dv_wide") profile = "dv_pal_wide";
440
441     // move playlists outside of tractor and add the tracks instead
442     int max = playlists.count();
443     for (int i = 0; i < max; i++) {
444         QDomNode n = playlists.at(i);
445         westley.insertBefore(n, QDomNode());
446         QDomElement pl = n.toElement();
447         QDomElement track = m_document.createElement("track");
448         QString trackType = pl.attribute("hide");
449         if (!trackType.isEmpty())
450             track.setAttribute("hide", trackType);
451         QString playlist_id =  pl.attribute("id");
452         if (playlist_id.isEmpty()) {
453             playlist_id = "black_track";
454             pl.setAttribute("id", playlist_id);
455         }
456         track.setAttribute("producer", playlist_id);
457         //tractor.appendChild(track);
458 #define KEEP_TRACK_ORDER 1
459 #ifdef KEEP_TRACK_ORDER
460         tractor.insertAfter(track, QDomNode());
461 #else
462         // Insert the new track in an order that hopefully matches the 3 video, then 2 audio tracks of Kdenlive 0.7.0
463         // insertion sort - O( tracks*tracks )
464         // Note, this breaks _all_ transitions - but you can move them up and down afterwards.
465         QDomElement tractor_elem = tractor.toElement();
466         if (! tractor_elem.isNull()) {
467             QDomNodeList tracks = tractor_elem.elementsByTagName("track");
468             int size = tracks.size();
469             if (size == 0) {
470                 tractor.insertAfter(track, QDomNode());
471             } else {
472                 bool inserted = false;
473                 for (int i = 0; i < size; ++i) {
474                     QDomElement track_elem = tracks.at(i).toElement();
475                     if (track_elem.isNull()) {
476                         tractor.insertAfter(track, QDomNode());
477                         inserted = true;
478                         break;
479                     } else {
480                         kDebug() << "playlist_id: " << playlist_id << " producer:" << track_elem.attribute("producer");
481                         if (playlist_id < track_elem.attribute("producer")) {
482                             tractor.insertBefore(track, track_elem);
483                             inserted = true;
484                             break;
485                         }
486                     }
487                 }
488                 // Reach here, no insertion, insert last
489                 if (!inserted) {
490                     tractor.insertAfter(track, QDomNode());
491                 }
492             }
493         } else {
494             kWarning() << "tractor was not a QDomElement";
495             tractor.insertAfter(track, QDomNode());
496         }
497 #endif
498     }
499     tractor.removeChild(multitrack);
500
501     // audio track mixing transitions should not be added to track view, so add required attribute
502     QDomNodeList transitions = m_document.elementsByTagName("transition");
503     max = transitions.count();
504     for (int i = 0; i < max; i++) {
505         QDomElement tr = transitions.at(i).toElement();
506         if (tr.attribute("combine") == "1" && tr.attribute("mlt_service") == "mix") {
507             QDomElement property = m_document.createElement("property");
508             property.setAttribute("name", "internal_added");
509             QDomText value = m_document.createTextNode("237");
510             property.appendChild(value);
511             tr.appendChild(property);
512         } else {
513             // convert transition
514             QDomNamedNodeMap attrs = tr.attributes();
515             for (unsigned int j = 0; j < attrs.count(); j++) {
516                 QString attrName = attrs.item(j).nodeName();
517                 if (attrName != "in" && attrName != "out" && attrName != "id") {
518                     QDomElement property = m_document.createElement("property");
519                     property.setAttribute("name", attrName);
520                     QDomText value = m_document.createTextNode(attrs.item(j).nodeValue());
521                     property.appendChild(value);
522                     tr.appendChild(property);
523                 }
524             }
525         }
526     }
527
528     // move transitions after tracks
529     for (int i = 0; i < max; i++) {
530         tractor.insertAfter(transitions.at(0), QDomNode());
531     }
532
533     // Fix filters format
534     QDomNodeList entries = m_document.elementsByTagName("entry");
535     max = entries.count();
536     for (int i = 0; i < max; i++) {
537         QString last_id;
538         int effectix = 0;
539         QDomNode m = entries.at(i).firstChild();
540         while (!m.isNull()) {
541             if (m.toElement().tagName() == "filter") {
542                 QDomElement filt = m.toElement();
543                 QDomNamedNodeMap attrs = filt.attributes();
544                 QString current_id = filt.attribute("kdenlive_id");
545                 if (current_id != last_id) {
546                     effectix++;
547                     last_id = current_id;
548                 }
549                 QDomElement e = m_document.createElement("property");
550                 e.setAttribute("name", "kdenlive_ix");
551                 QDomText value = m_document.createTextNode(QString::number(effectix));
552                 e.appendChild(value);
553                 filt.appendChild(e);
554                 for (int j = 0; j < attrs.count(); j++) {
555                     QDomAttr a = attrs.item(j).toAttr();
556                     if (!a.isNull()) {
557                         kDebug() << " FILTER; adding :" << a.name() << ":" << a.value();
558                         QDomElement e = m_document.createElement("property");
559                         e.setAttribute("name", a.name());
560                         QDomText value = m_document.createTextNode(a.value());
561                         e.appendChild(value);
562                         filt.appendChild(e);
563
564                     }
565                 }
566             }
567             m = m.nextSibling();
568         }
569     }
570
571     /*
572         QDomNodeList filters = m_document.elementsByTagName("filter");
573         max = filters.count();
574         QString last_id;
575         int effectix = 0;
576         for (int i = 0; i < max; i++) {
577             QDomElement filt = filters.at(i).toElement();
578             QDomNamedNodeMap attrs = filt.attributes();
579      QString current_id = filt.attribute("kdenlive_id");
580      if (current_id != last_id) {
581          effectix++;
582          last_id = current_id;
583      }
584      QDomElement e = m_document.createElement("property");
585             e.setAttribute("name", "kdenlive_ix");
586             QDomText value = m_document.createTextNode(QString::number(1));
587             e.appendChild(value);
588             filt.appendChild(e);
589             for (int j = 0; j < attrs.count(); j++) {
590                 QDomAttr a = attrs.item(j).toAttr();
591                 if (!a.isNull()) {
592                     kDebug() << " FILTER; adding :" << a.name() << ":" << a.value();
593                     QDomElement e = m_document.createElement("property");
594                     e.setAttribute("name", a.name());
595                     QDomText value = m_document.createTextNode(a.value());
596                     e.appendChild(value);
597                     filt.appendChild(e);
598                 }
599             }
600         }*/
601
602     // fix slowmotion
603     QDomNodeList producers = westley.toElement().elementsByTagName("producer");
604     max = producers.count();
605     for (int i = 0; i < max; i++) {
606         QDomElement prod = producers.at(i).toElement();
607         if (prod.attribute("mlt_service") == "framebuffer") {
608             QString slowmotionprod = prod.attribute("resource");
609             slowmotionprod.replace(':', '?');
610             kDebug() << "// FOUND WRONG SLOWMO, new: " << slowmotionprod;
611             prod.setAttribute("resource", slowmotionprod);
612         }
613     }
614     // move producers to correct place, markers to a global list, fix clip descriptions
615     QDomElement markers = m_document.createElement("markers");
616     // This will get the westley producers:
617     producers = m_document.elementsByTagName("producer");
618     max = producers.count();
619     for (int i = 0; i < max; i++) {
620         QDomElement prod = producers.at(0).toElement();
621         // add resource also as a property (to allow path correction in setNewResource())
622         // TODO: will it work with slowmotion? needs testing
623         if (!prod.attribute("resource").isEmpty()) {
624             QDomElement prop_resource = m_document.createElement("property");
625             prop_resource.setAttribute("name", "resource");
626             QDomText resource = m_document.createTextNode(prod.attribute("resource"));
627             prop_resource.appendChild(resource);
628             prod.appendChild(prop_resource);
629         }
630         QDomNode m = prod.firstChild();
631         if (!m.isNull()) {
632             if (m.toElement().tagName() == "markers") {
633                 QDomNodeList prodchilds = m.childNodes();
634                 int maxchild = prodchilds.count();
635                 for (int k = 0; k < maxchild; k++) {
636                     QDomElement mark = prodchilds.at(0).toElement();
637                     mark.setAttribute("id", prod.attribute("id"));
638                     markers.insertAfter(mark, QDomNode());
639                 }
640                 prod.removeChild(m);
641             } else if (prod.attribute("type").toInt() == TEXT) {
642                 // convert title clip
643                 if (m.toElement().tagName() == "textclip") {
644                     QDomDocument tdoc;
645                     QDomElement titleclip = m.toElement();
646                     QDomElement title = tdoc.createElement("kdenlivetitle");
647                     tdoc.appendChild(title);
648                     QDomNodeList objects = titleclip.childNodes();
649                     int maxchild = objects.count();
650                     for (int k = 0; k < maxchild; k++) {
651                         QString objectxml;
652                         QDomElement ob = objects.at(k).toElement();
653                         if (ob.attribute("type") == "3") {
654                             // text object - all of this goes into "xmldata"...
655                             QDomElement item = tdoc.createElement("item");
656                             item.setAttribute("z-index", ob.attribute("z"));
657                             item.setAttribute("type", "QGraphicsTextItem");
658                             QDomElement position = tdoc.createElement("position");
659                             position.setAttribute("x", ob.attribute("x"));
660                             position.setAttribute("y", ob.attribute("y"));
661                             QDomElement content = tdoc.createElement("content");
662                             content.setAttribute("font", ob.attribute("font_family"));
663                             content.setAttribute("font-size", ob.attribute("font_size"));
664                             content.setAttribute("font-bold", ob.attribute("bold"));
665                             content.setAttribute("font-italic", ob.attribute("italic"));
666                             content.setAttribute("font-underline", ob.attribute("underline"));
667                             QString col = ob.attribute("color");
668                             QColor c(col);
669                             content.setAttribute("font-color", colorToString(c));
670                             // todo: These fields are missing from the newly generated xmldata:
671                             // transform, startviewport, endviewport, background
672
673                             QDomText conttxt = tdoc.createTextNode(ob.attribute("text"));
674                             content.appendChild(conttxt);
675                             item.appendChild(position);
676                             item.appendChild(content);
677                             title.appendChild(item);
678                         } else if (ob.attribute("type") == "5") {
679                             // rectangle object
680                             QDomElement item = tdoc.createElement("item");
681                             item.setAttribute("z-index", ob.attribute("z"));
682                             item.setAttribute("type", "QGraphicsRectItem");
683                             QDomElement position = tdoc.createElement("position");
684                             position.setAttribute("x", ob.attribute("x"));
685                             position.setAttribute("y", ob.attribute("y"));
686                             QDomElement content = tdoc.createElement("content");
687                             QString col = ob.attribute("color");
688                             QColor c(col);
689                             content.setAttribute("brushcolor", colorToString(c));
690                             QString rect = "0,0,";
691                             rect.append(ob.attribute("width"));
692                             rect.append(",");
693                             rect.append(ob.attribute("height"));
694                             content.setAttribute("rect", rect);
695                             item.appendChild(position);
696                             item.appendChild(content);
697                             title.appendChild(item);
698                         }
699                     }
700                     prod.setAttribute("xmldata", tdoc.toString());
701                     // mbd todo: This clearly does not work, as every title gets the same name - trying to leave it empty
702                     // QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
703                     // prod.setAttribute("titlename", titleInfo.at(0));
704                     // prod.setAttribute("resource", titleInfo.at(1));
705                     //kDebug()<<"TITLE DATA:\n"<<tdoc.toString();
706                     prod.removeChild(m);
707                 } // End conversion of title clips.
708
709             } else if (m.isText()) {
710                 QString comment = m.nodeValue();
711                 if (!comment.isEmpty()) {
712                     prod.setAttribute("description", comment);
713                 }
714                 prod.removeChild(m);
715             }
716         }
717         int duration = prod.attribute("duration").toInt();
718         if (duration > 0) prod.setAttribute("out", QString::number(duration));
719         // The clip goes back in, but text clips should not go back in, at least not modified
720         westley.insertBefore(prod, QDomNode());
721
722     }
723
724     QDomNode westley0 = m_document.elementsByTagName("westley").at(0);
725     if (!markers.firstChild().isNull()) westley0.appendChild(markers);
726
727
728     // Convert as much of the kdenlivedoc as possible. Use the producer in westley
729     // First, remove the old stuff from westley, and add a new empty one
730     // Also, track the max id in order to use it for the adding of groups/folders
731     int max_kproducer_id = 0;
732     westley0.removeChild(kdenlivedoc);
733     QDomElement kdenlivedoc_new = m_document.createElement("kdenlivedoc");
734     kdenlivedoc_new.setAttribute("profile", profile);
735
736     // Add tracks info
737     QDomNodeList tracks = m_document.elementsByTagName("track");
738     max = tracks.count();
739     QDomElement tracksinfo = m_document.createElement("tracksinfo");
740     for (int i = 0; i < max; i++) {
741         QDomElement trackinfo = m_document.createElement("trackinfo");
742         QDomElement t = tracks.at(i).toElement();
743         if (t.attribute("hide") == "video") {
744             trackinfo.setAttribute("type", "audio");
745             trackinfo.setAttribute("blind", true);
746         } else trackinfo.setAttribute("blind", false);
747         trackinfo.setAttribute("mute", false);
748         trackinfo.setAttribute("locked", false);
749         if (t.attribute("producer") != "black_track") tracksinfo.appendChild(trackinfo);
750     }
751     kdenlivedoc_new.appendChild(tracksinfo);
752
753     // Add all the producers that has a ressource in westley
754     QDomElement westley_element = westley0.toElement();
755     if (westley_element.isNull()) {
756         kWarning() << "westley0 element in document was not a QDomElement - unable to add producers to new kdenlivedoc";
757     } else {
758         QDomNodeList wproducers = westley_element.elementsByTagName("producer");
759         int kmax = wproducers.count();
760         for (int i = 0; i < kmax; i++) {
761             QDomElement wproducer = wproducers.at(i).toElement();
762             if (wproducer.isNull()) {
763                 kWarning() << "Found producer in westley0, that was not a QDomElement";
764             } else {
765                 // We have to do slightly different things, depending on the type
766                 kDebug() << "Converting producer element with type" << wproducer.attribute("type");
767                 if (wproducer.attribute("type").toInt() == TEXT) {
768                     kDebug() << "Found TEXT element in producer" << endl;
769                     QDomElement kproducer = wproducer.cloneNode(true).toElement();
770                     kproducer.setTagName("kdenlive_producer");
771                     kdenlivedoc_new.appendChild(kproducer);
772                     // TODO: Perhaps needs some more changes here to "frequency", aspect ratio as a float, frame_size, channels, and later, ressource and title name
773                 } else {
774                     QDomElement kproducer = m_document.createElement("kdenlive_producer");
775                     kproducer.setAttribute("id", wproducer.attribute("id"));
776                     if (!wproducer.attribute("description").isEmpty())
777                         kproducer.setAttribute("description", wproducer.attribute("description"));
778                     kproducer.setAttribute("resource", wproducer.attribute("resource"));
779                     kproducer.setAttribute("type", wproducer.attribute("type"));
780                     // Testing fix for 358
781                     if (!wproducer.attribute("aspect_ratio").isEmpty()) {
782                         kproducer.setAttribute("aspect_ratio", wproducer.attribute("aspect_ratio"));
783                     }
784                     if (!wproducer.attribute("source_fps").isEmpty()) {
785                         kproducer.setAttribute("fps", wproducer.attribute("source_fps"));
786                     }
787                     if (!wproducer.attribute("length").isEmpty()) {
788                         kproducer.setAttribute("duration", wproducer.attribute("length"));
789                     }
790                     kdenlivedoc_new.appendChild(kproducer);
791                 }
792                 if (wproducer.attribute("id").toInt() > max_kproducer_id) {
793                     max_kproducer_id = wproducer.attribute("id").toInt();
794                 }
795             }
796         }
797     }
798 #define LOOKUP_FOLDER 1
799 #ifdef LOOKUP_FOLDER
800     // Look through all the folder elements of the old doc, for each folder, for each producer,
801     // get the id, look it up in the new doc, set the groupname and groupid
802     // Note, this does not work at the moment - at least one folders shows up missing, and clips with no folder
803     // does not show up.
804     //    QDomElement kdenlivedoc_old = kdenlivedoc.toElement();
805     if (!kdenlivedoc_old.isNull()) {
806         QDomNodeList folders = kdenlivedoc_old.elementsByTagName("folder");
807         int fsize = folders.size();
808         int groupId = max_kproducer_id + 1; // Start at +1 of max id of the kdenlive_producers
809         for (int i = 0; i < fsize; ++i) {
810             QDomElement folder = folders.at(i).toElement();
811             if (!folder.isNull()) {
812                 QString groupName = folder.attribute("name");
813                 kDebug() << "groupName: " << groupName << " with groupId: " << groupId;
814                 QDomNodeList fproducers = folder.elementsByTagName("producer");
815                 int psize = fproducers.size();
816                 for (int j = 0; j < psize; ++j) {
817                     QDomElement fproducer = fproducers.at(j).toElement();
818                     if (!fproducer.isNull()) {
819                         QString id = fproducer.attribute("id");
820                         // This is not very effective, but compared to loading the clips, its a breeze
821                         QDomNodeList kdenlive_producers = kdenlivedoc_new.elementsByTagName("kdenlive_producer");
822                         int kpsize = kdenlive_producers.size();
823                         for (int k = 0; k < kpsize; ++k) {
824                             QDomElement kproducer = kdenlive_producers.at(k).toElement(); // Its an element for sure
825                             if (id == kproducer.attribute("id")) {
826                                 // We do not check that it already is part of a folder
827                                 kproducer.setAttribute("groupid", groupId);
828                                 kproducer.setAttribute("groupname", groupName);
829                                 break;
830                             }
831                         }
832                     }
833                 }
834                 ++groupId;
835             }
836         }
837     }
838 #endif
839     westley0.appendChild(kdenlivedoc_new);
840
841     QDomNodeList elements = westley.childNodes();
842     max = elements.count();
843     for (int i = 0; i < max; i++) {
844         QDomElement prod = elements.at(0).toElement();
845         westley0.insertAfter(prod, QDomNode());
846     }
847
848     westley0.removeChild(westley);
849
850     // experimental and probably slow
851     // adds <avfile /> information to <kdenlive_producer />
852     QDomNodeList kproducers = m_document.elementsByTagName("kdenlive_producer");
853     QDomNodeList avfiles = kdenlivedoc_old.elementsByTagName("avfile");
854     kDebug() << "found" << avfiles.count() << "<avfile />s and" << kproducers.count() << "<kdenlive_producer />s";
855     for (int i = 0; i < avfiles.count(); ++i) {
856         QDomElement avfile = avfiles.at(i).toElement();
857         QDomElement kproducer = QDomElement();
858         if (avfile.isNull())
859             kWarning() << "found an <avfile /> that is not a QDomElement";
860         else {
861             QString id = avfile.attribute("id");
862             // this is horrible, must be rewritten, it's just for test
863             for (int j = 0; j < kproducers.count(); ++j) {
864                 //kDebug() << "checking <kdenlive_producer /> with id" << kproducers.at(j).toElement().attribute("id");
865                 if (kproducers.at(j).toElement().attribute("id") == id) {
866                     kproducer = kproducers.at(j).toElement();
867                     break;
868                 }
869             }
870             if (kproducer == QDomElement())
871                 kWarning() << "no match for <avfile /> with id =" << id;
872             else {
873                 //kDebug() << "ready to set additional <avfile />'s attributes (id =" << id << ")";
874                 kproducer.setAttribute("channels", avfile.attribute("channels"));
875                 kproducer.setAttribute("duration", avfile.attribute("duration"));
876                 kproducer.setAttribute("frame_size", avfile.attribute("width") + 'x' + avfile.attribute("height"));
877                 kproducer.setAttribute("frequency", avfile.attribute("frequency"));
878                 if (kproducer.attribute("description").isEmpty() && !avfile.attribute("description").isEmpty())
879                     kproducer.setAttribute("description", avfile.attribute("description"));
880             }
881         }
882     }
883
884     //kDebug() << "/////////////////  CONVERTED DOC:";
885     //kDebug() << m_document.toString();
886     /*
887     QFile file( "converted.kdenlive" );
888     if ( file.open( QIODevice::WriteOnly ) ) {
889       QTextStream stream( &file );
890       stream << m_document.toString();
891       file.close();
892     } else {
893       kDebug() << "Unable to dump file to converted.kdenlive";
894     }
895     */
896     //kDebug() << "/////////////////  END CONVERTED DOC:";
897
898     return true;
899 }
900
901 QString KdenliveDoc::colorToString(const QColor& c) {
902     QString ret = "%1,%2,%3,%4";
903     ret = ret.arg(c.red()).arg(c.green()).arg(c.blue()).arg(c.alpha());
904     return ret;
905 }
906
907 void KdenliveDoc::setZone(int start, int end) {
908     m_zoneStart = start;
909     m_zoneEnd = end;
910 }
911
912 QPoint KdenliveDoc::zone() const {
913     return QPoint(m_zoneStart, m_zoneEnd);
914 }
915
916 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene) {
917     QDomDocument sceneList;
918     sceneList.setContent(scene, true);
919     QDomNode wes = sceneList.elementsByTagName("westley").at(0);
920     QDomElement addedXml = sceneList.createElement("kdenlivedoc");
921     wes.appendChild(addedXml);
922
923     QDomElement markers = sceneList.createElement("markers");
924     addedXml.setAttribute("version", "0.82");
925     addedXml.setAttribute("profile", profilePath());
926     addedXml.setAttribute("position", m_render->seekPosition().frames(m_fps));
927     addedXml.setAttribute("zonein", m_zoneStart);
928     addedXml.setAttribute("zoneout", m_zoneEnd);
929     addedXml.setAttribute("projectfolder", m_projectFolder.path());
930     addedXml.setAttribute("zoom", m_zoom);
931
932     // tracks info
933     QDomElement tracksinfo = sceneList.createElement("tracksinfo");
934     foreach(const TrackInfo &info, m_tracksList) {
935         QDomElement trackinfo = sceneList.createElement("trackinfo");
936         if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
937         trackinfo.setAttribute("mute", info.isMute);
938         trackinfo.setAttribute("blind", info.isBlind);
939         trackinfo.setAttribute("locked", info.isLocked);
940         tracksinfo.appendChild(trackinfo);
941     }
942     addedXml.appendChild(tracksinfo);
943
944     // save project folders
945     QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
946
947     QMapIterator<QString, QString> f(folderlist);
948     while (f.hasNext()) {
949         f.next();
950         QDomElement folder = sceneList.createElement("folder");
951         folder.setAttribute("id", f.key());
952         folder.setAttribute("name", f.value());
953         addedXml.appendChild(folder);
954     }
955
956     // Save project clips
957     QDomElement e;
958     QList <DocClipBase*> list = m_clipManager->documentClipList();
959     for (int i = 0; i < list.count(); i++) {
960         e = list.at(i)->toXML();
961         e.setTagName("kdenlive_producer");
962         addedXml.appendChild(sceneList.importNode(e, true));
963         QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
964         for (int j = 0; j < marks.count(); j++) {
965             QDomElement marker = sceneList.createElement("marker");
966             marker.setAttribute("time", marks.at(j).time().ms() / 1000);
967             marker.setAttribute("comment", marks.at(j).comment());
968             marker.setAttribute("id", e.attribute("id"));
969             markers.appendChild(marker);
970         }
971     }
972     addedXml.appendChild(markers);
973     if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml, true));
974
975     //wes.appendChild(doc.importNode(kdenliveData, true));
976
977     QFile file(path);
978     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
979         kWarning() << "//////  ERROR writing to file: " << path;
980         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
981         return false;
982     }
983
984     QTextStream out(&file);
985     out << sceneList.toString();
986     file.close();
987     return true;
988 }
989
990 ClipManager *KdenliveDoc::clipManager() {
991     return m_clipManager;
992 }
993
994 KUrl KdenliveDoc::projectFolder() const {
995     //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
996     return m_projectFolder;
997 }
998
999 void KdenliveDoc::setProjectFolder(KUrl url) {
1000     if (url == m_projectFolder) return;
1001     setModified(true);
1002     KStandardDirs::makeDir(url.path());
1003     KStandardDirs::makeDir(url.path() + "/titles/");
1004     KStandardDirs::makeDir(url.path() + "/thumbs/");
1005     if (KMessageBox::questionYesNo(kapp->activeWindow(), i18n("You have changed the project folder. Do you want to copy the cached data from %1 to the new folder %2?").arg(m_projectFolder.path(), url.path())) == KMessageBox::Yes) moveProjectData(url);
1006     m_projectFolder = url;
1007 }
1008
1009 void KdenliveDoc::moveProjectData(KUrl url) {
1010     QList <DocClipBase*> list = m_clipManager->documentClipList();
1011     //TODO: Also move ladspa effects files
1012     for (int i = 0; i < list.count(); i++) {
1013         DocClipBase *clip = list.at(i);
1014         if (clip->clipType() == TEXT) {
1015             // the image for title clip must be moved
1016             KUrl oldUrl = clip->fileURL();
1017             KUrl newUrl = KUrl(url.path() + "/titles/" + oldUrl.fileName());
1018             KIO::Job *job = KIO::copy(oldUrl, newUrl);
1019             if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
1020         }
1021         QString hash = clip->getClipHash();
1022         KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path() + "/thumbs/" + hash + ".png");
1023         KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path() + "/thumbs/" + hash + ".thumb");
1024         if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
1025             KUrl newUrl = KUrl(url.path() + "/thumbs/" + hash + ".png");
1026             KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
1027             KIO::NetAccess::synchronousRun(job, 0);
1028         }
1029         if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
1030             KUrl newUrl = KUrl(url.path() + "/thumbs/" + hash + ".thumb");
1031             KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
1032             if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
1033         }
1034     }
1035 }
1036
1037 const QString &KdenliveDoc::profilePath() const {
1038     return m_profile.path;
1039 }
1040
1041 MltVideoProfile KdenliveDoc::mltProfile() const {
1042     return m_profile;
1043 }
1044
1045 void KdenliveDoc::setProfilePath(QString path) {
1046     if (path.isEmpty()) path = KdenliveSettings::default_profile();
1047     if (path.isEmpty()) path = "dv_pal";
1048     m_profile = ProfilesDialog::getVideoProfile(path);
1049     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
1050     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
1051     m_width = m_profile.width;
1052     m_height = m_profile.height;
1053     kDebug() << "KDEnnlive document, init timecode from path: " << path << ",  " << m_fps;
1054     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
1055     else m_timecode.setFormat((int) m_fps);
1056 }
1057
1058 const double KdenliveDoc::dar() {
1059     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
1060 }
1061
1062 void KdenliveDoc::setThumbsProgress(const QString &message, int progress) {
1063     emit progressInfo(message, progress);
1064 }
1065
1066 void KdenliveDoc::loadingProgressed() {
1067     m_documentLoadingProgress += m_documentLoadingStep;
1068     emit progressInfo(QString(), (int) m_documentLoadingProgress);
1069 }
1070
1071 QUndoStack *KdenliveDoc::commandStack() {
1072     return m_commandStack;
1073 }
1074
1075 /*
1076 void KdenliveDoc::setRenderer(Render *render) {
1077     if (m_render) return;
1078     m_render = render;
1079     emit progressInfo(i18n("Loading playlist..."), 0);
1080     //qApp->processEvents();
1081     if (m_render) {
1082         m_render->setSceneList(m_document.toString(), m_startPos);
1083         kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
1084         checkProjectClips();
1085     }
1086     emit progressInfo(QString(), -1);
1087 }*/
1088
1089 void KdenliveDoc::checkProjectClips() {
1090     if (m_render == NULL) return;
1091     QList <Mlt::Producer *> prods = m_render->producersList();
1092     QString id ;
1093     QString prodId ;
1094     QString prodTrack ;
1095     for (int i = 0; i < prods.count(); i++) {
1096         id = prods.at(i)->get("id");
1097         prodId = id.section('_', 0, 0);
1098         prodTrack = id.section('_', 1, 1);
1099         DocClipBase *clip = m_clipManager->getClipById(prodId);
1100         if (clip) clip->setProducer(prods.at(i));
1101         if (clip && clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
1102             // regenerate text clip image if required
1103             kDebug() << "// TITLE: " << clip->getProperty("titlename") << " Preview file: " << clip->getProperty("resource") << " DOES NOT EXIST";
1104             QString titlename = clip->getProperty("titlename");
1105             QString titleresource;
1106             if (titlename.isEmpty()) {
1107                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1108                 titlename = titleInfo.at(0);
1109                 titleresource = titleInfo.at(1);
1110                 clip->setProperty("titlename", titlename);
1111                 kDebug() << "// New title set to: " << titlename;
1112             } else {
1113                 titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
1114             }
1115             QString titlepath = projectFolder().path() + "/titles/";
1116             TitleWidget *dia_ui = new TitleWidget(KUrl(), titlepath, m_render, kapp->activeWindow());
1117             QDomDocument doc;
1118             doc.setContent(clip->getProperty("xmldata"));
1119             dia_ui->setXml(doc);
1120             QImage pix = dia_ui->renderedPixmap();
1121             pix.save(titleresource);
1122             clip->setProperty("resource", titleresource);
1123             delete dia_ui;
1124             clip->producer()->set("force_reload", 1);
1125         }
1126     }
1127 }
1128
1129 void KdenliveDoc::updatePreviewSettings() {
1130     m_clipManager->updatePreviewSettings();
1131     m_render->updatePreviewSettings();
1132     m_clipManager->resetProducersList(m_render->producersList());
1133
1134 }
1135
1136 Render *KdenliveDoc::renderer() {
1137     return m_render;
1138 }
1139
1140 void KdenliveDoc::updateClip(const QString &id) {
1141     emit updateClipDisplay(id);
1142 }
1143
1144 int KdenliveDoc::getFramePos(QString duration) {
1145     return m_timecode.getFrameCount(duration, m_fps);
1146 }
1147
1148 QString KdenliveDoc::producerName(const QString &id) {
1149     QString result = "unnamed";
1150     QDomNodeList prods = producersList();
1151     int ct = prods.count();
1152     for (int i = 0; i <  ct ; i++) {
1153         QDomElement e = prods.item(i).toElement();
1154         if (e.attribute("id") != "black" && e.attribute("id") == id) {
1155             result = e.attribute("name");
1156             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
1157             break;
1158         }
1159     }
1160     return result;
1161 }
1162
1163 void KdenliveDoc::setProducerDuration(const QString &id, int duration) {
1164     QDomNodeList prods = producersList();
1165     int ct = prods.count();
1166     for (int i = 0; i <  ct ; i++) {
1167         QDomElement e = prods.item(i).toElement();
1168         if (e.attribute("id") != "black" && e.attribute("id") == id) {
1169             e.setAttribute("duration", QString::number(duration));
1170             break;
1171         }
1172     }
1173 }
1174
1175 int KdenliveDoc::getProducerDuration(const QString &id) {
1176     int result = 0;
1177     QDomNodeList prods = producersList();
1178     int ct = prods.count();
1179     for (int i = 0; i <  ct ; i++) {
1180         QDomElement e = prods.item(i).toElement();
1181         if (e.attribute("id") != "black" && e.attribute("id") == id) {
1182             result = e.attribute("duration").toInt();
1183             break;
1184         }
1185     }
1186     return result;
1187 }
1188
1189
1190 QDomDocument KdenliveDoc::generateSceneList() {
1191     QDomDocument doc;
1192     QDomElement westley = doc.createElement("westley");
1193     doc.appendChild(westley);
1194     QDomElement prod = doc.createElement("producer");
1195 }
1196
1197 QDomDocument KdenliveDoc::toXml() {
1198     return m_document;
1199 }
1200
1201 Timecode KdenliveDoc::timecode() const {
1202     return m_timecode;
1203 }
1204
1205 QDomNodeList KdenliveDoc::producersList() {
1206     return m_document.elementsByTagName("producer");
1207 }
1208
1209 double KdenliveDoc::projectDuration() const {
1210     if (m_render)
1211         return GenTime(m_render->getLength(), m_fps).ms() / 1000;
1212     else
1213         return 0;
1214 }
1215
1216 double KdenliveDoc::fps() const {
1217     return m_fps;
1218 }
1219
1220 int KdenliveDoc::width() const {
1221     return m_width;
1222 }
1223
1224 int KdenliveDoc::height() const {
1225     return m_height;
1226 }
1227
1228 KUrl KdenliveDoc::url() const {
1229     return m_url;
1230 }
1231
1232 void KdenliveDoc::setUrl(KUrl url) {
1233     m_url = url;
1234 }
1235
1236 void KdenliveDoc::setModified(bool mod) {
1237     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
1238         m_autoSaveTimer->start(3000);
1239     }
1240     if (mod == m_modified) return;
1241     m_modified = mod;
1242     emit docModified(m_modified);
1243 }
1244
1245 bool KdenliveDoc::isModified() const {
1246     return m_modified;
1247 }
1248
1249 const QString KdenliveDoc::description() const {
1250     if (m_url.isEmpty())
1251         return i18n("Untitled") + " / " + m_profile.description;
1252     else
1253         return m_url.fileName() + " / " + m_profile.description;
1254 }
1255
1256 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem) {
1257     const QString producerId = clipId.section('_', 0, 0);
1258     DocClipBase *clip = m_clipManager->getClipById(producerId);
1259     if (clip == NULL) {
1260         elem.setAttribute("id", producerId);
1261         QString path = elem.attribute("resource");
1262         QString extension;
1263         if (elem.attribute("type").toInt() == SLIDESHOW) {
1264             extension = KUrl(path).fileName();
1265             path = KUrl(path).directory();
1266         }
1267         if (elem.attribute("type").toInt() == TEXT && !QFile::exists(path)) {
1268             kDebug() << "// TITLE: " << elem.attribute("titlename") << " Preview file: " << elem.attribute("resource") << " DOES NOT EXIST";
1269             QString titlename = elem.attribute("titlename");
1270             QString titleresource;
1271             if (titlename.isEmpty()) {
1272                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1273                 titlename = titleInfo.at(0);
1274                 titleresource = titleInfo.at(1);
1275                 elem.setAttribute("titlename", titlename);
1276                 kDebug() << "// New title set to: " << titlename;
1277             } else {
1278                 titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
1279             }
1280             QString titlepath = projectFolder().path() + "/titles/";
1281             TitleWidget *dia_ui = new TitleWidget(KUrl(), titlepath, m_render, kapp->activeWindow());
1282             QDomDocument doc;
1283             doc.setContent(elem.attribute("xmldata"));
1284             dia_ui->setXml(doc);
1285             QImage pix = dia_ui->renderedPixmap();
1286             pix.save(titleresource);
1287             elem.setAttribute("resource", titleresource);
1288             delete dia_ui;
1289         } else if (!path.isEmpty() && !QFile::exists(path) && elem.attribute("type").toInt() != TEXT) {
1290             kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1291             const QString size = elem.attribute("file_size");
1292             const QString hash = elem.attribute("file_hash");
1293             QString newpath;
1294             int action = KMessageBox::No;
1295             if (!size.isEmpty() && !hash.isEmpty()) {
1296                 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
1297                 else action = (KMessageBox::ButtonCode) KMessageBox::questionYesNoCancel(kapp->activeWindow(), i18n("Clip <b>%1</b><br>is invalid, what do you want to do?", path), i18n("File not found"), KGuiItem(i18n("Search automatically")), KGuiItem(i18n("Keep as placeholder")));
1298             } else {
1299                 if (elem.attribute("type").toInt() == SLIDESHOW) {
1300                     int res = KMessageBox::questionYesNoCancel(kapp->activeWindow(), i18n("Clip <b>%1</b><br>is invalid or missing, what do you want to do?", path), i18n("File not found"), KGuiItem(i18n("Search manually")), KGuiItem(i18n("Keep as placeholder")));
1301                     if (res == KMessageBox::Yes)
1302                         newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1303                     else if (res == KMessageBox::Cancel) {
1304                         // Abort project loading
1305                         action = KMessageBox::Cancel;
1306                     }
1307                 } else {
1308                     int res = KMessageBox::questionYesNoCancel(kapp->activeWindow(), i18n("Clip <b>%1</b><br>is invalid or missing, what do you want to do?", path), i18n("File not found"), KGuiItem(i18n("Search manually")), KGuiItem(i18n("Keep as placeholder")));
1309                     if (res == KMessageBox::Yes)
1310                         newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1311                     else if (res == KMessageBox::Cancel) {
1312                         // Abort project loading
1313                         action = KMessageBox::Cancel;
1314                     }
1315                 }
1316             }
1317             if (action == KMessageBox::Yes) {
1318                 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1319                 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1320                 if (!m_searchFolder.isEmpty()) {
1321                     newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1322                 }
1323             } else if (action == KMessageBox::Cancel) {
1324                 m_abortLoading = true;
1325                 return;
1326             }
1327             if (!newpath.isEmpty()) {
1328                 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
1329                 elem.setAttribute("resource", newpath);
1330                 setNewClipResource(clipId, newpath);
1331                 setModified(true);
1332             }
1333         }
1334         clip = new DocClipBase(m_clipManager, elem, producerId);
1335         m_clipManager->addClip(clip);
1336     }
1337
1338     if (createClipItem) {
1339         emit addProjectClip(clip);
1340         qApp->processEvents();
1341         m_render->getFileProperties(clip->toXML(), clip->getId());
1342     }
1343 }
1344
1345
1346 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path) {
1347     QDomNodeList prods = m_document.elementsByTagName("producer");
1348     int maxprod = prods.count();
1349     for (int i = 0; i < maxprod; i++) {
1350         QDomNode m = prods.at(i);
1351         QString prodId = m.toElement().attribute("id");
1352         if (prodId == id || prodId.startsWith(id + '_')) {
1353             QDomNodeList params = m.childNodes();
1354             for (int j = 0; j < params.count(); j++) {
1355                 QDomElement e = params.item(j).toElement();
1356                 if (e.attribute("name") == "resource") {
1357                     e.firstChild().setNodeValue(path);
1358                     break;
1359                 }
1360             }
1361         }
1362     }
1363 }
1364
1365 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const {
1366     QString foundFileName;
1367     QByteArray fileData;
1368     QByteArray fileHash;
1369     QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1370     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1371         QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1372         if (file.open(QIODevice::ReadOnly)) {
1373             if (QString::number(file.size()) == matchSize) {
1374                 /*
1375                 * 1 MB = 1 second per 450 files (or faster)
1376                 * 10 MB = 9 seconds per 450 files (or faster)
1377                 */
1378                 if (file.size() > 1000000*2) {
1379                     fileData = file.read(1000000);
1380                     if (file.seek(file.size() - 1000000))
1381                         fileData.append(file.readAll());
1382                 } else
1383                     fileData = file.readAll();
1384                 file.close();
1385                 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1386                 if (QString(fileHash.toHex()) == matchHash)
1387                     return file.fileName();
1388             }
1389         }
1390         kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1391     }
1392     filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1393     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1394         foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1395         if (!foundFileName.isEmpty())
1396             break;
1397     }
1398     return foundFileName;
1399 }
1400
1401 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId) {
1402     DocClipBase *clip = m_clipManager->getClipById(clipId);
1403     if (clip == NULL) {
1404         addClip(elem, clipId, false);
1405     } else {
1406         QMap <QString, QString> properties;
1407         QDomNamedNodeMap attributes = elem.attributes();
1408         QString attrname;
1409         for (unsigned int i = 0; i < attributes.count(); i++) {
1410             attrname = attributes.item(i).nodeName();
1411             if (attrname != "resource")
1412                 properties.insert(attrname, attributes.item(i).nodeValue());
1413             kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1414         }
1415         clip->setProperties(properties);
1416         emit addProjectClip(clip, false);
1417     }
1418     if (orig != QDomElement()) {
1419         QMap<QString, QString> meta;
1420         QDomNode m = orig.firstChild();
1421         while (!m.isNull()) {
1422             QString name = m.toElement().attribute("name");
1423             if (name.startsWith("meta.attr")) {
1424                 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1425             }
1426             m = m.nextSibling();
1427         }
1428         if (!meta.isEmpty()) {
1429             if (clip == NULL) clip = m_clipManager->getClipById(clipId);
1430             if (clip) clip->setMetadata(meta);
1431         }
1432     }
1433 }
1434
1435 void KdenliveDoc::deleteProjectClip(QList <QString> ids) {
1436     for (int i = 0; i < ids.size(); ++i) {
1437         emit deleteTimelineClip(ids.at(i));
1438         m_clipManager->slotDeleteClip(ids.at(i));
1439     }
1440     setModified(true);
1441 }
1442
1443 void KdenliveDoc::deleteClip(const QString &clipId) {
1444     emit signalDeleteProjectClip(clipId);
1445     m_clipManager->deleteClip(clipId);
1446 }
1447
1448 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId) {
1449     m_clipManager->slotAddClipList(urls, group, groupId);
1450     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1451     setModified(true);
1452 }
1453
1454
1455 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId) {
1456     //kDebug() << "/////////  DOCUM, ADD CLP: " << url;
1457     m_clipManager->slotAddClipFile(url, group, groupId);
1458     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1459     setModified(true);
1460 }
1461
1462 const QString KdenliveDoc::getFreeClipId() {
1463     return QString::number(m_clipManager->getFreeClipId());
1464 }
1465
1466 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId) {
1467     return m_clipManager->getClipById(clipId);
1468 }
1469
1470 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId) {
1471     QString titlesFolder = projectFolder().path() + "/titles/";
1472     KStandardDirs::makeDir(titlesFolder);
1473     TitleWidget *dia_ui = new TitleWidget(KUrl(), titlesFolder, m_render, kapp->activeWindow());
1474     if (dia_ui->exec() == QDialog::Accepted) {
1475         QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1476         QImage pix = dia_ui->renderedPixmap();
1477         pix.save(titleInfo.at(1));
1478         //dia_ui->saveTitle(path + ".kdenlivetitle");
1479         m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), QString(), QString());
1480         setModified(true);
1481     }
1482     delete dia_ui;
1483 }
1484
1485 int KdenliveDoc::tracksCount() const {
1486     return m_tracksList.count();
1487 }
1488
1489 TrackInfo KdenliveDoc::trackInfoAt(int ix) const {
1490     return m_tracksList.at(ix);
1491 }
1492
1493 void KdenliveDoc::switchTrackAudio(int ix, bool hide) {
1494     m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1495 }
1496
1497 void KdenliveDoc::switchTrackLock(int ix, bool lock) {
1498     m_tracksList[ix].isLocked = lock;
1499 }
1500
1501 bool KdenliveDoc::isTrackLocked(int ix) const {
1502     return m_tracksList[ix].isLocked;
1503 }
1504
1505 void KdenliveDoc::switchTrackVideo(int ix, bool hide) {
1506     m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1507 }
1508
1509 void KdenliveDoc::insertTrack(int ix, TrackInfo type) {
1510     if (ix == -1) m_tracksList << type;
1511     else m_tracksList.insert(ix, type);
1512 }
1513
1514 void KdenliveDoc::deleteTrack(int ix) {
1515     m_tracksList.removeAt(ix);
1516 }
1517
1518 void KdenliveDoc::setTrackType(int ix, TrackInfo type) {
1519     m_tracksList[ix].type = type.type;
1520     m_tracksList[ix].isMute = type.isMute;
1521     m_tracksList[ix].isBlind = type.isBlind;
1522     m_tracksList[ix].isLocked = type.isLocked;
1523 }
1524
1525 const QList <TrackInfo> KdenliveDoc::tracksList() const {
1526     return m_tracksList;
1527 }
1528
1529 QPoint KdenliveDoc::getTracksCount() const {
1530     int audio = 0;
1531     int video = 0;
1532     foreach(const TrackInfo &info, m_tracksList) {
1533         if (info.type == VIDEOTRACK) video++;
1534         else audio++;
1535     }
1536     return QPoint(video, audio);
1537 }
1538
1539 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const {
1540     pix.save(m_projectFolder.path() + "/thumbs/" + fileId + ".png");
1541 }
1542
1543 QString KdenliveDoc::getLadspaFile() const {
1544     int ct = 0;
1545     QString counter = QString::number(ct).rightJustified(5, '0', false);
1546     while (QFile::exists(m_projectFolder.path() + "/ladspa/" + counter + ".ladspa")) {
1547         ct++;
1548         counter = QString::number(ct).rightJustified(5, '0', false);
1549     }
1550     return m_projectFolder.path() + "/ladspa/" + counter + ".ladspa";
1551 }
1552
1553 #include "kdenlivedoc.moc"
1554