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