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