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