]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
Make sure we don't create a new profile with existing name, nor create a duplicate...
[kdenlive] / src / kdenlivedoc.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *                                                                         *
4  *   This program is free software; you can redistribute it and/or modify  *
5  *   it under the terms of the GNU General Public License as published by  *
6  *   the Free Software Foundation; either version 2 of the License, or     *
7  *   (at your option) any later version.                                   *
8  *                                                                         *
9  *   This program is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU General Public License for more details.                          *
13  *                                                                         *
14  *   You should have received a copy of the GNU General Public License     *
15  *   along with this program; if not, write to the                         *
16  *   Free Software Foundation, Inc.,                                       *
17  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA          *
18  ***************************************************************************/
19
20
21 #include "kdenlivedoc.h"
22 #include "docclipbase.h"
23 #include "profilesdialog.h"
24 #include "kdenlivesettings.h"
25 #include "renderer.h"
26 #include "clipmanager.h"
27 #include "titlewidget.h"
28 #include "mainwindow.h"
29 #include "documentchecker.h"
30 #include "documentvalidator.h"
31 #include "kdenlive-config.h"
32
33 #include <KDebug>
34 #include <KStandardDirs>
35 #include <KMessageBox>
36 #include <KLocale>
37 #include <KFileDialog>
38 #include <KIO/NetAccess>
39 #include <KIO/CopyJob>
40 #include <KApplication>
41
42 #include <QCryptographicHash>
43 #include <QFile>
44 #include <QInputDialog>
45
46 #include <mlt++/Mlt.h>
47
48 const double DOCUMENTVERSION = 0.83;
49
50 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, QString profileName, const QPoint tracks, Render *render, MainWindow *parent) :
51         QObject(parent),
52         m_autosave(NULL),
53         m_url(url),
54         m_zoom(7),
55         m_startPos(0),
56         m_render(render),
57         m_commandStack(new QUndoStack(undoGroup)),
58         m_modified(false),
59         m_projectFolder(projectFolder),
60         m_documentLoadingStep(0.0),
61         m_documentLoadingProgress(0),
62         m_abortLoading(false),
63         m_zoneStart(0),
64         m_zoneEnd(100)
65 {
66     m_clipManager = new ClipManager(this);
67     m_autoSaveTimer = new QTimer(this);
68     m_autoSaveTimer->setSingleShot(true);
69     bool success = false;
70     if (!url.isEmpty()) {
71         QString tmpFile;
72         success = KIO::NetAccess::download(url.path(), tmpFile, parent);
73         if (!success) // The file cannot be opened
74             KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
75         else {
76             QFile file(tmpFile);
77             QString errorMsg;
78             success = m_document.setContent(&file, false, &errorMsg);
79             file.close();
80             KIO::NetAccess::removeTempFile(tmpFile);
81             if (!success) // It is corrupted
82                 KMessageBox::error(parent, errorMsg);
83             else {
84                 DocumentValidator validator(m_document);
85                 success = validator.isProject();
86                 if (!success) // It is not a project file
87                     parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file.", m_url.path()), 100);
88                 else {
89                     /*
90                      * Validate the file against the current version (upgrade
91                      * and recover it if needed). It is NOT a passive operation
92                      */
93                     // TODO: backup the document or alert the user?
94                     success = validator.validate(DOCUMENTVERSION);
95                     if (success) { // Let the validator handle error messages
96                         setModified(validator.isModified());
97                         QDomElement mlt = m_document.firstChildElement("mlt");
98                         QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
99
100                         profileName = 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                         QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
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                             QDomElement markers = infoXml.firstChildElement("markers");
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                                 infoXml.removeChild(markers);
192                             }
193                             setProfilePath(profileName);
194                             mlt.removeChild(infoXml);
195                             kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
196                         }
197                     }
198                 }
199             }
200         }
201     } else setProfilePath(profileName);
202
203     // Something went wrong, or a new file was requested: create a new project
204     if (!success) {
205         m_url = KUrl();
206         m_document = createEmptyDocument(tracks.x(), tracks.y());
207     }
208
209     // Set the video profile (empty == default)
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     QDomElement mlt = sceneList.firstChildElement("mlt");
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     // Add profile info
429     QDomElement profileinfo = sceneList.createElement("profileinfo");
430     profileinfo.setAttribute("description", m_profile.description);
431     profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
432     profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
433     profileinfo.setAttribute("width", m_profile.width);
434     profileinfo.setAttribute("height", m_profile.height);
435     profileinfo.setAttribute("progressive", m_profile.progressive);
436     profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
437     profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
438     profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
439     profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
440     addedXml.appendChild(profileinfo);
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     if (m_profile.path.isEmpty()) {
576         // Profile not found, use embedded profile
577         QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
578         if (profileInfo.isNull()) {
579             KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
580             m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
581         } else {
582             m_profile.description = profileInfo.attribute("description");
583             m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
584             m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
585             m_profile.width = profileInfo.attribute("width").toInt();
586             m_profile.height = profileInfo.attribute("height").toInt();
587             m_profile.progressive = profileInfo.attribute("progressive").toInt();
588             m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
589             m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
590             m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
591             m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
592             QString existing = ProfilesDialog::existingProfile(m_profile);
593             if (!existing.isEmpty()) {
594                 m_profile = ProfilesDialog::getVideoProfile(existing);
595                 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
596             } else {
597                 QString newDesc = m_profile.description;
598                 bool ok = true;
599                 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
600                     newDesc = QInputDialog::getText(kapp->activeWindow(), i18n("Existing Profile"), i18n("Your project uses an unknown profile.\nIt uses an existing profile name: %1.\nPlease choose a new name to save it", newDesc), QLineEdit::Normal, newDesc, &ok);
601                 }
602                 if (ok == false) {
603                     // User canceled, use default profile
604                     m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
605                 } else {
606                     if (newDesc != m_profile.description) {
607                         // Profile description existed, was replaced by new one
608                         m_profile.description = newDesc;
609                     } else {
610                         KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
611                     }
612                     ProfilesDialog::saveProfile(m_profile);
613                 }
614             }
615             setModified(true);
616         }
617     }
618
619     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
620     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
621     KdenliveSettings::setProject_fps(m_fps);
622     m_width = m_profile.width;
623     m_height = m_profile.height;
624     kDebug() << "Kdenlive document, init timecode from path: " << path << ",  " << m_fps;
625     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
626     else m_timecode.setFormat((int) m_fps);
627 }
628
629 double KdenliveDoc::dar()
630 {
631     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
632 }
633
634 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
635 {
636     emit progressInfo(message, progress);
637 }
638
639 void KdenliveDoc::loadingProgressed()
640 {
641     m_documentLoadingProgress += m_documentLoadingStep;
642     emit progressInfo(QString(), (int) m_documentLoadingProgress);
643 }
644
645 QUndoStack *KdenliveDoc::commandStack()
646 {
647     return m_commandStack;
648 }
649
650 /*
651 void KdenliveDoc::setRenderer(Render *render) {
652     if (m_render) return;
653     m_render = render;
654     emit progressInfo(i18n("Loading playlist..."), 0);
655     //qApp->processEvents();
656     if (m_render) {
657         m_render->setSceneList(m_document.toString(), m_startPos);
658         kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
659         checkProjectClips();
660     }
661     emit progressInfo(QString(), -1);
662 }*/
663
664 void KdenliveDoc::checkProjectClips()
665 {
666     kDebug() << "+++++++++++++ + + + + CHK PCLIPS";
667     if (m_render == NULL) return;
668     m_clipManager->resetProducersList(m_render->producersList());
669     return;
670
671     // Useless now...
672     QList <Mlt::Producer *> prods = m_render->producersList();
673     QString id ;
674     QString prodId ;
675     QString prodTrack ;
676     for (int i = 0; i < prods.count(); i++) {
677         id = prods.at(i)->get("id");
678         prodId = id.section('_', 0, 0);
679         prodTrack = id.section('_', 1, 1);
680         DocClipBase *clip = m_clipManager->getClipById(prodId);
681         if (clip) clip->setProducer(prods.at(i));
682         if (clip && clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
683             // regenerate text clip image if required
684             //kDebug() << "// TITLE: " << clip->getProperty("titlename") << " Preview file: " << clip->getProperty("resource") << " DOES NOT EXIST";
685             QString titlename = clip->getProperty("name");
686             QString titleresource;
687             if (titlename.isEmpty()) {
688                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
689                 titlename = titleInfo.at(0);
690                 titleresource = titleInfo.at(1);
691                 clip->setProperty("name", titlename);
692                 kDebug() << "// New title set to: " << titlename;
693             } else {
694                 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
695                 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
696             }
697             TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
698             QDomDocument doc;
699             doc.setContent(clip->getProperty("xmldata"));
700             dia_ui->setXml(doc);
701             QImage pix = dia_ui->renderedPixmap();
702             pix.save(titleresource);
703             clip->setProperty("resource", titleresource);
704             delete dia_ui;
705             clip->producer()->set("force_reload", 1);
706         }
707     }
708 }
709
710 void KdenliveDoc::updatePreviewSettings()
711 {
712     m_clipManager->updatePreviewSettings();
713     m_render->updatePreviewSettings();
714     m_clipManager->resetProducersList(m_render->producersList());
715
716 }
717
718 Render *KdenliveDoc::renderer()
719 {
720     return m_render;
721 }
722
723 void KdenliveDoc::updateClip(const QString &id)
724 {
725     emit updateClipDisplay(id);
726 }
727
728 int KdenliveDoc::getFramePos(QString duration)
729 {
730     return m_timecode.getFrameCount(duration, m_fps);
731 }
732
733 QString KdenliveDoc::producerName(const QString &id)
734 {
735     QString result = "unnamed";
736     QDomNodeList prods = producersList();
737     int ct = prods.count();
738     for (int i = 0; i <  ct ; i++) {
739         QDomElement e = prods.item(i).toElement();
740         if (e.attribute("id") != "black" && e.attribute("id") == id) {
741             result = e.attribute("name");
742             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
743             break;
744         }
745     }
746     return result;
747 }
748
749 QDomDocument KdenliveDoc::toXml()
750 {
751     return m_document;
752 }
753
754 Timecode KdenliveDoc::timecode() const
755 {
756     return m_timecode;
757 }
758
759 QDomNodeList KdenliveDoc::producersList()
760 {
761     return m_document.elementsByTagName("producer");
762 }
763
764 double KdenliveDoc::projectDuration() const
765 {
766     if (m_render)
767         return GenTime(m_render->getLength(), m_fps).ms() / 1000;
768     else
769         return 0;
770 }
771
772 double KdenliveDoc::fps() const
773 {
774     return m_fps;
775 }
776
777 int KdenliveDoc::width() const
778 {
779     return m_width;
780 }
781
782 int KdenliveDoc::height() const
783 {
784     return m_height;
785 }
786
787 KUrl KdenliveDoc::url() const
788 {
789     return m_url;
790 }
791
792 void KdenliveDoc::setUrl(KUrl url)
793 {
794     m_url = url;
795 }
796
797 void KdenliveDoc::setModified(bool mod)
798 {
799     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
800         m_autoSaveTimer->start(3000);
801     }
802     if (mod == m_modified) return;
803     m_modified = mod;
804     emit docModified(m_modified);
805 }
806
807 bool KdenliveDoc::isModified() const
808 {
809     return m_modified;
810 }
811
812 const QString KdenliveDoc::description() const
813 {
814     if (m_url.isEmpty())
815         return i18n("Untitled") + " / " + m_profile.description;
816     else
817         return m_url.fileName() + " / " + m_profile.description;
818 }
819
820 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
821 {
822     const QString producerId = clipId.section('_', 0, 0);
823     DocClipBase *clip = m_clipManager->getClipById(producerId);
824
825     if (clip == NULL) {
826         elem.setAttribute("id", producerId);
827         QString path = elem.attribute("resource");
828         QString extension;
829         if (elem.attribute("type").toInt() == SLIDESHOW) {
830             extension = KUrl(path).fileName();
831             path = KUrl(path).directory();
832         } else if (elem.attribute("type").toInt() == TEXT && QFile::exists(path) == false) {
833             kDebug() << "// TITLE: " << elem.attribute("name") << " Preview file: " << elem.attribute("resource") << " DOES NOT EXIST";
834             QString titlename = elem.attribute("name");
835             QString titleresource;
836             if (titlename.isEmpty()) {
837                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
838                 titlename = titleInfo.at(0);
839                 titleresource = titleInfo.at(1);
840                 elem.setAttribute("name", titlename);
841                 kDebug() << "// New title set to: " << titlename;
842             } else {
843                 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
844                 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
845             }
846             TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
847             QDomDocument doc;
848             doc.setContent(elem.attribute("xmldata"));
849             dia_ui->setXml(doc);
850             QImage pix = dia_ui->renderedPixmap();
851             pix.save(titleresource);
852             elem.setAttribute("resource", titleresource);
853             setNewClipResource(clipId, titleresource);
854             delete dia_ui;
855         }
856
857         if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
858             kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
859             const QString size = elem.attribute("file_size");
860             const QString hash = elem.attribute("file_hash");
861             QString newpath;
862             int action = KMessageBox::No;
863             if (!size.isEmpty() && !hash.isEmpty()) {
864                 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
865                 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")));
866             } else {
867                 if (elem.attribute("type").toInt() == SLIDESHOW) {
868                     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")));
869                     if (res == KMessageBox::Yes)
870                         newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
871                     else {
872                         // Abort project loading
873                         action = res;
874                     }
875                 } else {
876                     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")));
877                     if (res == KMessageBox::Yes)
878                         newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
879                     else {
880                         // Abort project loading
881                         action = res;
882                     }
883                 }
884             }
885             if (action == KMessageBox::Yes) {
886                 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
887                 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
888                 if (!m_searchFolder.isEmpty()) {
889                     newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
890                 }
891             } else if (action == KMessageBox::Cancel) {
892                 m_abortLoading = true;
893                 return;
894             } else if (action == KMessageBox::No) {
895                 // Keep clip as placeHolder
896                 elem.setAttribute("placeholder", '1');
897             }
898             if (!newpath.isEmpty()) {
899                 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
900                 elem.setAttribute("resource", newpath);
901                 setNewClipResource(clipId, newpath);
902                 setModified(true);
903             }
904         }
905         clip = new DocClipBase(m_clipManager, elem, producerId);
906         m_clipManager->addClip(clip);
907     }
908
909     if (createClipItem) {
910         emit addProjectClip(clip);
911         qApp->processEvents();
912         m_render->getFileProperties(clip->toXML(), clip->getId());
913     }
914 }
915
916
917 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
918 {
919     QDomNodeList prods = m_document.elementsByTagName("producer");
920     int maxprod = prods.count();
921     for (int i = 0; i < maxprod; i++) {
922         QDomNode m = prods.at(i);
923         QString prodId = m.toElement().attribute("id");
924         if (prodId == id || prodId.startsWith(id + '_')) {
925             QDomNodeList params = m.childNodes();
926             for (int j = 0; j < params.count(); j++) {
927                 QDomElement e = params.item(j).toElement();
928                 if (e.attribute("name") == "resource") {
929                     e.firstChild().setNodeValue(path);
930                     break;
931                 }
932             }
933         }
934     }
935 }
936
937 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
938 {
939     QString foundFileName;
940     QByteArray fileData;
941     QByteArray fileHash;
942     QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
943     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
944         QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
945         if (file.open(QIODevice::ReadOnly)) {
946             if (QString::number(file.size()) == matchSize) {
947                 /*
948                 * 1 MB = 1 second per 450 files (or faster)
949                 * 10 MB = 9 seconds per 450 files (or faster)
950                 */
951                 if (file.size() > 1000000*2) {
952                     fileData = file.read(1000000);
953                     if (file.seek(file.size() - 1000000))
954                         fileData.append(file.readAll());
955                 } else
956                     fileData = file.readAll();
957                 file.close();
958                 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
959                 if (QString(fileHash.toHex()) == matchHash)
960                     return file.fileName();
961             }
962         }
963         kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
964     }
965     filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
966     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
967         foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
968         if (!foundFileName.isEmpty())
969             break;
970     }
971     return foundFileName;
972 }
973
974 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
975 {
976     DocClipBase *clip = m_clipManager->getClipById(clipId);
977     if (clip == NULL) {
978         addClip(elem, clipId, false);
979     } else {
980         QMap <QString, QString> properties;
981         QDomNamedNodeMap attributes = elem.attributes();
982         QString attrname;
983         for (int i = 0; i < attributes.count(); i++) {
984             attrname = attributes.item(i).nodeName();
985             if (attrname != "resource")
986                 properties.insert(attrname, attributes.item(i).nodeValue());
987             kDebug() << attrname << " = " << attributes.item(i).nodeValue();
988         }
989         clip->setProperties(properties);
990         emit addProjectClip(clip, false);
991     }
992     if (orig != QDomElement()) {
993         QMap<QString, QString> meta;
994         QDomNode m = orig.firstChild();
995         while (!m.isNull()) {
996             QString name = m.toElement().attribute("name");
997             if (name.startsWith("meta.attr")) {
998                 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
999             }
1000             m = m.nextSibling();
1001         }
1002         if (!meta.isEmpty()) {
1003             if (clip == NULL) clip = m_clipManager->getClipById(clipId);
1004             if (clip) clip->setMetadata(meta);
1005         }
1006     }
1007 }
1008
1009 void KdenliveDoc::deleteProjectClip(QList <QString> ids)
1010 {
1011     for (int i = 0; i < ids.size(); ++i) {
1012         emit deleteTimelineClip(ids.at(i));
1013         m_clipManager->slotDeleteClip(ids.at(i));
1014     }
1015     setModified(true);
1016 }
1017
1018 void KdenliveDoc::deleteClip(const QString &clipId)
1019 {
1020     emit signalDeleteProjectClip(clipId);
1021     m_clipManager->deleteClip(clipId);
1022 }
1023
1024 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1025 {
1026     m_clipManager->slotAddClipList(urls, group, groupId);
1027     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1028     setModified(true);
1029 }
1030
1031
1032 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1033 {
1034     //kDebug() << "/////////  DOCUM, ADD CLP: " << url;
1035     m_clipManager->slotAddClipFile(url, group, groupId);
1036     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1037     setModified(true);
1038 }
1039
1040 const QString KdenliveDoc::getFreeClipId()
1041 {
1042     return QString::number(m_clipManager->getFreeClipId());
1043 }
1044
1045 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1046 {
1047     return m_clipManager->getClipById(clipId);
1048 }
1049
1050 void KdenliveDoc::slotCreateTextClip(QString /*group*/, const QString &/*groupId*/)
1051 {
1052     QString titlesFolder = projectFolder().path() + "/titles/";
1053     KStandardDirs::makeDir(titlesFolder);
1054     TitleWidget *dia_ui = new TitleWidget(KUrl(), titlesFolder, m_render, kapp->activeWindow());
1055     if (dia_ui->exec() == QDialog::Accepted) {
1056         QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1057         QImage pix = dia_ui->renderedPixmap();
1058         pix.save(titleInfo.at(1));
1059         //dia_ui->saveTitle(path + ".kdenlivetitle");
1060         m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), QString(), QString());
1061         setModified(true);
1062     }
1063     delete dia_ui;
1064 }
1065
1066 int KdenliveDoc::tracksCount() const
1067 {
1068     return m_tracksList.count();
1069 }
1070
1071 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1072 {
1073     return m_tracksList.at(ix);
1074 }
1075
1076 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1077 {
1078     m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1079 }
1080
1081 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1082 {
1083     m_tracksList[ix].isLocked = lock;
1084 }
1085
1086 bool KdenliveDoc::isTrackLocked(int ix) const
1087 {
1088     return m_tracksList.at(ix).isLocked;
1089 }
1090
1091 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1092 {
1093     m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1094 }
1095
1096 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1097 {
1098     if (ix == -1) m_tracksList << type;
1099     else m_tracksList.insert(ix, type);
1100 }
1101
1102 void KdenliveDoc::deleteTrack(int ix)
1103 {
1104     m_tracksList.removeAt(ix);
1105 }
1106
1107 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1108 {
1109     m_tracksList[ix].type = type.type;
1110     m_tracksList[ix].isMute = type.isMute;
1111     m_tracksList[ix].isBlind = type.isBlind;
1112     m_tracksList[ix].isLocked = type.isLocked;
1113 }
1114
1115 const QList <TrackInfo> KdenliveDoc::tracksList() const
1116 {
1117     return m_tracksList;
1118 }
1119
1120 QPoint KdenliveDoc::getTracksCount() const
1121 {
1122     int audio = 0;
1123     int video = 0;
1124     foreach(const TrackInfo &info, m_tracksList) {
1125         if (info.type == VIDEOTRACK) video++;
1126         else audio++;
1127     }
1128     return QPoint(video, audio);
1129 }
1130
1131 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1132 {
1133     pix.save(m_projectFolder.path() + "/thumbs/" + fileId + ".png");
1134 }
1135
1136 QString KdenliveDoc::getLadspaFile() const
1137 {
1138     int ct = 0;
1139     QString counter = QString::number(ct).rightJustified(5, '0', false);
1140     while (QFile::exists(m_projectFolder.path() + "/ladspa/" + counter + ".ladspa")) {
1141         ct++;
1142         counter = QString::number(ct).rightJustified(5, '0', false);
1143     }
1144     return m_projectFolder.path() + "/ladspa/" + counter + ".ladspa";
1145 }
1146
1147 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1148 {
1149     int clipType;
1150     QDomElement e;
1151     QString id;
1152     QString resource;
1153     QList <QDomElement> missingClips;
1154     for (int i = 0; i < infoproducers.count(); i++) {
1155         e = infoproducers.item(i).toElement();
1156         clipType = e.attribute("type").toInt();
1157         if (clipType == TEXT || clipType == COLOR) continue;
1158         id = e.attribute("id");
1159         resource = e.attribute("resource");
1160         if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1161         if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1162             // Missing clip found
1163             missingClips.append(e);
1164         }
1165     }
1166     if (missingClips.isEmpty()) return true;
1167     DocumentChecker d(missingClips, m_document);
1168     return (d.exec() == QDialog::Accepted);
1169 }
1170
1171
1172 #include "kdenlivedoc.moc"
1173