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