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