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