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