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