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