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