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