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