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