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