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