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"
32 #include "initeffects.h"
35 #include <KStandardDirs>
36 #include <KMessageBox>
37 #include <KProgressDialog>
39 #include <KFileDialog>
40 #include <KIO/NetAccess>
41 #include <KIO/CopyJob>
42 #include <KIO/JobUiDelegate>
43 #include <KApplication>
45 #include <KBookmarkManager>
47 #include <KStandardDirs>
49 #include <QCryptographicHash>
51 #include <QInputDialog>
52 #include <QDomImplementation>
54 #include <mlt++/Mlt.h>
59 const double DOCUMENTVERSION = 0.88;
61 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, QString profileName, QMap <QString, QString> properties, const QPoint tracks, Render *render, KTextEdit *notes, bool *openBackup, MainWindow *parent, KProgressDialog *progressDialog) :
67 m_commandStack(new QUndoStack(undoGroup)),
69 m_projectFolder(projectFolder)
71 m_clipManager = new ClipManager(this);
72 m_autoSaveTimer = new QTimer(this);
73 m_autoSaveTimer->setSingleShot(true);
76 // init default document properties
77 m_documentProperties["zoom"] = "7";
78 m_documentProperties["verticalzoom"] = "1";
79 m_documentProperties["zonein"] = "0";
80 m_documentProperties["zoneout"] = "100";
81 m_documentProperties["enableproxy"] = QString::number((int) KdenliveSettings::enableproxy());
82 m_documentProperties["proxyparams"] = KdenliveSettings::proxyparams();
83 m_documentProperties["proxyextension"] = KdenliveSettings::proxyextension();
84 m_documentProperties["generateproxy"] = QString::number((int) KdenliveSettings::generateproxy());
85 m_documentProperties["proxyminsize"] = QString::number(KdenliveSettings::proxyminsize());
86 m_documentProperties["generateimageproxy"] = QString::number((int) KdenliveSettings::generateimageproxy());
87 m_documentProperties["proxyimageminsize"] = QString::number(KdenliveSettings::proxyimageminsize());
88 #if QT_VERSION >= 0x040700
89 m_documentProperties["documentid"] = QString::number(QDateTime::currentMSecsSinceEpoch());
91 QDateTime date = QDateTime::currentDateTime();
92 m_documentProperties["documentid"] = QString::number(date.toTime_t());
96 QMapIterator<QString, QString> i(properties);
99 m_documentProperties[i.key()] = i.value();
102 if (QLocale() != QLocale::system()) {
103 setlocale(LC_NUMERIC, "");
104 QLocale::setDefault(QLocale::system());
105 // locale conversion might need to be redone
106 initEffects::parseEffectFiles();
111 if (!url.isEmpty()) {
113 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
115 // The file cannot be opened
116 if (KMessageBox::warningContinueCancel(parent, i18n("Cannot open the project file, error is:\n%1\nDo you want to open a backup file?", KIO::NetAccess::lastErrorString()), i18n("Error opening file"), KGuiItem(i18n("Open Backup"))) == KMessageBox::Continue) {
119 //KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
124 QDomImplementation impl;
125 impl.setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
126 success = m_document.setContent(&file, false, &errorMsg);
128 KIO::NetAccess::removeTempFile(tmpFile);
132 if (KMessageBox::warningContinueCancel(parent, i18n("Cannot open the project file, error is:\n%1\nDo you want to open a backup file?", errorMsg), i18n("Error opening file"), KGuiItem(i18n("Open Backup"))) == KMessageBox::Continue) {
135 //KMessageBox::error(parent, errorMsg);
138 parent->slotGotProgressInfo(i18n("Validating"), 0);
139 qApp->processEvents();
140 DocumentValidator validator(m_document);
141 success = validator.isProject();
143 // It is not a project file
144 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
145 if (KMessageBox::warningContinueCancel(parent, i18n("File %1 is not a valid project file.\nDo you want to open a backup file?", m_url.path()), i18n("Error opening file"), KGuiItem(i18n("Open Backup"))) == KMessageBox::Continue) {
150 * Validate the file against the current version (upgrade
151 * and recover it if needed). It is NOT a passive operation
153 // TODO: backup the document or alert the user?
154 success = validator.validate(DOCUMENTVERSION);
155 if (success) { // Let the validator handle error messages
156 parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
157 qApp->processEvents();
158 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
159 success = checkDocumentClips(infoproducers);
161 if (m_document.documentElement().attribute("modified") == "1") setModified(true);
162 parent->slotGotProgressInfo(i18n("Loading"), 0);
163 QDomElement mlt = m_document.firstChildElement("mlt");
164 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
166 // Set profile, fps, etc for the document
167 setProfilePath(infoXml.attribute("profile"));
169 // Check embedded effects
170 QDomElement customeffects = infoXml.firstChildElement("customeffects");
171 if (!customeffects.isNull() && customeffects.hasChildNodes()) {
172 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
173 qApp->processEvents();
174 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
179 QDomElement notesxml = infoXml.firstChildElement("documentnotes");
180 if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
183 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
184 if (!tracksinfo.isNull()) {
185 QDomNodeList trackslist = tracksinfo.childNodes();
186 int maxchild = trackslist.count();
187 for (int k = 0; k < maxchild; k++) {
188 e = trackslist.at(k).toElement();
189 if (e.tagName() == "trackinfo") {
190 TrackInfo projectTrack;
191 if (e.attribute("type") == "audio")
192 projectTrack.type = AUDIOTRACK;
194 projectTrack.type = VIDEOTRACK;
195 projectTrack.isMute = e.attribute("mute").toInt();
196 projectTrack.isBlind = e.attribute("blind").toInt();
197 projectTrack.isLocked = e.attribute("locked").toInt();
198 projectTrack.trackName = e.attribute("trackname");
199 m_tracksList.append(projectTrack);
202 mlt.removeChild(tracksinfo);
204 QStringList expandedFolders;
205 QDomNodeList folders = m_document.elementsByTagName("folder");
206 for (int i = 0; i < folders.count(); i++) {
207 e = folders.item(i).cloneNode().toElement();
208 if (e.hasAttribute("opened")) expandedFolders.append(e.attribute("id"));
209 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
211 m_documentProperties["expandedfolders"] = expandedFolders.join(";");
213 const int infomax = infoproducers.count();
214 QDomNodeList producers = m_document.elementsByTagName("producer");
215 const int max = producers.count();
217 if (!progressDialog) {
218 progressDialog = new KProgressDialog(parent, i18n("Loading project"), i18n("Adding clips"));
219 progressDialog->setAllowCancel(false);
221 progressDialog->setLabelText(i18n("Adding clips"));
223 progressDialog->progressBar()->setMaximum(infomax);
224 progressDialog->show();
225 qApp->processEvents();
227 for (int i = 0; i < infomax; i++) {
228 e = infoproducers.item(i).cloneNode().toElement();
229 QString prodId = e.attribute("id");
230 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
231 e.setTagName("producer");
232 // Get MLT's original producer properties
234 for (int j = 0; j < max; j++) {
235 QDomNode o = producers.item(j);
236 QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
237 if (origId == prodId) {
238 orig = o.cloneNode().toElement();
243 if (!addClipInfo(e, orig, prodId)) {
244 // The user manually aborted the loading.
246 emit resetProjectList();
247 m_tracksList.clear();
248 m_clipManager->clear();
253 progressDialog->progressBar()->setValue(i);
257 QDomElement markers = infoXml.firstChildElement("markers");
258 if (!markers.isNull()) {
259 QDomNodeList markerslist = markers.childNodes();
260 int maxchild = markerslist.count();
261 for (int k = 0; k < maxchild; k++) {
262 e = markerslist.at(k).toElement();
263 if (e.tagName() == "marker")
264 m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
266 infoXml.removeChild(markers);
269 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
270 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
271 QDomNamedNodeMap props = docproperties.attributes();
272 for (int i = 0; i < props.count(); i++)
273 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
275 if (validator.isModified()) setModified(true);
276 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
285 // Something went wrong, or a new file was requested: create a new project
288 setProfilePath(profileName);
289 m_document = createEmptyDocument(tracks.x(), tracks.y());
292 // Ask to create the project directory if it does not exist
293 if (!QFile::exists(m_projectFolder.path())) {
294 int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
295 if (create == KMessageBox::Yes) {
296 QDir projectDir(m_projectFolder.path());
297 bool ok = projectDir.mkpath(m_projectFolder.path());
299 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
304 // Make sure the project folder is usable
305 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
306 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
307 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
310 // Make sure that the necessary folders exist
311 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
312 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
313 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/");
315 updateProjectFolderPlacesEntry();
317 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
318 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
321 KdenliveDoc::~KdenliveDoc()
323 m_autoSaveTimer->stop();
324 delete m_commandStack;
325 kDebug() << "// DEL CLP MAN";
326 delete m_clipManager;
327 kDebug() << "// DEL CLP MAN done";
328 delete m_autoSaveTimer;
330 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
335 int KdenliveDoc::setSceneList()
337 m_render->resetProfile(KdenliveSettings::current_profile(), true);
338 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
339 // INVALID MLT Consumer, something is wrong
342 m_documentProperties.remove("position");
343 // m_document xml is now useless, clear it
348 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
350 m_tracksList.clear();
352 // Tracks are added «backwards», so we need to reverse the track numbering
353 // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
354 // Better default names for tracks: Audio 1 etc. instead of blank numbers
355 for (int i = 0; i < audiotracks; i++) {
356 TrackInfo audioTrack;
357 audioTrack.type = AUDIOTRACK;
358 audioTrack.isMute = false;
359 audioTrack.isBlind = true;
360 audioTrack.isLocked = false;
361 audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
362 audioTrack.duration = 0;
363 m_tracksList.append(audioTrack);
366 for (int i = 0; i < videotracks; i++) {
367 TrackInfo videoTrack;
368 videoTrack.type = VIDEOTRACK;
369 videoTrack.isMute = false;
370 videoTrack.isBlind = false;
371 videoTrack.isLocked = false;
372 videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
373 videoTrack.duration = 0;
374 m_tracksList.append(videoTrack);
376 return createEmptyDocument(m_tracksList);
379 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
381 // Creating new document
383 QDomElement mlt = doc.createElement("mlt");
384 mlt.setAttribute("LC_NUMERIC", "");
385 doc.appendChild(mlt);
387 // Create black producer
388 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
389 // the composite transitions with the black track are corrupted.
390 QDomElement blk = doc.createElement("producer");
391 blk.setAttribute("in", 0);
392 blk.setAttribute("out", 500);
393 blk.setAttribute("id", "black");
395 QDomElement property = doc.createElement("property");
396 property.setAttribute("name", "mlt_type");
397 QDomText value = doc.createTextNode("producer");
398 property.appendChild(value);
399 blk.appendChild(property);
401 property = doc.createElement("property");
402 property.setAttribute("name", "aspect_ratio");
403 value = doc.createTextNode(QString::number(0));
404 property.appendChild(value);
405 blk.appendChild(property);
407 property = doc.createElement("property");
408 property.setAttribute("name", "length");
409 value = doc.createTextNode(QString::number(15000));
410 property.appendChild(value);
411 blk.appendChild(property);
413 property = doc.createElement("property");
414 property.setAttribute("name", "eof");
415 value = doc.createTextNode("pause");
416 property.appendChild(value);
417 blk.appendChild(property);
419 property = doc.createElement("property");
420 property.setAttribute("name", "resource");
421 value = doc.createTextNode("black");
422 property.appendChild(value);
423 blk.appendChild(property);
425 property = doc.createElement("property");
426 property.setAttribute("name", "mlt_service");
427 value = doc.createTextNode("colour");
428 property.appendChild(value);
429 blk.appendChild(property);
431 mlt.appendChild(blk);
434 QDomElement tractor = doc.createElement("tractor");
435 tractor.setAttribute("id", "maintractor");
436 QDomElement multitrack = doc.createElement("multitrack");
437 QDomElement playlist = doc.createElement("playlist");
438 playlist.setAttribute("id", "black_track");
439 mlt.appendChild(playlist);
441 QDomElement blank0 = doc.createElement("entry");
442 blank0.setAttribute("in", "0");
443 blank0.setAttribute("out", "1");
444 blank0.setAttribute("producer", "black");
445 playlist.appendChild(blank0);
448 int total = tracks.count() + 1;
450 for (int i = 1; i < total; i++) {
451 QDomElement playlist = doc.createElement("playlist");
452 playlist.setAttribute("id", "playlist" + QString::number(i));
453 mlt.appendChild(playlist);
456 QDomElement track0 = doc.createElement("track");
457 track0.setAttribute("producer", "black_track");
458 tractor.appendChild(track0);
460 // create audio and video tracks
461 for (int i = 1; i < total; i++) {
462 QDomElement track = doc.createElement("track");
463 track.setAttribute("producer", "playlist" + QString::number(i));
464 if (tracks.at(i - 1).type == AUDIOTRACK) {
465 track.setAttribute("hide", "video");
466 } else if (tracks.at(i - 1).isBlind)
467 track.setAttribute("hide", "video");
468 if (tracks.at(i - 1).isMute)
469 track.setAttribute("hide", "audio");
470 tractor.appendChild(track);
473 for (int i = 2; i < total ; i++) {
474 QDomElement transition = doc.createElement("transition");
475 transition.setAttribute("always_active", "1");
477 QDomElement property = doc.createElement("property");
478 property.setAttribute("name", "a_track");
479 QDomText value = doc.createTextNode(QString::number(1));
480 property.appendChild(value);
481 transition.appendChild(property);
483 property = doc.createElement("property");
484 property.setAttribute("name", "b_track");
485 value = doc.createTextNode(QString::number(i));
486 property.appendChild(value);
487 transition.appendChild(property);
489 property = doc.createElement("property");
490 property.setAttribute("name", "mlt_service");
491 value = doc.createTextNode("mix");
492 property.appendChild(value);
493 transition.appendChild(property);
495 property = doc.createElement("property");
496 property.setAttribute("name", "combine");
497 value = doc.createTextNode("1");
498 property.appendChild(value);
499 transition.appendChild(property);
501 property = doc.createElement("property");
502 property.setAttribute("name", "internal_added");
503 value = doc.createTextNode("237");
504 property.appendChild(value);
505 transition.appendChild(property);
506 tractor.appendChild(transition);
508 mlt.appendChild(tractor);
513 void KdenliveDoc::syncGuides(QList <Guide *> guides)
516 QDomElement guideNode = m_guidesXml.createElement("guides");
517 m_guidesXml.appendChild(guideNode);
520 for (int i = 0; i < guides.count(); i++) {
521 e = m_guidesXml.createElement("guide");
522 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
523 e.setAttribute("comment", guides.at(i)->label());
524 guideNode.appendChild(e);
527 emit guidesUpdated();
530 QDomElement KdenliveDoc::guidesXml() const
532 return m_guidesXml.documentElement();
535 void KdenliveDoc::slotAutoSave()
537 if (m_render && m_autosave) {
538 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
539 // show error: could not open the autosave file
540 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
542 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
543 saveSceneList(m_autosave->fileName(), m_render->sceneList(), QStringList(), true);
547 void KdenliveDoc::setZoom(int horizontal, int vertical)
549 m_documentProperties["zoom"] = QString::number(horizontal);
550 m_documentProperties["verticalzoom"] = QString::number(vertical);
553 QPoint KdenliveDoc::zoom() const
555 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
558 void KdenliveDoc::setZone(int start, int end)
560 m_documentProperties["zonein"] = QString::number(start);
561 m_documentProperties["zoneout"] = QString::number(end);
564 QPoint KdenliveDoc::zone() const
566 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
569 QDomDocument KdenliveDoc::xmlSceneList(const QString &scene, const QStringList expandedFolders)
571 QDomDocument sceneList;
572 sceneList.setContent(scene, true);
573 QDomElement mlt = sceneList.firstChildElement("mlt");
574 if (mlt.isNull() || !mlt.hasChildNodes()) {
575 //scenelist is corrupted
579 // Set playlist audio volume to 100%
580 QDomElement tractor = mlt.firstChildElement("tractor");
581 if (!tractor.isNull()) {
582 QDomNodeList props = tractor.elementsByTagName("property");
583 for (int i = 0; i < props.count(); i++) {
584 if (props.at(i).toElement().attribute("name") == "meta.volume") {
585 props.at(i).firstChild().setNodeValue("1");
591 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
592 mlt.appendChild(addedXml);
594 // check if project contains custom effects to embed them in project file
595 QDomNodeList effects = mlt.elementsByTagName("filter");
596 int maxEffects = effects.count();
597 kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
598 QMap <QString, QString> effectIds;
599 for (int i = 0; i < maxEffects; i++) {
600 QDomNode m = effects.at(i);
601 QDomNodeList params = m.childNodes();
604 for (int j = 0; j < params.count(); j++) {
605 QDomElement e = params.item(j).toElement();
606 if (e.attribute("name") == "kdenlive_id") {
607 id = e.firstChild().nodeValue();
609 if (e.attribute("name") == "tag") {
610 tag = e.firstChild().nodeValue();
612 if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
615 QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
616 addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
618 QDomElement markers = sceneList.createElement("markers");
619 addedXml.setAttribute("version", DOCUMENTVERSION);
620 addedXml.setAttribute("kdenliveversion", VERSION);
621 addedXml.setAttribute("profile", profilePath());
622 addedXml.setAttribute("projectfolder", m_projectFolder.path());
624 QDomElement docproperties = sceneList.createElement("documentproperties");
625 QMapIterator<QString, QString> i(m_documentProperties);
626 while (i.hasNext()) {
628 docproperties.setAttribute(i.key(), i.value());
630 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
631 addedXml.appendChild(docproperties);
633 QDomElement docnotes = sceneList.createElement("documentnotes");
634 QDomText value = sceneList.createTextNode(m_notesWidget->toHtml());
635 docnotes.appendChild(value);
636 addedXml.appendChild(docnotes);
639 QDomElement profileinfo = sceneList.createElement("profileinfo");
640 profileinfo.setAttribute("description", m_profile.description);
641 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
642 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
643 profileinfo.setAttribute("width", m_profile.width);
644 profileinfo.setAttribute("height", m_profile.height);
645 profileinfo.setAttribute("progressive", m_profile.progressive);
646 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
647 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
648 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
649 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
650 addedXml.appendChild(profileinfo);
653 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
654 foreach(const TrackInfo & info, m_tracksList) {
655 QDomElement trackinfo = sceneList.createElement("trackinfo");
656 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
657 trackinfo.setAttribute("mute", info.isMute);
658 trackinfo.setAttribute("blind", info.isBlind);
659 trackinfo.setAttribute("locked", info.isLocked);
660 trackinfo.setAttribute("trackname", info.trackName);
661 tracksinfo.appendChild(trackinfo);
663 addedXml.appendChild(tracksinfo);
665 // save project folders
666 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
668 QMapIterator<QString, QString> f(folderlist);
669 while (f.hasNext()) {
671 QDomElement folder = sceneList.createElement("folder");
672 folder.setAttribute("id", f.key());
673 folder.setAttribute("name", f.value());
674 if (expandedFolders.contains(f.key())) folder.setAttribute("opened", "1");
675 addedXml.appendChild(folder);
678 // Save project clips
680 QList <DocClipBase*> list = m_clipManager->documentClipList();
681 for (int i = 0; i < list.count(); i++) {
682 e = list.at(i)->toXML();
683 e.setTagName("kdenlive_producer");
684 addedXml.appendChild(sceneList.importNode(e, true));
685 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
686 for (int j = 0; j < marks.count(); j++) {
687 QDomElement marker = sceneList.createElement("marker");
688 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
689 marker.setAttribute("comment", marks.at(j).comment());
690 marker.setAttribute("id", e.attribute("id"));
691 markers.appendChild(marker);
694 addedXml.appendChild(markers);
697 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
700 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
702 //wes.appendChild(doc.importNode(kdenliveData, true));
706 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene, const QStringList expandedFolders, bool autosave)
708 QDomDocument sceneList = xmlSceneList(scene, expandedFolders);
709 if (sceneList.isNull()) {
710 //Make sure we don't save if scenelist is corrupted
711 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
715 // Backup current version
716 if (!autosave) backupLastSavedVersion(path);
719 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
720 kWarning() << "////// ERROR writing to file: " << path;
721 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
725 file.write(sceneList.toString().toUtf8());
726 if (file.error() != QFile::NoError) {
727 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
733 cleanupBackupFiles();
734 QFileInfo info(file);
735 QString fileName = KUrl(path).fileName().section('.', 0, -2);
736 fileName.append("-" + m_documentProperties.value("documentid"));
737 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
738 fileName.append(".kdenlive.png");
739 KUrl backupFile = m_projectFolder;
740 backupFile.addPath(".backup/");
741 backupFile.addPath(fileName);
742 emit saveTimelinePreview(backupFile.path());
747 ClipManager *KdenliveDoc::clipManager()
749 return m_clipManager;
752 KUrl KdenliveDoc::projectFolder() const
754 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
755 return m_projectFolder;
758 void KdenliveDoc::setProjectFolder(KUrl url)
760 if (url == m_projectFolder) return;
762 KStandardDirs::makeDir(url.path());
763 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
764 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
765 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);
766 m_projectFolder = url;
768 updateProjectFolderPlacesEntry();
771 void KdenliveDoc::moveProjectData(KUrl url)
773 QList <DocClipBase*> list = m_clipManager->documentClipList();
774 KUrl::List cacheUrls;
775 for (int i = 0; i < list.count(); i++) {
776 DocClipBase *clip = list.at(i);
777 if (clip->clipType() == TEXT) {
778 // the image for title clip must be moved
779 KUrl oldUrl = clip->fileURL();
780 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
781 KIO::Job *job = KIO::copy(oldUrl, newUrl);
782 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
784 QString hash = clip->getClipHash();
785 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
786 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
787 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
788 cacheUrls << oldVideoThumbUrl;
790 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
791 cacheUrls << oldAudioThumbUrl;
794 if (!cacheUrls.isEmpty()) {
795 KIO::Job *job = KIO::copy(cacheUrls, KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/"));
796 job->ui()->setWindow(kapp->activeWindow());
797 KIO::NetAccess::synchronousRun(job, 0);
801 const QString &KdenliveDoc::profilePath() const
803 return m_profile.path;
806 MltVideoProfile KdenliveDoc::mltProfile() const
811 bool KdenliveDoc::setProfilePath(QString path)
813 if (path.isEmpty()) path = KdenliveSettings::default_profile();
814 if (path.isEmpty()) path = "dv_pal";
815 m_profile = ProfilesDialog::getVideoProfile(path);
816 double current_fps = m_fps;
817 if (m_profile.path.isEmpty()) {
818 // Profile not found, use embedded profile
819 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
820 if (profileInfo.isNull()) {
821 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
822 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
824 m_profile.description = profileInfo.attribute("description");
825 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
826 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
827 m_profile.width = profileInfo.attribute("width").toInt();
828 m_profile.height = profileInfo.attribute("height").toInt();
829 m_profile.progressive = profileInfo.attribute("progressive").toInt();
830 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
831 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
832 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
833 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
834 QString existing = ProfilesDialog::existingProfile(m_profile);
835 if (!existing.isEmpty()) {
836 m_profile = ProfilesDialog::getVideoProfile(existing);
837 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
839 QString newDesc = m_profile.description;
841 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
842 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);
845 // User canceled, use default profile
846 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
848 if (newDesc != m_profile.description) {
849 // Profile description existed, was replaced by new one
850 m_profile.description = newDesc;
852 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
854 ProfilesDialog::saveProfile(m_profile);
861 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
862 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
863 KdenliveSettings::setProject_fps(m_fps);
864 m_width = m_profile.width;
865 m_height = m_profile.height;
866 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
867 m_timecode.setFormat(m_fps);
868 KdenliveSettings::setCurrent_profile(m_profile.path);
869 return (current_fps != m_fps);
872 double KdenliveDoc::dar() const
874 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
877 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
879 emit progressInfo(message, progress);
882 QUndoStack *KdenliveDoc::commandStack()
884 return m_commandStack;
888 void KdenliveDoc::setRenderer(Render *render) {
889 if (m_render) return;
891 emit progressInfo(i18n("Loading playlist..."), 0);
892 //qApp->processEvents();
894 m_render->setSceneList(m_document.toString(), m_startPos);
895 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
898 emit progressInfo(QString(), -1);
901 void KdenliveDoc::checkProjectClips(bool displayRatioChanged, bool fpsChanged)
903 if (m_render == NULL) return;
904 m_clipManager->resetProducersList(m_render->producersList(), displayRatioChanged, fpsChanged);
907 Render *KdenliveDoc::renderer()
912 void KdenliveDoc::updateClip(const QString id)
914 emit updateClipDisplay(id);
917 int KdenliveDoc::getFramePos(QString duration)
919 return m_timecode.getFrameCount(duration);
922 QString KdenliveDoc::producerName(const QString &id)
924 QString result = "unnamed";
925 QDomNodeList prods = producersList();
926 int ct = prods.count();
927 for (int i = 0; i < ct ; i++) {
928 QDomElement e = prods.item(i).toElement();
929 if (e.attribute("id") != "black" && e.attribute("id") == id) {
930 result = e.attribute("name");
931 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
938 QDomDocument KdenliveDoc::toXml()
943 Timecode KdenliveDoc::timecode() const
948 QDomNodeList KdenliveDoc::producersList()
950 return m_document.elementsByTagName("producer");
953 double KdenliveDoc::projectDuration() const
956 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
961 double KdenliveDoc::fps() const
966 int KdenliveDoc::width() const
971 int KdenliveDoc::height() const
976 KUrl KdenliveDoc::url() const
981 void KdenliveDoc::setUrl(KUrl url)
986 void KdenliveDoc::setModified(bool mod)
988 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
989 m_autoSaveTimer->start(3000);
991 if (mod == m_modified) return;
993 emit docModified(m_modified);
996 bool KdenliveDoc::isModified() const
1001 const QString KdenliveDoc::description() const
1003 if (m_url.isEmpty())
1004 return i18n("Untitled") + " / " + m_profile.description;
1006 return m_url.fileName() + " / " + m_profile.description;
1009 bool KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
1011 const QString producerId = clipId.section('_', 0, 0);
1012 DocClipBase *clip = m_clipManager->getClipById(producerId);
1015 elem.setAttribute("id", producerId);
1016 QString path = elem.attribute("resource");
1018 if (elem.attribute("type").toInt() == SLIDESHOW) {
1019 extension = KUrl(path).fileName();
1020 path = KUrl(path).directory();
1023 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
1024 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1025 const QString size = elem.attribute("file_size");
1026 const QString hash = elem.attribute("file_hash");
1028 int action = KMessageBox::No;
1029 if (!size.isEmpty() && !hash.isEmpty()) {
1030 if (!m_searchFolder.isEmpty())
1031 newpath = searchFileRecursively(m_searchFolder, size, hash);
1033 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")));
1035 if (elem.attribute("type").toInt() == SLIDESHOW) {
1036 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")));
1037 if (res == KMessageBox::Yes)
1038 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1040 // Abort project loading
1044 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")));
1045 if (res == KMessageBox::Yes)
1046 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1048 // Abort project loading
1053 if (action == KMessageBox::Yes) {
1054 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1055 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1056 if (!m_searchFolder.isEmpty())
1057 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1058 } else if (action == KMessageBox::Cancel) {
1060 } else if (action == KMessageBox::No) {
1061 // Keep clip as placeHolder
1062 elem.setAttribute("placeholder", '1');
1064 if (!newpath.isEmpty()) {
1065 if (elem.attribute("type").toInt() == SLIDESHOW)
1066 newpath.append('/' + extension);
1067 elem.setAttribute("resource", newpath);
1068 setNewClipResource(clipId, newpath);
1072 clip = new DocClipBase(m_clipManager, elem, producerId);
1073 m_clipManager->addClip(clip);
1076 if (createClipItem) {
1077 emit addProjectClip(clip);
1083 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1085 QDomNodeList prods = m_document.elementsByTagName("producer");
1086 int maxprod = prods.count();
1087 for (int i = 0; i < maxprod; i++) {
1088 QDomNode m = prods.at(i);
1089 QString prodId = m.toElement().attribute("id");
1090 if (prodId == id || prodId.startsWith(id + '_')) {
1091 QDomNodeList params = m.childNodes();
1092 for (int j = 0; j < params.count(); j++) {
1093 QDomElement e = params.item(j).toElement();
1094 if (e.attribute("name") == "resource") {
1095 e.firstChild().setNodeValue(path);
1103 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1105 QString foundFileName;
1106 QByteArray fileData;
1107 QByteArray fileHash;
1108 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1109 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1110 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1111 if (file.open(QIODevice::ReadOnly)) {
1112 if (QString::number(file.size()) == matchSize) {
1114 * 1 MB = 1 second per 450 files (or faster)
1115 * 10 MB = 9 seconds per 450 files (or faster)
1117 if (file.size() > 1000000 * 2) {
1118 fileData = file.read(1000000);
1119 if (file.seek(file.size() - 1000000))
1120 fileData.append(file.readAll());
1122 fileData = file.readAll();
1124 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1125 if (QString(fileHash.toHex()) == matchHash)
1126 return file.fileName();
1129 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1131 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1132 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1133 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1134 if (!foundFileName.isEmpty())
1137 return foundFileName;
1140 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1142 DocClipBase *clip = m_clipManager->getClipById(clipId);
1144 if (!addClip(elem, clipId, false))
1147 QMap <QString, QString> properties;
1148 QDomNamedNodeMap attributes = elem.attributes();
1149 for (int i = 0; i < attributes.count(); i++) {
1150 QString attrname = attributes.item(i).nodeName();
1151 if (attrname != "resource")
1152 properties.insert(attrname, attributes.item(i).nodeValue());
1153 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1155 clip->setProperties(properties);
1156 emit addProjectClip(clip, false);
1158 if (orig != QDomElement()) {
1159 QMap<QString, QString> meta;
1160 for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1161 QString name = m.toElement().attribute("name");
1162 if (name.startsWith("meta.attr"))
1163 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1165 if (!meta.isEmpty()) {
1167 clip = m_clipManager->getClipById(clipId);
1169 clip->setMetadata(meta);
1176 void KdenliveDoc::deleteClip(const QString &clipId)
1178 emit signalDeleteProjectClip(clipId);
1181 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1183 m_clipManager->slotAddClipList(urls, group, groupId);
1184 //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1189 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1191 m_clipManager->slotAddClipFile(url, group, groupId);
1192 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1196 const QString KdenliveDoc::getFreeClipId()
1198 return QString::number(m_clipManager->getFreeClipId());
1201 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1203 return m_clipManager->getClipById(clipId);
1206 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement xml, QString group, const QString &groupId)
1208 m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1210 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1213 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1215 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1217 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1220 void KdenliveDoc::slotCreateSlideshowClipFile(const QString name, const QString path, int count, const QString duration,
1221 const bool loop, const bool crop, const bool fade,
1222 const QString &luma_duration, const QString &luma_file, const int softness,
1223 const QString &animation, QString group, const QString &groupId)
1225 m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop,
1226 crop, fade, luma_duration,
1227 luma_file, softness,
1228 animation, group, groupId);
1230 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1233 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1235 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1236 KStandardDirs::makeDir(titlesFolder);
1237 TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1238 if (dia_ui->exec() == QDialog::Accepted) {
1239 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->outPoint(), dia_ui->xml().toString(), group, groupId);
1241 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1246 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1248 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1249 if (path.isEmpty()) {
1250 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1253 if (path.isEmpty()) return;
1255 //TODO: rewrite with new title system (just set resource)
1256 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1258 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1261 int KdenliveDoc::tracksCount() const
1263 return m_tracksList.count();
1266 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1268 if (ix < 0 || ix >= m_tracksList.count()) {
1269 kWarning() << "Track INFO outisde of range";
1272 return m_tracksList.at(ix);
1275 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1277 if (ix < 0 || ix >= m_tracksList.count()) {
1278 kWarning() << "SWITCH Track outisde of range";
1281 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1284 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1286 if (ix < 0 || ix >= m_tracksList.count()) {
1287 kWarning() << "Track Lock outisde of range";
1290 m_tracksList[ix].isLocked = lock;
1293 bool KdenliveDoc::isTrackLocked(int ix) const
1295 if (ix < 0 || ix >= m_tracksList.count()) {
1296 kWarning() << "Track Lock outisde of range";
1299 return m_tracksList.at(ix).isLocked;
1302 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1304 if (ix < 0 || ix >= m_tracksList.count()) {
1305 kWarning() << "SWITCH Track outisde of range";
1308 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1311 int KdenliveDoc::trackDuration(int ix)
1313 return m_tracksList.at(ix).duration;
1316 void KdenliveDoc::setTrackDuration(int ix, int duration)
1318 m_tracksList[ix].duration = duration;
1321 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1323 if (ix == -1) m_tracksList << type;
1324 else m_tracksList.insert(ix, type);
1327 void KdenliveDoc::deleteTrack(int ix)
1329 if (ix < 0 || ix >= m_tracksList.count()) {
1330 kWarning() << "Delete Track outisde of range";
1333 m_tracksList.removeAt(ix);
1336 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1338 if (ix < 0 || ix >= m_tracksList.count()) {
1339 kWarning() << "SET Track Type outisde of range";
1342 m_tracksList[ix].type = type.type;
1343 m_tracksList[ix].isMute = type.isMute;
1344 m_tracksList[ix].isBlind = type.isBlind;
1345 m_tracksList[ix].isLocked = type.isLocked;
1346 m_tracksList[ix].trackName = type.trackName;
1349 const QList <TrackInfo> KdenliveDoc::tracksList() const
1351 return m_tracksList;
1354 QPoint KdenliveDoc::getTracksCount() const
1358 foreach(const TrackInfo & info, m_tracksList) {
1359 if (info.type == VIDEOTRACK) video++;
1362 return QPoint(video, audio);
1365 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1367 pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1370 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1372 DocumentChecker d(infoproducers, m_document);
1373 return (d.hasErrorInClips() == false);
1379 QList <QDomElement> missingClips;
1380 for (int i = 0; i < infoproducers.count(); i++) {
1381 e = infoproducers.item(i).toElement();
1382 clipType = e.attribute("type").toInt();
1383 if (clipType == COLOR) continue;
1384 if (clipType == TEXT) {
1385 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1388 id = e.attribute("id");
1389 resource = e.attribute("resource");
1390 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1391 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1392 // Missing clip found
1393 missingClips.append(e);
1395 // Check if the clip has changed
1396 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1397 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1398 e.removeAttribute("file_hash");
1402 if (missingClips.isEmpty()) return true;
1403 DocumentChecker d(missingClips, m_document);
1404 return (d.exec() == QDialog::Accepted);*/
1407 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1409 m_documentProperties[name] = value;
1412 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1414 return m_documentProperties.value(name);
1417 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1419 QMap <QString, QString> renderProperties;
1420 QMapIterator<QString, QString> i(m_documentProperties);
1421 while (i.hasNext()) {
1423 if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1425 return renderProperties;
1428 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1430 if (ix < 0 || ix >= m_tracksList.count()) {
1431 kWarning() << "Add Track effect outisde of range";
1434 effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1436 // Init parameter value & keyframes if required
1437 QDomNodeList params = effect.elementsByTagName("parameter");
1438 for (int i = 0; i < params.count(); i++) {
1439 QDomElement e = params.item(i).toElement();
1441 // Check if this effect has a variable parameter
1442 if (e.attribute("default").contains('%')) {
1443 double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1444 e.setAttribute("default", evaluatedValue);
1445 if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1446 e.setAttribute("value", evaluatedValue);
1450 if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1451 QString def = e.attribute("default");
1452 // Effect has a keyframe type parameter, we need to set the values
1453 if (e.attribute("keyframes").isEmpty()) {
1454 e.setAttribute("keyframes", "0:" + def + ';');
1455 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1460 if (effect.attribute("id") == "crop") {
1461 // default use_profile to 1 for clips with proxies to avoid problems when rendering
1462 if (e.attribute("name") == "use_profile" && getDocumentProperty("enableproxy") == "1")
1463 e.setAttribute("value", "1");
1467 m_tracksList[ix].effectsList.append(effect);
1470 void KdenliveDoc::removeTrackEffect(int ix, QDomElement effect)
1472 if (ix < 0 || ix >= m_tracksList.count()) {
1473 kWarning() << "Remove Track effect outisde of range";
1477 QString toRemove = effect.attribute("kdenlive_ix");
1478 for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1479 index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix");
1480 if (toRemove == index) {
1481 m_tracksList[ix].effectsList.removeAt(i);
1483 } else if (index.toInt() > toRemove.toInt()) {
1484 m_tracksList[ix].effectsList.item(i).setAttribute("kdenlive_ix", index.toInt() - 1);
1489 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1491 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1492 kWarning() << "Set Track effect outisde of range";
1495 if (effectIndex < 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count() - 1) || effect.isNull()) {
1496 kDebug() << "Invalid effect index: " << effectIndex;
1499 effect.setAttribute("kdenlive_ix", effectIndex + 1);
1500 m_tracksList[trackIndex].effectsList.replace(effectIndex, effect);
1503 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1505 if (ix < 0 || ix >= m_tracksList.count()) {
1506 kWarning() << "Get Track effects outisde of range";
1507 return EffectsList();
1509 return m_tracksList.at(ix).effectsList;
1512 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1514 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1515 kWarning() << "Get Track effect outisde of range";
1516 return QDomElement();
1518 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1519 if (effectIndex > list.count() - 1 || effectIndex < 0 || list.at(effectIndex).isNull()) return QDomElement();
1520 return list.at(effectIndex).cloneNode().toElement();
1523 bool KdenliveDoc::saveCustomEffects(QDomNodeList customeffects)
1526 QStringList importedEffects;
1527 int maxchild = customeffects.count();
1528 for (int i = 0; i < maxchild; i++) {
1529 e = customeffects.at(i).toElement();
1530 QString id = e.attribute("id");
1531 QString tag = e.attribute("tag");
1532 if (!id.isEmpty()) {
1533 // Check if effect exists or save it
1534 if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1536 doc.appendChild(doc.importNode(e, true));
1537 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1538 path += id + ".xml";
1539 if (!QFile::exists(path)) {
1540 importedEffects << id;
1542 if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1543 QTextStream out(&file);
1544 out << doc.toString();
1550 if (!importedEffects.isEmpty()) KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1551 return (!importedEffects.isEmpty());
1554 void KdenliveDoc::updateProjectFolderPlacesEntry()
1557 * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1558 * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1561 const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1562 KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1563 KBookmarkGroup root = bookmarkManager->root();
1564 KBookmark bookmark = root.first();
1566 QString kdenliveName = KGlobal::mainComponent().componentName();
1567 KUrl documentLocation = m_projectFolder;
1569 bool exists = false;
1571 while (!bookmark.isNull()) {
1572 // UDI not empty indicates a device
1573 QString udi = bookmark.metaDataItem("UDI");
1574 QString appName = bookmark.metaDataItem("OnlyInApp");
1576 if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1577 if (bookmark.url() != documentLocation) {
1578 bookmark.setUrl(documentLocation);
1579 bookmarkManager->emitChanged(root);
1585 bookmark = root.next(bookmark);
1588 // if entry does not exist yet (was not found), well, create it then
1590 bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1591 // Make this user selectable ?
1592 bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1593 bookmarkManager->emitChanged(root);
1597 QStringList KdenliveDoc::getExpandedFolders()
1599 QStringList result = m_documentProperties.value("expandedfolders").split(';');
1600 // this property is only needed once when opening project, so clear it now
1601 m_documentProperties.remove("expandedfolders");
1606 double KdenliveDoc::getDisplayRatio(const QString &path)
1610 if (!file.open(QIODevice::ReadOnly)) {
1611 kWarning() << "ERROR, CANNOT READ: " << path;
1614 if (!doc.setContent(&file)) {
1615 kWarning() << "ERROR, CANNOT READ: " << path;
1620 QDomNodeList list = doc.elementsByTagName("profile");
1621 if (list.isEmpty()) return 0;
1622 QDomElement profile = list.at(0).toElement();
1623 double den = profile.attribute("display_aspect_den").toDouble();
1624 if (den > 0) return profile.attribute("display_aspect_num").toDouble() / den;
1628 void KdenliveDoc::backupLastSavedVersion(const QString &path)
1630 // Ensure backup folder exists
1631 if (path.isEmpty()) return;
1633 KUrl backupFile = m_projectFolder;
1634 backupFile.addPath(".backup/");
1635 KIO::NetAccess::mkdir(backupFile, kapp->activeWindow());
1636 QString fileName = KUrl(path).fileName().section('.', 0, -2);
1637 QFileInfo info(file);
1638 fileName.append("-" + m_documentProperties.value("documentid"));
1639 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
1640 fileName.append(".kdenlive");
1641 backupFile.addPath(fileName);
1643 if (file.exists()) {
1644 // delete previous backup if it was done less than 60 seconds ago
1645 QFile::remove(backupFile.path());
1646 if (!QFile::copy(path, backupFile.path())) {
1647 KMessageBox::information(kapp->activeWindow(), i18n("Cannot create backup copy:\n%1", backupFile.path()));
1652 void KdenliveDoc::cleanupBackupFiles()
1654 KUrl backupFile = m_projectFolder;
1655 backupFile.addPath(".backup/");
1656 QDir dir(backupFile.path());
1657 QString projectFile = url().fileName().section('.', 0, -2);
1658 projectFile.append("-" + m_documentProperties.value("documentid"));
1659 projectFile.append("-??");
1660 projectFile.append("??");
1661 projectFile.append("-??");
1662 projectFile.append("-??");
1663 projectFile.append("-??");
1664 projectFile.append("-??.kdenlive");
1667 backupFile.addPath(projectFile);
1668 filter << projectFile;
1669 dir.setNameFilters(filter);
1670 QFileInfoList resultList = dir.entryInfoList(QDir::Files, QDir::Time);
1672 QDateTime d = QDateTime::currentDateTime();
1673 QStringList hourList;
1674 QStringList dayList;
1675 QStringList weekList;
1676 QStringList oldList;
1677 for (int i = 0; i < resultList.count(); i++) {
1678 if (d.secsTo(resultList.at(i).lastModified()) < 3600) {
1679 // files created in the last hour
1680 hourList.append(resultList.at(i).absoluteFilePath());
1682 else if (d.secsTo(resultList.at(i).lastModified()) < 43200) {
1683 // files created in the day
1684 dayList.append(resultList.at(i).absoluteFilePath());
1686 else if (d.daysTo(resultList.at(i).lastModified()) < 8) {
1687 // files created in the week
1688 weekList.append(resultList.at(i).absoluteFilePath());
1692 oldList.append(resultList.at(i).absoluteFilePath());
1695 if (hourList.count() > 20) {
1696 int step = hourList.count() / 10;
1697 for (int i = 0; i < hourList.count(); i += step) {
1698 kDebug()<<"REMOVE AT: "<<i<<", COUNT: "<<hourList.count();
1699 hourList.removeAt(i);
1702 } else hourList.clear();
1703 if (dayList.count() > 20) {
1704 int step = dayList.count() / 10;
1705 for (int i = 0; i < dayList.count(); i += step) {
1706 dayList.removeAt(i);
1709 } else dayList.clear();
1710 if (weekList.count() > 20) {
1711 int step = weekList.count() / 10;
1712 for (int i = 0; i < weekList.count(); i += step) {
1713 weekList.removeAt(i);
1716 } else weekList.clear();
1717 if (oldList.count() > 20) {
1718 int step = oldList.count() / 10;
1719 for (int i = 0; i < oldList.count(); i += step) {
1720 oldList.removeAt(i);
1723 } else oldList.clear();
1726 while (hourList.count() > 0) {
1727 f = hourList.takeFirst();
1729 QFile::remove(f + ".png");
1731 while (dayList.count() > 0) {
1732 f = dayList.takeFirst();
1734 QFile::remove(f + ".png");
1736 while (weekList.count() > 0) {
1737 f = weekList.takeFirst();
1739 QFile::remove(f + ".png");
1741 while (oldList.count() > 0) {
1742 f = oldList.takeFirst();
1744 QFile::remove(f + ".png");
1748 #include "kdenlivedoc.moc"