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