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