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