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