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 "config-kdenlive.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, QMap <QString, QString> metadata, const QPoint &tracks, Render *render, KTextEdit *notes, bool *openBackup, MainWindow *parent, KProgressDialog *progressDialog) :
67 m_commandStack(new QUndoStack(undoGroup)),
69 m_projectFolder(projectFolder)
71 // init m_profile struct
72 m_profile.frame_rate_num = 0;
73 m_profile.frame_rate_den = 0;
76 m_profile.progressive = 0;
77 m_profile.sample_aspect_num = 0;
78 m_profile.sample_aspect_den = 0;
79 m_profile.display_aspect_num = 0;
80 m_profile.display_aspect_den = 0;
81 m_profile.colorspace = 0;
83 m_clipManager = new ClipManager(this);
84 m_autoSaveTimer = new QTimer(this);
85 m_autoSaveTimer->setSingleShot(true);
86 connect(m_clipManager, SIGNAL(displayMessage(QString, int)), parent, SLOT(slotGotProgressInfo(QString,int)));
89 // init default document properties
90 m_documentProperties["zoom"] = '7';
91 m_documentProperties["verticalzoom"] = '1';
92 m_documentProperties["zonein"] = '0';
93 m_documentProperties["zoneout"] = "100";
94 m_documentProperties["enableproxy"] = QString::number((int) KdenliveSettings::enableproxy());
95 m_documentProperties["proxyparams"] = KdenliveSettings::proxyparams();
96 m_documentProperties["proxyextension"] = KdenliveSettings::proxyextension();
97 m_documentProperties["generateproxy"] = QString::number((int) KdenliveSettings::generateproxy());
98 m_documentProperties["proxyminsize"] = QString::number(KdenliveSettings::proxyminsize());
99 m_documentProperties["generateimageproxy"] = QString::number((int) KdenliveSettings::generateimageproxy());
100 m_documentProperties["proxyimageminsize"] = QString::number(KdenliveSettings::proxyimageminsize());
101 #if QT_VERSION >= 0x040700
102 m_documentProperties["documentid"] = QString::number(QDateTime::currentMSecsSinceEpoch());
104 QDateTime date = QDateTime::currentDateTime();
105 m_documentProperties["documentid"] = QString::number(date.toTime_t());
109 QMapIterator<QString, QString> i(properties);
110 while (i.hasNext()) {
112 m_documentProperties[i.key()] = i.value();
116 QMapIterator<QString, QString> j(metadata);
117 while (j.hasNext()) {
119 m_documentMetadata[j.key()] = j.value();
122 if (QLocale().decimalPoint() != QLocale::system().decimalPoint()) {
123 setlocale(LC_NUMERIC, "");
124 QLocale systemLocale = QLocale::system();
125 systemLocale.setNumberOptions(QLocale::OmitGroupSeparator);
126 QLocale::setDefault(systemLocale);
127 // locale conversion might need to be redone
128 initEffects::parseEffectFiles(setlocale(LC_NUMERIC, NULL));
133 if (!url.isEmpty()) {
135 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
137 // The file cannot be opened
138 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) {
141 //KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
148 QDomImplementation::setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
149 success = m_document.setContent(&file, false, &errorMsg, &line, &col);
154 int answer = KMessageBox::warningYesNoCancel (parent, i18n("Cannot open the project file, error is:\n%1 (line %2, col %3)\nDo you want to open a backup file?", errorMsg, line, col), i18n("Error opening file"), KGuiItem(i18n("Open Backup")), KGuiItem(i18n("Recover")));
155 if (answer == KMessageBox::Yes) {
158 else if (answer == KMessageBox::No) {
159 // Try to recover broken file produced by Kdenlive 0.9.4
160 if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
162 QString playlist = file.readAll();
163 while (!success && correction < 2) {
167 for (int j = 0; j < line && errorPos < playlist.length(); j++) {
168 errorPos = playlist.indexOf("\n", errorPos);
172 if (errorPos >= playlist.length()) break;
173 playlist.remove(errorPos, 1);
176 success = m_document.setContent(playlist, false, &errorMsg, &line, &col);
180 KMessageBox::sorry(parent, i18n("Cannot recover this project file"));
183 // Document was modified, ask for backup
184 QDomElement mlt = m_document.documentElement();
185 QDomElement info = mlt.firstChildElement("kdenlivedoc");
186 if (!info.isNull()) info.setAttribute("modified", 1);
192 parent->slotGotProgressInfo(i18n("Validating"), 0);
193 qApp->processEvents();
194 DocumentValidator validator(m_document, url);
195 success = validator.isProject();
197 // It is not a project file
198 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
199 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) {
204 * Validate the file against the current version (upgrade
205 * and recover it if needed). It is NOT a passive operation
207 // TODO: backup the document or alert the user?
208 success = validator.validate(DOCUMENTVERSION);
209 if (success) { // Let the validator handle error messages
210 parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
211 qApp->processEvents();
212 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
213 success = checkDocumentClips(infoproducers);
215 if (m_document.documentElement().attribute("modified") == "1") setModified(true);
216 parent->slotGotProgressInfo(i18n("Loading"), 0);
217 QDomElement mlt = m_document.firstChildElement("mlt");
218 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
220 // Set profile, fps, etc for the document
221 setProfilePath(infoXml.attribute("profile"));
223 // Check embedded effects
224 QDomElement customeffects = infoXml.firstChildElement("customeffects");
225 if (!customeffects.isNull() && customeffects.hasChildNodes()) {
226 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
227 qApp->processEvents();
228 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
233 QDomElement notesxml = infoXml.firstChildElement("documentnotes");
234 if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
237 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
238 if (!tracksinfo.isNull()) {
239 QDomNodeList trackslist = tracksinfo.childNodes();
240 int maxchild = trackslist.count();
241 for (int k = 0; k < maxchild; k++) {
242 e = trackslist.at(k).toElement();
243 if (e.tagName() == "trackinfo") {
244 TrackInfo projectTrack;
245 if (e.attribute("type") == "audio")
246 projectTrack.type = AUDIOTRACK;
248 projectTrack.type = VIDEOTRACK;
249 projectTrack.isMute = e.attribute("mute").toInt();
250 projectTrack.isBlind = e.attribute("blind").toInt();
251 projectTrack.isLocked = e.attribute("locked").toInt();
252 projectTrack.trackName = e.attribute("trackname");
253 projectTrack.effectsList = EffectsList(true);
254 m_tracksList.append(projectTrack);
257 mlt.removeChild(tracksinfo);
259 QStringList expandedFolders;
260 QDomNodeList folders = m_document.elementsByTagName("folder");
261 for (int i = 0; i < folders.count(); i++) {
262 e = folders.item(i).cloneNode().toElement();
263 if (e.hasAttribute("opened")) expandedFolders.append(e.attribute("id"));
264 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
266 m_documentProperties["expandedfolders"] = expandedFolders.join(";");
268 const int infomax = infoproducers.count();
269 QDomNodeList producers = m_document.elementsByTagName("producer");
270 const int max = producers.count();
272 if (!progressDialog) {
273 progressDialog = new KProgressDialog(parent, i18n("Loading project"), i18n("Adding clips"));
274 progressDialog->setAllowCancel(false);
276 progressDialog->setLabelText(i18n("Adding clips"));
278 progressDialog->progressBar()->setMaximum(infomax);
279 progressDialog->show();
280 qApp->processEvents();
282 for (int i = 0; i < infomax; i++) {
283 e = infoproducers.item(i).cloneNode().toElement();
284 QString prodId = e.attribute("id");
285 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
286 e.setTagName("producer");
287 // Get MLT's original producer properties
289 for (int j = 0; j < max; j++) {
290 QDomNode o = producers.item(j);
291 QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
292 if (origId == prodId) {
293 orig = o.cloneNode().toElement();
298 if (!addClipInfo(e, orig, prodId)) {
299 // The user manually aborted the loading.
301 emit resetProjectList();
302 m_tracksList.clear();
303 m_clipManager->clear();
308 progressDialog->progressBar()->setValue(i);
312 QDomElement markers = infoXml.firstChildElement("markers");
313 if (!markers.isNull()) {
314 QDomNodeList markerslist = markers.childNodes();
315 int maxchild = markerslist.count();
316 for (int k = 0; k < maxchild; k++) {
317 e = markerslist.at(k).toElement();
318 if (e.tagName() == "marker") {
319 CommentedTime marker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"), e.attribute("type").toInt());
320 DocClipBase *baseClip = m_clipManager->getClipById(e.attribute("id"));
321 if (baseClip) baseClip->addSnapMarker(marker);
322 else kDebug()<< " / / Warning, missing clip: "<< e.attribute("id");
325 infoXml.removeChild(markers);
328 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
329 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
330 QDomNamedNodeMap props = docproperties.attributes();
331 for (int i = 0; i < props.count(); i++)
332 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
333 docproperties = infoXml.firstChildElement("documentmetadata");
334 props = docproperties.attributes();
335 for (int i = 0; i < props.count(); i++)
336 m_documentMetadata.insert(props.item(i).nodeName(), props.item(i).nodeValue());
338 if (validator.isModified()) setModified(true);
339 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
345 KIO::NetAccess::removeTempFile(tmpFile);
349 // Something went wrong, or a new file was requested: create a new project
352 setProfilePath(profileName);
353 m_document = createEmptyDocument(tracks.x(), tracks.y());
356 // Ask to create the project directory if it does not exist
357 if (!QFile::exists(m_projectFolder.path())) {
358 int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
359 if (create == KMessageBox::Yes) {
360 QDir projectDir(m_projectFolder.path());
361 bool ok = projectDir.mkpath(m_projectFolder.path());
363 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
368 // Make sure the project folder is usable
369 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
370 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
371 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
374 // Make sure that the necessary folders exist
375 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
376 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
377 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/");
379 updateProjectFolderPlacesEntry();
381 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
382 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
383 connect(m_render, SIGNAL(addClip(const KUrl &, stringMap)), this, SLOT(slotAddClipFile(const KUrl &, stringMap)));
386 KdenliveDoc::~KdenliveDoc()
388 m_autoSaveTimer->stop();
389 delete m_commandStack;
390 kDebug() << "// DEL CLP MAN";
391 delete m_clipManager;
392 kDebug() << "// DEL CLP MAN done";
393 delete m_autoSaveTimer;
395 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
400 int KdenliveDoc::setSceneList()
402 m_render->resetProfile(KdenliveSettings::current_profile(), true);
403 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
404 // INVALID MLT Consumer, something is wrong
407 m_documentProperties.remove("position");
408 // m_document xml is now useless, clear it
413 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
415 m_tracksList.clear();
417 // Tracks are added «backwards», so we need to reverse the track numbering
418 // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
419 // Better default names for tracks: Audio 1 etc. instead of blank numbers
420 for (int i = 0; i < audiotracks; i++) {
421 TrackInfo audioTrack;
422 audioTrack.type = AUDIOTRACK;
423 audioTrack.isMute = false;
424 audioTrack.isBlind = true;
425 audioTrack.isLocked = false;
426 audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
427 audioTrack.duration = 0;
428 audioTrack.effectsList = EffectsList(true);
429 m_tracksList.append(audioTrack);
432 for (int i = 0; i < videotracks; i++) {
433 TrackInfo videoTrack;
434 videoTrack.type = VIDEOTRACK;
435 videoTrack.isMute = false;
436 videoTrack.isBlind = false;
437 videoTrack.isLocked = false;
438 videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
439 videoTrack.duration = 0;
440 videoTrack.effectsList = EffectsList(true);
441 m_tracksList.append(videoTrack);
443 return createEmptyDocument(m_tracksList);
446 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
448 // Creating new document
450 QDomElement mlt = doc.createElement("mlt");
451 mlt.setAttribute("LC_NUMERIC", "");
452 doc.appendChild(mlt);
454 // Create black producer
455 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
456 // the composite transitions with the black track are corrupted.
457 QDomElement blk = doc.createElement("producer");
458 blk.setAttribute("in", 0);
459 blk.setAttribute("out", 500);
460 blk.setAttribute("id", "black");
462 QDomElement property = doc.createElement("property");
463 property.setAttribute("name", "mlt_type");
464 QDomText value = doc.createTextNode("producer");
465 property.appendChild(value);
466 blk.appendChild(property);
468 property = doc.createElement("property");
469 property.setAttribute("name", "aspect_ratio");
470 value = doc.createTextNode(QString::number(0));
471 property.appendChild(value);
472 blk.appendChild(property);
474 property = doc.createElement("property");
475 property.setAttribute("name", "length");
476 value = doc.createTextNode(QString::number(15000));
477 property.appendChild(value);
478 blk.appendChild(property);
480 property = doc.createElement("property");
481 property.setAttribute("name", "eof");
482 value = doc.createTextNode("pause");
483 property.appendChild(value);
484 blk.appendChild(property);
486 property = doc.createElement("property");
487 property.setAttribute("name", "resource");
488 value = doc.createTextNode("black");
489 property.appendChild(value);
490 blk.appendChild(property);
492 property = doc.createElement("property");
493 property.setAttribute("name", "mlt_service");
494 value = doc.createTextNode("colour");
495 property.appendChild(value);
496 blk.appendChild(property);
498 mlt.appendChild(blk);
501 QDomElement tractor = doc.createElement("tractor");
502 tractor.setAttribute("id", "maintractor");
503 QDomElement multitrack = doc.createElement("multitrack");
504 QDomElement playlist = doc.createElement("playlist");
505 playlist.setAttribute("id", "black_track");
506 mlt.appendChild(playlist);
508 QDomElement blank0 = doc.createElement("entry");
509 blank0.setAttribute("in", "0");
510 blank0.setAttribute("out", "1");
511 blank0.setAttribute("producer", "black");
512 playlist.appendChild(blank0);
515 int total = tracks.count() + 1;
517 for (int i = 1; i < total; i++) {
518 QDomElement playlist = doc.createElement("playlist");
519 playlist.setAttribute("id", "playlist" + QString::number(i));
520 mlt.appendChild(playlist);
523 QDomElement track0 = doc.createElement("track");
524 track0.setAttribute("producer", "black_track");
525 tractor.appendChild(track0);
527 // create audio and video tracks
528 for (int i = 1; i < total; i++) {
529 QDomElement track = doc.createElement("track");
530 track.setAttribute("producer", "playlist" + QString::number(i));
531 if (tracks.at(i - 1).type == AUDIOTRACK) {
532 track.setAttribute("hide", "video");
533 } else if (tracks.at(i - 1).isBlind)
534 track.setAttribute("hide", "video");
535 if (tracks.at(i - 1).isMute)
536 track.setAttribute("hide", "audio");
537 tractor.appendChild(track);
540 for (int i = 2; i < total ; i++) {
541 QDomElement transition = doc.createElement("transition");
542 transition.setAttribute("always_active", "1");
544 QDomElement property = doc.createElement("property");
545 property.setAttribute("name", "a_track");
546 QDomText value = doc.createTextNode(QString::number(1));
547 property.appendChild(value);
548 transition.appendChild(property);
550 property = doc.createElement("property");
551 property.setAttribute("name", "b_track");
552 value = doc.createTextNode(QString::number(i));
553 property.appendChild(value);
554 transition.appendChild(property);
556 property = doc.createElement("property");
557 property.setAttribute("name", "mlt_service");
558 value = doc.createTextNode("mix");
559 property.appendChild(value);
560 transition.appendChild(property);
562 property = doc.createElement("property");
563 property.setAttribute("name", "combine");
564 value = doc.createTextNode("1");
565 property.appendChild(value);
566 transition.appendChild(property);
568 property = doc.createElement("property");
569 property.setAttribute("name", "internal_added");
570 value = doc.createTextNode("237");
571 property.appendChild(value);
572 transition.appendChild(property);
573 tractor.appendChild(transition);
575 mlt.appendChild(tractor);
580 void KdenliveDoc::syncGuides(QList <Guide *> guides)
583 QDomElement guideNode = m_guidesXml.createElement("guides");
584 m_guidesXml.appendChild(guideNode);
587 for (int i = 0; i < guides.count(); i++) {
588 e = m_guidesXml.createElement("guide");
589 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
590 e.setAttribute("comment", guides.at(i)->label());
591 guideNode.appendChild(e);
594 emit guidesUpdated();
597 QDomElement KdenliveDoc::guidesXml() const
599 return m_guidesXml.documentElement();
602 void KdenliveDoc::slotAutoSave()
604 if (m_render && m_autosave) {
605 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
606 // show error: could not open the autosave file
607 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
609 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
610 saveSceneList(m_autosave->fileName(), m_render->sceneList(), QStringList(), true);
614 void KdenliveDoc::setZoom(int horizontal, int vertical)
616 m_documentProperties["zoom"] = QString::number(horizontal);
617 m_documentProperties["verticalzoom"] = QString::number(vertical);
620 QPoint KdenliveDoc::zoom() const
622 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
625 void KdenliveDoc::setZone(int start, int end)
627 m_documentProperties["zonein"] = QString::number(start);
628 m_documentProperties["zoneout"] = QString::number(end);
631 QPoint KdenliveDoc::zone() const
633 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
636 QDomDocument KdenliveDoc::xmlSceneList(const QString &scene, const QStringList &expandedFolders)
638 QDomDocument sceneList;
639 sceneList.setContent(scene, true);
640 QDomElement mlt = sceneList.firstChildElement("mlt");
641 if (mlt.isNull() || !mlt.hasChildNodes()) {
642 //scenelist is corrupted
646 // Set playlist audio volume to 100%
647 QDomElement tractor = mlt.firstChildElement("tractor");
648 if (!tractor.isNull()) {
649 QDomNodeList props = tractor.elementsByTagName("property");
650 for (int i = 0; i < props.count(); i++) {
651 if (props.at(i).toElement().attribute("name") == "meta.volume") {
652 props.at(i).firstChild().setNodeValue("1");
658 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
659 mlt.appendChild(addedXml);
661 // check if project contains custom effects to embed them in project file
662 QDomNodeList effects = mlt.elementsByTagName("filter");
663 int maxEffects = effects.count();
664 kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
665 QMap <QString, QString> effectIds;
666 for (int i = 0; i < maxEffects; i++) {
667 QDomNode m = effects.at(i);
668 QDomNodeList params = m.childNodes();
671 for (int j = 0; j < params.count(); j++) {
672 QDomElement e = params.item(j).toElement();
673 if (e.attribute("name") == "kdenlive_id") {
674 id = e.firstChild().nodeValue();
676 if (e.attribute("name") == "tag") {
677 tag = e.firstChild().nodeValue();
679 if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
682 QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
683 addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
685 QDomElement markers = sceneList.createElement("markers");
686 addedXml.setAttribute("version", DOCUMENTVERSION);
687 addedXml.setAttribute("kdenliveversion", VERSION);
688 addedXml.setAttribute("profile", profilePath());
689 addedXml.setAttribute("projectfolder", m_projectFolder.path());
691 QDomElement docproperties = sceneList.createElement("documentproperties");
692 QMapIterator<QString, QString> i(m_documentProperties);
693 while (i.hasNext()) {
695 docproperties.setAttribute(i.key(), i.value());
697 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
698 addedXml.appendChild(docproperties);
700 QDomElement docmetadata = sceneList.createElement("documentmetadata");
701 QMapIterator<QString, QString> j(m_documentMetadata);
702 while (j.hasNext()) {
704 docmetadata.setAttribute(j.key(), j.value());
706 addedXml.appendChild(docmetadata);
708 QDomElement docnotes = sceneList.createElement("documentnotes");
709 QDomText value = sceneList.createTextNode(m_notesWidget->toHtml());
710 docnotes.appendChild(value);
711 addedXml.appendChild(docnotes);
714 QDomElement profileinfo = sceneList.createElement("profileinfo");
715 profileinfo.setAttribute("description", m_profile.description);
716 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
717 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
718 profileinfo.setAttribute("width", m_profile.width);
719 profileinfo.setAttribute("height", m_profile.height);
720 profileinfo.setAttribute("progressive", m_profile.progressive);
721 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
722 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
723 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
724 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
725 addedXml.appendChild(profileinfo);
728 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
729 foreach(const TrackInfo & info, m_tracksList) {
730 QDomElement trackinfo = sceneList.createElement("trackinfo");
731 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
732 trackinfo.setAttribute("mute", info.isMute);
733 trackinfo.setAttribute("blind", info.isBlind);
734 trackinfo.setAttribute("locked", info.isLocked);
735 trackinfo.setAttribute("trackname", info.trackName);
736 tracksinfo.appendChild(trackinfo);
738 addedXml.appendChild(tracksinfo);
740 // save project folders
741 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
743 QMapIterator<QString, QString> f(folderlist);
744 while (f.hasNext()) {
746 QDomElement folder = sceneList.createElement("folder");
747 folder.setAttribute("id", f.key());
748 folder.setAttribute("name", f.value());
749 if (expandedFolders.contains(f.key())) folder.setAttribute("opened", "1");
750 addedXml.appendChild(folder);
753 // Save project clips
755 QList <DocClipBase*> list = m_clipManager->documentClipList();
756 for (int i = 0; i < list.count(); i++) {
757 e = list.at(i)->toXML(true);
758 e.setTagName("kdenlive_producer");
759 addedXml.appendChild(sceneList.importNode(e, true));
760 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
761 for (int j = 0; j < marks.count(); j++) {
762 QDomElement marker = sceneList.createElement("marker");
763 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
764 marker.setAttribute("comment", marks.at(j).comment());
765 marker.setAttribute("id", e.attribute("id"));
766 marker.setAttribute("type", marks.at(j).markerType());
767 markers.appendChild(marker);
770 addedXml.appendChild(markers);
773 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
776 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
778 //wes.appendChild(doc.importNode(kdenliveData, true));
782 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene, const QStringList &expandedFolders, bool autosave)
784 QDomDocument sceneList = xmlSceneList(scene, expandedFolders);
785 if (sceneList.isNull()) {
786 //Make sure we don't save if scenelist is corrupted
787 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
791 // Backup current version
792 if (!autosave) backupLastSavedVersion(path);
795 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
796 kWarning() << "////// ERROR writing to file: " << path;
797 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
801 file.write(sceneList.toString().toUtf8());
802 if (file.error() != QFile::NoError) {
803 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
809 cleanupBackupFiles();
810 QFileInfo info(file);
811 QString fileName = KUrl(path).fileName().section('.', 0, -2);
812 fileName.append('-' + m_documentProperties.value("documentid"));
813 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
814 fileName.append(".kdenlive.png");
815 KUrl backupFile = m_projectFolder;
816 backupFile.addPath(".backup/");
817 backupFile.addPath(fileName);
818 emit saveTimelinePreview(backupFile.path());
823 ClipManager *KdenliveDoc::clipManager()
825 return m_clipManager;
828 KUrl KdenliveDoc::projectFolder() const
830 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
831 return m_projectFolder;
834 void KdenliveDoc::setProjectFolder(KUrl url)
836 if (url == m_projectFolder) return;
838 KStandardDirs::makeDir(url.path());
839 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
840 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
841 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?", m_projectFolder.path(), url.path())) == KMessageBox::Yes) moveProjectData(url);
842 m_projectFolder = url;
844 updateProjectFolderPlacesEntry();
847 void KdenliveDoc::moveProjectData(KUrl url)
849 QList <DocClipBase*> list = m_clipManager->documentClipList();
850 KUrl::List cacheUrls;
851 for (int i = 0; i < list.count(); i++) {
852 DocClipBase *clip = list.at(i);
853 if (clip->clipType() == TEXT) {
854 // the image for title clip must be moved
855 KUrl oldUrl = clip->fileURL();
856 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
857 KIO::Job *job = KIO::copy(oldUrl, newUrl);
858 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
860 QString hash = clip->getClipHash();
861 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
862 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
863 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
864 cacheUrls << oldVideoThumbUrl;
866 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
867 cacheUrls << oldAudioThumbUrl;
870 if (!cacheUrls.isEmpty()) {
871 KIO::Job *job = KIO::copy(cacheUrls, KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/"));
872 job->ui()->setWindow(kapp->activeWindow());
873 KIO::NetAccess::synchronousRun(job, 0);
877 const QString &KdenliveDoc::profilePath() const
879 return m_profile.path;
882 MltVideoProfile KdenliveDoc::mltProfile() const
887 bool KdenliveDoc::setProfilePath(QString path)
889 if (path.isEmpty()) path = KdenliveSettings::default_profile();
890 if (path.isEmpty()) path = "dv_pal";
891 m_profile = ProfilesDialog::getVideoProfile(path);
892 double current_fps = m_fps;
893 if (m_profile.path.isEmpty()) {
894 // Profile not found, use embedded profile
895 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
896 if (profileInfo.isNull()) {
897 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
898 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
900 m_profile.description = profileInfo.attribute("description");
901 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
902 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
903 m_profile.width = profileInfo.attribute("width").toInt();
904 m_profile.height = profileInfo.attribute("height").toInt();
905 m_profile.progressive = profileInfo.attribute("progressive").toInt();
906 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
907 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
908 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
909 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
910 QString existing = ProfilesDialog::existingProfile(m_profile);
911 if (!existing.isEmpty()) {
912 m_profile = ProfilesDialog::getVideoProfile(existing);
913 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
915 QString newDesc = m_profile.description;
917 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
918 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);
921 // User canceled, use default profile
922 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
924 if (newDesc != m_profile.description) {
925 // Profile description existed, was replaced by new one
926 m_profile.description = newDesc;
928 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
930 ProfilesDialog::saveProfile(m_profile);
937 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
938 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
939 KdenliveSettings::setProject_fps(m_fps);
940 m_width = m_profile.width;
941 m_height = m_profile.height;
942 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
943 m_timecode.setFormat(m_fps);
944 KdenliveSettings::setCurrent_profile(m_profile.path);
945 return (current_fps != m_fps);
948 double KdenliveDoc::dar() const
950 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
953 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
955 emit progressInfo(message, progress);
958 QUndoStack *KdenliveDoc::commandStack()
960 return m_commandStack;
964 void KdenliveDoc::setRenderer(Render *render) {
965 if (m_render) return;
967 emit progressInfo(i18n("Loading playlist..."), 0);
968 //qApp->processEvents();
970 m_render->setSceneList(m_document.toString(), m_startPos);
971 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
974 emit progressInfo(QString(), -1);
977 void KdenliveDoc::checkProjectClips(bool displayRatioChanged, bool fpsChanged)
979 if (m_render == NULL) return;
980 m_clipManager->resetProducersList(m_render->producersList(), displayRatioChanged, fpsChanged);
983 Render *KdenliveDoc::renderer()
988 void KdenliveDoc::updateClip(const QString &id)
990 emit updateClipDisplay(id);
993 int KdenliveDoc::getFramePos(QString duration)
995 return m_timecode.getFrameCount(duration);
998 QString KdenliveDoc::producerName(const QString &id)
1000 QString result = "unnamed";
1001 QDomNodeList prods = producersList();
1002 int ct = prods.count();
1003 for (int i = 0; i < ct ; i++) {
1004 QDomElement e = prods.item(i).toElement();
1005 if (e.attribute("id") != "black" && e.attribute("id") == id) {
1006 result = e.attribute("name");
1007 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
1014 QDomDocument KdenliveDoc::toXml()
1019 Timecode KdenliveDoc::timecode() const
1024 QDomNodeList KdenliveDoc::producersList()
1026 return m_document.elementsByTagName("producer");
1029 double KdenliveDoc::projectDuration() const
1032 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
1037 double KdenliveDoc::fps() const
1042 int KdenliveDoc::width() const
1047 int KdenliveDoc::height() const
1052 KUrl KdenliveDoc::url() const
1057 void KdenliveDoc::setUrl(KUrl url)
1062 void KdenliveDoc::setModified(bool mod)
1064 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
1065 m_autoSaveTimer->start(3000);
1067 if (mod == m_modified) return;
1069 emit docModified(m_modified);
1072 bool KdenliveDoc::isModified() const
1077 const QString KdenliveDoc::description() const
1079 if (m_url.isEmpty())
1080 return i18n("Untitled") + " / " + m_profile.description;
1082 return m_url.fileName() + " / " + m_profile.description;
1085 bool KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
1087 const QString producerId = clipId.section('_', 0, 0);
1088 DocClipBase *clip = m_clipManager->getClipById(producerId);
1091 elem.setAttribute("id", producerId);
1092 QString path = elem.attribute("resource");
1094 if (elem.attribute("type").toInt() == SLIDESHOW) {
1095 extension = KUrl(path).fileName();
1096 path = KUrl(path).directory();
1098 if (elem.hasAttribute("_missingsource")) {
1099 // Clip has proxy but missing original source
1101 else if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
1102 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1103 const QString size = elem.attribute("file_size");
1104 const QString hash = elem.attribute("file_hash");
1106 int action = KMessageBox::No;
1107 if (!size.isEmpty() && !hash.isEmpty()) {
1108 if (!m_searchFolder.isEmpty())
1109 newpath = searchFileRecursively(m_searchFolder, size, hash);
1111 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")));
1113 if (elem.attribute("type").toInt() == SLIDESHOW) {
1114 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")));
1115 if (res == KMessageBox::Yes)
1116 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1118 // Abort project loading
1122 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")));
1123 if (res == KMessageBox::Yes)
1124 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1126 // Abort project loading
1131 if (action == KMessageBox::Yes) {
1132 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1133 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1134 if (!m_searchFolder.isEmpty())
1135 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1136 } else if (action == KMessageBox::Cancel) {
1138 } else if (action == KMessageBox::No) {
1139 // Keep clip as placeHolder
1140 elem.setAttribute("placeholder", '1');
1142 if (!newpath.isEmpty()) {
1143 if (elem.attribute("type").toInt() == SLIDESHOW)
1144 newpath.append('/' + extension);
1145 elem.setAttribute("resource", newpath);
1146 setNewClipResource(clipId, newpath);
1150 clip = new DocClipBase(m_clipManager, elem, producerId);
1151 m_clipManager->addClip(clip);
1154 if (createClipItem) {
1155 emit addProjectClip(clip);
1161 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1163 QDomNodeList prods = m_document.elementsByTagName("producer");
1164 int maxprod = prods.count();
1165 for (int i = 0; i < maxprod; i++) {
1166 QDomNode m = prods.at(i);
1167 QString prodId = m.toElement().attribute("id");
1168 if (prodId == id || prodId.startsWith(id + '_')) {
1169 QDomNodeList params = m.childNodes();
1170 for (int j = 0; j < params.count(); j++) {
1171 QDomElement e = params.item(j).toElement();
1172 if (e.attribute("name") == "resource") {
1173 e.firstChild().setNodeValue(path);
1181 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1183 QString foundFileName;
1184 QByteArray fileData;
1185 QByteArray fileHash;
1186 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1187 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1188 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1189 if (file.open(QIODevice::ReadOnly)) {
1190 if (QString::number(file.size()) == matchSize) {
1192 * 1 MB = 1 second per 450 files (or faster)
1193 * 10 MB = 9 seconds per 450 files (or faster)
1195 if (file.size() > 1000000 * 2) {
1196 fileData = file.read(1000000);
1197 if (file.seek(file.size() - 1000000))
1198 fileData.append(file.readAll());
1200 fileData = file.readAll();
1202 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1203 if (QString(fileHash.toHex()) == matchHash)
1204 return file.fileName();
1207 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1209 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1210 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1211 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1212 if (!foundFileName.isEmpty())
1215 return foundFileName;
1218 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1220 DocClipBase *clip = m_clipManager->getClipById(clipId);
1222 if (!addClip(elem, clipId, false))
1225 QMap <QString, QString> properties;
1226 QDomNamedNodeMap attributes = elem.attributes();
1227 for (int i = 0; i < attributes.count(); i++) {
1228 QString attrname = attributes.item(i).nodeName();
1229 if (attrname != "resource")
1230 properties.insert(attrname, attributes.item(i).nodeValue());
1231 //kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1233 clip->setProperties(properties);
1234 emit addProjectClip(clip, false);
1236 if (orig != QDomElement()) {
1237 QMap<QString, QString> meta;
1238 for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1239 QString name = m.toElement().attribute("name");
1240 if (name.startsWith("meta.attr")) {
1241 if (name.endsWith(".markup")) name = name.section('.', 0, -2);
1242 meta.insert(name.section('.', 2, -1), m.firstChild().nodeValue());
1245 if (!meta.isEmpty()) {
1247 clip = m_clipManager->getClipById(clipId);
1249 clip->setMetadata(meta);
1256 void KdenliveDoc::deleteClip(const QString &clipId)
1258 emit signalDeleteProjectClip(clipId);
1261 void KdenliveDoc::slotAddClipList(const KUrl::List urls, stringMap data)
1263 m_clipManager->slotAddClipList(urls, data);
1264 //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1269 void KdenliveDoc::slotAddClipFile(const KUrl &url, stringMap data)
1271 m_clipManager->slotAddClipFile(url, data);
1272 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1276 const QString KdenliveDoc::getFreeClipId()
1278 return QString::number(m_clipManager->getFreeClipId());
1281 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1283 return m_clipManager->getClipById(clipId);
1286 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement xml, QString group, const QString &groupId)
1288 m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1290 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1293 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1295 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1297 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1300 void KdenliveDoc::slotCreateSlideshowClipFile(QMap <QString, QString> properties, QString group, const QString &groupId)
1302 m_clipManager->slotAddSlideshowClipFile(properties, group, groupId);
1304 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1307 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1309 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1310 KStandardDirs::makeDir(titlesFolder);
1311 QPointer<TitleWidget> dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1312 if (dia_ui->exec() == QDialog::Accepted) {
1313 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->duration(), dia_ui->xml().toString(), group, groupId);
1315 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1320 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1322 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1323 if (path.isEmpty()) {
1324 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1327 if (path.isEmpty()) return;
1329 //TODO: rewrite with new title system (just set resource)
1330 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1332 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1335 int KdenliveDoc::tracksCount() const
1337 return m_tracksList.count();
1340 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1342 if (ix < 0 || ix >= m_tracksList.count()) {
1343 kWarning() << "Track INFO outisde of range";
1346 return m_tracksList.at(ix);
1349 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1351 if (ix < 0 || ix >= m_tracksList.count()) {
1352 kWarning() << "SWITCH Track outisde of range";
1355 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1358 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1360 if (ix < 0 || ix >= m_tracksList.count()) {
1361 kWarning() << "Track Lock outisde of range";
1364 m_tracksList[ix].isLocked = lock;
1367 bool KdenliveDoc::isTrackLocked(int ix) const
1369 if (ix < 0 || ix >= m_tracksList.count()) {
1370 kWarning() << "Track Lock outisde of range";
1373 return m_tracksList.at(ix).isLocked;
1376 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1378 if (ix < 0 || ix >= m_tracksList.count()) {
1379 kWarning() << "SWITCH Track outisde of range";
1382 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1385 int KdenliveDoc::trackDuration(int ix)
1387 return m_tracksList.at(ix).duration;
1390 void KdenliveDoc::setTrackDuration(int ix, int duration)
1392 m_tracksList[ix].duration = duration;
1395 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1397 if (ix == -1) m_tracksList << type;
1398 else m_tracksList.insert(ix, type);
1401 void KdenliveDoc::deleteTrack(int ix)
1403 if (ix < 0 || ix >= m_tracksList.count()) {
1404 kWarning() << "Delete Track outisde of range";
1407 m_tracksList.removeAt(ix);
1410 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1412 if (ix < 0 || ix >= m_tracksList.count()) {
1413 kWarning() << "SET Track Type outisde of range";
1416 m_tracksList[ix].type = type.type;
1417 m_tracksList[ix].isMute = type.isMute;
1418 m_tracksList[ix].isBlind = type.isBlind;
1419 m_tracksList[ix].isLocked = type.isLocked;
1420 m_tracksList[ix].trackName = type.trackName;
1423 const QList <TrackInfo> KdenliveDoc::tracksList() const
1425 return m_tracksList;
1428 QPoint KdenliveDoc::getTracksCount() const
1432 foreach(const TrackInfo & info, m_tracksList) {
1433 if (info.type == VIDEOTRACK) video++;
1436 return QPoint(video, audio);
1439 void KdenliveDoc::cacheImage(const QString &fileId, const QImage &img) const
1441 img.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1444 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1446 DocumentChecker d(infoproducers, m_document);
1447 return (d.hasErrorInClips() == false);
1453 QList <QDomElement> missingClips;
1454 for (int i = 0; i < infoproducers.count(); i++) {
1455 e = infoproducers.item(i).toElement();
1456 clipType = e.attribute("type").toInt();
1457 if (clipType == COLOR) continue;
1458 if (clipType == TEXT) {
1459 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1462 id = e.attribute("id");
1463 resource = e.attribute("resource");
1464 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1465 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1466 // Missing clip found
1467 missingClips.append(e);
1469 // Check if the clip has changed
1470 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1471 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1472 e.removeAttribute("file_hash");
1476 if (missingClips.isEmpty()) return true;
1477 DocumentChecker d(missingClips, m_document);
1478 return (d.exec() == QDialog::Accepted);*/
1481 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1483 m_documentProperties[name] = value;
1486 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1488 return m_documentProperties.value(name);
1491 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1493 QMap <QString, QString> renderProperties;
1494 QMapIterator<QString, QString> i(m_documentProperties);
1495 while (i.hasNext()) {
1497 if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1499 return renderProperties;
1502 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1504 if (ix < 0 || ix >= m_tracksList.count()) {
1505 kWarning() << "Add Track effect outisde of range";
1508 effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1510 // Init parameter value & keyframes if required
1511 QDomNodeList params = effect.elementsByTagName("parameter");
1512 for (int i = 0; i < params.count(); i++) {
1513 QDomElement e = params.item(i).toElement();
1515 // Check if this effect has a variable parameter
1516 if (e.attribute("default").contains('%')) {
1517 double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1518 e.setAttribute("default", evaluatedValue);
1519 if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1520 e.setAttribute("value", evaluatedValue);
1524 if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1525 QString def = e.attribute("default");
1526 // Effect has a keyframe type parameter, we need to set the values
1527 if (e.attribute("keyframes").isEmpty()) {
1528 e.setAttribute("keyframes", "0:" + def + ';');
1529 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1534 if (effect.attribute("id") == "crop") {
1535 // default use_profile to 1 for clips with proxies to avoid problems when rendering
1536 if (e.attribute("name") == "use_profile" && getDocumentProperty("enableproxy") == "1")
1537 e.setAttribute("value", "1");
1541 m_tracksList[ix].effectsList.append(effect);
1544 void KdenliveDoc::removeTrackEffect(int ix, QDomElement effect)
1546 if (ix < 0 || ix >= m_tracksList.count()) {
1547 kWarning() << "Remove Track effect outisde of range";
1551 int toRemove = effect.attribute("kdenlive_ix").toInt();
1552 for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1553 index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix").toInt();
1554 if (toRemove == index) {
1555 m_tracksList[ix].effectsList.removeAt(toRemove);
1561 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1563 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1564 kWarning() << "Set Track effect outisde of range";
1567 if (effectIndex <= 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count()) || effect.isNull()) {
1568 kDebug() << "Invalid effect index: " << effectIndex;
1571 m_tracksList[trackIndex].effectsList.removeAt(effect.attribute("kdenlive_ix").toInt());
1572 effect.setAttribute("kdenlive_ix", effectIndex);
1573 m_tracksList[trackIndex].effectsList.insert(effect);
1574 //m_tracksList[trackIndex].effectsList.updateEffect(effect);
1577 void KdenliveDoc::enableTrackEffects(int trackIndex, QList <int> effectIndexes, bool disable)
1579 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1580 kWarning() << "Set Track effect outisde of range";
1583 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1585 for (int i = 0; i < effectIndexes.count(); i++) {
1586 effect = list.itemFromIndex(effectIndexes.at(i));
1587 if (!effect.isNull()) effect.setAttribute("disable", (int) disable);
1591 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1593 if (ix < 0 || ix >= m_tracksList.count()) {
1594 kWarning() << "Get Track effects outisde of range";
1595 return EffectsList();
1597 return m_tracksList.at(ix).effectsList;
1600 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1602 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1603 kWarning() << "Get Track effect outisde of range";
1604 return QDomElement();
1606 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1607 if (effectIndex > list.count() || effectIndex < 1 || list.itemFromIndex(effectIndex).isNull()) return QDomElement();
1608 return list.itemFromIndex(effectIndex).cloneNode().toElement();
1611 int KdenliveDoc::hasTrackEffect(int trackIndex, const QString &tag, const QString &id) const
1613 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1614 kWarning() << "Get Track effect outisde of range";
1617 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1618 return list.hasEffect(tag, id);
1621 bool KdenliveDoc::saveCustomEffects(QDomNodeList customeffects)
1624 QStringList importedEffects;
1625 int maxchild = customeffects.count();
1626 for (int i = 0; i < maxchild; i++) {
1627 e = customeffects.at(i).toElement();
1628 QString id = e.attribute("id");
1629 QString tag = e.attribute("tag");
1630 if (!id.isEmpty()) {
1631 // Check if effect exists or save it
1632 if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1634 doc.appendChild(doc.importNode(e, true));
1635 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1636 path += id + ".xml";
1637 if (!QFile::exists(path)) {
1638 importedEffects << id;
1640 if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1641 QTextStream out(&file);
1642 out << doc.toString();
1648 if (!importedEffects.isEmpty()) KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1649 return (!importedEffects.isEmpty());
1652 void KdenliveDoc::updateProjectFolderPlacesEntry()
1655 * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1656 * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1659 const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1660 KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1661 if (!bookmarkManager) return;
1662 KBookmarkGroup root = bookmarkManager->root();
1664 KBookmark bookmark = root.first();
1666 QString kdenliveName = KGlobal::mainComponent().componentName();
1667 KUrl documentLocation = m_projectFolder;
1669 bool exists = false;
1671 while (!bookmark.isNull()) {
1672 // UDI not empty indicates a device
1673 QString udi = bookmark.metaDataItem("UDI");
1674 QString appName = bookmark.metaDataItem("OnlyInApp");
1676 if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1677 if (bookmark.url() != documentLocation) {
1678 bookmark.setUrl(documentLocation);
1679 bookmarkManager->emitChanged(root);
1685 bookmark = root.next(bookmark);
1688 // if entry does not exist yet (was not found), well, create it then
1690 bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1691 // Make this user selectable ?
1692 bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1693 bookmarkManager->emitChanged(root);
1697 QStringList KdenliveDoc::getExpandedFolders()
1699 QStringList result = m_documentProperties.value("expandedfolders").split(';');
1700 // this property is only needed once when opening project, so clear it now
1701 m_documentProperties.remove("expandedfolders");
1706 double KdenliveDoc::getDisplayRatio(const QString &path)
1710 if (!file.open(QIODevice::ReadOnly)) {
1711 kWarning() << "ERROR, CANNOT READ: " << path;
1714 if (!doc.setContent(&file)) {
1715 kWarning() << "ERROR, CANNOT READ: " << path;
1720 QDomNodeList list = doc.elementsByTagName("profile");
1721 if (list.isEmpty()) return 0;
1722 QDomElement profile = list.at(0).toElement();
1723 double den = profile.attribute("display_aspect_den").toDouble();
1724 if (den > 0) return profile.attribute("display_aspect_num").toDouble() / den;
1728 void KdenliveDoc::backupLastSavedVersion(const QString &path)
1730 // Ensure backup folder exists
1731 if (path.isEmpty()) return;
1733 KUrl backupFile = m_projectFolder;
1734 backupFile.addPath(".backup/");
1735 KIO::NetAccess::mkdir(backupFile, kapp->activeWindow());
1736 QString fileName = KUrl(path).fileName().section('.', 0, -2);
1737 QFileInfo info(file);
1738 fileName.append('-' + m_documentProperties.value("documentid"));
1739 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
1740 fileName.append(".kdenlive");
1741 backupFile.addPath(fileName);
1743 if (file.exists()) {
1744 // delete previous backup if it was done less than 60 seconds ago
1745 QFile::remove(backupFile.path());
1746 if (!QFile::copy(path, backupFile.path())) {
1747 KMessageBox::information(kapp->activeWindow(), i18n("Cannot create backup copy:\n%1", backupFile.path()));
1752 void KdenliveDoc::cleanupBackupFiles()
1754 KUrl backupFile = m_projectFolder;
1755 backupFile.addPath(".backup/");
1756 QDir dir(backupFile.path());
1757 QString projectFile = url().fileName().section('.', 0, -2);
1758 projectFile.append('-' + m_documentProperties.value("documentid"));
1759 projectFile.append("-??");
1760 projectFile.append("??");
1761 projectFile.append("-??");
1762 projectFile.append("-??");
1763 projectFile.append("-??");
1764 projectFile.append("-??.kdenlive");
1767 backupFile.addPath(projectFile);
1768 filter << projectFile;
1769 dir.setNameFilters(filter);
1770 QFileInfoList resultList = dir.entryInfoList(QDir::Files, QDir::Time);
1772 QDateTime d = QDateTime::currentDateTime();
1773 QStringList hourList;
1774 QStringList dayList;
1775 QStringList weekList;
1776 QStringList oldList;
1777 for (int i = 0; i < resultList.count(); i++) {
1778 if (d.secsTo(resultList.at(i).lastModified()) < 3600) {
1779 // files created in the last hour
1780 hourList.append(resultList.at(i).absoluteFilePath());
1782 else if (d.secsTo(resultList.at(i).lastModified()) < 43200) {
1783 // files created in the day
1784 dayList.append(resultList.at(i).absoluteFilePath());
1786 else if (d.daysTo(resultList.at(i).lastModified()) < 8) {
1787 // files created in the week
1788 weekList.append(resultList.at(i).absoluteFilePath());
1792 oldList.append(resultList.at(i).absoluteFilePath());
1795 if (hourList.count() > 20) {
1796 int step = hourList.count() / 10;
1797 for (int i = 0; i < hourList.count(); i += step) {
1798 kDebug()<<"REMOVE AT: "<<i<<", COUNT: "<<hourList.count();
1799 hourList.removeAt(i);
1802 } else hourList.clear();
1803 if (dayList.count() > 20) {
1804 int step = dayList.count() / 10;
1805 for (int i = 0; i < dayList.count(); i += step) {
1806 dayList.removeAt(i);
1809 } else dayList.clear();
1810 if (weekList.count() > 20) {
1811 int step = weekList.count() / 10;
1812 for (int i = 0; i < weekList.count(); i += step) {
1813 weekList.removeAt(i);
1816 } else weekList.clear();
1817 if (oldList.count() > 20) {
1818 int step = oldList.count() / 10;
1819 for (int i = 0; i < oldList.count(); i += step) {
1820 oldList.removeAt(i);
1823 } else oldList.clear();
1826 while (hourList.count() > 0) {
1827 f = hourList.takeFirst();
1829 QFile::remove(f + ".png");
1831 while (dayList.count() > 0) {
1832 f = dayList.takeFirst();
1834 QFile::remove(f + ".png");
1836 while (weekList.count() > 0) {
1837 f = weekList.takeFirst();
1839 QFile::remove(f + ".png");
1841 while (oldList.count() > 0) {
1842 f = oldList.takeFirst();
1844 QFile::remove(f + ".png");
1848 const QMap <QString, QString> KdenliveDoc::metadata() const
1850 return m_documentMetadata;
1853 void KdenliveDoc::setMetadata(const QMap <QString, QString> meta)
1856 m_documentMetadata = meta;
1859 #include "kdenlivedoc.moc"