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