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 "documentconvert.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>
45 #include <mlt++/Mlt.h>
47 const double DOCUMENTVERSION = 0.83;
49 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, const 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),
61 m_abortLoading(false),
65 m_clipManager = new ClipManager(this);
66 m_autoSaveTimer = new QTimer(this);
67 m_autoSaveTimer->setSingleShot(true);
70 bool success = KIO::NetAccess::download(url.path(), tmpFile, parent);
74 success = m_document.setContent(&file, false, &errorMsg);
76 if (success == false) {
77 // File is corrupted, warn user
78 KMessageBox::error(parent, errorMsg);
80 } else KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
83 QDomNode infoXmlNode = m_document.elementsByTagName("kdenlivedoc").at(0);
84 if (!infoXmlNode.isNull()) {
85 QDomElement infoXml = infoXmlNode.toElement();
86 double version = infoXml.attribute("version").toDouble();
88 // Upgrade old Kdenlive documents to current version
89 DocumentConvert converter(m_document);
90 if (!converter.doConvert(version, DOCUMENTVERSION)) {
92 m_document = createEmptyDocument(tracks.x(), tracks.y());
93 setProfilePath(profileName);
96 * read again <kdenlivedoc> and <mlt> to get all the new
97 * stuff (convertDocument() can now do anything without breaking
100 setModified(converter.isModified());
101 infoXmlNode = m_document.elementsByTagName("kdenlivedoc").at(0);
102 infoXml = infoXmlNode.toElement();
103 version = infoXml.attribute("version").toDouble();
104 QDomNode mlt = m_document.elementsByTagName("mlt").at(0);
106 QString profilePath = infoXml.attribute("profile");
107 QString projectFolderPath = infoXml.attribute("projectfolder");
108 if (!projectFolderPath.isEmpty()) m_projectFolder = KUrl(projectFolderPath);
110 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
111 // Make sure the project folder is usable
112 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
113 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
115 m_startPos = infoXml.attribute("position").toInt();
116 m_zoom = infoXml.attribute("zoom", "7").toInt();
117 m_zoneStart = infoXml.attribute("zonein", "0").toInt();
118 m_zoneEnd = infoXml.attribute("zoneout", "100").toInt();
119 setProfilePath(profilePath);
123 QDomNode tracksinfo = m_document.elementsByTagName("tracksinfo").at(0);
124 TrackInfo projectTrack;
125 if (!tracksinfo.isNull()) {
126 QDomNodeList trackslist = tracksinfo.childNodes();
127 int maxchild = trackslist.count();
128 for (int k = 0; k < maxchild; k++) {
129 e = trackslist.at(k).toElement();
130 if (e.tagName() == "trackinfo") {
131 if (e.attribute("type") == "audio") projectTrack.type = AUDIOTRACK;
132 else projectTrack.type = VIDEOTRACK;
133 projectTrack.isMute = e.attribute("mute").toInt();
134 projectTrack.isBlind = e.attribute("blind").toInt();
135 projectTrack.isLocked = e.attribute("locked").toInt();
136 m_tracksList.append(projectTrack);
139 mlt.removeChild(tracksinfo);
141 QDomNodeList producers = m_document.elementsByTagName("producer");
142 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
143 if (checkDocumentClips(producers, infoproducers) == false) m_abortLoading = true;
144 const int max = producers.count();
145 const int infomax = infoproducers.count();
147 QDomNodeList folders = m_document.elementsByTagName("folder");
148 for (int i = 0; i < folders.count(); i++) {
149 e = folders.item(i).cloneNode().toElement();
150 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
154 m_documentLoadingStep = 100.0 / (max + infomax + m_document.elementsByTagName("entry").count());
155 parent->slotGotProgressInfo(i18n("Loading project clips"), (int) m_documentLoadingProgress);
159 for (int i = 0; i < infomax && !m_abortLoading; i++) {
160 e = infoproducers.item(i).cloneNode().toElement();
161 if (m_documentLoadingStep > 0) {
162 m_documentLoadingProgress += m_documentLoadingStep;
163 parent->slotGotProgressInfo(QString(), (int) m_documentLoadingProgress);
164 //qApp->processEvents();
166 QString prodId = e.attribute("id");
167 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion") && !m_abortLoading) {
168 e.setTagName("producer");
169 // Get MLT's original producer properties
171 for (int j = 0; j < max; j++) {
172 QDomElement o = producers.item(j).cloneNode().toElement();
173 QString origId = o.attribute("id").section('_', 0, 0);
174 if (origId == prodId) {
179 addClipInfo(e, orig, prodId);
180 kDebug() << "// NLIVE PROD: " << prodId;
183 if (m_abortLoading) {
184 //parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
185 emit resetProjectList();
188 m_tracksList.clear();
189 kWarning() << "Aborted loading of: " << url.path();
190 m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
191 setProfilePath(KdenliveSettings::default_profile());
192 m_clipManager->clear();
194 QDomNode markers = m_document.elementsByTagName("markers").at(0);
195 if (!markers.isNull()) {
196 QDomNodeList markerslist = markers.childNodes();
197 int maxchild = markerslist.count();
198 for (int k = 0; k < maxchild; k++) {
199 e = markerslist.at(k).toElement();
200 if (e.tagName() == "marker") {
201 m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
204 mlt.removeChild(markers);
206 m_document.removeChild(infoXmlNode);
207 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
211 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
212 kWarning() << " NO KDENLIVE INFO FOUND IN FILE: " << url.path();
213 m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
215 setProfilePath(KdenliveSettings::default_profile());
217 KIO::NetAccess::removeTempFile(tmpFile);
219 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
221 m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
222 setProfilePath(KdenliveSettings::default_profile());
225 m_document = createEmptyDocument(tracks.x(), tracks.y());
226 setProfilePath(profileName);
228 if (m_projectFolder.isEmpty()) m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
230 // make sure that the necessary folders exist
231 KStandardDirs::makeDir(m_projectFolder.path() + "/titles/");
232 KStandardDirs::makeDir(m_projectFolder.path() + "/thumbs/");
233 KStandardDirs::makeDir(m_projectFolder.path() + "/ladspa/");
235 kDebug() << "KDEnlive document, init timecode: " << m_fps;
236 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
237 else m_timecode.setFormat((int) m_fps);
239 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
240 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
244 KdenliveDoc::~KdenliveDoc()
246 delete m_commandStack;
247 delete m_clipManager;
248 delete m_autoSaveTimer;
250 m_autosave->remove();
255 void KdenliveDoc::setSceneList()
257 m_render->setSceneList(m_document.toString(), m_startPos);
258 // m_document xml is now useless, clear it
263 QDomDocument KdenliveDoc::createEmptyDocument(const int videotracks, const int audiotracks)
265 // Creating new document
267 QDomElement mlt = doc.createElement("mlt");
268 doc.appendChild(mlt);
271 TrackInfo videoTrack;
272 videoTrack.type = VIDEOTRACK;
273 videoTrack.isMute = false;
274 videoTrack.isBlind = false;
275 videoTrack.isLocked = false;
277 TrackInfo audioTrack;
278 audioTrack.type = AUDIOTRACK;
279 audioTrack.isMute = false;
280 audioTrack.isBlind = true;
281 audioTrack.isLocked = false;
283 QDomElement tractor = doc.createElement("tractor");
284 tractor.setAttribute("id", "maintractor");
285 QDomElement multitrack = doc.createElement("multitrack");
286 QDomElement playlist = doc.createElement("playlist");
287 playlist.setAttribute("id", "black_track");
288 mlt.appendChild(playlist);
292 int total = audiotracks + videotracks + 1;
294 for (int i = 1; i < total; i++) {
295 QDomElement playlist = doc.createElement("playlist");
296 playlist.setAttribute("id", "playlist" + QString::number(i));
297 mlt.appendChild(playlist);
300 QDomElement track0 = doc.createElement("track");
301 track0.setAttribute("producer", "black_track");
302 tractor.appendChild(track0);
304 // create audio tracks
305 for (int i = 1; i < audiotracks + 1; i++) {
306 QDomElement track = doc.createElement("track");
307 track.setAttribute("producer", "playlist" + QString::number(i));
308 track.setAttribute("hide", "video");
309 tractor.appendChild(track);
310 m_tracksList.append(audioTrack);
313 // create video tracks
314 for (int i = audiotracks + 1; i < total; i++) {
315 QDomElement track = doc.createElement("track");
316 track.setAttribute("producer", "playlist" + QString::number(i));
317 tractor.appendChild(track);
318 m_tracksList.append(videoTrack);
321 for (int i = 2; i < total ; i++) {
322 QDomElement transition = doc.createElement("transition");
323 transition.setAttribute("always_active", "1");
325 QDomElement property = doc.createElement("property");
326 property.setAttribute("name", "a_track");
327 QDomText value = doc.createTextNode(QString::number(1));
328 property.appendChild(value);
329 transition.appendChild(property);
331 property = doc.createElement("property");
332 property.setAttribute("name", "b_track");
333 value = doc.createTextNode(QString::number(i));
334 property.appendChild(value);
335 transition.appendChild(property);
337 property = doc.createElement("property");
338 property.setAttribute("name", "mlt_service");
339 value = doc.createTextNode("mix");
340 property.appendChild(value);
341 transition.appendChild(property);
343 property = doc.createElement("property");
344 property.setAttribute("name", "combine");
345 value = doc.createTextNode("1");
346 property.appendChild(value);
347 transition.appendChild(property);
349 property = doc.createElement("property");
350 property.setAttribute("name", "internal_added");
351 value = doc.createTextNode("237");
352 property.appendChild(value);
353 transition.appendChild(property);
354 tractor.appendChild(transition);
356 mlt.appendChild(tractor);
361 void KdenliveDoc::syncGuides(QList <Guide *> guides)
364 QDomElement guideNode = m_guidesXml.createElement("guides");
365 m_guidesXml.appendChild(guideNode);
368 for (int i = 0; i < guides.count(); i++) {
369 e = m_guidesXml.createElement("guide");
370 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
371 e.setAttribute("comment", guides.at(i)->label());
372 guideNode.appendChild(e);
374 emit guidesUpdated();
377 QDomElement KdenliveDoc::guidesXml() const
379 return m_guidesXml.documentElement();
382 void KdenliveDoc::slotAutoSave()
384 if (m_render && m_autosave) {
385 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
386 // show error: could not open the autosave file
387 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
389 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
391 if (KdenliveSettings::dropbframes()) {
392 KdenliveSettings::setDropbframes(false);
393 m_clipManager->updatePreviewSettings();
394 doc = m_render->sceneList();
395 KdenliveSettings::setDropbframes(true);
396 m_clipManager->updatePreviewSettings();
397 } else doc = m_render->sceneList();
398 saveSceneList(m_autosave->fileName(), doc);
402 void KdenliveDoc::setZoom(int factor)
407 int KdenliveDoc::zoom() const
412 void KdenliveDoc::setZone(int start, int end)
418 QPoint KdenliveDoc::zone() const
420 return QPoint(m_zoneStart, m_zoneEnd);
423 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene)
425 QDomDocument sceneList;
426 sceneList.setContent(scene, true);
427 QDomNode mlt = sceneList.elementsByTagName("mlt").at(0);
428 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
429 mlt.appendChild(addedXml);
431 QDomElement markers = sceneList.createElement("markers");
432 addedXml.setAttribute("version", "0.82");
433 addedXml.setAttribute("kdenliveversion", VERSION);
434 addedXml.setAttribute("profile", profilePath());
435 addedXml.setAttribute("position", m_render->seekPosition().frames(m_fps));
436 addedXml.setAttribute("zonein", m_zoneStart);
437 addedXml.setAttribute("zoneout", m_zoneEnd);
438 addedXml.setAttribute("projectfolder", m_projectFolder.path());
439 addedXml.setAttribute("zoom", m_zoom);
442 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
443 foreach(const TrackInfo &info, m_tracksList) {
444 QDomElement trackinfo = sceneList.createElement("trackinfo");
445 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
446 trackinfo.setAttribute("mute", info.isMute);
447 trackinfo.setAttribute("blind", info.isBlind);
448 trackinfo.setAttribute("locked", info.isLocked);
449 tracksinfo.appendChild(trackinfo);
451 addedXml.appendChild(tracksinfo);
453 // save project folders
454 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
456 QMapIterator<QString, QString> f(folderlist);
457 while (f.hasNext()) {
459 QDomElement folder = sceneList.createElement("folder");
460 folder.setAttribute("id", f.key());
461 folder.setAttribute("name", f.value());
462 addedXml.appendChild(folder);
465 // Save project clips
467 QList <DocClipBase*> list = m_clipManager->documentClipList();
468 for (int i = 0; i < list.count(); i++) {
469 e = list.at(i)->toXML();
470 e.setTagName("kdenlive_producer");
471 addedXml.appendChild(sceneList.importNode(e, true));
472 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
473 for (int j = 0; j < marks.count(); j++) {
474 QDomElement marker = sceneList.createElement("marker");
475 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
476 marker.setAttribute("comment", marks.at(j).comment());
477 marker.setAttribute("id", e.attribute("id"));
478 markers.appendChild(marker);
481 addedXml.appendChild(markers);
484 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
487 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
489 //wes.appendChild(doc.importNode(kdenliveData, true));
492 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
493 kWarning() << "////// ERROR writing to file: " << path;
494 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
498 file.write(sceneList.toString().toUtf8());
499 if (file.error() != QFile::NoError) {
500 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
508 ClipManager *KdenliveDoc::clipManager()
510 return m_clipManager;
513 KUrl KdenliveDoc::projectFolder() const
515 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
516 return m_projectFolder;
519 void KdenliveDoc::setProjectFolder(KUrl url)
521 if (url == m_projectFolder) return;
523 KStandardDirs::makeDir(url.path());
524 KStandardDirs::makeDir(url.path() + "/titles/");
525 KStandardDirs::makeDir(url.path() + "/thumbs/");
526 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);
527 m_projectFolder = url;
530 void KdenliveDoc::moveProjectData(KUrl url)
532 QList <DocClipBase*> list = m_clipManager->documentClipList();
533 //TODO: Also move ladspa effects files
534 for (int i = 0; i < list.count(); i++) {
535 DocClipBase *clip = list.at(i);
536 if (clip->clipType() == TEXT) {
537 // the image for title clip must be moved
538 KUrl oldUrl = clip->fileURL();
539 KUrl newUrl = KUrl(url.path() + "/titles/" + oldUrl.fileName());
540 KIO::Job *job = KIO::copy(oldUrl, newUrl);
541 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
543 QString hash = clip->getClipHash();
544 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path() + "/thumbs/" + hash + ".png");
545 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path() + "/thumbs/" + hash + ".thumb");
546 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
547 KUrl newUrl = KUrl(url.path() + "/thumbs/" + hash + ".png");
548 KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
549 KIO::NetAccess::synchronousRun(job, 0);
551 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
552 KUrl newUrl = KUrl(url.path() + "/thumbs/" + hash + ".thumb");
553 KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
554 if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
559 const QString &KdenliveDoc::profilePath() const
561 return m_profile.path;
564 MltVideoProfile KdenliveDoc::mltProfile() const
569 void KdenliveDoc::setProfilePath(QString path)
571 if (path.isEmpty()) path = KdenliveSettings::default_profile();
572 if (path.isEmpty()) path = "dv_pal";
573 m_profile = ProfilesDialog::getVideoProfile(path);
574 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
575 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
576 KdenliveSettings::setProject_fps(m_fps);
577 m_width = m_profile.width;
578 m_height = m_profile.height;
579 kDebug() << "KDEnnlive document, init timecode from path: " << path << ", " << m_fps;
580 if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
581 else m_timecode.setFormat((int) m_fps);
584 double KdenliveDoc::dar()
586 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
589 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
591 emit progressInfo(message, progress);
594 void KdenliveDoc::loadingProgressed()
596 m_documentLoadingProgress += m_documentLoadingStep;
597 emit progressInfo(QString(), (int) m_documentLoadingProgress);
600 QUndoStack *KdenliveDoc::commandStack()
602 return m_commandStack;
606 void KdenliveDoc::setRenderer(Render *render) {
607 if (m_render) return;
609 emit progressInfo(i18n("Loading playlist..."), 0);
610 //qApp->processEvents();
612 m_render->setSceneList(m_document.toString(), m_startPos);
613 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
616 emit progressInfo(QString(), -1);
619 void KdenliveDoc::checkProjectClips()
621 kDebug() << "+++++++++++++ + + + + CHK PCLIPS";
622 if (m_render == NULL) return;
623 m_clipManager->resetProducersList(m_render->producersList());
627 QList <Mlt::Producer *> prods = m_render->producersList();
631 for (int i = 0; i < prods.count(); i++) {
632 id = prods.at(i)->get("id");
633 prodId = id.section('_', 0, 0);
634 prodTrack = id.section('_', 1, 1);
635 DocClipBase *clip = m_clipManager->getClipById(prodId);
636 if (clip) clip->setProducer(prods.at(i));
637 if (clip && clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
638 // regenerate text clip image if required
639 //kDebug() << "// TITLE: " << clip->getProperty("titlename") << " Preview file: " << clip->getProperty("resource") << " DOES NOT EXIST";
640 QString titlename = clip->getProperty("name");
641 QString titleresource;
642 if (titlename.isEmpty()) {
643 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
644 titlename = titleInfo.at(0);
645 titleresource = titleInfo.at(1);
646 clip->setProperty("name", titlename);
647 kDebug() << "// New title set to: " << titlename;
649 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
650 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
652 TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
654 doc.setContent(clip->getProperty("xmldata"));
656 QImage pix = dia_ui->renderedPixmap();
657 pix.save(titleresource);
658 clip->setProperty("resource", titleresource);
660 clip->producer()->set("force_reload", 1);
665 void KdenliveDoc::updatePreviewSettings()
667 m_clipManager->updatePreviewSettings();
668 m_render->updatePreviewSettings();
669 m_clipManager->resetProducersList(m_render->producersList());
673 Render *KdenliveDoc::renderer()
678 void KdenliveDoc::updateClip(const QString &id)
680 emit updateClipDisplay(id);
683 int KdenliveDoc::getFramePos(QString duration)
685 return m_timecode.getFrameCount(duration, m_fps);
688 QString KdenliveDoc::producerName(const QString &id)
690 QString result = "unnamed";
691 QDomNodeList prods = producersList();
692 int ct = prods.count();
693 for (int i = 0; i < ct ; i++) {
694 QDomElement e = prods.item(i).toElement();
695 if (e.attribute("id") != "black" && e.attribute("id") == id) {
696 result = e.attribute("name");
697 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
704 QDomDocument KdenliveDoc::toXml()
709 Timecode KdenliveDoc::timecode() const
714 QDomNodeList KdenliveDoc::producersList()
716 return m_document.elementsByTagName("producer");
719 double KdenliveDoc::projectDuration() const
722 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
727 double KdenliveDoc::fps() const
732 int KdenliveDoc::width() const
737 int KdenliveDoc::height() const
742 KUrl KdenliveDoc::url() const
747 void KdenliveDoc::setUrl(KUrl url)
752 void KdenliveDoc::setModified(bool mod)
754 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
755 m_autoSaveTimer->start(3000);
757 if (mod == m_modified) return;
759 emit docModified(m_modified);
762 bool KdenliveDoc::isModified() const
767 const QString KdenliveDoc::description() const
770 return i18n("Untitled") + " / " + m_profile.description;
772 return m_url.fileName() + " / " + m_profile.description;
775 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
777 const QString producerId = clipId.section('_', 0, 0);
778 DocClipBase *clip = m_clipManager->getClipById(producerId);
781 elem.setAttribute("id", producerId);
782 QString path = elem.attribute("resource");
784 if (elem.attribute("type").toInt() == SLIDESHOW) {
785 extension = KUrl(path).fileName();
786 path = KUrl(path).directory();
787 } else if (elem.attribute("type").toInt() == TEXT && QFile::exists(path) == false) {
788 kDebug() << "// TITLE: " << elem.attribute("name") << " Preview file: " << elem.attribute("resource") << " DOES NOT EXIST";
789 QString titlename = elem.attribute("name");
790 QString titleresource;
791 if (titlename.isEmpty()) {
792 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
793 titlename = titleInfo.at(0);
794 titleresource = titleInfo.at(1);
795 elem.setAttribute("name", titlename);
796 kDebug() << "// New title set to: " << titlename;
798 titleresource = TitleWidget::getFreeTitleInfo(projectFolder()).at(1);
799 //titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
801 TitleWidget *dia_ui = new TitleWidget(KUrl(), KUrl(titleresource).directory(), m_render, kapp->activeWindow());
803 doc.setContent(elem.attribute("xmldata"));
805 QImage pix = dia_ui->renderedPixmap();
806 pix.save(titleresource);
807 elem.setAttribute("resource", titleresource);
808 setNewClipResource(clipId, titleresource);
812 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
813 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
814 const QString size = elem.attribute("file_size");
815 const QString hash = elem.attribute("file_hash");
817 int action = KMessageBox::No;
818 if (!size.isEmpty() && !hash.isEmpty()) {
819 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
820 else action = (KMessageBox::ButtonCode) KMessageBox::questionYesNoCancel(kapp->activeWindow(), i18n("Clip <b>%1</b><br>is invalid, what do you want to do?", path), i18n("File not found"), KGuiItem(i18n("Search automatically")), KGuiItem(i18n("Keep as placeholder")));
822 if (elem.attribute("type").toInt() == SLIDESHOW) {
823 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")));
824 if (res == KMessageBox::Yes)
825 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
827 // Abort project loading
831 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")));
832 if (res == KMessageBox::Yes)
833 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
835 // Abort project loading
840 if (action == KMessageBox::Yes) {
841 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
842 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
843 if (!m_searchFolder.isEmpty()) {
844 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
846 } else if (action == KMessageBox::Cancel) {
847 m_abortLoading = true;
849 } else if (action == KMessageBox::No) {
850 // Keep clip as placeHolder
851 elem.setAttribute("placeholder", '1');
853 if (!newpath.isEmpty()) {
854 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
855 elem.setAttribute("resource", newpath);
856 setNewClipResource(clipId, newpath);
860 clip = new DocClipBase(m_clipManager, elem, producerId);
861 m_clipManager->addClip(clip);
864 if (createClipItem) {
865 emit addProjectClip(clip);
866 qApp->processEvents();
867 m_render->getFileProperties(clip->toXML(), clip->getId());
872 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
874 QDomNodeList prods = m_document.elementsByTagName("producer");
875 int maxprod = prods.count();
876 for (int i = 0; i < maxprod; i++) {
877 QDomNode m = prods.at(i);
878 QString prodId = m.toElement().attribute("id");
879 if (prodId == id || prodId.startsWith(id + '_')) {
880 QDomNodeList params = m.childNodes();
881 for (int j = 0; j < params.count(); j++) {
882 QDomElement e = params.item(j).toElement();
883 if (e.attribute("name") == "resource") {
884 e.firstChild().setNodeValue(path);
892 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
894 QString foundFileName;
897 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
898 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
899 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
900 if (file.open(QIODevice::ReadOnly)) {
901 if (QString::number(file.size()) == matchSize) {
903 * 1 MB = 1 second per 450 files (or faster)
904 * 10 MB = 9 seconds per 450 files (or faster)
906 if (file.size() > 1000000*2) {
907 fileData = file.read(1000000);
908 if (file.seek(file.size() - 1000000))
909 fileData.append(file.readAll());
911 fileData = file.readAll();
913 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
914 if (QString(fileHash.toHex()) == matchHash)
915 return file.fileName();
918 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
920 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
921 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
922 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
923 if (!foundFileName.isEmpty())
926 return foundFileName;
929 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
931 DocClipBase *clip = m_clipManager->getClipById(clipId);
933 addClip(elem, clipId, false);
935 QMap <QString, QString> properties;
936 QDomNamedNodeMap attributes = elem.attributes();
938 for (int i = 0; i < attributes.count(); i++) {
939 attrname = attributes.item(i).nodeName();
940 if (attrname != "resource")
941 properties.insert(attrname, attributes.item(i).nodeValue());
942 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
944 clip->setProperties(properties);
945 emit addProjectClip(clip, false);
947 if (orig != QDomElement()) {
948 QMap<QString, QString> meta;
949 QDomNode m = orig.firstChild();
950 while (!m.isNull()) {
951 QString name = m.toElement().attribute("name");
952 if (name.startsWith("meta.attr")) {
953 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
957 if (!meta.isEmpty()) {
958 if (clip == NULL) clip = m_clipManager->getClipById(clipId);
959 if (clip) clip->setMetadata(meta);
964 void KdenliveDoc::deleteProjectClip(QList <QString> ids)
966 for (int i = 0; i < ids.size(); ++i) {
967 emit deleteTimelineClip(ids.at(i));
968 m_clipManager->slotDeleteClip(ids.at(i));
973 void KdenliveDoc::deleteClip(const QString &clipId)
975 emit signalDeleteProjectClip(clipId);
976 m_clipManager->deleteClip(clipId);
979 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
981 m_clipManager->slotAddClipList(urls, group, groupId);
982 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
987 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
989 //kDebug() << "///////// DOCUM, ADD CLP: " << url;
990 m_clipManager->slotAddClipFile(url, group, groupId);
991 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
995 const QString KdenliveDoc::getFreeClipId()
997 return QString::number(m_clipManager->getFreeClipId());
1000 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1002 return m_clipManager->getClipById(clipId);
1005 void KdenliveDoc::slotCreateTextClip(QString /*group*/, const QString &/*groupId*/)
1007 QString titlesFolder = projectFolder().path() + "/titles/";
1008 KStandardDirs::makeDir(titlesFolder);
1009 TitleWidget *dia_ui = new TitleWidget(KUrl(), titlesFolder, m_render, kapp->activeWindow());
1010 if (dia_ui->exec() == QDialog::Accepted) {
1011 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1012 QImage pix = dia_ui->renderedPixmap();
1013 pix.save(titleInfo.at(1));
1014 //dia_ui->saveTitle(path + ".kdenlivetitle");
1015 m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), QString(), QString());
1021 int KdenliveDoc::tracksCount() const
1023 return m_tracksList.count();
1026 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1028 return m_tracksList.at(ix);
1031 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1033 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1036 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1038 m_tracksList[ix].isLocked = lock;
1041 bool KdenliveDoc::isTrackLocked(int ix) const
1043 return m_tracksList.at(ix).isLocked;
1046 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1048 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1051 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1053 if (ix == -1) m_tracksList << type;
1054 else m_tracksList.insert(ix, type);
1057 void KdenliveDoc::deleteTrack(int ix)
1059 m_tracksList.removeAt(ix);
1062 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1064 m_tracksList[ix].type = type.type;
1065 m_tracksList[ix].isMute = type.isMute;
1066 m_tracksList[ix].isBlind = type.isBlind;
1067 m_tracksList[ix].isLocked = type.isLocked;
1070 const QList <TrackInfo> KdenliveDoc::tracksList() const
1072 return m_tracksList;
1075 QPoint KdenliveDoc::getTracksCount() const
1079 foreach(const TrackInfo &info, m_tracksList) {
1080 if (info.type == VIDEOTRACK) video++;
1083 return QPoint(video, audio);
1086 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1088 pix.save(m_projectFolder.path() + "/thumbs/" + fileId + ".png");
1091 QString KdenliveDoc::getLadspaFile() const
1094 QString counter = QString::number(ct).rightJustified(5, '0', false);
1095 while (QFile::exists(m_projectFolder.path() + "/ladspa/" + counter + ".ladspa")) {
1097 counter = QString::number(ct).rightJustified(5, '0', false);
1099 return m_projectFolder.path() + "/ladspa/" + counter + ".ladspa";
1102 bool KdenliveDoc::checkDocumentClips(QDomNodeList producers, QDomNodeList infoproducers)
1108 QList <QDomElement> missingClips;
1109 for (int i = 0; i < infoproducers.count(); i++) {
1110 e = infoproducers.item(i).toElement();
1111 clipType = e.attribute("type").toInt();
1112 if (clipType == TEXT || clipType == COLOR) continue;
1113 id = e.attribute("id");
1114 resource = e.attribute("resource");
1115 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1116 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1117 // Missing clip found
1118 missingClips.append(e);
1121 if (missingClips.isEmpty()) return true;
1122 DocumentChecker d(producers, infoproducers, missingClips, m_document);
1123 return (d.exec() == QDialog::Accepted);
1127 #include "kdenlivedoc.moc"