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