]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
4551ee26bd3017ae6da0c2489327136b57cf79bd
[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     m_clipManager->resetProducersList(m_render->producersList());
749
750 }
751
752 Render *KdenliveDoc::renderer()
753 {
754     return m_render;
755 }
756
757 void KdenliveDoc::updateClip(const QString &id)
758 {
759     emit updateClipDisplay(id);
760 }
761
762 int KdenliveDoc::getFramePos(QString duration)
763 {
764     return m_timecode.getFrameCount(duration);
765 }
766
767 QString KdenliveDoc::producerName(const QString &id)
768 {
769     QString result = "unnamed";
770     QDomNodeList prods = producersList();
771     int ct = prods.count();
772     for (int i = 0; i <  ct ; i++) {
773         QDomElement e = prods.item(i).toElement();
774         if (e.attribute("id") != "black" && e.attribute("id") == id) {
775             result = e.attribute("name");
776             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
777             break;
778         }
779     }
780     return result;
781 }
782
783 QDomDocument KdenliveDoc::toXml()
784 {
785     return m_document;
786 }
787
788 Timecode KdenliveDoc::timecode() const
789 {
790     return m_timecode;
791 }
792
793 QDomNodeList KdenliveDoc::producersList()
794 {
795     return m_document.elementsByTagName("producer");
796 }
797
798 double KdenliveDoc::projectDuration() const
799 {
800     if (m_render)
801         return GenTime(m_render->getLength(), m_fps).ms() / 1000;
802     else
803         return 0;
804 }
805
806 double KdenliveDoc::fps() const
807 {
808     return m_fps;
809 }
810
811 int KdenliveDoc::width() const
812 {
813     return m_width;
814 }
815
816 int KdenliveDoc::height() const
817 {
818     return m_height;
819 }
820
821 KUrl KdenliveDoc::url() const
822 {
823     return m_url;
824 }
825
826 void KdenliveDoc::setUrl(KUrl url)
827 {
828     m_url = url;
829 }
830
831 void KdenliveDoc::setModified(bool mod)
832 {
833     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
834         m_autoSaveTimer->start(3000);
835     }
836     if (mod == m_modified) return;
837     m_modified = mod;
838     emit docModified(m_modified);
839 }
840
841 bool KdenliveDoc::isModified() const
842 {
843     return m_modified;
844 }
845
846 const QString KdenliveDoc::description() const
847 {
848     if (m_url.isEmpty())
849         return i18n("Untitled") + " / " + m_profile.description;
850     else
851         return m_url.fileName() + " / " + m_profile.description;
852 }
853
854 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
855 {
856     const QString producerId = clipId.section('_', 0, 0);
857     DocClipBase *clip = m_clipManager->getClipById(producerId);
858
859     if (clip == NULL) {
860         elem.setAttribute("id", producerId);
861         QString path = elem.attribute("resource");
862         QString extension;
863         if (elem.attribute("type").toInt() == SLIDESHOW) {
864             extension = KUrl(path).fileName();
865             path = KUrl(path).directory();
866         } /*else if (elem.attribute("type").toInt() == TEXT && QFile::exists(path) == false) {
867             kDebug() << "// TITLE: " << elem.attribute("name") << " Preview file: " << elem.attribute("resource") << " DOES NOT EXIST";
868             QString titlename = elem.attribute("name");
869             QString titleresource;
870             if (titlename.isEmpty()) {
871                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
872                 titlename = titleInfo.at(0);
873                 titleresource = titleInfo.at(1);
874                 elem.setAttribute("name", titlename);
875                 kDebug() << "// New title set to: " << titlename;
876             } else {
877                 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
878                 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
879             }
880             TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
881             QDomDocument doc;
882             doc.setContent(elem.attribute("xmldata"));
883             dia_ui->setXml(doc);
884             QImage pix = dia_ui->renderedPixmap();
885             pix.save(titleresource);
886             elem.setAttribute("resource", titleresource);
887             setNewClipResource(clipId, titleresource);
888             delete dia_ui;
889         }*/
890
891         if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
892             kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
893             const QString size = elem.attribute("file_size");
894             const QString hash = elem.attribute("file_hash");
895             QString newpath;
896             int action = KMessageBox::No;
897             if (!size.isEmpty() && !hash.isEmpty()) {
898                 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
899                 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")));
900             } else {
901                 if (elem.attribute("type").toInt() == SLIDESHOW) {
902                     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")));
903                     if (res == KMessageBox::Yes)
904                         newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
905                     else {
906                         // Abort project loading
907                         action = res;
908                     }
909                 } else {
910                     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")));
911                     if (res == KMessageBox::Yes)
912                         newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
913                     else {
914                         // Abort project loading
915                         action = res;
916                     }
917                 }
918             }
919             if (action == KMessageBox::Yes) {
920                 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
921                 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
922                 if (!m_searchFolder.isEmpty()) {
923                     newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
924                 }
925             } else if (action == KMessageBox::Cancel) {
926                 m_abortLoading = true;
927                 return;
928             } else if (action == KMessageBox::No) {
929                 // Keep clip as placeHolder
930                 elem.setAttribute("placeholder", '1');
931             }
932             if (!newpath.isEmpty()) {
933                 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
934                 elem.setAttribute("resource", newpath);
935                 setNewClipResource(clipId, newpath);
936                 setModified(true);
937             }
938         }
939         clip = new DocClipBase(m_clipManager, elem, producerId);
940         m_clipManager->addClip(clip);
941     }
942
943     if (createClipItem) {
944         emit addProjectClip(clip);
945         qApp->processEvents();
946         m_render->getFileProperties(clip->toXML(), clip->getId(), true);
947     }
948 }
949
950
951 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
952 {
953     QDomNodeList prods = m_document.elementsByTagName("producer");
954     int maxprod = prods.count();
955     for (int i = 0; i < maxprod; i++) {
956         QDomNode m = prods.at(i);
957         QString prodId = m.toElement().attribute("id");
958         if (prodId == id || prodId.startsWith(id + '_')) {
959             QDomNodeList params = m.childNodes();
960             for (int j = 0; j < params.count(); j++) {
961                 QDomElement e = params.item(j).toElement();
962                 if (e.attribute("name") == "resource") {
963                     e.firstChild().setNodeValue(path);
964                     break;
965                 }
966             }
967         }
968     }
969 }
970
971 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
972 {
973     QString foundFileName;
974     QByteArray fileData;
975     QByteArray fileHash;
976     QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
977     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
978         QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
979         if (file.open(QIODevice::ReadOnly)) {
980             if (QString::number(file.size()) == matchSize) {
981                 /*
982                 * 1 MB = 1 second per 450 files (or faster)
983                 * 10 MB = 9 seconds per 450 files (or faster)
984                 */
985                 if (file.size() > 1000000*2) {
986                     fileData = file.read(1000000);
987                     if (file.seek(file.size() - 1000000))
988                         fileData.append(file.readAll());
989                 } else
990                     fileData = file.readAll();
991                 file.close();
992                 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
993                 if (QString(fileHash.toHex()) == matchHash)
994                     return file.fileName();
995             }
996         }
997         kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
998     }
999     filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1000     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1001         foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1002         if (!foundFileName.isEmpty())
1003             break;
1004     }
1005     return foundFileName;
1006 }
1007
1008 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1009 {
1010     DocClipBase *clip = m_clipManager->getClipById(clipId);
1011     if (clip == NULL) {
1012         addClip(elem, clipId, false);
1013     } else {
1014         QMap <QString, QString> properties;
1015         QDomNamedNodeMap attributes = elem.attributes();
1016         QString attrname;
1017         for (int i = 0; i < attributes.count(); i++) {
1018             attrname = attributes.item(i).nodeName();
1019             if (attrname != "resource")
1020                 properties.insert(attrname, attributes.item(i).nodeValue());
1021             kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1022         }
1023         clip->setProperties(properties);
1024         emit addProjectClip(clip, false);
1025     }
1026     if (orig != QDomElement()) {
1027         QMap<QString, QString> meta;
1028         QDomNode m = orig.firstChild();
1029         while (!m.isNull()) {
1030             QString name = m.toElement().attribute("name");
1031             if (name.startsWith("meta.attr")) {
1032                 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1033             }
1034             m = m.nextSibling();
1035         }
1036         if (!meta.isEmpty()) {
1037             if (clip == NULL) clip = m_clipManager->getClipById(clipId);
1038             if (clip) clip->setMetadata(meta);
1039         }
1040     }
1041 }
1042
1043 void KdenliveDoc::deleteProjectClip(QList <QString> ids)
1044 {
1045     for (int i = 0; i < ids.size(); ++i) {
1046         emit deleteTimelineClip(ids.at(i));
1047         m_clipManager->slotDeleteClip(ids.at(i));
1048     }
1049     setModified(true);
1050 }
1051
1052 void KdenliveDoc::deleteClip(const QString &clipId)
1053 {
1054     emit signalDeleteProjectClip(clipId);
1055 }
1056
1057 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1058 {
1059     m_clipManager->slotAddClipList(urls, group, groupId);
1060     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1061     setModified(true);
1062 }
1063
1064
1065 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1066 {
1067     m_clipManager->slotAddClipFile(url, group, groupId);
1068     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1069     setModified(true);
1070 }
1071
1072 const QString KdenliveDoc::getFreeClipId()
1073 {
1074     return QString::number(m_clipManager->getFreeClipId());
1075 }
1076
1077 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1078 {
1079     return m_clipManager->getClipById(clipId);
1080 }
1081
1082 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1083 {
1084     m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1085     setModified(true);
1086     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1087 }
1088
1089 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)
1090 {
1091     m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop, fade, luma_duration, luma_file, softness, group, groupId);
1092     setModified(true);
1093     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1094 }
1095
1096 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1097 {
1098     QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1099     KStandardDirs::makeDir(titlesFolder);
1100     TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1101     if (dia_ui->exec() == QDialog::Accepted) {
1102         /*QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1103         QImage pix = dia_ui->renderedPixmap();
1104         pix.save(titleInfo.at(1));*/
1105         //dia_ui->saveTitle(path + ".kdenlivetitle");
1106         m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->duration(), dia_ui->xml().toString(), group, groupId);
1107         setModified(true);
1108         emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1109     }
1110     delete dia_ui;
1111 }
1112
1113 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1114 {
1115     QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1116     if (path.isEmpty()) {
1117         path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "*.kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1118     }
1119
1120     if (path.isEmpty()) return;
1121
1122     QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder(), true);
1123
1124     //TODO: rewrite with new title system (just set resource)
1125     /*TitleWidget *dia_ui = new TitleWidget(path, titlesFolder, m_render, kapp->activeWindow());
1126     QImage pix = dia_ui->renderedPixmap();
1127     pix.save(titleInfo.at(1));
1128     delete dia_ui;
1129     m_clipManager->slotAddTextTemplateClip(titleInfo.at(0), titleInfo.at(1), path, group, groupId);
1130     setModified(true);*/
1131     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1132 }
1133
1134 int KdenliveDoc::tracksCount() const
1135 {
1136     return m_tracksList.count();
1137 }
1138
1139 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1140 {
1141     return m_tracksList.at(ix);
1142 }
1143
1144 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1145 {
1146     m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1147 }
1148
1149 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1150 {
1151     m_tracksList[ix].isLocked = lock;
1152 }
1153
1154 bool KdenliveDoc::isTrackLocked(int ix) const
1155 {
1156     return m_tracksList.at(ix).isLocked;
1157 }
1158
1159 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1160 {
1161     m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1162 }
1163
1164 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1165 {
1166     if (ix == -1) m_tracksList << type;
1167     else m_tracksList.insert(ix, type);
1168 }
1169
1170 void KdenliveDoc::deleteTrack(int ix)
1171 {
1172     m_tracksList.removeAt(ix);
1173 }
1174
1175 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1176 {
1177     m_tracksList[ix].type = type.type;
1178     m_tracksList[ix].isMute = type.isMute;
1179     m_tracksList[ix].isBlind = type.isBlind;
1180     m_tracksList[ix].isLocked = type.isLocked;
1181     m_tracksList[ix].trackName = type.trackName;
1182 }
1183
1184 const QList <TrackInfo> KdenliveDoc::tracksList() const
1185 {
1186     return m_tracksList;
1187 }
1188
1189 QPoint KdenliveDoc::getTracksCount() const
1190 {
1191     int audio = 0;
1192     int video = 0;
1193     foreach(const TrackInfo &info, m_tracksList) {
1194         if (info.type == VIDEOTRACK) video++;
1195         else audio++;
1196     }
1197     return QPoint(video, audio);
1198 }
1199
1200 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1201 {
1202     pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1203 }
1204
1205 QString KdenliveDoc::getLadspaFile() const
1206 {
1207     int ct = 0;
1208     QString counter = QString::number(ct).rightJustified(5, '0', false);
1209     while (QFile::exists(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa")) {
1210         ct++;
1211         counter = QString::number(ct).rightJustified(5, '0', false);
1212     }
1213     return m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa";
1214 }
1215
1216 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1217 {
1218     int clipType;
1219     QDomElement e;
1220     QString id;
1221     QString resource;
1222     QList <QDomElement> missingClips;
1223     for (int i = 0; i < infoproducers.count(); i++) {
1224         e = infoproducers.item(i).toElement();
1225         clipType = e.attribute("type").toInt();
1226         if (clipType == COLOR) continue;
1227         if (clipType == TEXT) {
1228             //TODO: Check is clip template is missing (xmltemplate) or hash changed
1229             continue;
1230         }
1231         id = e.attribute("id");
1232         resource = e.attribute("resource");
1233         if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1234         if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1235             // Missing clip found
1236             missingClips.append(e);
1237         } else {
1238             // Check if the clip has changed
1239             if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1240                 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1241                     e.removeAttribute("file_hash");
1242             }
1243         }
1244     }
1245     if (missingClips.isEmpty()) return true;
1246     DocumentChecker d(missingClips, m_document);
1247     return (d.exec() == QDialog::Accepted);
1248 }
1249
1250 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1251 {
1252     m_documentProperties[name] = value;
1253 }
1254
1255 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1256 {
1257     return m_documentProperties.value(name);
1258 }
1259
1260 #include "kdenlivedoc.moc"
1261