]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
Preview monitor volume should not affect rendering:
[kdenlive] / src / kdenlivedoc.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
18  ***************************************************************************/
19
20
21 #include "kdenlivedoc.h"
22 #include "docclipbase.h"
23 #include "profilesdialog.h"
24 #include "kdenlivesettings.h"
25 #include "renderer.h"
26 #include "clipmanager.h"
27 #include "titlewidget.h"
28 #include "mainwindow.h"
29 #include "documentchecker.h"
30 #include "documentvalidator.h"
31 #include "kdenlive-config.h"
32 #include "initeffects.h"
33
34 #include <KDebug>
35 #include <KStandardDirs>
36 #include <KMessageBox>
37 #include <KProgressDialog>
38 #include <KLocale>
39 #include <KFileDialog>
40 #include <KIO/NetAccess>
41 #include <KIO/CopyJob>
42 #include <KApplication>
43 #include <KGlobal>
44 #include <KBookmarkManager>
45 #include <KBookmark>
46 #include <KStandardDirs>
47
48 #include <QCryptographicHash>
49 #include <QFile>
50 #include <QInputDialog>
51 #include <QDomImplementation>
52
53 #include <mlt++/Mlt.h>
54
55 const double DOCUMENTVERSION = 0.87;
56
57 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, QString profileName, QMap <QString, QString> properties, const QPoint tracks, Render *render, KTextEdit *notes, bool *openBackup, MainWindow *parent, KProgressDialog *progressDialog) :
58     QObject(parent),
59     m_autosave(NULL),
60     m_url(url),
61     m_render(render),
62     m_notesWidget(notes),
63     m_commandStack(new QUndoStack(undoGroup)),
64     m_modified(false),
65     m_projectFolder(projectFolder)
66 {
67     m_clipManager = new ClipManager(this);
68     m_autoSaveTimer = new QTimer(this);
69     m_autoSaveTimer->setSingleShot(true);
70     bool success = false;
71
72     // init default document properties
73     m_documentProperties["zoom"] = "7";
74     m_documentProperties["verticalzoom"] = "1";
75     m_documentProperties["zonein"] = "0";
76     m_documentProperties["zoneout"] = "100";
77     m_documentProperties["enableproxy"] = QString::number((int) KdenliveSettings::enableproxy());
78     m_documentProperties["proxyparams"] = KdenliveSettings::proxyparams();
79     m_documentProperties["proxyextension"] = KdenliveSettings::proxyextension();
80     m_documentProperties["generateproxy"] = QString::number((int) KdenliveSettings::generateproxy());
81     m_documentProperties["proxyminsize"] = QString::number(KdenliveSettings::proxyminsize());
82     m_documentProperties["generateimageproxy"] = QString::number((int) KdenliveSettings::generateimageproxy());
83     m_documentProperties["proxyimageminsize"] = QString::number(KdenliveSettings::proxyimageminsize());
84 #if QT_VERSION >= 0x040700
85     m_documentProperties["documentid"] = QString::number(QDateTime::currentMSecsSinceEpoch());
86 #else
87     QDateTime date = QDateTime::currentDateTime();
88     m_documentProperties["documentid"] = QString::number(date.toTime_t());
89 #endif
90
91     // Load properties
92     QMapIterator<QString, QString> i(properties);
93     while (i.hasNext()) {
94         i.next();
95         m_documentProperties[i.key()] = i.value();
96     }
97
98     *openBackup = false;
99     
100     if (!url.isEmpty()) {
101         QString tmpFile;
102         success = KIO::NetAccess::download(url.path(), tmpFile, parent);
103         if (!success) {
104             // The file cannot be opened
105             if (KMessageBox::warningContinueCancel(parent, i18n("Cannot open the project file, error is:\n%1\nDo you want to open a backup file?", KIO::NetAccess::lastErrorString()), i18n("Error opening file"), KGuiItem(i18n("Open Backup"))) == KMessageBox::Continue) {
106                 *openBackup = true;
107             }
108             //KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
109         }
110         else {
111             QFile file(tmpFile);
112             QString errorMsg;
113             QDomImplementation impl;
114             impl.setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
115             success = m_document.setContent(&file, false, &errorMsg);
116             file.close();
117             KIO::NetAccess::removeTempFile(tmpFile);
118
119             if (!success) {
120                 // It is corrupted
121                 if (KMessageBox::warningContinueCancel(parent, i18n("Cannot open the project file, error is:\n%1\nDo you want to open a backup file?", errorMsg), i18n("Error opening file"), KGuiItem(i18n("Open Backup"))) == KMessageBox::Continue) {
122                 *openBackup = true;
123             }
124                 //KMessageBox::error(parent, errorMsg);
125             }
126             else {
127                 parent->slotGotProgressInfo(i18n("Validating"), 0);
128                 qApp->processEvents();
129                 DocumentValidator validator(m_document);
130                 success = validator.isProject();
131                 if (!success) {
132                     // It is not a project file
133                     parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
134                     if (KMessageBox::warningContinueCancel(parent, i18n("File %1 is not a valid project file.\nDo you want to open a backup file?", m_url.path()), i18n("Error opening file"), KGuiItem(i18n("Open Backup"))) == KMessageBox::Continue) {
135                         *openBackup = true;
136                     }
137                 } else {
138                     /*
139                      * Validate the file against the current version (upgrade
140                      * and recover it if needed). It is NOT a passive operation
141                      */
142                     // TODO: backup the document or alert the user?
143                     success = validator.validate(DOCUMENTVERSION);
144                     if (success) { // Let the validator handle error messages
145                         parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
146                         qApp->processEvents();
147                         QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
148                         success = checkDocumentClips(infoproducers);
149                         if (success) {
150                             if (m_document.documentElement().attribute("modified") == "1") setModified(true);
151                             parent->slotGotProgressInfo(i18n("Loading"), 0);
152                             QDomElement mlt = m_document.firstChildElement("mlt");
153                             QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
154
155                             // Set profile, fps, etc for the document
156                             setProfilePath(infoXml.attribute("profile"));
157
158                             // Check embedded effects
159                             QDomElement customeffects = infoXml.firstChildElement("customeffects");
160                             if (!customeffects.isNull() && customeffects.hasChildNodes()) {
161                                 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
162                                 qApp->processEvents();
163                                 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
164                             }
165
166                             QDomElement e;
167                             // Read notes
168                             QDomElement notesxml = infoXml.firstChildElement("documentnotes");
169                             if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
170
171                             // Build tracks
172                             QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
173                             if (!tracksinfo.isNull()) {
174                                 QDomNodeList trackslist = tracksinfo.childNodes();
175                                 int maxchild = trackslist.count();
176                                 for (int k = 0; k < maxchild; k++) {
177                                     e = trackslist.at(k).toElement();
178                                     if (e.tagName() == "trackinfo") {
179                                         TrackInfo projectTrack;
180                                         if (e.attribute("type") == "audio")
181                                             projectTrack.type = AUDIOTRACK;
182                                         else
183                                             projectTrack.type = VIDEOTRACK;
184                                         projectTrack.isMute = e.attribute("mute").toInt();
185                                         projectTrack.isBlind = e.attribute("blind").toInt();
186                                         projectTrack.isLocked = e.attribute("locked").toInt();
187                                         projectTrack.trackName = e.attribute("trackname");
188                                         m_tracksList.append(projectTrack);
189                                     }
190                                 }
191                                 mlt.removeChild(tracksinfo);
192                             }
193                             QStringList expandedFolders;
194                             QDomNodeList folders = m_document.elementsByTagName("folder");
195                             for (int i = 0; i < folders.count(); i++) {
196                                 e = folders.item(i).cloneNode().toElement();
197                                 if (e.hasAttribute("opened")) expandedFolders.append(e.attribute("id"));
198                                 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
199                             }
200                             m_documentProperties["expandedfolders"] = expandedFolders.join(";");
201
202                             const int infomax = infoproducers.count();
203                             QDomNodeList producers = m_document.elementsByTagName("producer");
204                             const int max = producers.count();
205
206                             if (!progressDialog) {
207                                 progressDialog = new KProgressDialog(parent, i18n("Loading project"), i18n("Adding clips"));
208                                 progressDialog->setAllowCancel(false);
209                             } else {
210                                 progressDialog->setLabelText(i18n("Adding clips"));
211                             }
212                             progressDialog->progressBar()->setMaximum(infomax);
213                             progressDialog->show();
214                             qApp->processEvents();
215
216                             for (int i = 0; i < infomax; i++) {
217                                 e = infoproducers.item(i).cloneNode().toElement();
218                                 QString prodId = e.attribute("id");
219                                 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
220                                     e.setTagName("producer");
221                                     // Get MLT's original producer properties
222                                     QDomElement orig;
223                                     for (int j = 0; j < max; j++) {
224                                         QDomNode o = producers.item(j);
225                                         QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
226                                         if (origId == prodId) {
227                                             orig = o.cloneNode().toElement();
228                                             break;
229                                         }
230                                     }
231
232                                     if (!addClipInfo(e, orig, prodId)) {
233                                         // The user manually aborted the loading.
234                                         success = false;
235                                         emit resetProjectList();
236                                         m_tracksList.clear();
237                                         m_clipManager->clear();
238                                         break;
239                                     }
240                                 }
241                                 if (i % 10 == 0)
242                                     progressDialog->progressBar()->setValue(i);
243                             }
244
245                             if (success) {
246                                 QDomElement markers = infoXml.firstChildElement("markers");
247                                 if (!markers.isNull()) {
248                                     QDomNodeList markerslist = markers.childNodes();
249                                     int maxchild = markerslist.count();
250                                     for (int k = 0; k < maxchild; k++) {
251                                         e = markerslist.at(k).toElement();
252                                         if (e.tagName() == "marker")
253                                             m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
254                                     }
255                                     infoXml.removeChild(markers);
256                                 }
257
258                                 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
259                                 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
260                                 QDomNamedNodeMap props = docproperties.attributes();
261                                 for (int i = 0; i < props.count(); i++)
262                                     m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
263
264                                 if (validator.isModified()) setModified(true);
265                                 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
266                             }
267                         }
268                     }
269                 }
270             }
271         }
272     }
273     
274     // Something went wrong, or a new file was requested: create a new project
275     if (!success) {
276         m_url.clear();
277         setProfilePath(profileName);
278         m_document = createEmptyDocument(tracks.x(), tracks.y());
279     }
280
281     // Ask to create the project directory if it does not exist
282     if (!QFile::exists(m_projectFolder.path())) {
283         int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
284         if (create == KMessageBox::Yes) {
285             QDir projectDir(m_projectFolder.path());
286             bool ok = projectDir.mkpath(m_projectFolder.path());
287             if (!ok) {
288                 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
289             }
290         }
291     }
292
293     // Make sure the project folder is usable
294     if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
295         KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
296         m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
297     }
298
299     // Make sure that the necessary folders exist
300     KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
301     KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
302     KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/");
303     KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/");
304
305     updateProjectFolderPlacesEntry();
306
307     //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
308     connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
309 }
310
311 KdenliveDoc::~KdenliveDoc()
312 {
313     m_autoSaveTimer->stop();
314     delete m_commandStack;
315     kDebug() << "// DEL CLP MAN";
316     delete m_clipManager;
317     kDebug() << "// DEL CLP MAN done";
318     delete m_autoSaveTimer;
319     if (m_autosave) {
320         if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
321         delete m_autosave;
322     }
323 }
324
325 int KdenliveDoc::setSceneList()
326 {
327     m_render->resetProfile(KdenliveSettings::current_profile(), true);
328     if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
329         // INVALID MLT Consumer, something is wrong
330         return -1;
331     }
332     m_documentProperties.remove("position");
333     // m_document xml is now useless, clear it
334     m_document.clear();
335     return 0;
336 }
337
338 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
339 {
340     m_tracksList.clear();
341
342     // Tracks are added Â«backwards», so we need to reverse the track numbering
343     // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
344     // Better default names for tracks: Audio 1 etc. instead of blank numbers
345     for (int i = 0; i < audiotracks; i++) {
346         TrackInfo audioTrack;
347         audioTrack.type = AUDIOTRACK;
348         audioTrack.isMute = false;
349         audioTrack.isBlind = true;
350         audioTrack.isLocked = false;
351         audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
352         audioTrack.duration = 0;
353         m_tracksList.append(audioTrack);
354
355     }
356     for (int i = 0; i < videotracks; i++) {
357         TrackInfo videoTrack;
358         videoTrack.type = VIDEOTRACK;
359         videoTrack.isMute = false;
360         videoTrack.isBlind = false;
361         videoTrack.isLocked = false;
362         videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
363         videoTrack.duration = 0;
364         m_tracksList.append(videoTrack);
365     }
366     return createEmptyDocument(m_tracksList);
367 }
368
369 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
370 {
371     // Creating new document
372     QDomDocument doc;
373     QDomElement mlt = doc.createElement("mlt");
374     mlt.setAttribute("LC_NUMERIC", "");
375     doc.appendChild(mlt);
376     
377     // Create black producer
378     // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
379     // the composite transitions with the black track are corrupted.
380     QDomElement blk = doc.createElement("producer");
381     blk.setAttribute("in", 0);
382     blk.setAttribute("out", 500);
383     blk.setAttribute("id", "black");
384
385     QDomElement property = doc.createElement("property");
386     property.setAttribute("name", "mlt_type");
387     QDomText value = doc.createTextNode("producer");
388     property.appendChild(value);
389     blk.appendChild(property);
390
391     property = doc.createElement("property");
392     property.setAttribute("name", "aspect_ratio");
393     value = doc.createTextNode(QString::number(0));
394     property.appendChild(value);
395     blk.appendChild(property);
396
397     property = doc.createElement("property");
398     property.setAttribute("name", "length");
399     value = doc.createTextNode(QString::number(15000));
400     property.appendChild(value);
401     blk.appendChild(property);
402
403     property = doc.createElement("property");
404     property.setAttribute("name", "eof");
405     value = doc.createTextNode("pause");
406     property.appendChild(value);
407     blk.appendChild(property);
408
409     property = doc.createElement("property");
410     property.setAttribute("name", "resource");
411     value = doc.createTextNode("black");
412     property.appendChild(value);
413     blk.appendChild(property);
414
415     property = doc.createElement("property");
416     property.setAttribute("name", "mlt_service");
417     value = doc.createTextNode("colour");
418     property.appendChild(value);
419     blk.appendChild(property);
420
421     mlt.appendChild(blk);
422
423
424     QDomElement tractor = doc.createElement("tractor");
425     tractor.setAttribute("id", "maintractor");
426     QDomElement multitrack = doc.createElement("multitrack");
427     QDomElement playlist = doc.createElement("playlist");
428     playlist.setAttribute("id", "black_track");
429     mlt.appendChild(playlist);
430
431     QDomElement blank0 = doc.createElement("entry");
432     blank0.setAttribute("in", "0");
433     blank0.setAttribute("out", "1");
434     blank0.setAttribute("producer", "black");
435     playlist.appendChild(blank0);
436
437     // create playlists
438     int total = tracks.count() + 1;
439
440     for (int i = 1; i < total; i++) {
441         QDomElement playlist = doc.createElement("playlist");
442         playlist.setAttribute("id", "playlist" + QString::number(i));
443         mlt.appendChild(playlist);
444     }
445
446     QDomElement track0 = doc.createElement("track");
447     track0.setAttribute("producer", "black_track");
448     tractor.appendChild(track0);
449
450     // create audio and video tracks
451     for (int i = 1; i < total; i++) {
452         QDomElement track = doc.createElement("track");
453         track.setAttribute("producer", "playlist" + QString::number(i));
454         if (tracks.at(i - 1).type == AUDIOTRACK) {
455             track.setAttribute("hide", "video");
456         } else if (tracks.at(i - 1).isBlind)
457             track.setAttribute("hide", "video");
458         if (tracks.at(i - 1).isMute)
459             track.setAttribute("hide", "audio");
460         tractor.appendChild(track);
461     }
462
463     for (int i = 2; i < total ; i++) {
464         QDomElement transition = doc.createElement("transition");
465         transition.setAttribute("always_active", "1");
466
467         QDomElement property = doc.createElement("property");
468         property.setAttribute("name", "a_track");
469         QDomText value = doc.createTextNode(QString::number(1));
470         property.appendChild(value);
471         transition.appendChild(property);
472
473         property = doc.createElement("property");
474         property.setAttribute("name", "b_track");
475         value = doc.createTextNode(QString::number(i));
476         property.appendChild(value);
477         transition.appendChild(property);
478
479         property = doc.createElement("property");
480         property.setAttribute("name", "mlt_service");
481         value = doc.createTextNode("mix");
482         property.appendChild(value);
483         transition.appendChild(property);
484
485         property = doc.createElement("property");
486         property.setAttribute("name", "combine");
487         value = doc.createTextNode("1");
488         property.appendChild(value);
489         transition.appendChild(property);
490
491         property = doc.createElement("property");
492         property.setAttribute("name", "internal_added");
493         value = doc.createTextNode("237");
494         property.appendChild(value);
495         transition.appendChild(property);
496         tractor.appendChild(transition);
497     }
498     mlt.appendChild(tractor);
499     return doc;
500 }
501
502
503 void KdenliveDoc::syncGuides(QList <Guide *> guides)
504 {
505     m_guidesXml.clear();
506     QDomElement guideNode = m_guidesXml.createElement("guides");
507     m_guidesXml.appendChild(guideNode);
508     QDomElement e;
509
510     for (int i = 0; i < guides.count(); i++) {
511         e = m_guidesXml.createElement("guide");
512         e.setAttribute("time", guides.at(i)->position().ms() / 1000);
513         e.setAttribute("comment", guides.at(i)->label());
514         guideNode.appendChild(e);
515     }
516     setModified(true);
517     emit guidesUpdated();
518 }
519
520 QDomElement KdenliveDoc::guidesXml() const
521 {
522     return m_guidesXml.documentElement();
523 }
524
525 void KdenliveDoc::slotAutoSave()
526 {
527     if (m_render && m_autosave) {
528         if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
529             // show error: could not open the autosave file
530             kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
531         }
532         kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
533         saveSceneList(m_autosave->fileName(), m_render->sceneList(), QStringList(), true);
534     }
535 }
536
537 void KdenliveDoc::setZoom(int horizontal, int vertical)
538 {
539     m_documentProperties["zoom"] = QString::number(horizontal);
540     m_documentProperties["verticalzoom"] = QString::number(vertical);
541 }
542
543 QPoint KdenliveDoc::zoom() const
544 {
545     return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
546 }
547
548 void KdenliveDoc::setZone(int start, int end)
549 {
550     m_documentProperties["zonein"] = QString::number(start);
551     m_documentProperties["zoneout"] = QString::number(end);
552 }
553
554 QPoint KdenliveDoc::zone() const
555 {
556     return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
557 }
558
559 QDomDocument KdenliveDoc::xmlSceneList(const QString &scene, const QStringList expandedFolders)
560 {
561     QDomDocument sceneList;
562     sceneList.setContent(scene, true);
563     QDomElement mlt = sceneList.firstChildElement("mlt");
564     if (mlt.isNull() || !mlt.hasChildNodes()) {
565         //scenelist is corrupted
566         return sceneList;
567     }
568
569     // Set playlist audio volume to 100%
570     QDomElement tractor = mlt.firstChildElement("tractor");
571     if (!tractor.isNull()) {
572         QDomNodeList props = tractor.elementsByTagName("property");
573         for (int i = 0; i < props.count(); i++) {
574             if (props.at(i).toElement().attribute("name") == "meta.volume") {
575                 props.at(i).firstChild().setNodeValue("1");
576                 break;
577             }
578         }
579     }
580
581     QDomElement addedXml = sceneList.createElement("kdenlivedoc");
582     mlt.appendChild(addedXml);
583
584     // check if project contains custom effects to embed them in project file
585     QDomNodeList effects = mlt.elementsByTagName("filter");
586     int maxEffects = effects.count();
587     kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
588     QMap <QString, QString> effectIds;
589     for (int i = 0; i < maxEffects; i++) {
590         QDomNode m = effects.at(i);
591         QDomNodeList params = m.childNodes();
592         QString id;
593         QString tag;
594         for (int j = 0; j < params.count(); j++) {
595             QDomElement e = params.item(j).toElement();
596             if (e.attribute("name") == "kdenlive_id") {
597                 id = e.firstChild().nodeValue();
598             }
599             if (e.attribute("name") == "tag") {
600                 tag = e.firstChild().nodeValue();
601             }
602             if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
603         }
604     }
605     QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
606     addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
607
608     QDomElement markers = sceneList.createElement("markers");
609     addedXml.setAttribute("version", DOCUMENTVERSION);
610     addedXml.setAttribute("kdenliveversion", VERSION);
611     addedXml.setAttribute("profile", profilePath());
612     addedXml.setAttribute("projectfolder", m_projectFolder.path());
613
614     QDomElement docproperties = sceneList.createElement("documentproperties");
615     QMapIterator<QString, QString> i(m_documentProperties);
616     while (i.hasNext()) {
617         i.next();
618         docproperties.setAttribute(i.key(), i.value());
619     }
620     docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
621     addedXml.appendChild(docproperties);
622
623     QDomElement docnotes = sceneList.createElement("documentnotes");
624     QDomText value = sceneList.createTextNode(m_notesWidget->toHtml());
625     docnotes.appendChild(value);
626     addedXml.appendChild(docnotes);
627
628     // Add profile info
629     QDomElement profileinfo = sceneList.createElement("profileinfo");
630     profileinfo.setAttribute("description", m_profile.description);
631     profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
632     profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
633     profileinfo.setAttribute("width", m_profile.width);
634     profileinfo.setAttribute("height", m_profile.height);
635     profileinfo.setAttribute("progressive", m_profile.progressive);
636     profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
637     profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
638     profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
639     profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
640     addedXml.appendChild(profileinfo);
641
642     // tracks info
643     QDomElement tracksinfo = sceneList.createElement("tracksinfo");
644     foreach(const TrackInfo & info, m_tracksList) {
645         QDomElement trackinfo = sceneList.createElement("trackinfo");
646         if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
647         trackinfo.setAttribute("mute", info.isMute);
648         trackinfo.setAttribute("blind", info.isBlind);
649         trackinfo.setAttribute("locked", info.isLocked);
650         trackinfo.setAttribute("trackname", info.trackName);
651         tracksinfo.appendChild(trackinfo);
652     }
653     addedXml.appendChild(tracksinfo);
654
655     // save project folders
656     QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
657
658     QMapIterator<QString, QString> f(folderlist);
659     while (f.hasNext()) {
660         f.next();
661         QDomElement folder = sceneList.createElement("folder");
662         folder.setAttribute("id", f.key());
663         folder.setAttribute("name", f.value());
664         if (expandedFolders.contains(f.key())) folder.setAttribute("opened", "1");
665         addedXml.appendChild(folder);
666     }
667
668     // Save project clips
669     QDomElement e;
670     QList <DocClipBase*> list = m_clipManager->documentClipList();
671     for (int i = 0; i < list.count(); i++) {
672         e = list.at(i)->toXML();
673         e.setTagName("kdenlive_producer");
674         addedXml.appendChild(sceneList.importNode(e, true));
675         QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
676         for (int j = 0; j < marks.count(); j++) {
677             QDomElement marker = sceneList.createElement("marker");
678             marker.setAttribute("time", marks.at(j).time().ms() / 1000);
679             marker.setAttribute("comment", marks.at(j).comment());
680             marker.setAttribute("id", e.attribute("id"));
681             markers.appendChild(marker);
682         }
683     }
684     addedXml.appendChild(markers);
685
686     // Add guides
687     if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
688
689     // Add clip groups
690     addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
691
692     //wes.appendChild(doc.importNode(kdenliveData, true));
693     return sceneList;
694 }
695
696 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene, const QStringList expandedFolders, bool autosave)
697 {
698     QDomDocument sceneList = xmlSceneList(scene, expandedFolders);
699     if (sceneList.isNull()) {
700         //Make sure we don't save if scenelist is corrupted
701         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
702         return false;
703     }
704     
705     // Backup current version
706     if (!autosave) backupLastSavedVersion(path);
707     QFile file(path);
708     
709     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
710         kWarning() << "//////  ERROR writing to file: " << path;
711         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
712         return false;
713     }
714
715     file.write(sceneList.toString().toUtf8());
716     if (file.error() != QFile::NoError) {
717         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
718         file.close();
719         return false;
720     }
721     file.close();
722     if (!autosave) {
723         cleanupBackupFiles();
724         QFileInfo info(file);
725         QString fileName = KUrl(path).fileName().section('.', 0, -2);   
726         fileName.append("-" + m_documentProperties.value("documentid"));
727         fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
728         fileName.append(".kdenlive.png");
729         KUrl backupFile = m_projectFolder;
730         backupFile.addPath(".backup/");
731         backupFile.addPath(fileName);
732         emit saveTimelinePreview(backupFile.path());
733     }
734     return true;
735 }
736
737 ClipManager *KdenliveDoc::clipManager()
738 {
739     return m_clipManager;
740 }
741
742 KUrl KdenliveDoc::projectFolder() const
743 {
744     //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
745     return m_projectFolder;
746 }
747
748 void KdenliveDoc::setProjectFolder(KUrl url)
749 {
750     if (url == m_projectFolder) return;
751     setModified(true);
752     KStandardDirs::makeDir(url.path());
753     KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
754     KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
755     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);
756     m_projectFolder = url;
757
758     updateProjectFolderPlacesEntry();
759 }
760
761 void KdenliveDoc::moveProjectData(KUrl url)
762 {
763     QList <DocClipBase*> list = m_clipManager->documentClipList();
764     //TODO: Also move ladspa effects files
765     for (int i = 0; i < list.count(); i++) {
766         DocClipBase *clip = list.at(i);
767         if (clip->clipType() == TEXT) {
768             // the image for title clip must be moved
769             KUrl oldUrl = clip->fileURL();
770             KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
771             KIO::Job *job = KIO::copy(oldUrl, newUrl);
772             if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
773         }
774         QString hash = clip->getClipHash();
775         KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
776         KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
777         if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
778             KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
779             KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
780             KIO::NetAccess::synchronousRun(job, 0);
781         }
782         if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
783             KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
784             KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
785             if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
786         }
787     }
788 }
789
790 const QString &KdenliveDoc::profilePath() const
791 {
792     return m_profile.path;
793 }
794
795 MltVideoProfile KdenliveDoc::mltProfile() const
796 {
797     return m_profile;
798 }
799
800 bool KdenliveDoc::setProfilePath(QString path)
801 {
802     if (path.isEmpty()) path = KdenliveSettings::default_profile();
803     if (path.isEmpty()) path = "dv_pal";
804     m_profile = ProfilesDialog::getVideoProfile(path);
805     double current_fps = m_fps;
806     if (m_profile.path.isEmpty()) {
807         // Profile not found, use embedded profile
808         QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
809         if (profileInfo.isNull()) {
810             KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
811             m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
812         } else {
813             m_profile.description = profileInfo.attribute("description");
814             m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
815             m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
816             m_profile.width = profileInfo.attribute("width").toInt();
817             m_profile.height = profileInfo.attribute("height").toInt();
818             m_profile.progressive = profileInfo.attribute("progressive").toInt();
819             m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
820             m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
821             m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
822             m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
823             QString existing = ProfilesDialog::existingProfile(m_profile);
824             if (!existing.isEmpty()) {
825                 m_profile = ProfilesDialog::getVideoProfile(existing);
826                 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
827             } else {
828                 QString newDesc = m_profile.description;
829                 bool ok = true;
830                 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
831                     newDesc = QInputDialog::getText(kapp->activeWindow(), i18n("Existing Profile"), i18n("Your project uses an unknown profile.\nIt uses an existing profile name: %1.\nPlease choose a new name to save it", newDesc), QLineEdit::Normal, newDesc, &ok);
832                 }
833                 if (ok == false) {
834                     // User canceled, use default profile
835                     m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
836                 } else {
837                     if (newDesc != m_profile.description) {
838                         // Profile description existed, was replaced by new one
839                         m_profile.description = newDesc;
840                     } else {
841                         KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
842                     }
843                     ProfilesDialog::saveProfile(m_profile);
844                 }
845             }
846             setModified(true);
847         }
848     }
849
850     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
851     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
852     KdenliveSettings::setProject_fps(m_fps);
853     m_width = m_profile.width;
854     m_height = m_profile.height;
855     kDebug() << "Kdenlive document, init timecode from path: " << path << ",  " << m_fps;
856     m_timecode.setFormat(m_fps);
857     KdenliveSettings::setCurrent_profile(m_profile.path);
858     return (current_fps != m_fps);
859 }
860
861 double KdenliveDoc::dar() const
862 {
863     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
864 }
865
866 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
867 {
868     emit progressInfo(message, progress);
869 }
870
871 QUndoStack *KdenliveDoc::commandStack()
872 {
873     return m_commandStack;
874 }
875
876 /*
877 void KdenliveDoc::setRenderer(Render *render) {
878     if (m_render) return;
879     m_render = render;
880     emit progressInfo(i18n("Loading playlist..."), 0);
881     //qApp->processEvents();
882     if (m_render) {
883         m_render->setSceneList(m_document.toString(), m_startPos);
884         kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
885         checkProjectClips();
886     }
887     emit progressInfo(QString(), -1);
888 }*/
889
890 void KdenliveDoc::checkProjectClips(bool displayRatioChanged, bool fpsChanged)
891 {
892     if (m_render == NULL) return;
893     m_clipManager->resetProducersList(m_render->producersList(), displayRatioChanged, fpsChanged);
894 }
895
896 Render *KdenliveDoc::renderer()
897 {
898     return m_render;
899 }
900
901 void KdenliveDoc::updateClip(const QString id)
902 {
903     emit updateClipDisplay(id);
904 }
905
906 int KdenliveDoc::getFramePos(QString duration)
907 {
908     return m_timecode.getFrameCount(duration);
909 }
910
911 QString KdenliveDoc::producerName(const QString &id)
912 {
913     QString result = "unnamed";
914     QDomNodeList prods = producersList();
915     int ct = prods.count();
916     for (int i = 0; i <  ct ; i++) {
917         QDomElement e = prods.item(i).toElement();
918         if (e.attribute("id") != "black" && e.attribute("id") == id) {
919             result = e.attribute("name");
920             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
921             break;
922         }
923     }
924     return result;
925 }
926
927 QDomDocument KdenliveDoc::toXml()
928 {
929     return m_document;
930 }
931
932 Timecode KdenliveDoc::timecode() const
933 {
934     return m_timecode;
935 }
936
937 QDomNodeList KdenliveDoc::producersList()
938 {
939     return m_document.elementsByTagName("producer");
940 }
941
942 double KdenliveDoc::projectDuration() const
943 {
944     if (m_render)
945         return GenTime(m_render->getLength(), m_fps).ms() / 1000;
946     else
947         return 0;
948 }
949
950 double KdenliveDoc::fps() const
951 {
952     return m_fps;
953 }
954
955 int KdenliveDoc::width() const
956 {
957     return m_width;
958 }
959
960 int KdenliveDoc::height() const
961 {
962     return m_height;
963 }
964
965 KUrl KdenliveDoc::url() const
966 {
967     return m_url;
968 }
969
970 void KdenliveDoc::setUrl(KUrl url)
971 {
972     m_url = url;
973 }
974
975 void KdenliveDoc::setModified(bool mod)
976 {
977     if (isReadOnly()) return;
978     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
979         m_autoSaveTimer->start(3000);
980     }
981     if (mod == m_modified) return;
982     m_modified = mod;
983     emit docModified(m_modified);
984 }
985
986 bool KdenliveDoc::isModified() const
987 {
988     return m_modified;
989 }
990
991 const QString KdenliveDoc::description() const
992 {
993     if (m_url.isEmpty())
994         return i18n("Untitled") + " / " + m_profile.description;
995     else
996         return m_url.fileName() + " / " + m_profile.description;
997 }
998
999 bool KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
1000 {
1001     const QString producerId = clipId.section('_', 0, 0);
1002     DocClipBase *clip = m_clipManager->getClipById(producerId);
1003
1004     if (clip == NULL) {
1005         elem.setAttribute("id", producerId);
1006         QString path = elem.attribute("resource");
1007         QString extension;
1008         if (elem.attribute("type").toInt() == SLIDESHOW) {
1009             extension = KUrl(path).fileName();
1010             path = KUrl(path).directory();
1011         }
1012
1013         if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
1014             kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1015             const QString size = elem.attribute("file_size");
1016             const QString hash = elem.attribute("file_hash");
1017             QString newpath;
1018             int action = KMessageBox::No;
1019             if (!size.isEmpty() && !hash.isEmpty()) {
1020                 if (!m_searchFolder.isEmpty())
1021                     newpath = searchFileRecursively(m_searchFolder, size, hash);
1022                 else
1023                     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")));
1024             } else {
1025                 if (elem.attribute("type").toInt() == SLIDESHOW) {
1026                     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")));
1027                     if (res == KMessageBox::Yes)
1028                         newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1029                     else {
1030                         // Abort project loading
1031                         action = res;
1032                     }
1033                 } else {
1034                     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")));
1035                     if (res == KMessageBox::Yes)
1036                         newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1037                     else {
1038                         // Abort project loading
1039                         action = res;
1040                     }
1041                 }
1042             }
1043             if (action == KMessageBox::Yes) {
1044                 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1045                 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1046                 if (!m_searchFolder.isEmpty())
1047                     newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1048             } else if (action == KMessageBox::Cancel) {
1049                 return false;
1050             } else if (action == KMessageBox::No) {
1051                 // Keep clip as placeHolder
1052                 elem.setAttribute("placeholder", '1');
1053             }
1054             if (!newpath.isEmpty()) {
1055                 if (elem.attribute("type").toInt() == SLIDESHOW)
1056                     newpath.append('/' + extension);
1057                 elem.setAttribute("resource", newpath);
1058                 setNewClipResource(clipId, newpath);
1059                 setModified(true);
1060             }
1061         }
1062         clip = new DocClipBase(m_clipManager, elem, producerId);
1063         m_clipManager->addClip(clip);
1064     }
1065
1066     if (createClipItem) {
1067         emit addProjectClip(clip);
1068     }
1069
1070     return true;
1071 }
1072
1073 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1074 {
1075     QDomNodeList prods = m_document.elementsByTagName("producer");
1076     int maxprod = prods.count();
1077     for (int i = 0; i < maxprod; i++) {
1078         QDomNode m = prods.at(i);
1079         QString prodId = m.toElement().attribute("id");
1080         if (prodId == id || prodId.startsWith(id + '_')) {
1081             QDomNodeList params = m.childNodes();
1082             for (int j = 0; j < params.count(); j++) {
1083                 QDomElement e = params.item(j).toElement();
1084                 if (e.attribute("name") == "resource") {
1085                     e.firstChild().setNodeValue(path);
1086                     break;
1087                 }
1088             }
1089         }
1090     }
1091 }
1092
1093 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1094 {
1095     QString foundFileName;
1096     QByteArray fileData;
1097     QByteArray fileHash;
1098     QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1099     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1100         QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1101         if (file.open(QIODevice::ReadOnly)) {
1102             if (QString::number(file.size()) == matchSize) {
1103                 /*
1104                 * 1 MB = 1 second per 450 files (or faster)
1105                 * 10 MB = 9 seconds per 450 files (or faster)
1106                 */
1107                 if (file.size() > 1000000 * 2) {
1108                     fileData = file.read(1000000);
1109                     if (file.seek(file.size() - 1000000))
1110                         fileData.append(file.readAll());
1111                 } else
1112                     fileData = file.readAll();
1113                 file.close();
1114                 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1115                 if (QString(fileHash.toHex()) == matchHash)
1116                     return file.fileName();
1117             }
1118         }
1119         kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1120     }
1121     filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1122     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1123         foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1124         if (!foundFileName.isEmpty())
1125             break;
1126     }
1127     return foundFileName;
1128 }
1129
1130 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1131 {
1132     DocClipBase *clip = m_clipManager->getClipById(clipId);
1133     if (clip == NULL) {
1134         if (!addClip(elem, clipId, false))
1135             return false;
1136     } else {
1137         QMap <QString, QString> properties;
1138         QDomNamedNodeMap attributes = elem.attributes();
1139         for (int i = 0; i < attributes.count(); i++) {
1140             QString attrname = attributes.item(i).nodeName();
1141             if (attrname != "resource")
1142                 properties.insert(attrname, attributes.item(i).nodeValue());
1143             kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1144         }
1145         clip->setProperties(properties);
1146         emit addProjectClip(clip, false);
1147     }
1148     if (orig != QDomElement()) {
1149         QMap<QString, QString> meta;
1150         for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1151             QString name = m.toElement().attribute("name");
1152             if (name.startsWith("meta.attr"))
1153                 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1154         }
1155         if (!meta.isEmpty()) {
1156             if (clip == NULL)
1157                 clip = m_clipManager->getClipById(clipId);
1158             if (clip)
1159                 clip->setMetadata(meta);
1160         }
1161     }
1162     return true;
1163 }
1164
1165
1166 void KdenliveDoc::deleteClip(const QString &clipId)
1167 {
1168     emit signalDeleteProjectClip(clipId);
1169 }
1170
1171 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1172 {
1173     m_clipManager->slotAddClipList(urls, group, groupId);
1174     //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1175     setModified(true);
1176 }
1177
1178
1179 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1180 {
1181     m_clipManager->slotAddClipFile(url, group, groupId);
1182     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1183     setModified(true);
1184 }
1185
1186 const QString KdenliveDoc::getFreeClipId()
1187 {
1188     return QString::number(m_clipManager->getFreeClipId());
1189 }
1190
1191 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1192 {
1193     return m_clipManager->getClipById(clipId);
1194 }
1195
1196 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement xml, QString group, const QString &groupId)
1197 {
1198     m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1199     setModified(true);
1200     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1201 }
1202
1203 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1204 {
1205     m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1206     setModified(true);
1207     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1208 }
1209
1210 void KdenliveDoc::slotCreateSlideshowClipFile(const QString name, const QString path, int count, const QString duration,
1211         const bool loop, const bool crop, const bool fade,
1212         const QString &luma_duration, const QString &luma_file, const int softness,
1213         const QString &animation, QString group, const QString &groupId)
1214 {
1215     m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop,
1216                                             crop, fade, luma_duration,
1217                                             luma_file, softness,
1218                                             animation, group, groupId);
1219     setModified(true);
1220     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1221 }
1222
1223 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1224 {
1225     QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1226     KStandardDirs::makeDir(titlesFolder);
1227     TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1228     if (dia_ui->exec() == QDialog::Accepted) {
1229         m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->outPoint(), dia_ui->xml().toString(), group, groupId);
1230         setModified(true);
1231         emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1232     }
1233     delete dia_ui;
1234 }
1235
1236 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1237 {
1238     QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1239     if (path.isEmpty()) {
1240         path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1241     }
1242
1243     if (path.isEmpty()) return;
1244
1245     //TODO: rewrite with new title system (just set resource)
1246     m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1247     setModified(true);
1248     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1249 }
1250
1251 int KdenliveDoc::tracksCount() const
1252 {
1253     return m_tracksList.count();
1254 }
1255
1256 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1257 {
1258     if (ix < 0 || ix >= m_tracksList.count()) {
1259         kWarning() << "Track INFO outisde of range";
1260         return TrackInfo();
1261     }
1262     return m_tracksList.at(ix);
1263 }
1264
1265 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1266 {
1267     if (ix < 0 || ix >= m_tracksList.count()) {
1268         kWarning() << "SWITCH Track outisde of range";
1269         return;
1270     }
1271     m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1272 }
1273
1274 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1275 {
1276     if (ix < 0 || ix >= m_tracksList.count()) {
1277         kWarning() << "Track Lock outisde of range";
1278         return;
1279     }
1280     m_tracksList[ix].isLocked = lock;
1281 }
1282
1283 bool KdenliveDoc::isTrackLocked(int ix) const
1284 {
1285     if (ix < 0 || ix >= m_tracksList.count()) {
1286         kWarning() << "Track Lock outisde of range";
1287         return true;
1288     }
1289     return m_tracksList.at(ix).isLocked;
1290 }
1291
1292 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1293 {
1294     if (ix < 0 || ix >= m_tracksList.count()) {
1295         kWarning() << "SWITCH Track outisde of range";
1296         return;
1297     }
1298     m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1299 }
1300
1301 int KdenliveDoc::trackDuration(int ix)
1302 {
1303     return m_tracksList.at(ix).duration; 
1304 }
1305
1306 void KdenliveDoc::setTrackDuration(int ix, int duration)
1307 {
1308     m_tracksList[ix].duration = duration;
1309 }
1310
1311 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1312 {
1313     if (ix == -1) m_tracksList << type;
1314     else m_tracksList.insert(ix, type);
1315 }
1316
1317 void KdenliveDoc::deleteTrack(int ix)
1318 {
1319     if (ix < 0 || ix >= m_tracksList.count()) {
1320         kWarning() << "Delete Track outisde of range";
1321         return;
1322     }
1323     m_tracksList.removeAt(ix);
1324 }
1325
1326 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1327 {
1328     if (ix < 0 || ix >= m_tracksList.count()) {
1329         kWarning() << "SET Track Type outisde of range";
1330         return;
1331     }
1332     m_tracksList[ix].type = type.type;
1333     m_tracksList[ix].isMute = type.isMute;
1334     m_tracksList[ix].isBlind = type.isBlind;
1335     m_tracksList[ix].isLocked = type.isLocked;
1336     m_tracksList[ix].trackName = type.trackName;
1337 }
1338
1339 const QList <TrackInfo> KdenliveDoc::tracksList() const
1340 {
1341     return m_tracksList;
1342 }
1343
1344 QPoint KdenliveDoc::getTracksCount() const
1345 {
1346     int audio = 0;
1347     int video = 0;
1348     foreach(const TrackInfo & info, m_tracksList) {
1349         if (info.type == VIDEOTRACK) video++;
1350         else audio++;
1351     }
1352     return QPoint(video, audio);
1353 }
1354
1355 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1356 {
1357     pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1358 }
1359
1360 QString KdenliveDoc::getLadspaFile() const
1361 {
1362     int ct = 0;
1363     QString counter = QString::number(ct).rightJustified(5, '0', false);
1364     while (QFile::exists(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa")) {
1365         ct++;
1366         counter = QString::number(ct).rightJustified(5, '0', false);
1367     }
1368     return m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa";
1369 }
1370
1371 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1372 {
1373     DocumentChecker d(infoproducers, m_document);
1374     return (d.hasErrorInClips() == false);
1375
1376     /*    int clipType;
1377         QDomElement e;
1378         QString id;
1379         QString resource;
1380         QList <QDomElement> missingClips;
1381         for (int i = 0; i < infoproducers.count(); i++) {
1382             e = infoproducers.item(i).toElement();
1383             clipType = e.attribute("type").toInt();
1384             if (clipType == COLOR) continue;
1385             if (clipType == TEXT) {
1386                 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1387                 continue;
1388             }
1389             id = e.attribute("id");
1390             resource = e.attribute("resource");
1391             if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1392             if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1393                 // Missing clip found
1394                 missingClips.append(e);
1395             } else {
1396                 // Check if the clip has changed
1397                 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1398                     if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1399                         e.removeAttribute("file_hash");
1400                 }
1401             }
1402         }
1403         if (missingClips.isEmpty()) return true;
1404         DocumentChecker d(missingClips, m_document);
1405         return (d.exec() == QDialog::Accepted);*/
1406 }
1407
1408 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1409 {
1410     m_documentProperties[name] = value;
1411 }
1412
1413 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1414 {
1415     return m_documentProperties.value(name);
1416 }
1417
1418 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1419 {
1420     QMap <QString, QString> renderProperties;
1421     QMapIterator<QString, QString> i(m_documentProperties);
1422     while (i.hasNext()) {
1423         i.next();
1424         if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1425     }
1426     return renderProperties;
1427 }
1428
1429 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1430 {
1431     if (ix < 0 || ix >= m_tracksList.count()) {
1432         kWarning() << "Add Track effect outisde of range";
1433         return;
1434     }
1435     effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1436
1437     // Init parameter value & keyframes if required
1438     QDomNodeList params = effect.elementsByTagName("parameter");
1439     for (int i = 0; i < params.count(); i++) {
1440         QDomElement e = params.item(i).toElement();
1441
1442         // Check if this effect has a variable parameter
1443         if (e.attribute("default").contains('%')) {
1444             double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1445             e.setAttribute("default", evaluatedValue);
1446             if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1447                 e.setAttribute("value", evaluatedValue);
1448             }
1449         }
1450
1451         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1452             QString def = e.attribute("default");
1453             // Effect has a keyframe type parameter, we need to set the values
1454             if (e.attribute("keyframes").isEmpty()) {
1455                 e.setAttribute("keyframes", "0:" + def + ';');
1456                 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1457                 //break;
1458             }
1459         }
1460
1461         if (effect.attribute("id") == "crop") {
1462             // default use_profile to 1 for clips with proxies to avoid problems when rendering
1463             if (e.attribute("name") == "use_profile" && getDocumentProperty("enableproxy") == "1")
1464                 e.setAttribute("value", "1");
1465         }
1466     }
1467
1468     m_tracksList[ix].effectsList.append(effect);
1469 }
1470
1471 void KdenliveDoc::removeTrackEffect(int ix, QDomElement effect)
1472 {
1473     if (ix < 0 || ix >= m_tracksList.count()) {
1474         kWarning() << "Remove Track effect outisde of range";
1475         return;
1476     }
1477     QString index;
1478     QString toRemove = effect.attribute("kdenlive_ix");
1479     for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1480         index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix");
1481         if (toRemove == index) {
1482             m_tracksList[ix].effectsList.removeAt(i);
1483             i--;
1484         } else if (index.toInt() > toRemove.toInt()) {
1485             m_tracksList[ix].effectsList.item(i).setAttribute("kdenlive_ix", index.toInt() - 1);
1486         }
1487     }
1488 }
1489
1490 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1491 {
1492     if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1493         kWarning() << "Set Track effect outisde of range";
1494         return;
1495     }
1496     if (effectIndex < 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count() - 1) || effect.isNull()) {
1497         kDebug() << "Invalid effect index: " << effectIndex;
1498         return;
1499     }
1500     effect.setAttribute("kdenlive_ix", effectIndex + 1);
1501     m_tracksList[trackIndex].effectsList.replace(effectIndex, effect);
1502 }
1503
1504 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1505 {
1506     if (ix < 0 || ix >= m_tracksList.count()) {
1507         kWarning() << "Get Track effects outisde of range";
1508         return EffectsList();
1509     }
1510     return m_tracksList.at(ix).effectsList;
1511 }
1512
1513 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1514 {
1515     if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1516         kWarning() << "Get Track effect outisde of range";
1517         return QDomElement();
1518     }
1519     EffectsList list = m_tracksList.at(trackIndex).effectsList;
1520     if (effectIndex > list.count() - 1 || effectIndex < 0 || list.at(effectIndex).isNull()) return QDomElement();
1521     return list.at(effectIndex).cloneNode().toElement();
1522 }
1523
1524 bool KdenliveDoc::saveCustomEffects(QDomNodeList customeffects)
1525 {
1526     QDomElement e;
1527     QStringList importedEffects;
1528     int maxchild = customeffects.count();
1529     for (int i = 0; i < maxchild; i++) {
1530         e = customeffects.at(i).toElement();
1531         QString id = e.attribute("id");
1532         QString tag = e.attribute("tag");
1533         if (!id.isEmpty()) {
1534             // Check if effect exists or save it
1535             if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1536                 QDomDocument doc;
1537                 doc.appendChild(doc.importNode(e, true));
1538                 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1539                 path += id + ".xml";
1540                 if (!QFile::exists(path)) {
1541                     importedEffects << id;
1542                     QFile file(path);
1543                     if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1544                         QTextStream out(&file);
1545                         out << doc.toString();
1546                     }
1547                 }
1548             }
1549         }
1550     }
1551     if (!importedEffects.isEmpty()) KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1552     return (!importedEffects.isEmpty());
1553 }
1554
1555 void KdenliveDoc::updateProjectFolderPlacesEntry()
1556 {
1557     /*
1558      * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1559      * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1560      */
1561
1562     const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1563     KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1564     KBookmarkGroup root = bookmarkManager->root();
1565     KBookmark bookmark = root.first();
1566
1567     QString kdenliveName = KGlobal::mainComponent().componentName();
1568     KUrl documentLocation = m_projectFolder;
1569
1570     bool exists = false;
1571
1572     while (!bookmark.isNull()) {
1573         // UDI not empty indicates a device
1574         QString udi = bookmark.metaDataItem("UDI");
1575         QString appName = bookmark.metaDataItem("OnlyInApp");
1576
1577         if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1578             if (bookmark.url() != documentLocation) {
1579                 bookmark.setUrl(documentLocation);
1580                 bookmarkManager->emitChanged(root);
1581             }
1582             exists = true;
1583             break;
1584         }
1585
1586         bookmark = root.next(bookmark);
1587     }
1588
1589     // if entry does not exist yet (was not found), well, create it then
1590     if (!exists) {
1591         bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1592         // Make this user selectable ?
1593         bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1594         bookmarkManager->emitChanged(root);
1595     }
1596 }
1597
1598 QStringList KdenliveDoc::getExpandedFolders()
1599 {
1600     QStringList result = m_documentProperties.value("expandedfolders").split(';');
1601     // this property is only needed once when opening project, so clear it now
1602     m_documentProperties.remove("expandedfolders");
1603     return result;
1604 }
1605
1606 // static
1607 double KdenliveDoc::getDisplayRatio(const QString &path)
1608 {
1609     QFile file(path);
1610     QDomDocument doc;
1611     if (!file.open(QIODevice::ReadOnly)) {
1612         kWarning() << "ERROR, CANNOT READ: " << path;
1613         return 0;
1614     }
1615     if (!doc.setContent(&file)) {
1616         kWarning() << "ERROR, CANNOT READ: " << path;
1617         file.close();
1618         return 0;
1619     }
1620     file.close();
1621     QDomNodeList list = doc.elementsByTagName("profile");
1622     if (list.isEmpty()) return 0;
1623     QDomElement profile = list.at(0).toElement();
1624     double den = profile.attribute("display_aspect_den").toDouble();
1625     if (den > 0) return profile.attribute("display_aspect_num").toDouble() / den;
1626     return 0;
1627 }
1628
1629 void KdenliveDoc::backupLastSavedVersion(const QString &path)
1630 {
1631     // Ensure backup folder exists
1632     if (path.isEmpty()) return;
1633     QFile file(path);
1634     KUrl backupFile = m_projectFolder;
1635     backupFile.addPath(".backup/");
1636     KIO::NetAccess::mkdir(backupFile, kapp->activeWindow());
1637     QString fileName = KUrl(path).fileName().section('.', 0, -2);
1638     QFileInfo info(file);
1639     fileName.append("-" + m_documentProperties.value("documentid"));
1640     fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
1641     fileName.append(".kdenlive");
1642     backupFile.addPath(fileName);
1643
1644     if (file.exists()) {
1645         // delete previous backup if it was done less than 60 seconds ago
1646         QFile::remove(backupFile.path());
1647         if (!QFile::copy(path, backupFile.path())) {
1648             KMessageBox::information(kapp->activeWindow(), i18n("Cannot create backup copy:\n%1", backupFile.path()));
1649         }
1650     }    
1651 }
1652
1653 bool KdenliveDoc::isReadOnly() const
1654 {
1655     return m_documentProperties.contains("readonly");
1656 }
1657
1658 void KdenliveDoc::cleanupBackupFiles()
1659 {
1660     KUrl backupFile = m_projectFolder;
1661     backupFile.addPath(".backup/");
1662     QDir dir(backupFile.path());
1663     QString projectFile = url().fileName().section('.', 0, -2);
1664     projectFile.append("-" + m_documentProperties.value("documentid"));
1665     projectFile.append("-??");
1666     projectFile.append("??");
1667     projectFile.append("-??");
1668     projectFile.append("-??");
1669     projectFile.append("-??");
1670     projectFile.append("-??.kdenlive");
1671
1672     QStringList filter;
1673     backupFile.addPath(projectFile);
1674     filter << projectFile;
1675     dir.setNameFilters(filter);
1676     QFileInfoList resultList = dir.entryInfoList(QDir::Files, QDir::Time);
1677
1678     QDateTime d = QDateTime::currentDateTime();
1679     QStringList hourList;
1680     QStringList dayList;
1681     QStringList weekList;
1682     QStringList oldList;
1683     for (int i = 0; i < resultList.count(); i++) {
1684         if (d.secsTo(resultList.at(i).lastModified()) < 3600) {
1685             // files created in the last hour
1686             hourList.append(resultList.at(i).absoluteFilePath());
1687         }
1688         else if (d.secsTo(resultList.at(i).lastModified()) < 43200) {
1689             // files created in the day
1690             dayList.append(resultList.at(i).absoluteFilePath());
1691         }
1692         else if (d.daysTo(resultList.at(i).lastModified()) < 8) {
1693             // files created in the week
1694             weekList.append(resultList.at(i).absoluteFilePath());
1695         }
1696         else {
1697             // older files
1698             oldList.append(resultList.at(i).absoluteFilePath());
1699         }
1700     }
1701     if (hourList.count() > 20) {
1702         int step = hourList.count() / 10;
1703         for (int i = 0; i < hourList.count(); i += step) {
1704             kDebug()<<"REMOVE AT: "<<i<<", COUNT: "<<hourList.count();
1705             hourList.removeAt(i);
1706             i--;
1707         }
1708     } else hourList.clear();
1709     if (dayList.count() > 20) {
1710         int step = dayList.count() / 10;
1711         for (int i = 0; i < dayList.count(); i += step) {
1712             dayList.removeAt(i);
1713             i--;
1714         }
1715     } else dayList.clear();
1716     if (weekList.count() > 20) {
1717         int step = weekList.count() / 10;
1718         for (int i = 0; i < weekList.count(); i += step) {
1719             weekList.removeAt(i);
1720             i--;
1721         }
1722     } else weekList.clear();
1723     if (oldList.count() > 20) {
1724         int step = oldList.count() / 10;
1725         for (int i = 0; i < oldList.count(); i += step) {
1726             oldList.removeAt(i);
1727             i--;
1728         }
1729     } else oldList.clear();
1730     
1731     QString f;
1732     while (hourList.count() > 0) {
1733         f = hourList.takeFirst();
1734         QFile::remove(f);
1735         QFile::remove(f + ".png");
1736     }
1737     while (dayList.count() > 0) {
1738         f = dayList.takeFirst();
1739         QFile::remove(f);
1740         QFile::remove(f + ".png");
1741     }
1742     while (weekList.count() > 0) {
1743         f = weekList.takeFirst();
1744         QFile::remove(f);
1745         QFile::remove(f + ".png");
1746     }
1747     while (oldList.count() > 0) {
1748         f = oldList.takeFirst();
1749         QFile::remove(f);
1750         QFile::remove(f + ".png");
1751     }
1752 }
1753
1754 #include "kdenlivedoc.moc"
1755