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