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