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