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