]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
0275c2dc16ff66242c1669d2fb3b3c976f037dc5
[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
44 #include <QCryptographicHash>
45 #include <QFile>
46 #include <QInputDialog>
47 #include <QDomImplementation>
48
49 #include <mlt++/Mlt.h>
50
51 const double DOCUMENTVERSION = 0.85;
52
53 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, QString profileName, const QPoint tracks, Render *render, KTextEdit *notes, MainWindow *parent, KProgressDialog *progressDialog) :
54     QObject(parent),
55     m_autosave(NULL),
56     m_url(url),
57     m_render(render),
58     m_notesWidget(notes),
59     m_commandStack(new QUndoStack(undoGroup)),
60     m_modified(false),
61     m_projectFolder(projectFolder)
62 {
63     m_clipManager = new ClipManager(this);
64     m_autoSaveTimer = new QTimer(this);
65     m_autoSaveTimer->setSingleShot(true);
66     bool success = false;
67
68     // init default document properties
69     m_documentProperties["zoom"] = "7";
70     m_documentProperties["verticalzoom"] = "1";
71     m_documentProperties["zonein"] = "0";
72     m_documentProperties["zoneout"] = "100";
73
74     if (!url.isEmpty()) {
75         QString tmpFile;
76         success = KIO::NetAccess::download(url.path(), tmpFile, parent);
77         if (!success) // The file cannot be opened
78             KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
79         else {
80             QFile file(tmpFile);
81             QString errorMsg;
82             QDomImplementation impl;
83             impl.setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
84             success = m_document.setContent(&file, false, &errorMsg);
85             file.close();
86             KIO::NetAccess::removeTempFile(tmpFile);
87
88             if (!success) // It is corrupted
89                 KMessageBox::error(parent, errorMsg);
90             else {
91                 parent->slotGotProgressInfo(i18n("Validating"), 0);
92                 qApp->processEvents();
93                 DocumentValidator validator(m_document);
94                 success = validator.isProject();
95                 if (!success) {
96                     // It is not a project file
97                     parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
98                 } else {
99                     /*
100                      * Validate the file against the current version (upgrade
101                      * and recover it if needed). It is NOT a passive operation
102                      */
103                     // TODO: backup the document or alert the user?
104                     success = validator.validate(DOCUMENTVERSION);
105                     if (success) { // Let the validator handle error messages
106                         parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
107                         qApp->processEvents();
108                         QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
109                         success = checkDocumentClips(infoproducers);
110                         if (success) {
111                             if (m_document.documentElement().attribute("modified") == "1") setModified(true);
112                             parent->slotGotProgressInfo(i18n("Loading"), 0);
113                             QDomElement mlt = m_document.firstChildElement("mlt");
114                             QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
115
116                             // Check embedded effects
117                             QDomElement customeffects = infoXml.firstChildElement("customeffects");
118                             if (!customeffects.isNull() && customeffects.hasChildNodes()) {
119                                 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
120                                 qApp->processEvents();
121                                 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
122                             }
123
124                             QDomElement e;
125                             // Read notes
126                             QDomElement notesxml = infoXml.firstChildElement("documentnotes");
127                             if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
128
129                             // Build tracks
130                             QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
131                             if (!tracksinfo.isNull()) {
132                                 QDomNodeList trackslist = tracksinfo.childNodes();
133                                 int maxchild = trackslist.count();
134                                 for (int k = 0; k < maxchild; k++) {
135                                     e = trackslist.at(k).toElement();
136                                     if (e.tagName() == "trackinfo") {
137                                         TrackInfo projectTrack;
138                                         if (e.attribute("type") == "audio")
139                                             projectTrack.type = AUDIOTRACK;
140                                         else
141                                             projectTrack.type = VIDEOTRACK;
142                                         projectTrack.isMute = e.attribute("mute").toInt();
143                                         projectTrack.isBlind = e.attribute("blind").toInt();
144                                         projectTrack.isLocked = e.attribute("locked").toInt();
145                                         projectTrack.trackName = e.attribute("trackname");
146                                         m_tracksList.append(projectTrack);
147                                     }
148                                 }
149                                 mlt.removeChild(tracksinfo);
150                             }
151
152                             QDomNodeList folders = m_document.elementsByTagName("folder");
153                             for (int i = 0; i < folders.count(); i++) {
154                                 e = folders.item(i).cloneNode().toElement();
155                                 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
156                             }
157
158                             const int infomax = infoproducers.count();
159                             QDomNodeList producers = m_document.elementsByTagName("producer");
160                             const int max = producers.count();
161
162                             if (!progressDialog) {
163                                 progressDialog = new KProgressDialog(parent, i18n("Loading project"), i18n("Adding clips"));
164                                 progressDialog->setAllowCancel(false);
165                             } else {
166                                 progressDialog->setLabelText(i18n("Adding clips"));
167                             }
168                             progressDialog->progressBar()->setMaximum(infomax);
169                             progressDialog->show();
170                             qApp->processEvents();
171
172                             for (int i = 0; i < infomax; i++) {
173                                 e = infoproducers.item(i).cloneNode().toElement();
174                                 QString prodId = e.attribute("id");
175                                 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
176                                     e.setTagName("producer");
177                                     // Get MLT's original producer properties
178                                     QDomElement orig;
179                                     for (int j = 0; j < max; j++) {
180                                         QDomNode o = producers.item(j);
181                                         QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
182                                         if (origId == prodId) {
183                                             orig = o.cloneNode().toElement();
184                                             break;
185                                         }
186                                     }
187
188                                     if (!addClipInfo(e, orig, prodId)) {
189                                         // The user manually aborted the loading.
190                                         success = false;
191                                         emit resetProjectList();
192                                         m_tracksList.clear();
193                                         m_clipManager->clear();
194                                         break;
195                                     }
196                                 }
197                                 if (i % 10 == 0)
198                                     progressDialog->progressBar()->setValue(i);
199                             }
200
201                             if (success) {
202                                 QDomElement markers = infoXml.firstChildElement("markers");
203                                 if (!markers.isNull()) {
204                                     QDomNodeList markerslist = markers.childNodes();
205                                     int maxchild = markerslist.count();
206                                     for (int k = 0; k < maxchild; k++) {
207                                         e = markerslist.at(k).toElement();
208                                         if (e.tagName() == "marker")
209                                             m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
210                                     }
211                                     infoXml.removeChild(markers);
212                                 }
213
214                                 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
215                                 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
216                                 QDomNamedNodeMap props = docproperties.attributes();
217                                 for (int i = 0; i < props.count(); i++)
218                                     m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
219                                 setProfilePath(infoXml.attribute("profile"));
220                                 if (validator.isModified()) setModified(true);
221                                 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
222                             }
223                         }
224                     }
225                 }
226             }
227         }
228     }
229
230     // Something went wrong, or a new file was requested: create a new project
231     if (!success) {
232         m_url = KUrl();
233         setProfilePath(profileName);
234         m_document = createEmptyDocument(tracks.x(), tracks.y());
235     }
236
237     // Set the video profile (empty == default)
238     KdenliveSettings::setCurrent_profile(profilePath());
239
240     // Ask to create the project directory if it does not exist
241     if (!QFile::exists(m_projectFolder.path())) {
242         int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
243         if (create == KMessageBox::Yes) {
244             QDir projectDir(m_projectFolder.path());
245             bool ok = projectDir.mkpath(m_projectFolder.path());
246             if (!ok) {
247                 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
248             }
249         }
250     }
251
252     // Make sure the project folder is usable
253     if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
254         KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
255         m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
256     }
257
258     // Make sure that the necessary folders exist
259     KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
260     KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
261     KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/");
262
263     //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
264     connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
265 }
266
267 KdenliveDoc::~KdenliveDoc()
268 {
269     m_autoSaveTimer->stop();
270     delete m_commandStack;
271     kDebug() << "// DEL CLP MAN";
272     delete m_clipManager;
273     kDebug() << "// DEL CLP MAN done";
274     delete m_autoSaveTimer;
275     if (m_autosave) {
276         if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
277         delete m_autosave;
278     }
279 }
280
281 int KdenliveDoc::setSceneList()
282 {
283     m_render->resetProfile(KdenliveSettings::current_profile());
284     if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
285         // INVALID MLT Consumer, something is wrong
286         return -1;
287     }
288     m_documentProperties.remove("position");
289     // m_document xml is now useless, clear it
290     m_document.clear();
291     return 0;
292 }
293
294 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
295 {
296     m_tracksList.clear();
297
298     // Tracks are added Â«backwards», so we need to reverse the track numbering
299     // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
300     // Better default names for tracks: Audio 1 etc. instead of blank numbers
301     for (int i = 0; i < audiotracks; i++) {
302         TrackInfo audioTrack;
303         audioTrack.type = AUDIOTRACK;
304         audioTrack.isMute = false;
305         audioTrack.isBlind = true;
306         audioTrack.isLocked = false;
307         audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
308         m_tracksList.append(audioTrack);
309
310     }
311     for (int i = 0; i < videotracks; i++) {
312         TrackInfo videoTrack;
313         videoTrack.type = VIDEOTRACK;
314         videoTrack.isMute = false;
315         videoTrack.isBlind = false;
316         videoTrack.isLocked = false;
317         videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
318         m_tracksList.append(videoTrack);
319     }
320     return createEmptyDocument(m_tracksList);
321 }
322
323 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
324 {
325     // Creating new document
326     QDomDocument doc;
327     QDomElement mlt = doc.createElement("mlt");
328     doc.appendChild(mlt);
329
330
331     // Create black producer
332     // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
333     // the composite transitions with the black track are corrupted.
334     QDomElement blk = doc.createElement("producer");
335     blk.setAttribute("in", 0);
336     blk.setAttribute("out", 500);
337     blk.setAttribute("id", "black");
338
339     QDomElement property = doc.createElement("property");
340     property.setAttribute("name", "mlt_type");
341     QDomText value = doc.createTextNode("producer");
342     property.appendChild(value);
343     blk.appendChild(property);
344
345     property = doc.createElement("property");
346     property.setAttribute("name", "aspect_ratio");
347     value = doc.createTextNode(QString::number(0.0));
348     property.appendChild(value);
349     blk.appendChild(property);
350
351     property = doc.createElement("property");
352     property.setAttribute("name", "length");
353     value = doc.createTextNode(QString::number(15000));
354     property.appendChild(value);
355     blk.appendChild(property);
356
357     property = doc.createElement("property");
358     property.setAttribute("name", "eof");
359     value = doc.createTextNode("pause");
360     property.appendChild(value);
361     blk.appendChild(property);
362
363     property = doc.createElement("property");
364     property.setAttribute("name", "resource");
365     value = doc.createTextNode("black");
366     property.appendChild(value);
367     blk.appendChild(property);
368
369     property = doc.createElement("property");
370     property.setAttribute("name", "mlt_service");
371     value = doc.createTextNode("colour");
372     property.appendChild(value);
373     blk.appendChild(property);
374
375     mlt.appendChild(blk);
376
377
378     QDomElement tractor = doc.createElement("tractor");
379     tractor.setAttribute("id", "maintractor");
380     QDomElement multitrack = doc.createElement("multitrack");
381     QDomElement playlist = doc.createElement("playlist");
382     playlist.setAttribute("id", "black_track");
383     mlt.appendChild(playlist);
384
385     QDomElement blank0 = doc.createElement("entry");
386     blank0.setAttribute("in", "0");
387     blank0.setAttribute("out", "1");
388     blank0.setAttribute("producer", "black");
389     playlist.appendChild(blank0);
390
391     // create playlists
392     int total = tracks.count() + 1;
393
394     for (int i = 1; i < total; i++) {
395         QDomElement playlist = doc.createElement("playlist");
396         playlist.setAttribute("id", "playlist" + QString::number(i));
397         mlt.appendChild(playlist);
398     }
399
400     QDomElement track0 = doc.createElement("track");
401     track0.setAttribute("producer", "black_track");
402     tractor.appendChild(track0);
403
404     // create audio and video tracks
405     for (int i = 1; i < total; i++) {
406         QDomElement track = doc.createElement("track");
407         track.setAttribute("producer", "playlist" + QString::number(i));
408         if (tracks.at(i - 1).type == AUDIOTRACK) {
409             track.setAttribute("hide", "video");
410         } else if (tracks.at(i - 1).isBlind)
411             track.setAttribute("hide", "video");
412         if (tracks.at(i - 1).isMute)
413             track.setAttribute("hide", "audio");
414         tractor.appendChild(track);
415     }
416
417     for (int i = 2; i < total ; i++) {
418         QDomElement transition = doc.createElement("transition");
419         transition.setAttribute("always_active", "1");
420
421         QDomElement property = doc.createElement("property");
422         property.setAttribute("name", "a_track");
423         QDomText value = doc.createTextNode(QString::number(1));
424         property.appendChild(value);
425         transition.appendChild(property);
426
427         property = doc.createElement("property");
428         property.setAttribute("name", "b_track");
429         value = doc.createTextNode(QString::number(i));
430         property.appendChild(value);
431         transition.appendChild(property);
432
433         property = doc.createElement("property");
434         property.setAttribute("name", "mlt_service");
435         value = doc.createTextNode("mix");
436         property.appendChild(value);
437         transition.appendChild(property);
438
439         property = doc.createElement("property");
440         property.setAttribute("name", "combine");
441         value = doc.createTextNode("1");
442         property.appendChild(value);
443         transition.appendChild(property);
444
445         property = doc.createElement("property");
446         property.setAttribute("name", "internal_added");
447         value = doc.createTextNode("237");
448         property.appendChild(value);
449         transition.appendChild(property);
450         tractor.appendChild(transition);
451     }
452     mlt.appendChild(tractor);
453     return doc;
454 }
455
456
457 void KdenliveDoc::syncGuides(QList <Guide *> guides)
458 {
459     m_guidesXml.clear();
460     QDomElement guideNode = m_guidesXml.createElement("guides");
461     m_guidesXml.appendChild(guideNode);
462     QDomElement e;
463
464     for (int i = 0; i < guides.count(); i++) {
465         e = m_guidesXml.createElement("guide");
466         e.setAttribute("time", guides.at(i)->position().ms() / 1000);
467         e.setAttribute("comment", guides.at(i)->label());
468         guideNode.appendChild(e);
469     }
470     setModified(true);
471     emit guidesUpdated();
472 }
473
474 QDomElement KdenliveDoc::guidesXml() const
475 {
476     return m_guidesXml.documentElement();
477 }
478
479 void KdenliveDoc::slotAutoSave()
480 {
481     if (m_render && m_autosave) {
482         if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
483             // show error: could not open the autosave file
484             kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
485         }
486         kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
487         saveSceneList(m_autosave->fileName(), m_render->sceneList());
488     }
489 }
490
491 void KdenliveDoc::setZoom(int horizontal, int vertical)
492 {
493     m_documentProperties["zoom"] = QString::number(horizontal);
494     m_documentProperties["verticalzoom"] = QString::number(vertical);
495 }
496
497 QPoint KdenliveDoc::zoom() const
498 {
499     return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
500 }
501
502 void KdenliveDoc::setZone(int start, int end)
503 {
504     m_documentProperties["zonein"] = QString::number(start);
505     m_documentProperties["zoneout"] = QString::number(end);
506 }
507
508 QPoint KdenliveDoc::zone() const
509 {
510     return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
511 }
512
513 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene)
514 {
515     QDomDocument sceneList;
516     sceneList.setContent(scene, true);
517     QDomElement mlt = sceneList.firstChildElement("mlt");
518     if (mlt.isNull() || !mlt.hasChildNodes()) {
519         //Make sure we don't save if scenelist is corrupted
520         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
521         return false;
522     }
523
524     QDomElement addedXml = sceneList.createElement("kdenlivedoc");
525     mlt.appendChild(addedXml);
526
527     // check if project contains custom effects to embed them in project file
528     QDomNodeList effects = mlt.elementsByTagName("filter");
529     int maxEffects = effects.count();
530     kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
531     QMap <QString, QString> effectIds;
532     for (int i = 0; i < maxEffects; i++) {
533         QDomNode m = effects.at(i);
534         QDomNodeList params = m.childNodes();
535         QString id;
536         QString tag;
537         for (int j = 0; j < params.count(); j++) {
538             QDomElement e = params.item(j).toElement();
539             if (e.attribute("name") == "kdenlive_id") {
540                 id = e.firstChild().nodeValue();
541             }
542             if (e.attribute("name") == "tag") {
543                 tag = e.firstChild().nodeValue();
544             }
545             if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
546         }
547     }
548     QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
549     addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
550
551     QDomElement markers = sceneList.createElement("markers");
552     addedXml.setAttribute("version", DOCUMENTVERSION);
553     addedXml.setAttribute("kdenliveversion", VERSION);
554     addedXml.setAttribute("profile", profilePath());
555     addedXml.setAttribute("projectfolder", m_projectFolder.path());
556
557     QDomElement docproperties = sceneList.createElement("documentproperties");
558     QMapIterator<QString, QString> i(m_documentProperties);
559     while (i.hasNext()) {
560         i.next();
561         docproperties.setAttribute(i.key(), i.value());
562     }
563     docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
564     addedXml.appendChild(docproperties);
565
566     QDomElement docnotes = sceneList.createElement("documentnotes");
567     QDomText value = sceneList.createTextNode(m_notesWidget->toPlainText());
568     docnotes.appendChild(value);
569     addedXml.appendChild(docnotes);
570
571     // Add profile info
572     QDomElement profileinfo = sceneList.createElement("profileinfo");
573     profileinfo.setAttribute("description", m_profile.description);
574     profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
575     profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
576     profileinfo.setAttribute("width", m_profile.width);
577     profileinfo.setAttribute("height", m_profile.height);
578     profileinfo.setAttribute("progressive", m_profile.progressive);
579     profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
580     profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
581     profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
582     profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
583     addedXml.appendChild(profileinfo);
584
585     // tracks info
586     QDomElement tracksinfo = sceneList.createElement("tracksinfo");
587     foreach(const TrackInfo & info, m_tracksList) {
588         QDomElement trackinfo = sceneList.createElement("trackinfo");
589         if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
590         trackinfo.setAttribute("mute", info.isMute);
591         trackinfo.setAttribute("blind", info.isBlind);
592         trackinfo.setAttribute("locked", info.isLocked);
593         trackinfo.setAttribute("trackname", info.trackName);
594         tracksinfo.appendChild(trackinfo);
595     }
596     addedXml.appendChild(tracksinfo);
597
598     // save project folders
599     QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
600
601     QMapIterator<QString, QString> f(folderlist);
602     while (f.hasNext()) {
603         f.next();
604         QDomElement folder = sceneList.createElement("folder");
605         folder.setAttribute("id", f.key());
606         folder.setAttribute("name", f.value());
607         addedXml.appendChild(folder);
608     }
609
610     // Save project clips
611     QDomElement e;
612     QList <DocClipBase*> list = m_clipManager->documentClipList();
613     for (int i = 0; i < list.count(); i++) {
614         e = list.at(i)->toXML();
615         e.setTagName("kdenlive_producer");
616         addedXml.appendChild(sceneList.importNode(e, true));
617         QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
618         for (int j = 0; j < marks.count(); j++) {
619             QDomElement marker = sceneList.createElement("marker");
620             marker.setAttribute("time", marks.at(j).time().ms() / 1000);
621             marker.setAttribute("comment", marks.at(j).comment());
622             marker.setAttribute("id", e.attribute("id"));
623             markers.appendChild(marker);
624         }
625     }
626     addedXml.appendChild(markers);
627
628     // Add guides
629     if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
630
631     // Add clip groups
632     addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
633
634     //wes.appendChild(doc.importNode(kdenliveData, true));
635
636     QFile file(path);
637     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
638         kWarning() << "//////  ERROR writing to file: " << path;
639         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
640         return false;
641     }
642
643     file.write(sceneList.toString().toUtf8());
644     if (file.error() != QFile::NoError) {
645         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
646         file.close();
647         return false;
648     }
649     file.close();
650     return true;
651 }
652
653 ClipManager *KdenliveDoc::clipManager()
654 {
655     return m_clipManager;
656 }
657
658 KUrl KdenliveDoc::projectFolder() const
659 {
660     //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
661     return m_projectFolder;
662 }
663
664 void KdenliveDoc::setProjectFolder(KUrl url)
665 {
666     if (url == m_projectFolder) return;
667     setModified(true);
668     KStandardDirs::makeDir(url.path());
669     KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
670     KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
671     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);
672     m_projectFolder = url;
673 }
674
675 void KdenliveDoc::moveProjectData(KUrl url)
676 {
677     QList <DocClipBase*> list = m_clipManager->documentClipList();
678     //TODO: Also move ladspa effects files
679     for (int i = 0; i < list.count(); i++) {
680         DocClipBase *clip = list.at(i);
681         if (clip->clipType() == TEXT) {
682             // the image for title clip must be moved
683             KUrl oldUrl = clip->fileURL();
684             KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
685             KIO::Job *job = KIO::copy(oldUrl, newUrl);
686             if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
687         }
688         QString hash = clip->getClipHash();
689         KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
690         KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
691         if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
692             KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
693             KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
694             KIO::NetAccess::synchronousRun(job, 0);
695         }
696         if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
697             KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
698             KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
699             if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
700         }
701     }
702 }
703
704 const QString &KdenliveDoc::profilePath() const
705 {
706     return m_profile.path;
707 }
708
709 MltVideoProfile KdenliveDoc::mltProfile() const
710 {
711     return m_profile;
712 }
713
714 bool KdenliveDoc::setProfilePath(QString path)
715 {
716     if (path.isEmpty()) path = KdenliveSettings::default_profile();
717     if (path.isEmpty()) path = "dv_pal";
718     m_profile = ProfilesDialog::getVideoProfile(path);
719     bool current_fps = m_fps;
720     if (m_profile.path.isEmpty()) {
721         // Profile not found, use embedded profile
722         QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
723         if (profileInfo.isNull()) {
724             KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
725             m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
726         } else {
727             m_profile.description = profileInfo.attribute("description");
728             m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
729             m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
730             m_profile.width = profileInfo.attribute("width").toInt();
731             m_profile.height = profileInfo.attribute("height").toInt();
732             m_profile.progressive = profileInfo.attribute("progressive").toInt();
733             m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
734             m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
735             m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
736             m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
737             QString existing = ProfilesDialog::existingProfile(m_profile);
738             if (!existing.isEmpty()) {
739                 m_profile = ProfilesDialog::getVideoProfile(existing);
740                 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
741             } else {
742                 QString newDesc = m_profile.description;
743                 bool ok = true;
744                 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
745                     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);
746                 }
747                 if (ok == false) {
748                     // User canceled, use default profile
749                     m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
750                 } else {
751                     if (newDesc != m_profile.description) {
752                         // Profile description existed, was replaced by new one
753                         m_profile.description = newDesc;
754                     } else {
755                         KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
756                     }
757                     ProfilesDialog::saveProfile(m_profile);
758                 }
759             }
760             setModified(true);
761         }
762     }
763
764     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
765     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
766     KdenliveSettings::setProject_fps(m_fps);
767     m_width = m_profile.width;
768     m_height = m_profile.height;
769     kDebug() << "Kdenlive document, init timecode from path: " << path << ",  " << m_fps;
770     m_timecode.setFormat(m_fps);
771     return (current_fps != m_fps);
772 }
773
774 double KdenliveDoc::dar() const
775 {
776     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
777 }
778
779 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
780 {
781     emit progressInfo(message, progress);
782 }
783
784 QUndoStack *KdenliveDoc::commandStack()
785 {
786     return m_commandStack;
787 }
788
789 /*
790 void KdenliveDoc::setRenderer(Render *render) {
791     if (m_render) return;
792     m_render = render;
793     emit progressInfo(i18n("Loading playlist..."), 0);
794     //qApp->processEvents();
795     if (m_render) {
796         m_render->setSceneList(m_document.toString(), m_startPos);
797         kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
798         checkProjectClips();
799     }
800     emit progressInfo(QString(), -1);
801 }*/
802
803 void KdenliveDoc::checkProjectClips()
804 {
805     if (m_render == NULL) return;
806     m_clipManager->resetProducersList(m_render->producersList());
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), "application/x-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