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