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 QLocale locale = QLocale::system();
103 locale.setNumberOptions(QLocale::OmitGroupSeparator);
104 if (QLocale() != locale) {
105 setlocale(LC_NUMERIC, "");
106 QLocale::setDefault(QLocale::system());
107 // locale conversion might need to be redone
108 initEffects::parseEffectFiles();
113 if (!url.isEmpty()) {
115 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
117 // The file cannot be opened
118 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) {
121 //KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
126 QDomImplementation impl;
127 impl.setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
128 success = m_document.setContent(&file, false, &errorMsg);
130 KIO::NetAccess::removeTempFile(tmpFile);
134 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) {
137 //KMessageBox::error(parent, errorMsg);
140 parent->slotGotProgressInfo(i18n("Validating"), 0);
141 qApp->processEvents();
142 DocumentValidator validator(m_document);
143 success = validator.isProject();
145 // It is not a project file
146 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
147 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) {
152 * Validate the file against the current version (upgrade
153 * and recover it if needed). It is NOT a passive operation
155 // TODO: backup the document or alert the user?
156 success = validator.validate(DOCUMENTVERSION);
157 if (success) { // Let the validator handle error messages
158 parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
159 qApp->processEvents();
160 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
161 success = checkDocumentClips(infoproducers);
163 if (m_document.documentElement().attribute("modified") == "1") setModified(true);
164 parent->slotGotProgressInfo(i18n("Loading"), 0);
165 QDomElement mlt = m_document.firstChildElement("mlt");
166 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
168 // Set profile, fps, etc for the document
169 setProfilePath(infoXml.attribute("profile"));
171 // Check embedded effects
172 QDomElement customeffects = infoXml.firstChildElement("customeffects");
173 if (!customeffects.isNull() && customeffects.hasChildNodes()) {
174 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
175 qApp->processEvents();
176 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
181 QDomElement notesxml = infoXml.firstChildElement("documentnotes");
182 if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
185 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
186 if (!tracksinfo.isNull()) {
187 QDomNodeList trackslist = tracksinfo.childNodes();
188 int maxchild = trackslist.count();
189 for (int k = 0; k < maxchild; k++) {
190 e = trackslist.at(k).toElement();
191 if (e.tagName() == "trackinfo") {
192 TrackInfo projectTrack;
193 if (e.attribute("type") == "audio")
194 projectTrack.type = AUDIOTRACK;
196 projectTrack.type = VIDEOTRACK;
197 projectTrack.isMute = e.attribute("mute").toInt();
198 projectTrack.isBlind = e.attribute("blind").toInt();
199 projectTrack.isLocked = e.attribute("locked").toInt();
200 projectTrack.trackName = e.attribute("trackname");
201 m_tracksList.append(projectTrack);
204 mlt.removeChild(tracksinfo);
206 QStringList expandedFolders;
207 QDomNodeList folders = m_document.elementsByTagName("folder");
208 for (int i = 0; i < folders.count(); i++) {
209 e = folders.item(i).cloneNode().toElement();
210 if (e.hasAttribute("opened")) expandedFolders.append(e.attribute("id"));
211 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
213 m_documentProperties["expandedfolders"] = expandedFolders.join(";");
215 const int infomax = infoproducers.count();
216 QDomNodeList producers = m_document.elementsByTagName("producer");
217 const int max = producers.count();
219 if (!progressDialog) {
220 progressDialog = new KProgressDialog(parent, i18n("Loading project"), i18n("Adding clips"));
221 progressDialog->setAllowCancel(false);
223 progressDialog->setLabelText(i18n("Adding clips"));
225 progressDialog->progressBar()->setMaximum(infomax);
226 progressDialog->show();
227 qApp->processEvents();
229 for (int i = 0; i < infomax; i++) {
230 e = infoproducers.item(i).cloneNode().toElement();
231 QString prodId = e.attribute("id");
232 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
233 e.setTagName("producer");
234 // Get MLT's original producer properties
236 for (int j = 0; j < max; j++) {
237 QDomNode o = producers.item(j);
238 QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
239 if (origId == prodId) {
240 orig = o.cloneNode().toElement();
245 if (!addClipInfo(e, orig, prodId)) {
246 // The user manually aborted the loading.
248 emit resetProjectList();
249 m_tracksList.clear();
250 m_clipManager->clear();
255 progressDialog->progressBar()->setValue(i);
259 QDomElement markers = infoXml.firstChildElement("markers");
260 if (!markers.isNull()) {
261 QDomNodeList markerslist = markers.childNodes();
262 int maxchild = markerslist.count();
263 for (int k = 0; k < maxchild; k++) {
264 e = markerslist.at(k).toElement();
265 if (e.tagName() == "marker")
266 m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
268 infoXml.removeChild(markers);
271 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
272 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
273 QDomNamedNodeMap props = docproperties.attributes();
274 for (int i = 0; i < props.count(); i++)
275 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
277 if (validator.isModified()) setModified(true);
278 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
287 // Something went wrong, or a new file was requested: create a new project
290 setProfilePath(profileName);
291 m_document = createEmptyDocument(tracks.x(), tracks.y());
294 // Ask to create the project directory if it does not exist
295 if (!QFile::exists(m_projectFolder.path())) {
296 int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
297 if (create == KMessageBox::Yes) {
298 QDir projectDir(m_projectFolder.path());
299 bool ok = projectDir.mkpath(m_projectFolder.path());
301 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
306 // Make sure the project folder is usable
307 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
308 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
309 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
312 // Make sure that the necessary folders exist
313 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
314 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
315 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/");
317 updateProjectFolderPlacesEntry();
319 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
320 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
323 KdenliveDoc::~KdenliveDoc()
325 m_autoSaveTimer->stop();
326 delete m_commandStack;
327 kDebug() << "// DEL CLP MAN";
328 delete m_clipManager;
329 kDebug() << "// DEL CLP MAN done";
330 delete m_autoSaveTimer;
332 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
337 int KdenliveDoc::setSceneList()
339 m_render->resetProfile(KdenliveSettings::current_profile(), true);
340 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
341 // INVALID MLT Consumer, something is wrong
344 m_documentProperties.remove("position");
345 // m_document xml is now useless, clear it
350 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
352 m_tracksList.clear();
354 // Tracks are added «backwards», so we need to reverse the track numbering
355 // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
356 // Better default names for tracks: Audio 1 etc. instead of blank numbers
357 for (int i = 0; i < audiotracks; i++) {
358 TrackInfo audioTrack;
359 audioTrack.type = AUDIOTRACK;
360 audioTrack.isMute = false;
361 audioTrack.isBlind = true;
362 audioTrack.isLocked = false;
363 audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
364 audioTrack.duration = 0;
365 m_tracksList.append(audioTrack);
368 for (int i = 0; i < videotracks; i++) {
369 TrackInfo videoTrack;
370 videoTrack.type = VIDEOTRACK;
371 videoTrack.isMute = false;
372 videoTrack.isBlind = false;
373 videoTrack.isLocked = false;
374 videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
375 videoTrack.duration = 0;
376 m_tracksList.append(videoTrack);
378 return createEmptyDocument(m_tracksList);
381 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
383 // Creating new document
385 QDomElement mlt = doc.createElement("mlt");
386 mlt.setAttribute("LC_NUMERIC", "");
387 doc.appendChild(mlt);
389 // Create black producer
390 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
391 // the composite transitions with the black track are corrupted.
392 QDomElement blk = doc.createElement("producer");
393 blk.setAttribute("in", 0);
394 blk.setAttribute("out", 500);
395 blk.setAttribute("id", "black");
397 QDomElement property = doc.createElement("property");
398 property.setAttribute("name", "mlt_type");
399 QDomText value = doc.createTextNode("producer");
400 property.appendChild(value);
401 blk.appendChild(property);
403 property = doc.createElement("property");
404 property.setAttribute("name", "aspect_ratio");
405 value = doc.createTextNode(QString::number(0));
406 property.appendChild(value);
407 blk.appendChild(property);
409 property = doc.createElement("property");
410 property.setAttribute("name", "length");
411 value = doc.createTextNode(QString::number(15000));
412 property.appendChild(value);
413 blk.appendChild(property);
415 property = doc.createElement("property");
416 property.setAttribute("name", "eof");
417 value = doc.createTextNode("pause");
418 property.appendChild(value);
419 blk.appendChild(property);
421 property = doc.createElement("property");
422 property.setAttribute("name", "resource");
423 value = doc.createTextNode("black");
424 property.appendChild(value);
425 blk.appendChild(property);
427 property = doc.createElement("property");
428 property.setAttribute("name", "mlt_service");
429 value = doc.createTextNode("colour");
430 property.appendChild(value);
431 blk.appendChild(property);
433 mlt.appendChild(blk);
436 QDomElement tractor = doc.createElement("tractor");
437 tractor.setAttribute("id", "maintractor");
438 QDomElement multitrack = doc.createElement("multitrack");
439 QDomElement playlist = doc.createElement("playlist");
440 playlist.setAttribute("id", "black_track");
441 mlt.appendChild(playlist);
443 QDomElement blank0 = doc.createElement("entry");
444 blank0.setAttribute("in", "0");
445 blank0.setAttribute("out", "1");
446 blank0.setAttribute("producer", "black");
447 playlist.appendChild(blank0);
450 int total = tracks.count() + 1;
452 for (int i = 1; i < total; i++) {
453 QDomElement playlist = doc.createElement("playlist");
454 playlist.setAttribute("id", "playlist" + QString::number(i));
455 mlt.appendChild(playlist);
458 QDomElement track0 = doc.createElement("track");
459 track0.setAttribute("producer", "black_track");
460 tractor.appendChild(track0);
462 // create audio and video tracks
463 for (int i = 1; i < total; i++) {
464 QDomElement track = doc.createElement("track");
465 track.setAttribute("producer", "playlist" + QString::number(i));
466 if (tracks.at(i - 1).type == AUDIOTRACK) {
467 track.setAttribute("hide", "video");
468 } else if (tracks.at(i - 1).isBlind)
469 track.setAttribute("hide", "video");
470 if (tracks.at(i - 1).isMute)
471 track.setAttribute("hide", "audio");
472 tractor.appendChild(track);
475 for (int i = 2; i < total ; i++) {
476 QDomElement transition = doc.createElement("transition");
477 transition.setAttribute("always_active", "1");
479 QDomElement property = doc.createElement("property");
480 property.setAttribute("name", "a_track");
481 QDomText value = doc.createTextNode(QString::number(1));
482 property.appendChild(value);
483 transition.appendChild(property);
485 property = doc.createElement("property");
486 property.setAttribute("name", "b_track");
487 value = doc.createTextNode(QString::number(i));
488 property.appendChild(value);
489 transition.appendChild(property);
491 property = doc.createElement("property");
492 property.setAttribute("name", "mlt_service");
493 value = doc.createTextNode("mix");
494 property.appendChild(value);
495 transition.appendChild(property);
497 property = doc.createElement("property");
498 property.setAttribute("name", "combine");
499 value = doc.createTextNode("1");
500 property.appendChild(value);
501 transition.appendChild(property);
503 property = doc.createElement("property");
504 property.setAttribute("name", "internal_added");
505 value = doc.createTextNode("237");
506 property.appendChild(value);
507 transition.appendChild(property);
508 tractor.appendChild(transition);
510 mlt.appendChild(tractor);
515 void KdenliveDoc::syncGuides(QList <Guide *> guides)
518 QDomElement guideNode = m_guidesXml.createElement("guides");
519 m_guidesXml.appendChild(guideNode);
522 for (int i = 0; i < guides.count(); i++) {
523 e = m_guidesXml.createElement("guide");
524 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
525 e.setAttribute("comment", guides.at(i)->label());
526 guideNode.appendChild(e);
529 emit guidesUpdated();
532 QDomElement KdenliveDoc::guidesXml() const
534 return m_guidesXml.documentElement();
537 void KdenliveDoc::slotAutoSave()
539 if (m_render && m_autosave) {
540 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
541 // show error: could not open the autosave file
542 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
544 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
545 saveSceneList(m_autosave->fileName(), m_render->sceneList(), QStringList(), true);
549 void KdenliveDoc::setZoom(int horizontal, int vertical)
551 m_documentProperties["zoom"] = QString::number(horizontal);
552 m_documentProperties["verticalzoom"] = QString::number(vertical);
555 QPoint KdenliveDoc::zoom() const
557 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
560 void KdenliveDoc::setZone(int start, int end)
562 m_documentProperties["zonein"] = QString::number(start);
563 m_documentProperties["zoneout"] = QString::number(end);
566 QPoint KdenliveDoc::zone() const
568 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
571 QDomDocument KdenliveDoc::xmlSceneList(const QString &scene, const QStringList expandedFolders)
573 QDomDocument sceneList;
574 sceneList.setContent(scene, true);
575 QDomElement mlt = sceneList.firstChildElement("mlt");
576 if (mlt.isNull() || !mlt.hasChildNodes()) {
577 //scenelist is corrupted
581 // Set playlist audio volume to 100%
582 QDomElement tractor = mlt.firstChildElement("tractor");
583 if (!tractor.isNull()) {
584 QDomNodeList props = tractor.elementsByTagName("property");
585 for (int i = 0; i < props.count(); i++) {
586 if (props.at(i).toElement().attribute("name") == "meta.volume") {
587 props.at(i).firstChild().setNodeValue("1");
593 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
594 mlt.appendChild(addedXml);
596 // check if project contains custom effects to embed them in project file
597 QDomNodeList effects = mlt.elementsByTagName("filter");
598 int maxEffects = effects.count();
599 kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
600 QMap <QString, QString> effectIds;
601 for (int i = 0; i < maxEffects; i++) {
602 QDomNode m = effects.at(i);
603 QDomNodeList params = m.childNodes();
606 for (int j = 0; j < params.count(); j++) {
607 QDomElement e = params.item(j).toElement();
608 if (e.attribute("name") == "kdenlive_id") {
609 id = e.firstChild().nodeValue();
611 if (e.attribute("name") == "tag") {
612 tag = e.firstChild().nodeValue();
614 if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
617 QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
618 addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
620 QDomElement markers = sceneList.createElement("markers");
621 addedXml.setAttribute("version", DOCUMENTVERSION);
622 addedXml.setAttribute("kdenliveversion", VERSION);
623 addedXml.setAttribute("profile", profilePath());
624 addedXml.setAttribute("projectfolder", m_projectFolder.path());
626 QDomElement docproperties = sceneList.createElement("documentproperties");
627 QMapIterator<QString, QString> i(m_documentProperties);
628 while (i.hasNext()) {
630 docproperties.setAttribute(i.key(), i.value());
632 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
633 addedXml.appendChild(docproperties);
635 QDomElement docnotes = sceneList.createElement("documentnotes");
636 QDomText value = sceneList.createTextNode(m_notesWidget->toHtml());
637 docnotes.appendChild(value);
638 addedXml.appendChild(docnotes);
641 QDomElement profileinfo = sceneList.createElement("profileinfo");
642 profileinfo.setAttribute("description", m_profile.description);
643 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
644 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
645 profileinfo.setAttribute("width", m_profile.width);
646 profileinfo.setAttribute("height", m_profile.height);
647 profileinfo.setAttribute("progressive", m_profile.progressive);
648 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
649 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
650 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
651 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
652 addedXml.appendChild(profileinfo);
655 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
656 foreach(const TrackInfo & info, m_tracksList) {
657 QDomElement trackinfo = sceneList.createElement("trackinfo");
658 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
659 trackinfo.setAttribute("mute", info.isMute);
660 trackinfo.setAttribute("blind", info.isBlind);
661 trackinfo.setAttribute("locked", info.isLocked);
662 trackinfo.setAttribute("trackname", info.trackName);
663 tracksinfo.appendChild(trackinfo);
665 addedXml.appendChild(tracksinfo);
667 // save project folders
668 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
670 QMapIterator<QString, QString> f(folderlist);
671 while (f.hasNext()) {
673 QDomElement folder = sceneList.createElement("folder");
674 folder.setAttribute("id", f.key());
675 folder.setAttribute("name", f.value());
676 if (expandedFolders.contains(f.key())) folder.setAttribute("opened", "1");
677 addedXml.appendChild(folder);
680 // Save project clips
682 QList <DocClipBase*> list = m_clipManager->documentClipList();
683 for (int i = 0; i < list.count(); i++) {
684 e = list.at(i)->toXML();
685 e.setTagName("kdenlive_producer");
686 addedXml.appendChild(sceneList.importNode(e, true));
687 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
688 for (int j = 0; j < marks.count(); j++) {
689 QDomElement marker = sceneList.createElement("marker");
690 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
691 marker.setAttribute("comment", marks.at(j).comment());
692 marker.setAttribute("id", e.attribute("id"));
693 markers.appendChild(marker);
696 addedXml.appendChild(markers);
699 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
702 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
704 //wes.appendChild(doc.importNode(kdenliveData, true));
708 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene, const QStringList expandedFolders, bool autosave)
710 QDomDocument sceneList = xmlSceneList(scene, expandedFolders);
711 if (sceneList.isNull()) {
712 //Make sure we don't save if scenelist is corrupted
713 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
717 // Backup current version
718 if (!autosave) backupLastSavedVersion(path);
721 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
722 kWarning() << "////// ERROR writing to file: " << path;
723 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
727 file.write(sceneList.toString().toUtf8());
728 if (file.error() != QFile::NoError) {
729 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
735 cleanupBackupFiles();
736 QFileInfo info(file);
737 QString fileName = KUrl(path).fileName().section('.', 0, -2);
738 fileName.append("-" + m_documentProperties.value("documentid"));
739 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
740 fileName.append(".kdenlive.png");
741 KUrl backupFile = m_projectFolder;
742 backupFile.addPath(".backup/");
743 backupFile.addPath(fileName);
744 emit saveTimelinePreview(backupFile.path());
749 ClipManager *KdenliveDoc::clipManager()
751 return m_clipManager;
754 KUrl KdenliveDoc::projectFolder() const
756 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
757 return m_projectFolder;
760 void KdenliveDoc::setProjectFolder(KUrl url)
762 if (url == m_projectFolder) return;
764 KStandardDirs::makeDir(url.path());
765 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
766 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
767 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);
768 m_projectFolder = url;
770 updateProjectFolderPlacesEntry();
773 void KdenliveDoc::moveProjectData(KUrl url)
775 QList <DocClipBase*> list = m_clipManager->documentClipList();
776 KUrl::List cacheUrls;
777 for (int i = 0; i < list.count(); i++) {
778 DocClipBase *clip = list.at(i);
779 if (clip->clipType() == TEXT) {
780 // the image for title clip must be moved
781 KUrl oldUrl = clip->fileURL();
782 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
783 KIO::Job *job = KIO::copy(oldUrl, newUrl);
784 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
786 QString hash = clip->getClipHash();
787 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
788 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
789 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
790 cacheUrls << oldVideoThumbUrl;
792 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
793 cacheUrls << oldAudioThumbUrl;
796 if (!cacheUrls.isEmpty()) {
797 KIO::Job *job = KIO::copy(cacheUrls, KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/"));
798 job->ui()->setWindow(kapp->activeWindow());
799 KIO::NetAccess::synchronousRun(job, 0);
803 const QString &KdenliveDoc::profilePath() const
805 return m_profile.path;
808 MltVideoProfile KdenliveDoc::mltProfile() const
813 bool KdenliveDoc::setProfilePath(QString path)
815 if (path.isEmpty()) path = KdenliveSettings::default_profile();
816 if (path.isEmpty()) path = "dv_pal";
817 m_profile = ProfilesDialog::getVideoProfile(path);
818 double current_fps = m_fps;
819 if (m_profile.path.isEmpty()) {
820 // Profile not found, use embedded profile
821 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
822 if (profileInfo.isNull()) {
823 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
824 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
826 m_profile.description = profileInfo.attribute("description");
827 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
828 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
829 m_profile.width = profileInfo.attribute("width").toInt();
830 m_profile.height = profileInfo.attribute("height").toInt();
831 m_profile.progressive = profileInfo.attribute("progressive").toInt();
832 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
833 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
834 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
835 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
836 QString existing = ProfilesDialog::existingProfile(m_profile);
837 if (!existing.isEmpty()) {
838 m_profile = ProfilesDialog::getVideoProfile(existing);
839 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
841 QString newDesc = m_profile.description;
843 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
844 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);
847 // User canceled, use default profile
848 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
850 if (newDesc != m_profile.description) {
851 // Profile description existed, was replaced by new one
852 m_profile.description = newDesc;
854 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
856 ProfilesDialog::saveProfile(m_profile);
863 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
864 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
865 KdenliveSettings::setProject_fps(m_fps);
866 m_width = m_profile.width;
867 m_height = m_profile.height;
868 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
869 m_timecode.setFormat(m_fps);
870 KdenliveSettings::setCurrent_profile(m_profile.path);
871 return (current_fps != m_fps);
874 double KdenliveDoc::dar() const
876 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
879 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
881 emit progressInfo(message, progress);
884 QUndoStack *KdenliveDoc::commandStack()
886 return m_commandStack;
890 void KdenliveDoc::setRenderer(Render *render) {
891 if (m_render) return;
893 emit progressInfo(i18n("Loading playlist..."), 0);
894 //qApp->processEvents();
896 m_render->setSceneList(m_document.toString(), m_startPos);
897 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
900 emit progressInfo(QString(), -1);
903 void KdenliveDoc::checkProjectClips(bool displayRatioChanged, bool fpsChanged)
905 if (m_render == NULL) return;
906 m_clipManager->resetProducersList(m_render->producersList(), displayRatioChanged, fpsChanged);
909 Render *KdenliveDoc::renderer()
914 void KdenliveDoc::updateClip(const QString id)
916 emit updateClipDisplay(id);
919 int KdenliveDoc::getFramePos(QString duration)
921 return m_timecode.getFrameCount(duration);
924 QString KdenliveDoc::producerName(const QString &id)
926 QString result = "unnamed";
927 QDomNodeList prods = producersList();
928 int ct = prods.count();
929 for (int i = 0; i < ct ; i++) {
930 QDomElement e = prods.item(i).toElement();
931 if (e.attribute("id") != "black" && e.attribute("id") == id) {
932 result = e.attribute("name");
933 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
940 QDomDocument KdenliveDoc::toXml()
945 Timecode KdenliveDoc::timecode() const
950 QDomNodeList KdenliveDoc::producersList()
952 return m_document.elementsByTagName("producer");
955 double KdenliveDoc::projectDuration() const
958 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
963 double KdenliveDoc::fps() const
968 int KdenliveDoc::width() const
973 int KdenliveDoc::height() const
978 KUrl KdenliveDoc::url() const
983 void KdenliveDoc::setUrl(KUrl url)
988 void KdenliveDoc::setModified(bool mod)
990 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
991 m_autoSaveTimer->start(3000);
993 if (mod == m_modified) return;
995 emit docModified(m_modified);
998 bool KdenliveDoc::isModified() const
1003 const QString KdenliveDoc::description() const
1005 if (m_url.isEmpty())
1006 return i18n("Untitled") + " / " + m_profile.description;
1008 return m_url.fileName() + " / " + m_profile.description;
1011 bool KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
1013 const QString producerId = clipId.section('_', 0, 0);
1014 DocClipBase *clip = m_clipManager->getClipById(producerId);
1017 elem.setAttribute("id", producerId);
1018 QString path = elem.attribute("resource");
1020 if (elem.attribute("type").toInt() == SLIDESHOW) {
1021 extension = KUrl(path).fileName();
1022 path = KUrl(path).directory();
1025 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
1026 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1027 const QString size = elem.attribute("file_size");
1028 const QString hash = elem.attribute("file_hash");
1030 int action = KMessageBox::No;
1031 if (!size.isEmpty() && !hash.isEmpty()) {
1032 if (!m_searchFolder.isEmpty())
1033 newpath = searchFileRecursively(m_searchFolder, size, hash);
1035 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")));
1037 if (elem.attribute("type").toInt() == SLIDESHOW) {
1038 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")));
1039 if (res == KMessageBox::Yes)
1040 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1042 // Abort project loading
1046 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")));
1047 if (res == KMessageBox::Yes)
1048 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1050 // Abort project loading
1055 if (action == KMessageBox::Yes) {
1056 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1057 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1058 if (!m_searchFolder.isEmpty())
1059 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1060 } else if (action == KMessageBox::Cancel) {
1062 } else if (action == KMessageBox::No) {
1063 // Keep clip as placeHolder
1064 elem.setAttribute("placeholder", '1');
1066 if (!newpath.isEmpty()) {
1067 if (elem.attribute("type").toInt() == SLIDESHOW)
1068 newpath.append('/' + extension);
1069 elem.setAttribute("resource", newpath);
1070 setNewClipResource(clipId, newpath);
1074 clip = new DocClipBase(m_clipManager, elem, producerId);
1075 m_clipManager->addClip(clip);
1078 if (createClipItem) {
1079 emit addProjectClip(clip);
1085 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1087 QDomNodeList prods = m_document.elementsByTagName("producer");
1088 int maxprod = prods.count();
1089 for (int i = 0; i < maxprod; i++) {
1090 QDomNode m = prods.at(i);
1091 QString prodId = m.toElement().attribute("id");
1092 if (prodId == id || prodId.startsWith(id + '_')) {
1093 QDomNodeList params = m.childNodes();
1094 for (int j = 0; j < params.count(); j++) {
1095 QDomElement e = params.item(j).toElement();
1096 if (e.attribute("name") == "resource") {
1097 e.firstChild().setNodeValue(path);
1105 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1107 QString foundFileName;
1108 QByteArray fileData;
1109 QByteArray fileHash;
1110 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1111 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1112 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1113 if (file.open(QIODevice::ReadOnly)) {
1114 if (QString::number(file.size()) == matchSize) {
1116 * 1 MB = 1 second per 450 files (or faster)
1117 * 10 MB = 9 seconds per 450 files (or faster)
1119 if (file.size() > 1000000 * 2) {
1120 fileData = file.read(1000000);
1121 if (file.seek(file.size() - 1000000))
1122 fileData.append(file.readAll());
1124 fileData = file.readAll();
1126 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1127 if (QString(fileHash.toHex()) == matchHash)
1128 return file.fileName();
1131 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1133 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1134 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1135 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1136 if (!foundFileName.isEmpty())
1139 return foundFileName;
1142 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1144 DocClipBase *clip = m_clipManager->getClipById(clipId);
1146 if (!addClip(elem, clipId, false))
1149 QMap <QString, QString> properties;
1150 QDomNamedNodeMap attributes = elem.attributes();
1151 for (int i = 0; i < attributes.count(); i++) {
1152 QString attrname = attributes.item(i).nodeName();
1153 if (attrname != "resource")
1154 properties.insert(attrname, attributes.item(i).nodeValue());
1155 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1157 clip->setProperties(properties);
1158 emit addProjectClip(clip, false);
1160 if (orig != QDomElement()) {
1161 QMap<QString, QString> meta;
1162 for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1163 QString name = m.toElement().attribute("name");
1164 if (name.startsWith("meta.attr"))
1165 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1167 if (!meta.isEmpty()) {
1169 clip = m_clipManager->getClipById(clipId);
1171 clip->setMetadata(meta);
1178 void KdenliveDoc::deleteClip(const QString &clipId)
1180 emit signalDeleteProjectClip(clipId);
1183 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1185 m_clipManager->slotAddClipList(urls, group, groupId);
1186 //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1191 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1193 m_clipManager->slotAddClipFile(url, group, groupId);
1194 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1198 const QString KdenliveDoc::getFreeClipId()
1200 return QString::number(m_clipManager->getFreeClipId());
1203 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1205 return m_clipManager->getClipById(clipId);
1208 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement xml, QString group, const QString &groupId)
1210 m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1212 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1215 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1217 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1219 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1222 void KdenliveDoc::slotCreateSlideshowClipFile(const QString name, const QString path, int count, const QString duration,
1223 const bool loop, const bool crop, const bool fade,
1224 const QString &luma_duration, const QString &luma_file, const int softness,
1225 const QString &animation, QString group, const QString &groupId)
1227 m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop,
1228 crop, fade, luma_duration,
1229 luma_file, softness,
1230 animation, group, groupId);
1232 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1235 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1237 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1238 KStandardDirs::makeDir(titlesFolder);
1239 TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1240 if (dia_ui->exec() == QDialog::Accepted) {
1241 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->outPoint(), dia_ui->xml().toString(), group, groupId);
1243 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1248 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1250 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1251 if (path.isEmpty()) {
1252 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1255 if (path.isEmpty()) return;
1257 //TODO: rewrite with new title system (just set resource)
1258 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1260 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1263 int KdenliveDoc::tracksCount() const
1265 return m_tracksList.count();
1268 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1270 if (ix < 0 || ix >= m_tracksList.count()) {
1271 kWarning() << "Track INFO outisde of range";
1274 return m_tracksList.at(ix);
1277 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1279 if (ix < 0 || ix >= m_tracksList.count()) {
1280 kWarning() << "SWITCH Track outisde of range";
1283 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1286 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1288 if (ix < 0 || ix >= m_tracksList.count()) {
1289 kWarning() << "Track Lock outisde of range";
1292 m_tracksList[ix].isLocked = lock;
1295 bool KdenliveDoc::isTrackLocked(int ix) const
1297 if (ix < 0 || ix >= m_tracksList.count()) {
1298 kWarning() << "Track Lock outisde of range";
1301 return m_tracksList.at(ix).isLocked;
1304 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1306 if (ix < 0 || ix >= m_tracksList.count()) {
1307 kWarning() << "SWITCH Track outisde of range";
1310 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1313 int KdenliveDoc::trackDuration(int ix)
1315 return m_tracksList.at(ix).duration;
1318 void KdenliveDoc::setTrackDuration(int ix, int duration)
1320 m_tracksList[ix].duration = duration;
1323 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1325 if (ix == -1) m_tracksList << type;
1326 else m_tracksList.insert(ix, type);
1329 void KdenliveDoc::deleteTrack(int ix)
1331 if (ix < 0 || ix >= m_tracksList.count()) {
1332 kWarning() << "Delete Track outisde of range";
1335 m_tracksList.removeAt(ix);
1338 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1340 if (ix < 0 || ix >= m_tracksList.count()) {
1341 kWarning() << "SET Track Type outisde of range";
1344 m_tracksList[ix].type = type.type;
1345 m_tracksList[ix].isMute = type.isMute;
1346 m_tracksList[ix].isBlind = type.isBlind;
1347 m_tracksList[ix].isLocked = type.isLocked;
1348 m_tracksList[ix].trackName = type.trackName;
1351 const QList <TrackInfo> KdenliveDoc::tracksList() const
1353 return m_tracksList;
1356 QPoint KdenliveDoc::getTracksCount() const
1360 foreach(const TrackInfo & info, m_tracksList) {
1361 if (info.type == VIDEOTRACK) video++;
1364 return QPoint(video, audio);
1367 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1369 pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1372 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1374 DocumentChecker d(infoproducers, m_document);
1375 return (d.hasErrorInClips() == false);
1381 QList <QDomElement> missingClips;
1382 for (int i = 0; i < infoproducers.count(); i++) {
1383 e = infoproducers.item(i).toElement();
1384 clipType = e.attribute("type").toInt();
1385 if (clipType == COLOR) continue;
1386 if (clipType == TEXT) {
1387 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1390 id = e.attribute("id");
1391 resource = e.attribute("resource");
1392 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1393 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1394 // Missing clip found
1395 missingClips.append(e);
1397 // Check if the clip has changed
1398 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1399 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1400 e.removeAttribute("file_hash");
1404 if (missingClips.isEmpty()) return true;
1405 DocumentChecker d(missingClips, m_document);
1406 return (d.exec() == QDialog::Accepted);*/
1409 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1411 m_documentProperties[name] = value;
1414 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1416 return m_documentProperties.value(name);
1419 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1421 QMap <QString, QString> renderProperties;
1422 QMapIterator<QString, QString> i(m_documentProperties);
1423 while (i.hasNext()) {
1425 if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1427 return renderProperties;
1430 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1432 if (ix < 0 || ix >= m_tracksList.count()) {
1433 kWarning() << "Add Track effect outisde of range";
1436 effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1438 // Init parameter value & keyframes if required
1439 QDomNodeList params = effect.elementsByTagName("parameter");
1440 for (int i = 0; i < params.count(); i++) {
1441 QDomElement e = params.item(i).toElement();
1443 // Check if this effect has a variable parameter
1444 if (e.attribute("default").contains('%')) {
1445 double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1446 e.setAttribute("default", evaluatedValue);
1447 if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1448 e.setAttribute("value", evaluatedValue);
1452 if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1453 QString def = e.attribute("default");
1454 // Effect has a keyframe type parameter, we need to set the values
1455 if (e.attribute("keyframes").isEmpty()) {
1456 e.setAttribute("keyframes", "0:" + def + ';');
1457 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1462 if (effect.attribute("id") == "crop") {
1463 // default use_profile to 1 for clips with proxies to avoid problems when rendering
1464 if (e.attribute("name") == "use_profile" && getDocumentProperty("enableproxy") == "1")
1465 e.setAttribute("value", "1");
1469 m_tracksList[ix].effectsList.append(effect);
1472 void KdenliveDoc::removeTrackEffect(int ix, QDomElement effect)
1474 if (ix < 0 || ix >= m_tracksList.count()) {
1475 kWarning() << "Remove Track effect outisde of range";
1479 QString toRemove = effect.attribute("kdenlive_ix");
1480 for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1481 index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix");
1482 if (toRemove == index) {
1483 m_tracksList[ix].effectsList.removeAt(i);
1485 } else if (index.toInt() > toRemove.toInt()) {
1486 m_tracksList[ix].effectsList.item(i).setAttribute("kdenlive_ix", index.toInt() - 1);
1491 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1493 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1494 kWarning() << "Set Track effect outisde of range";
1497 if (effectIndex < 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count() - 1) || effect.isNull()) {
1498 kDebug() << "Invalid effect index: " << effectIndex;
1501 effect.setAttribute("kdenlive_ix", effectIndex + 1);
1502 m_tracksList[trackIndex].effectsList.replace(effectIndex, effect);
1505 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1507 if (ix < 0 || ix >= m_tracksList.count()) {
1508 kWarning() << "Get Track effects outisde of range";
1509 return EffectsList();
1511 return m_tracksList.at(ix).effectsList;
1514 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1516 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1517 kWarning() << "Get Track effect outisde of range";
1518 return QDomElement();
1520 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1521 if (effectIndex > list.count() - 1 || effectIndex < 0 || list.at(effectIndex).isNull()) return QDomElement();
1522 return list.at(effectIndex).cloneNode().toElement();
1525 bool KdenliveDoc::saveCustomEffects(QDomNodeList customeffects)
1528 QStringList importedEffects;
1529 int maxchild = customeffects.count();
1530 for (int i = 0; i < maxchild; i++) {
1531 e = customeffects.at(i).toElement();
1532 QString id = e.attribute("id");
1533 QString tag = e.attribute("tag");
1534 if (!id.isEmpty()) {
1535 // Check if effect exists or save it
1536 if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1538 doc.appendChild(doc.importNode(e, true));
1539 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1540 path += id + ".xml";
1541 if (!QFile::exists(path)) {
1542 importedEffects << id;
1544 if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1545 QTextStream out(&file);
1546 out << doc.toString();
1552 if (!importedEffects.isEmpty()) KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1553 return (!importedEffects.isEmpty());
1556 void KdenliveDoc::updateProjectFolderPlacesEntry()
1559 * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1560 * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1563 const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1564 KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1565 KBookmarkGroup root = bookmarkManager->root();
1566 KBookmark bookmark = root.first();
1568 QString kdenliveName = KGlobal::mainComponent().componentName();
1569 KUrl documentLocation = m_projectFolder;
1571 bool exists = false;
1573 while (!bookmark.isNull()) {
1574 // UDI not empty indicates a device
1575 QString udi = bookmark.metaDataItem("UDI");
1576 QString appName = bookmark.metaDataItem("OnlyInApp");
1578 if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1579 if (bookmark.url() != documentLocation) {
1580 bookmark.setUrl(documentLocation);
1581 bookmarkManager->emitChanged(root);
1587 bookmark = root.next(bookmark);
1590 // if entry does not exist yet (was not found), well, create it then
1592 bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1593 // Make this user selectable ?
1594 bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1595 bookmarkManager->emitChanged(root);
1599 QStringList KdenliveDoc::getExpandedFolders()
1601 QStringList result = m_documentProperties.value("expandedfolders").split(';');
1602 // this property is only needed once when opening project, so clear it now
1603 m_documentProperties.remove("expandedfolders");
1608 double KdenliveDoc::getDisplayRatio(const QString &path)
1612 if (!file.open(QIODevice::ReadOnly)) {
1613 kWarning() << "ERROR, CANNOT READ: " << path;
1616 if (!doc.setContent(&file)) {
1617 kWarning() << "ERROR, CANNOT READ: " << path;
1622 QDomNodeList list = doc.elementsByTagName("profile");
1623 if (list.isEmpty()) return 0;
1624 QDomElement profile = list.at(0).toElement();
1625 double den = profile.attribute("display_aspect_den").toDouble();
1626 if (den > 0) return profile.attribute("display_aspect_num").toDouble() / den;
1630 void KdenliveDoc::backupLastSavedVersion(const QString &path)
1632 // Ensure backup folder exists
1633 if (path.isEmpty()) return;
1635 KUrl backupFile = m_projectFolder;
1636 backupFile.addPath(".backup/");
1637 KIO::NetAccess::mkdir(backupFile, kapp->activeWindow());
1638 QString fileName = KUrl(path).fileName().section('.', 0, -2);
1639 QFileInfo info(file);
1640 fileName.append("-" + m_documentProperties.value("documentid"));
1641 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
1642 fileName.append(".kdenlive");
1643 backupFile.addPath(fileName);
1645 if (file.exists()) {
1646 // delete previous backup if it was done less than 60 seconds ago
1647 QFile::remove(backupFile.path());
1648 if (!QFile::copy(path, backupFile.path())) {
1649 KMessageBox::information(kapp->activeWindow(), i18n("Cannot create backup copy:\n%1", backupFile.path()));
1654 void KdenliveDoc::cleanupBackupFiles()
1656 KUrl backupFile = m_projectFolder;
1657 backupFile.addPath(".backup/");
1658 QDir dir(backupFile.path());
1659 QString projectFile = url().fileName().section('.', 0, -2);
1660 projectFile.append("-" + m_documentProperties.value("documentid"));
1661 projectFile.append("-??");
1662 projectFile.append("??");
1663 projectFile.append("-??");
1664 projectFile.append("-??");
1665 projectFile.append("-??");
1666 projectFile.append("-??.kdenlive");
1669 backupFile.addPath(projectFile);
1670 filter << projectFile;
1671 dir.setNameFilters(filter);
1672 QFileInfoList resultList = dir.entryInfoList(QDir::Files, QDir::Time);
1674 QDateTime d = QDateTime::currentDateTime();
1675 QStringList hourList;
1676 QStringList dayList;
1677 QStringList weekList;
1678 QStringList oldList;
1679 for (int i = 0; i < resultList.count(); i++) {
1680 if (d.secsTo(resultList.at(i).lastModified()) < 3600) {
1681 // files created in the last hour
1682 hourList.append(resultList.at(i).absoluteFilePath());
1684 else if (d.secsTo(resultList.at(i).lastModified()) < 43200) {
1685 // files created in the day
1686 dayList.append(resultList.at(i).absoluteFilePath());
1688 else if (d.daysTo(resultList.at(i).lastModified()) < 8) {
1689 // files created in the week
1690 weekList.append(resultList.at(i).absoluteFilePath());
1694 oldList.append(resultList.at(i).absoluteFilePath());
1697 if (hourList.count() > 20) {
1698 int step = hourList.count() / 10;
1699 for (int i = 0; i < hourList.count(); i += step) {
1700 kDebug()<<"REMOVE AT: "<<i<<", COUNT: "<<hourList.count();
1701 hourList.removeAt(i);
1704 } else hourList.clear();
1705 if (dayList.count() > 20) {
1706 int step = dayList.count() / 10;
1707 for (int i = 0; i < dayList.count(); i += step) {
1708 dayList.removeAt(i);
1711 } else dayList.clear();
1712 if (weekList.count() > 20) {
1713 int step = weekList.count() / 10;
1714 for (int i = 0; i < weekList.count(); i += step) {
1715 weekList.removeAt(i);
1718 } else weekList.clear();
1719 if (oldList.count() > 20) {
1720 int step = oldList.count() / 10;
1721 for (int i = 0; i < oldList.count(); i += step) {
1722 oldList.removeAt(i);
1725 } else oldList.clear();
1728 while (hourList.count() > 0) {
1729 f = hourList.takeFirst();
1731 QFile::remove(f + ".png");
1733 while (dayList.count() > 0) {
1734 f = dayList.takeFirst();
1736 QFile::remove(f + ".png");
1738 while (weekList.count() > 0) {
1739 f = weekList.takeFirst();
1741 QFile::remove(f + ".png");
1743 while (oldList.count() > 0) {
1744 f = oldList.takeFirst();
1746 QFile::remove(f + ".png");
1750 #include "kdenlivedoc.moc"