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