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