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