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