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