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