1 /***************************************************************************
2 * Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org) *
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. *
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. *
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 ***************************************************************************/
21 #include "kdenlivedoc.h"
22 #include "docclipbase.h"
23 #include "profilesdialog.h"
24 #include "kdenlivesettings.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"
34 #include <KStandardDirs>
35 #include <KMessageBox>
37 #include <KFileDialog>
38 #include <KIO/NetAccess>
39 #include <KIO/CopyJob>
40 #include <KApplication>
42 #include <QCryptographicHash>
44 #include <QInputDialog>
46 #include <mlt++/Mlt.h>
48 const double DOCUMENTVERSION = 0.83;
50 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, QString profileName, const QPoint tracks, Render *render, MainWindow *parent) :
56 m_commandStack(new QUndoStack(undoGroup)),
58 m_projectFolder(projectFolder),
59 m_documentLoadingStep(0.0),
60 m_documentLoadingProgress(0),
63 m_clipManager = new ClipManager(this);
64 m_autoSaveTimer = new QTimer(this);
65 m_autoSaveTimer->setSingleShot(true);
68 // init default document properties
69 m_documentProperties["zoom"] = "7";
70 m_documentProperties["zonein"] = "0";
71 m_documentProperties["zoneout"] = "100";
75 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
76 if (!success) // The file cannot be opened
77 KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
81 success = m_document.setContent(&file, false, &errorMsg);
83 KIO::NetAccess::removeTempFile(tmpFile);
84 if (!success) // It is corrupted
85 KMessageBox::error(parent, errorMsg);
87 DocumentValidator validator(m_document);
88 success = validator.isProject();
89 if (!success) // It is not a project file
90 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file.", m_url.path()), 100);
93 * Validate the file against the current version (upgrade
94 * and recover it if needed). It is NOT a passive operation
96 // TODO: backup the document or alert the user?
97 success = validator.validate(DOCUMENTVERSION);
98 if (success) { // Let the validator handle error messages
99 setModified(validator.isModified());
100 QDomElement mlt = m_document.firstChildElement("mlt");
101 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
103 profileName = infoXml.attribute("profile");
104 m_projectFolder = infoXml.attribute("projectfolder");
105 m_startPos = infoXml.attribute("position").toInt();
107 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
108 QDomNamedNodeMap props = docproperties.attributes();
109 for (int i = 0; i < props.count(); i++) {
110 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
115 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
116 TrackInfo projectTrack;
117 if (!tracksinfo.isNull()) {
118 QDomNodeList trackslist = tracksinfo.childNodes();
119 int maxchild = trackslist.count();
120 for (int k = 0; k < maxchild; k++) {
121 e = trackslist.at(k).toElement();
122 if (e.tagName() == "trackinfo") {
123 if (e.attribute("type") == "audio") projectTrack.type = AUDIOTRACK;
124 else projectTrack.type = VIDEOTRACK;
125 projectTrack.isMute = e.attribute("mute").toInt();
126 projectTrack.isBlind = e.attribute("blind").toInt();
127 projectTrack.isLocked = e.attribute("locked").toInt();
128 m_tracksList.append(projectTrack);
131 mlt.removeChild(tracksinfo);
133 QDomNodeList producers = m_document.elementsByTagName("producer");
134 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
135 if (checkDocumentClips(infoproducers) == false) m_abortLoading = true;
136 const int max = producers.count();
137 const int infomax = infoproducers.count();
139 QDomNodeList folders = m_document.elementsByTagName("folder");
140 for (int i = 0; i < folders.count(); i++) {
141 e = folders.item(i).cloneNode().toElement();
142 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
146 m_documentLoadingStep = 100.0 / (max + infomax + m_document.elementsByTagName("entry").count());
147 parent->slotGotProgressInfo(i18n("Loading project clips"), (int) m_documentLoadingProgress);
151 for (int i = 0; i < infomax && !m_abortLoading; i++) {
152 e = infoproducers.item(i).cloneNode().toElement();
153 if (m_documentLoadingStep > 0) {
154 m_documentLoadingProgress += m_documentLoadingStep;
155 parent->slotGotProgressInfo(QString(), (int) m_documentLoadingProgress);
156 //qApp->processEvents();
158 QString prodId = e.attribute("id");
159 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion") && !m_abortLoading) {
160 e.setTagName("producer");
161 // Get MLT's original producer properties
163 for (int j = 0; j < max; j++) {
164 QDomElement o = producers.item(j).cloneNode().toElement();
165 QString origId = o.attribute("id").section('_', 0, 0);
166 if (origId == prodId) {
171 addClipInfo(e, orig, prodId);
172 kDebug() << "// KDENLIVE PRODUCER: " << prodId;
175 if (m_abortLoading) {
176 //parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
177 emit resetProjectList();
180 m_tracksList.clear();
181 kWarning() << "Aborted loading of: " << url.path();
182 m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
183 setProfilePath(KdenliveSettings::default_profile());
184 m_clipManager->clear();
186 QDomElement markers = infoXml.firstChildElement("markers");
187 if (!markers.isNull()) {
188 QDomNodeList markerslist = markers.childNodes();
189 int maxchild = markerslist.count();
190 for (int k = 0; k < maxchild; k++) {
191 e = markerslist.at(k).toElement();
192 if (e.tagName() == "marker") {
193 m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
196 infoXml.removeChild(markers);
198 setProfilePath(profileName);
199 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
205 } else setProfilePath(profileName);
207 // Something went wrong, or a new file was requested: create a new project
210 m_document = createEmptyDocument(tracks.x(), tracks.y());
213 // Set the video profile (empty == default)
215 // Make sure the project folder is usable
216 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
217 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
218 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
221 // Make sure that the necessary folders exist
222 KStandardDirs::makeDir(m_projectFolder.path() + "/titles/");
223 KStandardDirs::makeDir(m_projectFolder.path() + "/thumbs/");
224 KStandardDirs::makeDir(m_projectFolder.path() + "/ladspa/");
226 kDebug() << "Kdenlive document, init timecode: " << m_fps;
227 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
228 else m_timecode.setFormat((int) m_fps);
230 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
231 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
234 KdenliveDoc::~KdenliveDoc()
236 delete m_commandStack;
237 delete m_clipManager;
238 delete m_autoSaveTimer;
240 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
245 void KdenliveDoc::setSceneList()
247 m_render->setSceneList(m_document.toString(), m_startPos);
248 // m_document xml is now useless, clear it
253 QDomDocument KdenliveDoc::createEmptyDocument(const int videotracks, const int audiotracks)
255 // Creating new document
257 QDomElement mlt = doc.createElement("mlt");
258 doc.appendChild(mlt);
261 TrackInfo videoTrack;
262 videoTrack.type = VIDEOTRACK;
263 videoTrack.isMute = false;
264 videoTrack.isBlind = false;
265 videoTrack.isLocked = false;
267 TrackInfo audioTrack;
268 audioTrack.type = AUDIOTRACK;
269 audioTrack.isMute = false;
270 audioTrack.isBlind = true;
271 audioTrack.isLocked = false;
273 QDomElement tractor = doc.createElement("tractor");
274 tractor.setAttribute("id", "maintractor");
275 QDomElement multitrack = doc.createElement("multitrack");
276 QDomElement playlist = doc.createElement("playlist");
277 playlist.setAttribute("id", "black_track");
278 mlt.appendChild(playlist);
282 int total = audiotracks + videotracks + 1;
284 for (int i = 1; i < total; i++) {
285 QDomElement playlist = doc.createElement("playlist");
286 playlist.setAttribute("id", "playlist" + QString::number(i));
287 mlt.appendChild(playlist);
290 QDomElement track0 = doc.createElement("track");
291 track0.setAttribute("producer", "black_track");
292 tractor.appendChild(track0);
294 // create audio tracks
295 for (int i = 1; i < audiotracks + 1; i++) {
296 QDomElement track = doc.createElement("track");
297 track.setAttribute("producer", "playlist" + QString::number(i));
298 track.setAttribute("hide", "video");
299 tractor.appendChild(track);
300 m_tracksList.append(audioTrack);
303 // create video tracks
304 for (int i = audiotracks + 1; i < total; i++) {
305 QDomElement track = doc.createElement("track");
306 track.setAttribute("producer", "playlist" + QString::number(i));
307 tractor.appendChild(track);
308 m_tracksList.append(videoTrack);
311 for (int i = 2; i < total ; i++) {
312 QDomElement transition = doc.createElement("transition");
313 transition.setAttribute("always_active", "1");
315 QDomElement property = doc.createElement("property");
316 property.setAttribute("name", "a_track");
317 QDomText value = doc.createTextNode(QString::number(1));
318 property.appendChild(value);
319 transition.appendChild(property);
321 property = doc.createElement("property");
322 property.setAttribute("name", "b_track");
323 value = doc.createTextNode(QString::number(i));
324 property.appendChild(value);
325 transition.appendChild(property);
327 property = doc.createElement("property");
328 property.setAttribute("name", "mlt_service");
329 value = doc.createTextNode("mix");
330 property.appendChild(value);
331 transition.appendChild(property);
333 property = doc.createElement("property");
334 property.setAttribute("name", "combine");
335 value = doc.createTextNode("1");
336 property.appendChild(value);
337 transition.appendChild(property);
339 property = doc.createElement("property");
340 property.setAttribute("name", "internal_added");
341 value = doc.createTextNode("237");
342 property.appendChild(value);
343 transition.appendChild(property);
344 tractor.appendChild(transition);
346 mlt.appendChild(tractor);
351 void KdenliveDoc::syncGuides(QList <Guide *> guides)
354 QDomElement guideNode = m_guidesXml.createElement("guides");
355 m_guidesXml.appendChild(guideNode);
358 for (int i = 0; i < guides.count(); i++) {
359 e = m_guidesXml.createElement("guide");
360 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
361 e.setAttribute("comment", guides.at(i)->label());
362 guideNode.appendChild(e);
365 emit guidesUpdated();
368 QDomElement KdenliveDoc::guidesXml() const
370 return m_guidesXml.documentElement();
373 void KdenliveDoc::slotAutoSave()
375 if (m_render && m_autosave) {
376 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
377 // show error: could not open the autosave file
378 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
380 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
382 if (KdenliveSettings::dropbframes()) {
383 KdenliveSettings::setDropbframes(false);
384 m_clipManager->updatePreviewSettings();
385 doc = m_render->sceneList();
386 KdenliveSettings::setDropbframes(true);
387 m_clipManager->updatePreviewSettings();
388 } else doc = m_render->sceneList();
389 saveSceneList(m_autosave->fileName(), doc);
393 void KdenliveDoc::setZoom(int factor)
395 m_documentProperties["zoom"] = QString::number(factor);
398 int KdenliveDoc::zoom() const
400 return m_documentProperties.value("zoom").toInt();
403 void KdenliveDoc::setZone(int start, int end)
405 m_documentProperties["zonein"] = QString::number(start);
406 m_documentProperties["zoneout"] = QString::number(end);
409 QPoint KdenliveDoc::zone() const
411 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
414 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene)
416 QDomDocument sceneList;
417 sceneList.setContent(scene, true);
418 QDomElement mlt = sceneList.firstChildElement("mlt");
419 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
420 mlt.appendChild(addedXml);
422 QDomElement markers = sceneList.createElement("markers");
423 addedXml.setAttribute("version", DOCUMENTVERSION);
424 addedXml.setAttribute("kdenliveversion", VERSION);
425 addedXml.setAttribute("profile", profilePath());
426 addedXml.setAttribute("position", m_render->seekPosition().frames(m_fps));
427 addedXml.setAttribute("projectfolder", m_projectFolder.path());
429 QDomElement docproperties = sceneList.createElement("documentproperties");
430 QMapIterator<QString, QString> i(m_documentProperties);
431 while (i.hasNext()) {
433 docproperties.setAttribute(i.key(), i.value());
435 addedXml.appendChild(docproperties);
438 QDomElement profileinfo = sceneList.createElement("profileinfo");
439 profileinfo.setAttribute("description", m_profile.description);
440 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
441 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
442 profileinfo.setAttribute("width", m_profile.width);
443 profileinfo.setAttribute("height", m_profile.height);
444 profileinfo.setAttribute("progressive", m_profile.progressive);
445 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
446 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
447 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
448 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
449 addedXml.appendChild(profileinfo);
452 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
453 foreach(const TrackInfo &info, m_tracksList) {
454 QDomElement trackinfo = sceneList.createElement("trackinfo");
455 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
456 trackinfo.setAttribute("mute", info.isMute);
457 trackinfo.setAttribute("blind", info.isBlind);
458 trackinfo.setAttribute("locked", info.isLocked);
459 tracksinfo.appendChild(trackinfo);
461 addedXml.appendChild(tracksinfo);
463 // save project folders
464 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
466 QMapIterator<QString, QString> f(folderlist);
467 while (f.hasNext()) {
469 QDomElement folder = sceneList.createElement("folder");
470 folder.setAttribute("id", f.key());
471 folder.setAttribute("name", f.value());
472 addedXml.appendChild(folder);
475 // Save project clips
477 QList <DocClipBase*> list = m_clipManager->documentClipList();
478 for (int i = 0; i < list.count(); i++) {
479 e = list.at(i)->toXML();
480 e.setTagName("kdenlive_producer");
481 addedXml.appendChild(sceneList.importNode(e, true));
482 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
483 for (int j = 0; j < marks.count(); j++) {
484 QDomElement marker = sceneList.createElement("marker");
485 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
486 marker.setAttribute("comment", marks.at(j).comment());
487 marker.setAttribute("id", e.attribute("id"));
488 markers.appendChild(marker);
491 addedXml.appendChild(markers);
494 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
497 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
499 //wes.appendChild(doc.importNode(kdenliveData, true));
502 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
503 kWarning() << "////// ERROR writing to file: " << path;
504 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
508 file.write(sceneList.toString().toUtf8());
509 if (file.error() != QFile::NoError) {
510 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
518 ClipManager *KdenliveDoc::clipManager()
520 return m_clipManager;
523 KUrl KdenliveDoc::projectFolder() const
525 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
526 return m_projectFolder;
529 void KdenliveDoc::setProjectFolder(KUrl url)
531 if (url == m_projectFolder) return;
533 KStandardDirs::makeDir(url.path());
534 KStandardDirs::makeDir(url.path() + "/titles/");
535 KStandardDirs::makeDir(url.path() + "/thumbs/");
536 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);
537 m_projectFolder = url;
540 void KdenliveDoc::moveProjectData(KUrl url)
542 QList <DocClipBase*> list = m_clipManager->documentClipList();
543 //TODO: Also move ladspa effects files
544 for (int i = 0; i < list.count(); i++) {
545 DocClipBase *clip = list.at(i);
546 if (clip->clipType() == TEXT) {
547 // the image for title clip must be moved
548 KUrl oldUrl = clip->fileURL();
549 KUrl newUrl = KUrl(url.path() + "/titles/" + oldUrl.fileName());
550 KIO::Job *job = KIO::copy(oldUrl, newUrl);
551 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
553 QString hash = clip->getClipHash();
554 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path() + "/thumbs/" + hash + ".png");
555 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path() + "/thumbs/" + hash + ".thumb");
556 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
557 KUrl newUrl = KUrl(url.path() + "/thumbs/" + hash + ".png");
558 KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
559 KIO::NetAccess::synchronousRun(job, 0);
561 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
562 KUrl newUrl = KUrl(url.path() + "/thumbs/" + hash + ".thumb");
563 KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
564 if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
569 const QString &KdenliveDoc::profilePath() const
571 return m_profile.path;
574 MltVideoProfile KdenliveDoc::mltProfile() const
579 void KdenliveDoc::setProfilePath(QString path)
581 if (path.isEmpty()) path = KdenliveSettings::default_profile();
582 if (path.isEmpty()) path = "dv_pal";
583 m_profile = ProfilesDialog::getVideoProfile(path);
584 if (m_profile.path.isEmpty()) {
585 // Profile not found, use embedded profile
586 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
587 if (profileInfo.isNull()) {
588 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
589 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
591 m_profile.description = profileInfo.attribute("description");
592 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
593 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
594 m_profile.width = profileInfo.attribute("width").toInt();
595 m_profile.height = profileInfo.attribute("height").toInt();
596 m_profile.progressive = profileInfo.attribute("progressive").toInt();
597 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
598 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
599 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
600 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
601 QString existing = ProfilesDialog::existingProfile(m_profile);
602 if (!existing.isEmpty()) {
603 m_profile = ProfilesDialog::getVideoProfile(existing);
604 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
606 QString newDesc = m_profile.description;
608 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
609 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);
612 // User canceled, use default profile
613 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
615 if (newDesc != m_profile.description) {
616 // Profile description existed, was replaced by new one
617 m_profile.description = newDesc;
619 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
621 ProfilesDialog::saveProfile(m_profile);
628 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
629 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
630 KdenliveSettings::setProject_fps(m_fps);
631 m_width = m_profile.width;
632 m_height = m_profile.height;
633 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
634 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
635 else m_timecode.setFormat((int) m_fps);
638 double KdenliveDoc::dar()
640 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
643 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
645 emit progressInfo(message, progress);
648 void KdenliveDoc::loadingProgressed()
650 m_documentLoadingProgress += m_documentLoadingStep;
651 emit progressInfo(QString(), (int) m_documentLoadingProgress);
654 QUndoStack *KdenliveDoc::commandStack()
656 return m_commandStack;
660 void KdenliveDoc::setRenderer(Render *render) {
661 if (m_render) return;
663 emit progressInfo(i18n("Loading playlist..."), 0);
664 //qApp->processEvents();
666 m_render->setSceneList(m_document.toString(), m_startPos);
667 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
670 emit progressInfo(QString(), -1);
673 void KdenliveDoc::checkProjectClips()
675 kDebug() << "+++++++++++++ + + + + CHK PCLIPS";
676 if (m_render == NULL) return;
677 m_clipManager->resetProducersList(m_render->producersList());
681 QList <Mlt::Producer *> prods = m_render->producersList();
685 for (int i = 0; i < prods.count(); i++) {
686 id = prods.at(i)->get("id");
687 prodId = id.section('_', 0, 0);
688 prodTrack = id.section('_', 1, 1);
689 DocClipBase *clip = m_clipManager->getClipById(prodId);
690 if (clip) clip->setProducer(prods.at(i));
691 if (clip && clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
692 // regenerate text clip image if required
693 //kDebug() << "// TITLE: " << clip->getProperty("titlename") << " Preview file: " << clip->getProperty("resource") << " DOES NOT EXIST";
694 QString titlename = clip->getProperty("name");
695 QString titleresource;
696 if (titlename.isEmpty()) {
697 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
698 titlename = titleInfo.at(0);
699 titleresource = titleInfo.at(1);
700 clip->setProperty("name", titlename);
701 kDebug() << "// New title set to: " << titlename;
703 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
704 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
706 TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
708 doc.setContent(clip->getProperty("xmldata"));
710 QImage pix = dia_ui->renderedPixmap();
711 pix.save(titleresource);
712 clip->setProperty("resource", titleresource);
714 clip->producer()->set("force_reload", 1);
719 void KdenliveDoc::updatePreviewSettings()
721 m_clipManager->updatePreviewSettings();
722 m_render->updatePreviewSettings();
723 m_clipManager->resetProducersList(m_render->producersList());
727 Render *KdenliveDoc::renderer()
732 void KdenliveDoc::updateClip(const QString &id)
734 emit updateClipDisplay(id);
737 int KdenliveDoc::getFramePos(QString duration)
739 return m_timecode.getFrameCount(duration, m_fps);
742 QString KdenliveDoc::producerName(const QString &id)
744 QString result = "unnamed";
745 QDomNodeList prods = producersList();
746 int ct = prods.count();
747 for (int i = 0; i < ct ; i++) {
748 QDomElement e = prods.item(i).toElement();
749 if (e.attribute("id") != "black" && e.attribute("id") == id) {
750 result = e.attribute("name");
751 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
758 QDomDocument KdenliveDoc::toXml()
763 Timecode KdenliveDoc::timecode() const
768 QDomNodeList KdenliveDoc::producersList()
770 return m_document.elementsByTagName("producer");
773 double KdenliveDoc::projectDuration() const
776 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
781 double KdenliveDoc::fps() const
786 int KdenliveDoc::width() const
791 int KdenliveDoc::height() const
796 KUrl KdenliveDoc::url() const
801 void KdenliveDoc::setUrl(KUrl url)
806 void KdenliveDoc::setModified(bool mod)
808 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
809 m_autoSaveTimer->start(3000);
811 if (mod == m_modified) return;
813 emit docModified(m_modified);
816 bool KdenliveDoc::isModified() const
821 const QString KdenliveDoc::description() const
824 return i18n("Untitled") + " / " + m_profile.description;
826 return m_url.fileName() + " / " + m_profile.description;
829 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
831 const QString producerId = clipId.section('_', 0, 0);
832 DocClipBase *clip = m_clipManager->getClipById(producerId);
835 elem.setAttribute("id", producerId);
836 QString path = elem.attribute("resource");
838 if (elem.attribute("type").toInt() == SLIDESHOW) {
839 extension = KUrl(path).fileName();
840 path = KUrl(path).directory();
841 } else if (elem.attribute("type").toInt() == TEXT && QFile::exists(path) == false) {
842 kDebug() << "// TITLE: " << elem.attribute("name") << " Preview file: " << elem.attribute("resource") << " DOES NOT EXIST";
843 QString titlename = elem.attribute("name");
844 QString titleresource;
845 if (titlename.isEmpty()) {
846 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
847 titlename = titleInfo.at(0);
848 titleresource = titleInfo.at(1);
849 elem.setAttribute("name", titlename);
850 kDebug() << "// New title set to: " << titlename;
852 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
853 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
855 TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
857 doc.setContent(elem.attribute("xmldata"));
859 QImage pix = dia_ui->renderedPixmap();
860 pix.save(titleresource);
861 elem.setAttribute("resource", titleresource);
862 setNewClipResource(clipId, titleresource);
866 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
867 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
868 const QString size = elem.attribute("file_size");
869 const QString hash = elem.attribute("file_hash");
871 int action = KMessageBox::No;
872 if (!size.isEmpty() && !hash.isEmpty()) {
873 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
874 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")));
876 if (elem.attribute("type").toInt() == SLIDESHOW) {
877 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")));
878 if (res == KMessageBox::Yes)
879 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
881 // Abort project loading
885 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")));
886 if (res == KMessageBox::Yes)
887 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
889 // Abort project loading
894 if (action == KMessageBox::Yes) {
895 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
896 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
897 if (!m_searchFolder.isEmpty()) {
898 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
900 } else if (action == KMessageBox::Cancel) {
901 m_abortLoading = true;
903 } else if (action == KMessageBox::No) {
904 // Keep clip as placeHolder
905 elem.setAttribute("placeholder", '1');
907 if (!newpath.isEmpty()) {
908 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
909 elem.setAttribute("resource", newpath);
910 setNewClipResource(clipId, newpath);
914 clip = new DocClipBase(m_clipManager, elem, producerId);
915 m_clipManager->addClip(clip);
918 if (createClipItem) {
919 emit addProjectClip(clip);
920 qApp->processEvents();
921 m_render->getFileProperties(clip->toXML(), clip->getId());
926 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
928 QDomNodeList prods = m_document.elementsByTagName("producer");
929 int maxprod = prods.count();
930 for (int i = 0; i < maxprod; i++) {
931 QDomNode m = prods.at(i);
932 QString prodId = m.toElement().attribute("id");
933 if (prodId == id || prodId.startsWith(id + '_')) {
934 QDomNodeList params = m.childNodes();
935 for (int j = 0; j < params.count(); j++) {
936 QDomElement e = params.item(j).toElement();
937 if (e.attribute("name") == "resource") {
938 e.firstChild().setNodeValue(path);
946 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
948 QString foundFileName;
951 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
952 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
953 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
954 if (file.open(QIODevice::ReadOnly)) {
955 if (QString::number(file.size()) == matchSize) {
957 * 1 MB = 1 second per 450 files (or faster)
958 * 10 MB = 9 seconds per 450 files (or faster)
960 if (file.size() > 1000000*2) {
961 fileData = file.read(1000000);
962 if (file.seek(file.size() - 1000000))
963 fileData.append(file.readAll());
965 fileData = file.readAll();
967 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
968 if (QString(fileHash.toHex()) == matchHash)
969 return file.fileName();
972 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
974 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
975 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
976 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
977 if (!foundFileName.isEmpty())
980 return foundFileName;
983 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
985 DocClipBase *clip = m_clipManager->getClipById(clipId);
987 addClip(elem, clipId, false);
989 QMap <QString, QString> properties;
990 QDomNamedNodeMap attributes = elem.attributes();
992 for (int i = 0; i < attributes.count(); i++) {
993 attrname = attributes.item(i).nodeName();
994 if (attrname != "resource")
995 properties.insert(attrname, attributes.item(i).nodeValue());
996 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
998 clip->setProperties(properties);
999 emit addProjectClip(clip, false);
1001 if (orig != QDomElement()) {
1002 QMap<QString, QString> meta;
1003 QDomNode m = orig.firstChild();
1004 while (!m.isNull()) {
1005 QString name = m.toElement().attribute("name");
1006 if (name.startsWith("meta.attr")) {
1007 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1009 m = m.nextSibling();
1011 if (!meta.isEmpty()) {
1012 if (clip == NULL) clip = m_clipManager->getClipById(clipId);
1013 if (clip) clip->setMetadata(meta);
1018 void KdenliveDoc::deleteProjectClip(QList <QString> ids)
1020 for (int i = 0; i < ids.size(); ++i) {
1021 emit deleteTimelineClip(ids.at(i));
1022 m_clipManager->slotDeleteClip(ids.at(i));
1027 void KdenliveDoc::deleteClip(const QString &clipId)
1029 emit signalDeleteProjectClip(clipId);
1030 m_clipManager->deleteClip(clipId);
1033 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1035 m_clipManager->slotAddClipList(urls, group, groupId);
1036 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1041 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1043 //kDebug() << "///////// DOCUM, ADD CLP: " << url;
1044 m_clipManager->slotAddClipFile(url, group, groupId);
1045 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1049 const QString KdenliveDoc::getFreeClipId()
1051 return QString::number(m_clipManager->getFreeClipId());
1054 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1056 return m_clipManager->getClipById(clipId);
1059 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1061 QString titlesFolder = projectFolder().path() + "/titles/";
1062 KStandardDirs::makeDir(titlesFolder);
1063 TitleWidget *dia_ui = new TitleWidget(templatePath, titlesFolder, m_render, kapp->activeWindow());
1064 if (dia_ui->exec() == QDialog::Accepted) {
1065 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1066 QImage pix = dia_ui->renderedPixmap();
1067 pix.save(titleInfo.at(1));
1068 //dia_ui->saveTitle(path + ".kdenlivetitle");
1069 m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), group, groupId);
1075 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1077 QString titlesFolder = projectFolder().path() + "/titles/";
1078 if (path.isEmpty()) {
1079 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "*.kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1082 if (path.isEmpty()) return;
1084 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1086 TitleWidget *dia_ui = new TitleWidget(path, titlesFolder, m_render, kapp->activeWindow());
1087 QImage pix = dia_ui->renderedPixmap();
1088 pix.save(titleInfo.at(1));
1090 m_clipManager->slotAddTextTemplateClip(titleInfo.at(0), titleInfo.at(1), path, group, groupId);
1094 int KdenliveDoc::tracksCount() const
1096 return m_tracksList.count();
1099 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1101 return m_tracksList.at(ix);
1104 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1106 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1109 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1111 m_tracksList[ix].isLocked = lock;
1114 bool KdenliveDoc::isTrackLocked(int ix) const
1116 return m_tracksList.at(ix).isLocked;
1119 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1121 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1124 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1126 if (ix == -1) m_tracksList << type;
1127 else m_tracksList.insert(ix, type);
1130 void KdenliveDoc::deleteTrack(int ix)
1132 m_tracksList.removeAt(ix);
1135 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1137 m_tracksList[ix].type = type.type;
1138 m_tracksList[ix].isMute = type.isMute;
1139 m_tracksList[ix].isBlind = type.isBlind;
1140 m_tracksList[ix].isLocked = type.isLocked;
1143 const QList <TrackInfo> KdenliveDoc::tracksList() const
1145 return m_tracksList;
1148 QPoint KdenliveDoc::getTracksCount() const
1152 foreach(const TrackInfo &info, m_tracksList) {
1153 if (info.type == VIDEOTRACK) video++;
1156 return QPoint(video, audio);
1159 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1161 pix.save(m_projectFolder.path() + "/thumbs/" + fileId + ".png");
1164 QString KdenliveDoc::getLadspaFile() const
1167 QString counter = QString::number(ct).rightJustified(5, '0', false);
1168 while (QFile::exists(m_projectFolder.path() + "/ladspa/" + counter + ".ladspa")) {
1170 counter = QString::number(ct).rightJustified(5, '0', false);
1172 return m_projectFolder.path() + "/ladspa/" + counter + ".ladspa";
1175 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1181 QList <QDomElement> missingClips;
1182 for (int i = 0; i < infoproducers.count(); i++) {
1183 e = infoproducers.item(i).toElement();
1184 clipType = e.attribute("type").toInt();
1185 if (clipType == TEXT || clipType == COLOR) continue;
1186 id = e.attribute("id");
1187 resource = e.attribute("resource");
1188 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1189 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1190 // Missing clip found
1191 missingClips.append(e);
1194 if (missingClips.isEmpty()) return true;
1195 DocumentChecker d(missingClips, m_document);
1196 return (d.exec() == QDialog::Accepted);
1199 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1201 m_documentProperties[name] = value;
1204 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1206 return m_documentProperties.value(name);
1209 #include "kdenlivedoc.moc"