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