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