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