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