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