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