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