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