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