]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
Various changes for getting an OpenGL context (almost) everywhere it is needed.
[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, QGLWidget *glContext, 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, glContext);
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     KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "proxy/");
845     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);
846     m_projectFolder = url;
847
848     updateProjectFolderPlacesEntry();
849 }
850
851 void KdenliveDoc::moveProjectData(const KUrl &url)
852 {
853     QList <DocClipBase*> list = m_clipManager->documentClipList();
854     KUrl::List cacheUrls;
855     for (int i = 0; i < list.count(); ++i) {
856         DocClipBase *clip = list.at(i);
857         if (clip->clipType() == Text) {
858             // the image for title clip must be moved
859             KUrl oldUrl = clip->fileURL();
860             KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
861             KIO::Job *job = KIO::copy(oldUrl, newUrl);
862             if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
863         }
864         QString hash = clip->getClipHash();
865         KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
866         if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
867             cacheUrls << oldVideoThumbUrl;
868         }
869         KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
870         if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
871             cacheUrls << oldAudioThumbUrl;
872         }
873         KUrl oldVideoProxyUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/" + hash + '.' + KdenliveSettings::proxyextension());
874         if (KIO::NetAccess::exists(oldVideoProxyUrl, KIO::NetAccess::SourceSide, 0)) {
875             cacheUrls << oldVideoProxyUrl;
876         }
877     }
878     if (!cacheUrls.isEmpty()) {
879         KIO::Job *job = KIO::copy(cacheUrls, KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/"));
880         job->ui()->setWindow(kapp->activeWindow());
881         KIO::NetAccess::synchronousRun(job, 0);
882     }
883 }
884
885 const QString &KdenliveDoc::profilePath() const
886 {
887     return m_profile.path;
888 }
889
890 MltVideoProfile KdenliveDoc::mltProfile() const
891 {
892     return m_profile;
893 }
894
895 bool KdenliveDoc::setProfilePath(QString path)
896 {
897     if (path.isEmpty())
898         path = KdenliveSettings::default_profile();
899     if (path.isEmpty())
900         path = QLatin1String("dv_pal");
901     m_profile = ProfilesDialog::getVideoProfile(path);
902     double current_fps = m_fps;
903     if (m_profile.path.isEmpty()) {
904         // Profile not found, use embedded profile
905         QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
906         if (profileInfo.isNull()) {
907             KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
908             m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
909         } else {
910             m_profile.description = profileInfo.attribute("description");
911             m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
912             m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
913             m_profile.width = profileInfo.attribute("width").toInt();
914             m_profile.height = profileInfo.attribute("height").toInt();
915             m_profile.progressive = profileInfo.attribute("progressive").toInt();
916             m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
917             m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
918             m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
919             m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
920             QString existing = ProfilesDialog::existingProfile(m_profile);
921             if (!existing.isEmpty()) {
922                 m_profile = ProfilesDialog::getVideoProfile(existing);
923                 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
924             } else {
925                 QString newDesc = m_profile.description;
926                 bool ok = true;
927                 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
928                     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);
929                 }
930                 if (ok == false) {
931                     // User canceled, use default profile
932                     m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
933                 } else {
934                     if (newDesc != m_profile.description) {
935                         // Profile description existed, was replaced by new one
936                         m_profile.description = newDesc;
937                     } else {
938                         KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
939                     }
940                     ProfilesDialog::saveProfile(m_profile);
941                 }
942             }
943             setModified(true);
944         }
945     }
946
947     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
948     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
949     KdenliveSettings::setProject_fps(m_fps);
950     m_width = m_profile.width;
951     m_height = m_profile.height;
952     kDebug() << "Kdenlive document, init timecode from path: " << path << ",  " << m_fps;
953     m_timecode.setFormat(m_fps);
954     KdenliveSettings::setCurrent_profile(m_profile.path);
955     return (current_fps != m_fps);
956 }
957
958 double KdenliveDoc::dar() const
959 {
960     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
961 }
962
963 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
964 {
965     emit progressInfo(message, progress);
966 }
967
968 QUndoStack *KdenliveDoc::commandStack()
969 {
970     return m_commandStack;
971 }
972
973 /*
974 void KdenliveDoc::setRenderer(Render *render) {
975     if (m_render) return;
976     m_render = render;
977     emit progressInfo(i18n("Loading playlist..."), 0);
978     //qApp->processEvents();
979     if (m_render) {
980         m_render->setSceneList(m_document.toString(), m_startPos);
981         kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
982         checkProjectClips();
983     }
984     emit progressInfo(QString(), -1);
985 }*/
986
987 void KdenliveDoc::checkProjectClips(bool displayRatioChanged, bool fpsChanged)
988 {
989     if (m_render == NULL) return;
990     m_clipManager->resetProducersList(m_render->producersList(), displayRatioChanged, fpsChanged);
991 }
992
993 Render *KdenliveDoc::renderer()
994 {
995     return m_render;
996 }
997
998 void KdenliveDoc::updateClip(const QString &id)
999 {
1000     emit updateClipDisplay(id);
1001 }
1002
1003 int KdenliveDoc::getFramePos(const QString &duration)
1004 {
1005     return m_timecode.getFrameCount(duration);
1006 }
1007
1008 QString KdenliveDoc::producerName(const QString &id)
1009 {
1010     QString result = "unnamed";
1011     QDomNodeList prods = producersList();
1012     int ct = prods.count();
1013     for (int i = 0; i <  ct ; ++i) {
1014         QDomElement e = prods.item(i).toElement();
1015         if (e.attribute("id") != "black" && e.attribute("id") == id) {
1016             result = e.attribute("name");
1017             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
1018             break;
1019         }
1020     }
1021     return result;
1022 }
1023
1024 QDomDocument KdenliveDoc::toXml()
1025 {
1026     return m_document;
1027 }
1028
1029 Timecode KdenliveDoc::timecode() const
1030 {
1031     return m_timecode;
1032 }
1033
1034 QDomNodeList KdenliveDoc::producersList()
1035 {
1036     return m_document.elementsByTagName("producer");
1037 }
1038
1039 double KdenliveDoc::projectDuration() const
1040 {
1041     if (m_render)
1042         return GenTime(m_render->getLength(), m_fps).ms() / 1000;
1043     else
1044         return 0;
1045 }
1046
1047 double KdenliveDoc::fps() const
1048 {
1049     return m_fps;
1050 }
1051
1052 int KdenliveDoc::width() const
1053 {
1054     return m_width;
1055 }
1056
1057 int KdenliveDoc::height() const
1058 {
1059     return m_height;
1060 }
1061
1062 KUrl KdenliveDoc::url() const
1063 {
1064     return m_url;
1065 }
1066
1067 void KdenliveDoc::setUrl(const KUrl &url)
1068 {
1069     m_url = url;
1070 }
1071
1072 void KdenliveDoc::setModified(bool mod)
1073 {
1074     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
1075         m_autoSaveTimer->start(3000);
1076     }
1077     if (mod == m_modified) return;
1078     m_modified = mod;
1079     emit docModified(m_modified);
1080 }
1081
1082 bool KdenliveDoc::isModified() const
1083 {
1084     return m_modified;
1085 }
1086
1087 const QString KdenliveDoc::description() const
1088 {
1089     if (m_url.isEmpty())
1090         return i18n("Untitled") + " / " + m_profile.description;
1091     else
1092         return m_url.fileName() + " / " + m_profile.description;
1093 }
1094
1095 bool KdenliveDoc::addClip(QDomElement elem, const QString &clipId, bool createClipItem)
1096 {
1097     const QString producerId = clipId.section('_', 0, 0);
1098     DocClipBase *clip = m_clipManager->getClipById(producerId);
1099
1100     if (clip == NULL) {
1101         elem.setAttribute("id", producerId);
1102         QString path = elem.attribute("resource");
1103         QString extension;
1104         if (elem.attribute("type").toInt() == SlideShow) {
1105             extension = KUrl(path).fileName();
1106             path = KUrl(path).directory();
1107         }
1108         if (elem.hasAttribute("_missingsource")) {
1109             // Clip has proxy but missing original source
1110         }
1111         else if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != Text && !elem.hasAttribute("placeholder")) {
1112             kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1113             const QString size = elem.attribute("file_size");
1114             const QString hash = elem.attribute("file_hash");
1115             QString newpath;
1116             int action = KMessageBox::No;
1117             if (!size.isEmpty() && !hash.isEmpty()) {
1118                 if (!m_searchFolder.isEmpty())
1119                     newpath = searchFileRecursively(m_searchFolder, size, hash);
1120                 else
1121                     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")));
1122             } else {
1123                 if (elem.attribute("type").toInt() == SlideShow) {
1124                     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")));
1125                     if (res == KMessageBox::Yes)
1126                         newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1127                     else {
1128                         // Abort project loading
1129                         action = res;
1130                     }
1131                 } else {
1132                     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")));
1133                     if (res == KMessageBox::Yes)
1134                         newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1135                     else {
1136                         // Abort project loading
1137                         action = res;
1138                     }
1139                 }
1140             }
1141             if (action == KMessageBox::Yes) {
1142                 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1143                 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1144                 if (!m_searchFolder.isEmpty())
1145                     newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1146             } else if (action == KMessageBox::Cancel) {
1147                 return false;
1148             } else if (action == KMessageBox::No) {
1149                 // Keep clip as placeHolder
1150                 elem.setAttribute("placeholder", '1');
1151             }
1152             if (!newpath.isEmpty()) {
1153                 kDebug() << "// NEW CLIP PATH FOR CLIP " << clipId << " : " << newpath;
1154                 if (elem.attribute("type").toInt() == SlideShow)
1155                     newpath.append('/' + extension);
1156                 elem.setAttribute("resource", newpath);
1157                 setNewClipResource(clipId, newpath);
1158                 setModified(true);
1159             }
1160         }
1161         clip = new DocClipBase(m_clipManager, elem, producerId);
1162         m_clipManager->addClip(clip);
1163     }
1164
1165     if (createClipItem) {
1166         emit addProjectClip(clip);
1167     }
1168
1169     return true;
1170 }
1171
1172 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1173 {
1174     QDomNodeList prods = m_document.elementsByTagName("producer");
1175     int maxprod = prods.count();
1176     for (int i = 0; i < maxprod; ++i) {
1177         QDomNode m = prods.at(i);
1178         QString prodId = m.toElement().attribute("id");
1179         if (prodId == id || prodId.startsWith(id + '_')) {
1180             QDomNodeList params = m.childNodes();
1181             for (int j = 0; j < params.count(); j++) {
1182                 QDomElement e = params.item(j).toElement();
1183                 if (e.attribute("name") == "resource") {
1184                     e.firstChild().setNodeValue(path);
1185                     break;
1186                 }
1187             }
1188         }
1189     }
1190 }
1191
1192 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1193 {
1194     QString foundFileName;
1195     QByteArray fileData;
1196     QByteArray fileHash;
1197     QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1198     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); ++i) {
1199         QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1200         if (file.open(QIODevice::ReadOnly)) {
1201             if (QString::number(file.size()) == matchSize) {
1202                 /*
1203                 * 1 MB = 1 second per 450 files (or faster)
1204                 * 10 MB = 9 seconds per 450 files (or faster)
1205                 */
1206                 if (file.size() > 1000000 * 2) {
1207                     fileData = file.read(1000000);
1208                     if (file.seek(file.size() - 1000000))
1209                         fileData.append(file.readAll());
1210                 } else
1211                     fileData = file.readAll();
1212                 file.close();
1213                 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1214                 if (QString(fileHash.toHex()) == matchHash)
1215                     return file.fileName();
1216                 else
1217                     kDebug() << filesAndDirs.at(i) << "size match but not hash";
1218             }
1219         }
1220         //kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1221     }
1222     filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1223     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); ++i) {
1224         foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1225         if (!foundFileName.isEmpty())
1226             break;
1227     }
1228     return foundFileName;
1229 }
1230
1231 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, const QString &clipId)
1232 {
1233     DocClipBase *clip = m_clipManager->getClipById(clipId);
1234     if (clip == NULL) {
1235         if (!addClip(elem, clipId, false))
1236             return false;
1237     } else {
1238         QMap <QString, QString> properties;
1239         QDomNamedNodeMap attributes = elem.attributes();
1240         for (int i = 0; i < attributes.count(); ++i) {
1241             QString attrname = attributes.item(i).nodeName();
1242             if (attrname != "resource")
1243                 properties.insert(attrname, attributes.item(i).nodeValue());
1244             //kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1245         }
1246         clip->setProperties(properties);
1247         emit addProjectClip(clip, false);
1248     }
1249     if (orig != QDomElement()) {
1250         QMap<QString, QString> meta;
1251         for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1252             QString name = m.toElement().attribute("name");
1253             if (name.startsWith("meta.attr")) {
1254                 if (name.endsWith(".markup")) name = name.section('.', 0, -2);
1255                 meta.insert(name.section('.', 2, -1), m.firstChild().nodeValue());
1256             }
1257         }
1258         if (!meta.isEmpty()) {
1259             if (clip == NULL)
1260                 clip = m_clipManager->getClipById(clipId);
1261             if (clip)
1262                 clip->setMetadata(meta);
1263         }
1264     }
1265     return true;
1266 }
1267
1268
1269 void KdenliveDoc::deleteClip(const QString &clipId)
1270 {
1271     emit signalDeleteProjectClip(clipId);
1272 }
1273
1274 void KdenliveDoc::slotAddClipList(const KUrl::List &urls, const stringMap &data)
1275 {
1276     m_clipManager->slotAddClipList(urls, data);
1277     //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1278     setModified(true);
1279 }
1280
1281
1282 void KdenliveDoc::slotAddClipFile(const KUrl &url, const stringMap &data)
1283 {
1284     m_clipManager->slotAddClipFile(url, data);
1285     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1286     setModified(true);
1287 }
1288
1289 const QString KdenliveDoc::getFreeClipId()
1290 {
1291     return QString::number(m_clipManager->getFreeClipId());
1292 }
1293
1294 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1295 {
1296     return m_clipManager->getClipById(clipId);
1297 }
1298
1299 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement &xml, const QString &group, const QString &groupId)
1300 {
1301     m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1302     setModified(true);
1303     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1304 }
1305
1306 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, const QString &group, const QString &groupId)
1307 {
1308     m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1309     setModified(true);
1310     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1311 }
1312
1313 void KdenliveDoc::slotCreateSlideshowClipFile(const QMap <QString, QString> &properties, const QString &group, const QString &groupId)
1314 {
1315     m_clipManager->slotAddSlideshowClipFile(properties, group, groupId);
1316     setModified(true);
1317     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1318 }
1319
1320 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1321 {
1322     QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1323     KStandardDirs::makeDir(titlesFolder);
1324     QPointer<TitleWidget> dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1325     if (dia_ui->exec() == QDialog::Accepted) {
1326         m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->duration(), dia_ui->xml().toString(), group, groupId);
1327         setModified(true);
1328         emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1329     }
1330     delete dia_ui;
1331 }
1332
1333 void KdenliveDoc::slotCreateTextTemplateClip(const QString &group, const QString &groupId, KUrl path)
1334 {
1335     QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1336     if (path.isEmpty()) {
1337         path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1338     }
1339
1340     if (path.isEmpty()) return;
1341
1342     //TODO: rewrite with new title system (just set resource)
1343     m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1344     setModified(true);
1345     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1346 }
1347
1348 int KdenliveDoc::tracksCount() const
1349 {
1350     return m_tracksList.count();
1351 }
1352
1353 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1354 {
1355     if (ix < 0 || ix >= m_tracksList.count()) {
1356         kWarning() << "Track INFO outisde of range";
1357         return TrackInfo();
1358     }
1359     return m_tracksList.at(ix);
1360 }
1361
1362 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1363 {
1364     if (ix < 0 || ix >= m_tracksList.count()) {
1365         kWarning() << "SWITCH Track outisde of range";
1366         return;
1367     }
1368     m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1369 }
1370
1371 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1372 {
1373     if (ix < 0 || ix >= m_tracksList.count()) {
1374         kWarning() << "Track Lock outisde of range";
1375         return;
1376     }
1377     m_tracksList[ix].isLocked = lock;
1378 }
1379
1380 bool KdenliveDoc::isTrackLocked(int ix) const
1381 {
1382     if (ix < 0 || ix >= m_tracksList.count()) {
1383         kWarning() << "Track Lock outisde of range";
1384         return true;
1385     }
1386     return m_tracksList.at(ix).isLocked;
1387 }
1388
1389 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1390 {
1391     if (ix < 0 || ix >= m_tracksList.count()) {
1392         kWarning() << "SWITCH Track outisde of range";
1393         return;
1394     }
1395     m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1396 }
1397
1398 int KdenliveDoc::trackDuration(int ix)
1399 {
1400     return m_tracksList.at(ix).duration;
1401 }
1402
1403 void KdenliveDoc::setTrackDuration(int ix, int duration)
1404 {
1405     m_tracksList[ix].duration = duration;
1406 }
1407
1408 void KdenliveDoc::insertTrack(int ix, const TrackInfo &type)
1409 {
1410     if (ix == -1) m_tracksList << type;
1411     else m_tracksList.insert(ix, type);
1412 }
1413
1414 void KdenliveDoc::deleteTrack(int ix)
1415 {
1416     if (ix < 0 || ix >= m_tracksList.count()) {
1417         kWarning() << "Delete Track outisde of range";
1418         return;
1419     }
1420     m_tracksList.removeAt(ix);
1421 }
1422
1423 void KdenliveDoc::setTrackType(int ix, const TrackInfo &type)
1424 {
1425     if (ix < 0 || ix >= m_tracksList.count()) {
1426         kWarning() << "SET Track Type outisde of range";
1427         return;
1428     }
1429     m_tracksList[ix].type = type.type;
1430     m_tracksList[ix].isMute = type.isMute;
1431     m_tracksList[ix].isBlind = type.isBlind;
1432     m_tracksList[ix].isLocked = type.isLocked;
1433     m_tracksList[ix].trackName = type.trackName;
1434 }
1435
1436 const QList <TrackInfo> KdenliveDoc::tracksList() const
1437 {
1438     return m_tracksList;
1439 }
1440
1441 QPoint KdenliveDoc::getTracksCount() const
1442 {
1443     int audio = 0;
1444     int video = 0;
1445     foreach(const TrackInfo & info, m_tracksList) {
1446         if (info.type == VideoTrack) video++;
1447         else audio++;
1448     }
1449     return QPoint(video, audio);
1450 }
1451
1452 void KdenliveDoc::cacheImage(const QString &fileId, const QImage &img) const
1453 {
1454     img.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1455 }
1456
1457 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1458 {
1459     DocumentChecker d(infoproducers, m_document);
1460     return (d.hasErrorInClips() == false);
1461
1462     /*    int clipType;
1463         QDomElement e;
1464         QString id;
1465         QString resource;
1466         QList <QDomElement> missingClips;
1467         for (int i = 0; i < infoproducers.count(); ++i) {
1468             e = infoproducers.item(i).toElement();
1469             clipType = e.attribute("type").toInt();
1470             if (clipType == COLOR) continue;
1471             if (clipType == TEXT) {
1472                 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1473                 continue;
1474             }
1475             id = e.attribute("id");
1476             resource = e.attribute("resource");
1477             if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1478             if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1479                 // Missing clip found
1480                 missingClips.append(e);
1481             } else {
1482                 // Check if the clip has changed
1483                 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1484                     if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1485                         e.removeAttribute("file_hash");
1486                 }
1487             }
1488         }
1489         if (missingClips.isEmpty()) return true;
1490         DocumentChecker d(missingClips, m_document);
1491         return (d.exec() == QDialog::Accepted);*/
1492 }
1493
1494 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1495 {
1496     m_documentProperties[name] = value;
1497 }
1498
1499 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1500 {
1501     return m_documentProperties.value(name);
1502 }
1503
1504 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1505 {
1506     QMap <QString, QString> renderProperties;
1507     QMapIterator<QString, QString> i(m_documentProperties);
1508     while (i.hasNext()) {
1509         i.next();
1510         if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1511     }
1512     return renderProperties;
1513 }
1514
1515 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1516 {
1517     if (ix < 0 || ix >= m_tracksList.count()) {
1518         kWarning() << "Add Track effect outisde of range";
1519         return;
1520     }
1521     effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1522
1523     // Init parameter value & keyframes if required
1524     QDomNodeList params = effect.elementsByTagName("parameter");
1525     for (int i = 0; i < params.count(); ++i) {
1526         QDomElement e = params.item(i).toElement();
1527
1528         // Check if this effect has a variable parameter
1529         if (e.attribute("default").contains('%')) {
1530             double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1531             e.setAttribute("default", evaluatedValue);
1532             if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1533                 e.setAttribute("value", evaluatedValue);
1534             }
1535         }
1536
1537         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1538             QString def = e.attribute("default");
1539             // Effect has a keyframe type parameter, we need to set the values
1540             if (e.attribute("keyframes").isEmpty()) {
1541                 e.setAttribute("keyframes", "0:" + def + ';');
1542                 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1543                 //break;
1544             }
1545         }
1546
1547         if (effect.attribute("id") == "crop") {
1548             // default use_profile to 1 for clips with proxies to avoid problems when rendering
1549             if (e.attribute("name") == "use_profile" && getDocumentProperty("enableproxy") == "1")
1550                 e.setAttribute("value", "1");
1551         }
1552     }
1553
1554     m_tracksList[ix].effectsList.append(effect);
1555 }
1556
1557 void KdenliveDoc::removeTrackEffect(int ix, const QDomElement &effect)
1558 {
1559     if (ix < 0 || ix >= m_tracksList.count()) {
1560         kWarning() << "Remove Track effect outisde of range";
1561         return;
1562     }
1563     int index;
1564     int toRemove = effect.attribute("kdenlive_ix").toInt();
1565     for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1566         index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix").toInt();
1567         if (toRemove == index) {
1568             m_tracksList[ix].effectsList.removeAt(toRemove);
1569             break;
1570         }
1571     }
1572 }
1573
1574 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1575 {
1576     if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1577         kWarning() << "Set Track effect outisde of range";
1578         return;
1579     }
1580     if (effectIndex <= 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count()) || effect.isNull()) {
1581         kDebug() << "Invalid effect index: " << effectIndex;
1582         return;
1583     }
1584     m_tracksList[trackIndex].effectsList.removeAt(effect.attribute("kdenlive_ix").toInt());
1585     effect.setAttribute("kdenlive_ix", effectIndex);
1586     m_tracksList[trackIndex].effectsList.insert(effect);
1587     //m_tracksList[trackIndex].effectsList.updateEffect(effect);
1588 }
1589
1590 void KdenliveDoc::enableTrackEffects(int trackIndex, const QList <int> &effectIndexes, bool disable)
1591 {
1592     if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1593         kWarning() << "Set Track effect outisde of range";
1594         return;
1595     }
1596     EffectsList list = m_tracksList.at(trackIndex).effectsList;
1597     QDomElement effect;
1598     for (int i = 0; i < effectIndexes.count(); ++i) {
1599         effect = list.itemFromIndex(effectIndexes.at(i));
1600         if (!effect.isNull()) effect.setAttribute("disable", (int) disable);
1601     }
1602 }
1603
1604 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1605 {
1606     if (ix < 0 || ix >= m_tracksList.count()) {
1607         kWarning() << "Get Track effects outisde of range";
1608         return EffectsList();
1609     }
1610     return m_tracksList.at(ix).effectsList;
1611 }
1612
1613 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1614 {
1615     if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1616         kWarning() << "Get Track effect outisde of range";
1617         return QDomElement();
1618     }
1619     EffectsList list = m_tracksList.at(trackIndex).effectsList;
1620     if (effectIndex > list.count() || effectIndex < 1 || list.itemFromIndex(effectIndex).isNull()) return QDomElement();
1621     return list.itemFromIndex(effectIndex).cloneNode().toElement();
1622 }
1623
1624 int KdenliveDoc::hasTrackEffect(int trackIndex, const QString &tag, const QString &id) const
1625 {
1626     if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1627         kWarning() << "Get Track effect outisde of range";
1628         return -1;
1629     }
1630     EffectsList list = m_tracksList.at(trackIndex).effectsList;
1631     return list.hasEffect(tag, id);
1632 }
1633
1634 bool KdenliveDoc::saveCustomEffects(const QDomNodeList &customeffects)
1635 {
1636     QDomElement e;
1637     QStringList importedEffects;
1638     int maxchild = customeffects.count();
1639     for (int i = 0; i < maxchild; ++i) {
1640         e = customeffects.at(i).toElement();
1641         const QString id = e.attribute("id");
1642         const QString tag = e.attribute("tag");
1643         if (!id.isEmpty()) {
1644             // Check if effect exists or save it
1645             if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1646                 QDomDocument doc;
1647                 doc.appendChild(doc.importNode(e, true));
1648                 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1649                 path += id + ".xml";
1650                 if (!QFile::exists(path)) {
1651                     importedEffects << id;
1652                     QFile file(path);
1653                     if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1654                         QTextStream out(&file);
1655                         out << doc.toString();
1656                     }
1657                 }
1658             }
1659         }
1660     }
1661     if (!importedEffects.isEmpty())
1662         KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1663     return (!importedEffects.isEmpty());
1664 }
1665
1666 void KdenliveDoc::updateProjectFolderPlacesEntry()
1667 {
1668     /*
1669      * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1670      * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1671      */
1672
1673     const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1674     KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1675     if (!bookmarkManager) return;
1676     KBookmarkGroup root = bookmarkManager->root();
1677     
1678     KBookmark bookmark = root.first();
1679
1680     QString kdenliveName = KGlobal::mainComponent().componentName();
1681     KUrl documentLocation = m_projectFolder;
1682
1683     bool exists = false;
1684
1685     while (!bookmark.isNull()) {
1686         // UDI not empty indicates a device
1687         QString udi = bookmark.metaDataItem("UDI");
1688         QString appName = bookmark.metaDataItem("OnlyInApp");
1689
1690         if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1691             if (bookmark.url() != documentLocation) {
1692                 bookmark.setUrl(documentLocation);
1693                 bookmarkManager->emitChanged(root);
1694             }
1695             exists = true;
1696             break;
1697         }
1698
1699         bookmark = root.next(bookmark);
1700     }
1701
1702     // if entry does not exist yet (was not found), well, create it then
1703     if (!exists) {
1704         bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1705         // Make this user selectable ?
1706         bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1707         bookmarkManager->emitChanged(root);
1708     }
1709 }
1710
1711 QStringList KdenliveDoc::getExpandedFolders()
1712 {
1713     QStringList result = m_documentProperties.value("expandedfolders").split(';');
1714     // this property is only needed once when opening project, so clear it now
1715     m_documentProperties.remove("expandedfolders");
1716     return result;
1717 }
1718
1719 // static
1720 double KdenliveDoc::getDisplayRatio(const QString &path)
1721 {
1722     QFile file(path);
1723     QDomDocument doc;
1724     if (!file.open(QIODevice::ReadOnly)) {
1725         kWarning() << "ERROR, CANNOT READ: " << path;
1726         return 0;
1727     }
1728     if (!doc.setContent(&file)) {
1729         kWarning() << "ERROR, CANNOT READ: " << path;
1730         file.close();
1731         return 0;
1732     }
1733     file.close();
1734     QDomNodeList list = doc.elementsByTagName("profile");
1735     if (list.isEmpty()) return 0;
1736     QDomElement profile = list.at(0).toElement();
1737     double den = profile.attribute("display_aspect_den").toDouble();
1738     if (den > 0) return profile.attribute("display_aspect_num").toDouble() / den;
1739     return 0;
1740 }
1741
1742 void KdenliveDoc::backupLastSavedVersion(const QString &path)
1743 {
1744     // Ensure backup folder exists
1745     if (path.isEmpty()) return;
1746     QFile file(path);
1747     KUrl backupFile = m_projectFolder;
1748     backupFile.addPath(".backup/");
1749     KIO::NetAccess::mkdir(backupFile, kapp->activeWindow());
1750     QString fileName = KUrl(path).fileName().section('.', 0, -2);
1751     QFileInfo info(file);
1752     fileName.append('-' + m_documentProperties.value("documentid"));
1753     fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
1754     fileName.append(".kdenlive");
1755     backupFile.addPath(fileName);
1756
1757     if (file.exists()) {
1758         // delete previous backup if it was done less than 60 seconds ago
1759         QFile::remove(backupFile.path());
1760         if (!QFile::copy(path, backupFile.path())) {
1761             KMessageBox::information(kapp->activeWindow(), i18n("Cannot create backup copy:\n%1", backupFile.path()));
1762         }
1763     }
1764 }
1765
1766 void KdenliveDoc::cleanupBackupFiles()
1767 {
1768     KUrl backupFile = m_projectFolder;
1769     backupFile.addPath(".backup/");
1770     QDir dir(backupFile.path());
1771     QString projectFile = url().fileName().section('.', 0, -2);
1772     projectFile.append('-' + m_documentProperties.value("documentid"));
1773     projectFile.append("-??");
1774     projectFile.append("??");
1775     projectFile.append("-??");
1776     projectFile.append("-??");
1777     projectFile.append("-??");
1778     projectFile.append("-??.kdenlive");
1779
1780     QStringList filter;
1781     backupFile.addPath(projectFile);
1782     filter << projectFile;
1783     dir.setNameFilters(filter);
1784     QFileInfoList resultList = dir.entryInfoList(QDir::Files, QDir::Time);
1785
1786     QDateTime d = QDateTime::currentDateTime();
1787     QStringList hourList;
1788     QStringList dayList;
1789     QStringList weekList;
1790     QStringList oldList;
1791     for (int i = 0; i < resultList.count(); ++i) {
1792         if (d.secsTo(resultList.at(i).lastModified()) < 3600) {
1793             // files created in the last hour
1794             hourList.append(resultList.at(i).absoluteFilePath());
1795         }
1796         else if (d.secsTo(resultList.at(i).lastModified()) < 43200) {
1797             // files created in the day
1798             dayList.append(resultList.at(i).absoluteFilePath());
1799         }
1800         else if (d.daysTo(resultList.at(i).lastModified()) < 8) {
1801             // files created in the week
1802             weekList.append(resultList.at(i).absoluteFilePath());
1803         }
1804         else {
1805             // older files
1806             oldList.append(resultList.at(i).absoluteFilePath());
1807         }
1808     }
1809     if (hourList.count() > 20) {
1810         int step = hourList.count() / 10;
1811         for (int i = 0; i < hourList.count(); i += step) {
1812             kDebug()<<"REMOVE AT: "<<i<<", COUNT: "<<hourList.count();
1813             hourList.removeAt(i);
1814             --i;
1815         }
1816     } else hourList.clear();
1817     if (dayList.count() > 20) {
1818         int step = dayList.count() / 10;
1819         for (int i = 0; i < dayList.count(); i += step) {
1820             dayList.removeAt(i);
1821             --i;
1822         }
1823     } else dayList.clear();
1824     if (weekList.count() > 20) {
1825         int step = weekList.count() / 10;
1826         for (int i = 0; i < weekList.count(); i += step) {
1827             weekList.removeAt(i);
1828             --i;
1829         }
1830     } else weekList.clear();
1831     if (oldList.count() > 20) {
1832         int step = oldList.count() / 10;
1833         for (int i = 0; i < oldList.count(); i += step) {
1834             oldList.removeAt(i);
1835             --i;
1836         }
1837     } else oldList.clear();
1838     
1839     QString f;
1840     while (hourList.count() > 0) {
1841         f = hourList.takeFirst();
1842         QFile::remove(f);
1843         QFile::remove(f + ".png");
1844     }
1845     while (dayList.count() > 0) {
1846         f = dayList.takeFirst();
1847         QFile::remove(f);
1848         QFile::remove(f + ".png");
1849     }
1850     while (weekList.count() > 0) {
1851         f = weekList.takeFirst();
1852         QFile::remove(f);
1853         QFile::remove(f + ".png");
1854     }
1855     while (oldList.count() > 0) {
1856         f = oldList.takeFirst();
1857         QFile::remove(f);
1858         QFile::remove(f + ".png");
1859     }
1860 }
1861
1862 const QMap <QString, QString> KdenliveDoc::metadata() const
1863 {
1864     return m_documentMetadata;
1865 }
1866
1867 void KdenliveDoc::setMetadata(const QMap<QString, QString> &meta)
1868 {
1869     setModified(true);
1870     m_documentMetadata = meta;
1871 }
1872
1873 #include "kdenlivedoc.moc"
1874