]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
Hide the "avformat-novalidate" trick for faster loading, caused crash:
[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) + "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(), true);
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     // 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.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     QDomElement addedXml = sceneList.createElement("kdenlivedoc");
569     mlt.appendChild(addedXml);
570
571     // check if project contains custom effects to embed them in project file
572     QDomNodeList effects = mlt.elementsByTagName("filter");
573     int maxEffects = effects.count();
574     kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
575     QMap <QString, QString> effectIds;
576     for (int i = 0; i < maxEffects; i++) {
577         QDomNode m = effects.at(i);
578         QDomNodeList params = m.childNodes();
579         QString id;
580         QString tag;
581         for (int j = 0; j < params.count(); j++) {
582             QDomElement e = params.item(j).toElement();
583             if (e.attribute("name") == "kdenlive_id") {
584                 id = e.firstChild().nodeValue();
585             }
586             if (e.attribute("name") == "tag") {
587                 tag = e.firstChild().nodeValue();
588             }
589             if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
590         }
591     }
592     QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
593     addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
594
595     QDomElement markers = sceneList.createElement("markers");
596     addedXml.setAttribute("version", DOCUMENTVERSION);
597     addedXml.setAttribute("kdenliveversion", VERSION);
598     addedXml.setAttribute("profile", profilePath());
599     addedXml.setAttribute("projectfolder", m_projectFolder.path());
600
601     QDomElement docproperties = sceneList.createElement("documentproperties");
602     QMapIterator<QString, QString> i(m_documentProperties);
603     while (i.hasNext()) {
604         i.next();
605         docproperties.setAttribute(i.key(), i.value());
606     }
607     docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
608     addedXml.appendChild(docproperties);
609
610     QDomElement docnotes = sceneList.createElement("documentnotes");
611     QDomText value = sceneList.createTextNode(m_notesWidget->toHtml());
612     docnotes.appendChild(value);
613     addedXml.appendChild(docnotes);
614
615     // Add profile info
616     QDomElement profileinfo = sceneList.createElement("profileinfo");
617     profileinfo.setAttribute("description", m_profile.description);
618     profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
619     profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
620     profileinfo.setAttribute("width", m_profile.width);
621     profileinfo.setAttribute("height", m_profile.height);
622     profileinfo.setAttribute("progressive", m_profile.progressive);
623     profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
624     profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
625     profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
626     profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
627     addedXml.appendChild(profileinfo);
628
629     // tracks info
630     QDomElement tracksinfo = sceneList.createElement("tracksinfo");
631     foreach(const TrackInfo & info, m_tracksList) {
632         QDomElement trackinfo = sceneList.createElement("trackinfo");
633         if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
634         trackinfo.setAttribute("mute", info.isMute);
635         trackinfo.setAttribute("blind", info.isBlind);
636         trackinfo.setAttribute("locked", info.isLocked);
637         trackinfo.setAttribute("trackname", info.trackName);
638         tracksinfo.appendChild(trackinfo);
639     }
640     addedXml.appendChild(tracksinfo);
641
642     // save project folders
643     QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
644
645     QMapIterator<QString, QString> f(folderlist);
646     while (f.hasNext()) {
647         f.next();
648         QDomElement folder = sceneList.createElement("folder");
649         folder.setAttribute("id", f.key());
650         folder.setAttribute("name", f.value());
651         if (expandedFolders.contains(f.key())) folder.setAttribute("opened", "1");
652         addedXml.appendChild(folder);
653     }
654
655     // Save project clips
656     QDomElement e;
657     QList <DocClipBase*> list = m_clipManager->documentClipList();
658     for (int i = 0; i < list.count(); i++) {
659         e = list.at(i)->toXML();
660         e.setTagName("kdenlive_producer");
661         addedXml.appendChild(sceneList.importNode(e, true));
662         QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
663         for (int j = 0; j < marks.count(); j++) {
664             QDomElement marker = sceneList.createElement("marker");
665             marker.setAttribute("time", marks.at(j).time().ms() / 1000);
666             marker.setAttribute("comment", marks.at(j).comment());
667             marker.setAttribute("id", e.attribute("id"));
668             markers.appendChild(marker);
669         }
670     }
671     addedXml.appendChild(markers);
672
673     // Add guides
674     if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
675
676     // Add clip groups
677     addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
678
679     //wes.appendChild(doc.importNode(kdenliveData, true));
680     return sceneList;
681 }
682
683 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene, const QStringList expandedFolders, bool autosave)
684 {
685     QDomDocument sceneList = xmlSceneList(scene, expandedFolders);
686     if (sceneList.isNull()) {
687         //Make sure we don't save if scenelist is corrupted
688         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
689         return false;
690     }
691     
692     // Backup current version
693     if (!autosave) backupLastSavedVersion(path);
694     QFile file(path);
695     
696     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
697         kWarning() << "//////  ERROR writing to file: " << path;
698         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
699         return false;
700     }
701
702     file.write(sceneList.toString().toUtf8());
703     if (file.error() != QFile::NoError) {
704         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
705         file.close();
706         return false;
707     }
708     file.close();
709     if (!autosave) {
710         cleanupBackupFiles();
711         QFileInfo info(file);
712         QString fileName = KUrl(path).fileName().section('.', 0, -2);   
713         fileName.append("-" + m_documentProperties.value("documentid"));
714         fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
715         fileName.append(".kdenlive.png");
716         KUrl backupFile = m_projectFolder;
717         backupFile.addPath(".backup/");
718         backupFile.addPath(fileName);
719         emit saveTimelinePreview(backupFile.path());
720     }
721     return true;
722 }
723
724 ClipManager *KdenliveDoc::clipManager()
725 {
726     return m_clipManager;
727 }
728
729 KUrl KdenliveDoc::projectFolder() const
730 {
731     //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
732     return m_projectFolder;
733 }
734
735 void KdenliveDoc::setProjectFolder(KUrl url)
736 {
737     if (url == m_projectFolder) return;
738     setModified(true);
739     KStandardDirs::makeDir(url.path());
740     KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
741     KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
742     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);
743     m_projectFolder = url;
744
745     updateProjectFolderPlacesEntry();
746 }
747
748 void KdenliveDoc::moveProjectData(KUrl url)
749 {
750     QList <DocClipBase*> list = m_clipManager->documentClipList();
751     //TODO: Also move ladspa effects files
752     for (int i = 0; i < list.count(); i++) {
753         DocClipBase *clip = list.at(i);
754         if (clip->clipType() == TEXT) {
755             // the image for title clip must be moved
756             KUrl oldUrl = clip->fileURL();
757             KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
758             KIO::Job *job = KIO::copy(oldUrl, newUrl);
759             if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
760         }
761         QString hash = clip->getClipHash();
762         KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
763         KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
764         if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
765             KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
766             KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
767             KIO::NetAccess::synchronousRun(job, 0);
768         }
769         if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
770             KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
771             KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
772             if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
773         }
774     }
775 }
776
777 const QString &KdenliveDoc::profilePath() const
778 {
779     return m_profile.path;
780 }
781
782 MltVideoProfile KdenliveDoc::mltProfile() const
783 {
784     return m_profile;
785 }
786
787 bool KdenliveDoc::setProfilePath(QString path)
788 {
789     if (path.isEmpty()) path = KdenliveSettings::default_profile();
790     if (path.isEmpty()) path = "dv_pal";
791     m_profile = ProfilesDialog::getVideoProfile(path);
792     double current_fps = m_fps;
793     if (m_profile.path.isEmpty()) {
794         // Profile not found, use embedded profile
795         QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
796         if (profileInfo.isNull()) {
797             KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
798             m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
799         } else {
800             m_profile.description = profileInfo.attribute("description");
801             m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
802             m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
803             m_profile.width = profileInfo.attribute("width").toInt();
804             m_profile.height = profileInfo.attribute("height").toInt();
805             m_profile.progressive = profileInfo.attribute("progressive").toInt();
806             m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
807             m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
808             m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
809             m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
810             QString existing = ProfilesDialog::existingProfile(m_profile);
811             if (!existing.isEmpty()) {
812                 m_profile = ProfilesDialog::getVideoProfile(existing);
813                 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
814             } else {
815                 QString newDesc = m_profile.description;
816                 bool ok = true;
817                 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
818                     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);
819                 }
820                 if (ok == false) {
821                     // User canceled, use default profile
822                     m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
823                 } else {
824                     if (newDesc != m_profile.description) {
825                         // Profile description existed, was replaced by new one
826                         m_profile.description = newDesc;
827                     } else {
828                         KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
829                     }
830                     ProfilesDialog::saveProfile(m_profile);
831                 }
832             }
833             setModified(true);
834         }
835     }
836
837     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
838     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
839     KdenliveSettings::setProject_fps(m_fps);
840     m_width = m_profile.width;
841     m_height = m_profile.height;
842     kDebug() << "Kdenlive document, init timecode from path: " << path << ",  " << m_fps;
843     m_timecode.setFormat(m_fps);
844     KdenliveSettings::setCurrent_profile(m_profile.path);
845     return (current_fps != m_fps);
846 }
847
848 double KdenliveDoc::dar() const
849 {
850     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
851 }
852
853 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
854 {
855     emit progressInfo(message, progress);
856 }
857
858 QUndoStack *KdenliveDoc::commandStack()
859 {
860     return m_commandStack;
861 }
862
863 /*
864 void KdenliveDoc::setRenderer(Render *render) {
865     if (m_render) return;
866     m_render = render;
867     emit progressInfo(i18n("Loading playlist..."), 0);
868     //qApp->processEvents();
869     if (m_render) {
870         m_render->setSceneList(m_document.toString(), m_startPos);
871         kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
872         checkProjectClips();
873     }
874     emit progressInfo(QString(), -1);
875 }*/
876
877 void KdenliveDoc::checkProjectClips(bool displayRatioChanged, bool fpsChanged)
878 {
879     if (m_render == NULL) return;
880     m_clipManager->resetProducersList(m_render->producersList(), displayRatioChanged, fpsChanged);
881 }
882
883 Render *KdenliveDoc::renderer()
884 {
885     return m_render;
886 }
887
888 void KdenliveDoc::updateClip(const QString id)
889 {
890     emit updateClipDisplay(id);
891 }
892
893 int KdenliveDoc::getFramePos(QString duration)
894 {
895     return m_timecode.getFrameCount(duration);
896 }
897
898 QString KdenliveDoc::producerName(const QString &id)
899 {
900     QString result = "unnamed";
901     QDomNodeList prods = producersList();
902     int ct = prods.count();
903     for (int i = 0; i <  ct ; i++) {
904         QDomElement e = prods.item(i).toElement();
905         if (e.attribute("id") != "black" && e.attribute("id") == id) {
906             result = e.attribute("name");
907             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
908             break;
909         }
910     }
911     return result;
912 }
913
914 QDomDocument KdenliveDoc::toXml()
915 {
916     return m_document;
917 }
918
919 Timecode KdenliveDoc::timecode() const
920 {
921     return m_timecode;
922 }
923
924 QDomNodeList KdenliveDoc::producersList()
925 {
926     return m_document.elementsByTagName("producer");
927 }
928
929 double KdenliveDoc::projectDuration() const
930 {
931     if (m_render)
932         return GenTime(m_render->getLength(), m_fps).ms() / 1000;
933     else
934         return 0;
935 }
936
937 double KdenliveDoc::fps() const
938 {
939     return m_fps;
940 }
941
942 int KdenliveDoc::width() const
943 {
944     return m_width;
945 }
946
947 int KdenliveDoc::height() const
948 {
949     return m_height;
950 }
951
952 KUrl KdenliveDoc::url() const
953 {
954     return m_url;
955 }
956
957 void KdenliveDoc::setUrl(KUrl url)
958 {
959     m_url = url;
960 }
961
962 void KdenliveDoc::setModified(bool mod)
963 {
964     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
965         m_autoSaveTimer->start(3000);
966     }
967     if (mod == m_modified) return;
968     m_modified = mod;
969     emit docModified(m_modified);
970 }
971
972 bool KdenliveDoc::isModified() const
973 {
974     return m_modified;
975 }
976
977 const QString KdenliveDoc::description() const
978 {
979     if (m_url.isEmpty())
980         return i18n("Untitled") + " / " + m_profile.description;
981     else
982         return m_url.fileName() + " / " + m_profile.description;
983 }
984
985 bool KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
986 {
987     const QString producerId = clipId.section('_', 0, 0);
988     DocClipBase *clip = m_clipManager->getClipById(producerId);
989
990     if (clip == NULL) {
991         elem.setAttribute("id", producerId);
992         QString path = elem.attribute("resource");
993         QString extension;
994         if (elem.attribute("type").toInt() == SLIDESHOW) {
995             extension = KUrl(path).fileName();
996             path = KUrl(path).directory();
997         }
998
999         if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
1000             kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1001             const QString size = elem.attribute("file_size");
1002             const QString hash = elem.attribute("file_hash");
1003             QString newpath;
1004             int action = KMessageBox::No;
1005             if (!size.isEmpty() && !hash.isEmpty()) {
1006                 if (!m_searchFolder.isEmpty())
1007                     newpath = searchFileRecursively(m_searchFolder, size, hash);
1008                 else
1009                     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")));
1010             } else {
1011                 if (elem.attribute("type").toInt() == SLIDESHOW) {
1012                     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")));
1013                     if (res == KMessageBox::Yes)
1014                         newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1015                     else {
1016                         // Abort project loading
1017                         action = res;
1018                     }
1019                 } else {
1020                     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")));
1021                     if (res == KMessageBox::Yes)
1022                         newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1023                     else {
1024                         // Abort project loading
1025                         action = res;
1026                     }
1027                 }
1028             }
1029             if (action == KMessageBox::Yes) {
1030                 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1031                 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1032                 if (!m_searchFolder.isEmpty())
1033                     newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1034             } else if (action == KMessageBox::Cancel) {
1035                 return false;
1036             } else if (action == KMessageBox::No) {
1037                 // Keep clip as placeHolder
1038                 elem.setAttribute("placeholder", '1');
1039             }
1040             if (!newpath.isEmpty()) {
1041                 if (elem.attribute("type").toInt() == SLIDESHOW)
1042                     newpath.append('/' + extension);
1043                 elem.setAttribute("resource", newpath);
1044                 setNewClipResource(clipId, newpath);
1045                 setModified(true);
1046             }
1047         }
1048         clip = new DocClipBase(m_clipManager, elem, producerId);
1049         m_clipManager->addClip(clip);
1050     }
1051
1052     if (createClipItem) {
1053         emit addProjectClip(clip);
1054     }
1055
1056     return true;
1057 }
1058
1059 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1060 {
1061     QDomNodeList prods = m_document.elementsByTagName("producer");
1062     int maxprod = prods.count();
1063     for (int i = 0; i < maxprod; i++) {
1064         QDomNode m = prods.at(i);
1065         QString prodId = m.toElement().attribute("id");
1066         if (prodId == id || prodId.startsWith(id + '_')) {
1067             QDomNodeList params = m.childNodes();
1068             for (int j = 0; j < params.count(); j++) {
1069                 QDomElement e = params.item(j).toElement();
1070                 if (e.attribute("name") == "resource") {
1071                     e.firstChild().setNodeValue(path);
1072                     break;
1073                 }
1074             }
1075         }
1076     }
1077 }
1078
1079 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1080 {
1081     QString foundFileName;
1082     QByteArray fileData;
1083     QByteArray fileHash;
1084     QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1085     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1086         QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1087         if (file.open(QIODevice::ReadOnly)) {
1088             if (QString::number(file.size()) == matchSize) {
1089                 /*
1090                 * 1 MB = 1 second per 450 files (or faster)
1091                 * 10 MB = 9 seconds per 450 files (or faster)
1092                 */
1093                 if (file.size() > 1000000 * 2) {
1094                     fileData = file.read(1000000);
1095                     if (file.seek(file.size() - 1000000))
1096                         fileData.append(file.readAll());
1097                 } else
1098                     fileData = file.readAll();
1099                 file.close();
1100                 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1101                 if (QString(fileHash.toHex()) == matchHash)
1102                     return file.fileName();
1103             }
1104         }
1105         kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1106     }
1107     filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1108     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1109         foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1110         if (!foundFileName.isEmpty())
1111             break;
1112     }
1113     return foundFileName;
1114 }
1115
1116 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1117 {
1118     DocClipBase *clip = m_clipManager->getClipById(clipId);
1119     if (clip == NULL) {
1120         if (!addClip(elem, clipId, false))
1121             return false;
1122     } else {
1123         QMap <QString, QString> properties;
1124         QDomNamedNodeMap attributes = elem.attributes();
1125         for (int i = 0; i < attributes.count(); i++) {
1126             QString attrname = attributes.item(i).nodeName();
1127             if (attrname != "resource")
1128                 properties.insert(attrname, attributes.item(i).nodeValue());
1129             kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1130         }
1131         clip->setProperties(properties);
1132         emit addProjectClip(clip, false);
1133     }
1134     if (orig != QDomElement()) {
1135         QMap<QString, QString> meta;
1136         for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1137             QString name = m.toElement().attribute("name");
1138             if (name.startsWith("meta.attr"))
1139                 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1140         }
1141         if (!meta.isEmpty()) {
1142             if (clip == NULL)
1143                 clip = m_clipManager->getClipById(clipId);
1144             if (clip)
1145                 clip->setMetadata(meta);
1146         }
1147     }
1148     return true;
1149 }
1150
1151
1152 void KdenliveDoc::deleteClip(const QString &clipId)
1153 {
1154     emit signalDeleteProjectClip(clipId);
1155 }
1156
1157 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1158 {
1159     m_clipManager->slotAddClipList(urls, group, groupId);
1160     //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1161     setModified(true);
1162 }
1163
1164
1165 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1166 {
1167     m_clipManager->slotAddClipFile(url, group, groupId);
1168     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1169     setModified(true);
1170 }
1171
1172 const QString KdenliveDoc::getFreeClipId()
1173 {
1174     return QString::number(m_clipManager->getFreeClipId());
1175 }
1176
1177 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1178 {
1179     return m_clipManager->getClipById(clipId);
1180 }
1181
1182 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement xml, QString group, const QString &groupId)
1183 {
1184     m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1185     setModified(true);
1186     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1187 }
1188
1189 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1190 {
1191     m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1192     setModified(true);
1193     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1194 }
1195
1196 void KdenliveDoc::slotCreateSlideshowClipFile(const QString name, const QString path, int count, const QString duration,
1197         const bool loop, const bool crop, const bool fade,
1198         const QString &luma_duration, const QString &luma_file, const int softness,
1199         const QString &animation, QString group, const QString &groupId)
1200 {
1201     m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop,
1202                                             crop, fade, luma_duration,
1203                                             luma_file, softness,
1204                                             animation, group, groupId);
1205     setModified(true);
1206     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1207 }
1208
1209 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1210 {
1211     QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1212     KStandardDirs::makeDir(titlesFolder);
1213     TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1214     if (dia_ui->exec() == QDialog::Accepted) {
1215         m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->outPoint(), dia_ui->xml().toString(), group, groupId);
1216         setModified(true);
1217         emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1218     }
1219     delete dia_ui;
1220 }
1221
1222 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1223 {
1224     QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1225     if (path.isEmpty()) {
1226         path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1227     }
1228
1229     if (path.isEmpty()) return;
1230
1231     //TODO: rewrite with new title system (just set resource)
1232     m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1233     setModified(true);
1234     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1235 }
1236
1237 int KdenliveDoc::tracksCount() const
1238 {
1239     return m_tracksList.count();
1240 }
1241
1242 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1243 {
1244     if (ix < 0 || ix >= m_tracksList.count()) {
1245         kWarning() << "Track INFO outisde of range";
1246         return TrackInfo();
1247     }
1248     return m_tracksList.at(ix);
1249 }
1250
1251 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1252 {
1253     if (ix < 0 || ix >= m_tracksList.count()) {
1254         kWarning() << "SWITCH Track outisde of range";
1255         return;
1256     }
1257     m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1258 }
1259
1260 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1261 {
1262     if (ix < 0 || ix >= m_tracksList.count()) {
1263         kWarning() << "Track Lock outisde of range";
1264         return;
1265     }
1266     m_tracksList[ix].isLocked = lock;
1267 }
1268
1269 bool KdenliveDoc::isTrackLocked(int ix) const
1270 {
1271     if (ix < 0 || ix >= m_tracksList.count()) {
1272         kWarning() << "Track Lock outisde of range";
1273         return true;
1274     }
1275     return m_tracksList.at(ix).isLocked;
1276 }
1277
1278 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1279 {
1280     if (ix < 0 || ix >= m_tracksList.count()) {
1281         kWarning() << "SWITCH Track outisde of range";
1282         return;
1283     }
1284     m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1285 }
1286
1287 int KdenliveDoc::trackDuration(int ix)
1288 {
1289     return m_tracksList.at(ix).duration; 
1290 }
1291
1292 void KdenliveDoc::setTrackDuration(int ix, int duration)
1293 {
1294     m_tracksList[ix].duration = duration;
1295 }
1296
1297 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1298 {
1299     if (ix == -1) m_tracksList << type;
1300     else m_tracksList.insert(ix, type);
1301 }
1302
1303 void KdenliveDoc::deleteTrack(int ix)
1304 {
1305     if (ix < 0 || ix >= m_tracksList.count()) {
1306         kWarning() << "Delete Track outisde of range";
1307         return;
1308     }
1309     m_tracksList.removeAt(ix);
1310 }
1311
1312 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1313 {
1314     if (ix < 0 || ix >= m_tracksList.count()) {
1315         kWarning() << "SET Track Type outisde of range";
1316         return;
1317     }
1318     m_tracksList[ix].type = type.type;
1319     m_tracksList[ix].isMute = type.isMute;
1320     m_tracksList[ix].isBlind = type.isBlind;
1321     m_tracksList[ix].isLocked = type.isLocked;
1322     m_tracksList[ix].trackName = type.trackName;
1323 }
1324
1325 const QList <TrackInfo> KdenliveDoc::tracksList() const
1326 {
1327     return m_tracksList;
1328 }
1329
1330 QPoint KdenliveDoc::getTracksCount() const
1331 {
1332     int audio = 0;
1333     int video = 0;
1334     foreach(const TrackInfo & info, m_tracksList) {
1335         if (info.type == VIDEOTRACK) video++;
1336         else audio++;
1337     }
1338     return QPoint(video, audio);
1339 }
1340
1341 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1342 {
1343     pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1344 }
1345
1346 QString KdenliveDoc::getLadspaFile() const
1347 {
1348     int ct = 0;
1349     QString counter = QString::number(ct).rightJustified(5, '0', false);
1350     while (QFile::exists(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa")) {
1351         ct++;
1352         counter = QString::number(ct).rightJustified(5, '0', false);
1353     }
1354     return m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa";
1355 }
1356
1357 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1358 {
1359     DocumentChecker d(infoproducers, m_document);
1360     return (d.hasErrorInClips() == false);
1361
1362     /*    int clipType;
1363         QDomElement e;
1364         QString id;
1365         QString resource;
1366         QList <QDomElement> missingClips;
1367         for (int i = 0; i < infoproducers.count(); i++) {
1368             e = infoproducers.item(i).toElement();
1369             clipType = e.attribute("type").toInt();
1370             if (clipType == COLOR) continue;
1371             if (clipType == TEXT) {
1372                 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1373                 continue;
1374             }
1375             id = e.attribute("id");
1376             resource = e.attribute("resource");
1377             if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1378             if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1379                 // Missing clip found
1380                 missingClips.append(e);
1381             } else {
1382                 // Check if the clip has changed
1383                 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1384                     if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1385                         e.removeAttribute("file_hash");
1386                 }
1387             }
1388         }
1389         if (missingClips.isEmpty()) return true;
1390         DocumentChecker d(missingClips, m_document);
1391         return (d.exec() == QDialog::Accepted);*/
1392 }
1393
1394 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1395 {
1396     m_documentProperties[name] = value;
1397 }
1398
1399 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1400 {
1401     return m_documentProperties.value(name);
1402 }
1403
1404 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1405 {
1406     QMap <QString, QString> renderProperties;
1407     QMapIterator<QString, QString> i(m_documentProperties);
1408     while (i.hasNext()) {
1409         i.next();
1410         if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1411     }
1412     return renderProperties;
1413 }
1414
1415 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1416 {
1417     if (ix < 0 || ix >= m_tracksList.count()) {
1418         kWarning() << "Add Track effect outisde of range";
1419         return;
1420     }
1421     effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1422
1423     // Init parameter value & keyframes if required
1424     QDomNodeList params = effect.elementsByTagName("parameter");
1425     for (int i = 0; i < params.count(); i++) {
1426         QDomElement e = params.item(i).toElement();
1427
1428         // Check if this effect has a variable parameter
1429         if (e.attribute("default").contains('%')) {
1430             double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1431             e.setAttribute("default", evaluatedValue);
1432             if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1433                 e.setAttribute("value", evaluatedValue);
1434             }
1435         }
1436
1437         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1438             QString def = e.attribute("default");
1439             // Effect has a keyframe type parameter, we need to set the values
1440             if (e.attribute("keyframes").isEmpty()) {
1441                 e.setAttribute("keyframes", "0:" + def + ';');
1442                 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1443                 //break;
1444             }
1445         }
1446
1447         if (effect.attribute("id") == "crop") {
1448             // default use_profile to 1 for clips with proxies to avoid problems when rendering
1449             if (e.attribute("name") == "use_profile" && getDocumentProperty("enableproxy") == "1")
1450                 e.setAttribute("value", "1");
1451         }
1452     }
1453
1454     m_tracksList[ix].effectsList.append(effect);
1455 }
1456
1457 void KdenliveDoc::removeTrackEffect(int ix, QDomElement effect)
1458 {
1459     if (ix < 0 || ix >= m_tracksList.count()) {
1460         kWarning() << "Remove Track effect outisde of range";
1461         return;
1462     }
1463     QString index;
1464     QString toRemove = effect.attribute("kdenlive_ix");
1465     for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1466         index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix");
1467         if (toRemove == index) {
1468             m_tracksList[ix].effectsList.removeAt(i);
1469             i--;
1470         } else if (index.toInt() > toRemove.toInt()) {
1471             m_tracksList[ix].effectsList.item(i).setAttribute("kdenlive_ix", index.toInt() - 1);
1472         }
1473     }
1474 }
1475
1476 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1477 {
1478     if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1479         kWarning() << "Set Track effect outisde of range";
1480         return;
1481     }
1482     if (effectIndex < 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count() - 1) || effect.isNull()) {
1483         kDebug() << "Invalid effect index: " << effectIndex;
1484         return;
1485     }
1486     effect.setAttribute("kdenlive_ix", effectIndex + 1);
1487     m_tracksList[trackIndex].effectsList.replace(effectIndex, effect);
1488 }
1489
1490 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1491 {
1492     if (ix < 0 || ix >= m_tracksList.count()) {
1493         kWarning() << "Get Track effects outisde of range";
1494         return EffectsList();
1495     }
1496     return m_tracksList.at(ix).effectsList;
1497 }
1498
1499 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1500 {
1501     if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1502         kWarning() << "Get Track effect outisde of range";
1503         return QDomElement();
1504     }
1505     EffectsList list = m_tracksList.at(trackIndex).effectsList;
1506     if (effectIndex > list.count() - 1 || effectIndex < 0 || list.at(effectIndex).isNull()) return QDomElement();
1507     return list.at(effectIndex).cloneNode().toElement();
1508 }
1509
1510 bool KdenliveDoc::saveCustomEffects(QDomNodeList customeffects)
1511 {
1512     QDomElement e;
1513     QStringList importedEffects;
1514     int maxchild = customeffects.count();
1515     for (int i = 0; i < maxchild; i++) {
1516         e = customeffects.at(i).toElement();
1517         QString id = e.attribute("id");
1518         QString tag = e.attribute("tag");
1519         if (!id.isEmpty()) {
1520             // Check if effect exists or save it
1521             if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1522                 QDomDocument doc;
1523                 doc.appendChild(doc.importNode(e, true));
1524                 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1525                 path += id + ".xml";
1526                 if (!QFile::exists(path)) {
1527                     importedEffects << id;
1528                     QFile file(path);
1529                     if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1530                         QTextStream out(&file);
1531                         out << doc.toString();
1532                     }
1533                 }
1534             }
1535         }
1536     }
1537     if (!importedEffects.isEmpty()) KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1538     return (!importedEffects.isEmpty());
1539 }
1540
1541 void KdenliveDoc::updateProjectFolderPlacesEntry()
1542 {
1543     /*
1544      * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1545      * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1546      */
1547
1548     const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1549     KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1550     KBookmarkGroup root = bookmarkManager->root();
1551     KBookmark bookmark = root.first();
1552
1553     QString kdenliveName = KGlobal::mainComponent().componentName();
1554     KUrl documentLocation = m_projectFolder;
1555
1556     bool exists = false;
1557
1558     while (!bookmark.isNull()) {
1559         // UDI not empty indicates a device
1560         QString udi = bookmark.metaDataItem("UDI");
1561         QString appName = bookmark.metaDataItem("OnlyInApp");
1562
1563         if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1564             if (bookmark.url() != documentLocation) {
1565                 bookmark.setUrl(documentLocation);
1566                 bookmarkManager->emitChanged(root);
1567             }
1568             exists = true;
1569             break;
1570         }
1571
1572         bookmark = root.next(bookmark);
1573     }
1574
1575     // if entry does not exist yet (was not found), well, create it then
1576     if (!exists) {
1577         bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1578         // Make this user selectable ?
1579         bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1580         bookmarkManager->emitChanged(root);
1581     }
1582 }
1583
1584 QStringList KdenliveDoc::getExpandedFolders()
1585 {
1586     QStringList result = m_documentProperties.value("expandedfolders").split(';');
1587     // this property is only needed once when opening project, so clear it now
1588     m_documentProperties.remove("expandedfolders");
1589     return result;
1590 }
1591
1592 // static
1593 double KdenliveDoc::getDisplayRatio(const QString &path)
1594 {
1595     QFile file(path);
1596     QDomDocument doc;
1597     if (!file.open(QIODevice::ReadOnly)) {
1598         kWarning() << "ERROR, CANNOT READ: " << path;
1599         return 0;
1600     }
1601     if (!doc.setContent(&file)) {
1602         kWarning() << "ERROR, CANNOT READ: " << path;
1603         file.close();
1604         return 0;
1605     }
1606     file.close();
1607     QDomNodeList list = doc.elementsByTagName("profile");
1608     if (list.isEmpty()) return 0;
1609     QDomElement profile = list.at(0).toElement();
1610     double den = profile.attribute("display_aspect_den").toDouble();
1611     if (den > 0) return profile.attribute("display_aspect_num").toDouble() / den;
1612     return 0;
1613 }
1614
1615 void KdenliveDoc::backupLastSavedVersion(const QString &path)
1616 {
1617     // Ensure backup folder exists
1618     if (path.isEmpty()) return;
1619     QFile file(path);
1620     KUrl backupFile = m_projectFolder;
1621     backupFile.addPath(".backup/");
1622     KIO::NetAccess::mkdir(backupFile, kapp->activeWindow());
1623     QString fileName = KUrl(path).fileName().section('.', 0, -2);
1624     QFileInfo info(file);
1625     fileName.append("-" + m_documentProperties.value("documentid"));
1626     fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
1627     fileName.append(".kdenlive");
1628     backupFile.addPath(fileName);
1629
1630     if (file.exists()) {
1631         // delete previous backup if it was done less than 60 seconds ago
1632         QFile::remove(backupFile.path());
1633         if (!QFile::copy(path, backupFile.path())) {
1634             KMessageBox::information(kapp->activeWindow(), i18n("Cannot create backup copy:\n%1", backupFile.path()));
1635         }
1636     }    
1637 }
1638
1639 void KdenliveDoc::cleanupBackupFiles()
1640 {
1641     KUrl backupFile = m_projectFolder;
1642     backupFile.addPath(".backup/");
1643     QDir dir(backupFile.path());
1644     QString projectFile = url().fileName().section('.', 0, -2);
1645     projectFile.append("-" + m_documentProperties.value("documentid"));
1646     projectFile.append("-??");
1647     projectFile.append("??");
1648     projectFile.append("-??");
1649     projectFile.append("-??");
1650     projectFile.append("-??");
1651     projectFile.append("-??.kdenlive");
1652
1653     QStringList filter;
1654     backupFile.addPath(projectFile);
1655     filter << projectFile;
1656     dir.setNameFilters(filter);
1657     QFileInfoList resultList = dir.entryInfoList(QDir::Files, QDir::Time);
1658
1659     QDateTime d = QDateTime::currentDateTime();
1660     QStringList hourList;
1661     QStringList dayList;
1662     QStringList weekList;
1663     QStringList oldList;
1664     for (int i = 0; i < resultList.count(); i++) {
1665         if (d.secsTo(resultList.at(i).lastModified()) < 3600) {
1666             // files created in the last hour
1667             hourList.append(resultList.at(i).absoluteFilePath());
1668         }
1669         else if (d.secsTo(resultList.at(i).lastModified()) < 43200) {
1670             // files created in the day
1671             dayList.append(resultList.at(i).absoluteFilePath());
1672         }
1673         else if (d.daysTo(resultList.at(i).lastModified()) < 8) {
1674             // files created in the week
1675             weekList.append(resultList.at(i).absoluteFilePath());
1676         }
1677         else {
1678             // older files
1679             oldList.append(resultList.at(i).absoluteFilePath());
1680         }
1681     }
1682     if (hourList.count() > 20) {
1683         int step = hourList.count() / 10;
1684         for (int i = 0; i < hourList.count(); i += step) {
1685             kDebug()<<"REMOVE AT: "<<i<<", COUNT: "<<hourList.count();
1686             hourList.removeAt(i);
1687             i--;
1688         }
1689     } else hourList.clear();
1690     if (dayList.count() > 20) {
1691         int step = dayList.count() / 10;
1692         for (int i = 0; i < dayList.count(); i += step) {
1693             dayList.removeAt(i);
1694             i--;
1695         }
1696     } else dayList.clear();
1697     if (weekList.count() > 20) {
1698         int step = weekList.count() / 10;
1699         for (int i = 0; i < weekList.count(); i += step) {
1700             weekList.removeAt(i);
1701             i--;
1702         }
1703     } else weekList.clear();
1704     if (oldList.count() > 20) {
1705         int step = oldList.count() / 10;
1706         for (int i = 0; i < oldList.count(); i += step) {
1707             oldList.removeAt(i);
1708             i--;
1709         }
1710     } else oldList.clear();
1711     
1712     QString f;
1713     while (hourList.count() > 0) {
1714         f = hourList.takeFirst();
1715         QFile::remove(f);
1716         QFile::remove(f + ".png");
1717     }
1718     while (dayList.count() > 0) {
1719         f = dayList.takeFirst();
1720         QFile::remove(f);
1721         QFile::remove(f + ".png");
1722     }
1723     while (weekList.count() > 0) {
1724         f = weekList.takeFirst();
1725         QFile::remove(f);
1726         QFile::remove(f + ".png");
1727     }
1728     while (oldList.count() > 0) {
1729         f = oldList.takeFirst();
1730         QFile::remove(f);
1731         QFile::remove(f + ".png");
1732     }
1733 }
1734
1735 #include "kdenlivedoc.moc"
1736