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>
53 #include <QTextBoundaryFinder>
55 #include <mlt++/Mlt.h>
60 const double DOCUMENTVERSION = 0.88;
62 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) :
68 m_commandStack(new QUndoStack(undoGroup)),
70 m_projectFolder(projectFolder)
72 // init m_profile struct
73 m_profile.frame_rate_num = 0;
74 m_profile.frame_rate_den = 0;
77 m_profile.progressive = 0;
78 m_profile.sample_aspect_num = 0;
79 m_profile.sample_aspect_den = 0;
80 m_profile.display_aspect_num = 0;
81 m_profile.display_aspect_den = 0;
82 m_profile.colorspace = 0;
84 m_clipManager = new ClipManager(this);
85 m_autoSaveTimer = new QTimer(this);
86 m_autoSaveTimer->setSingleShot(true);
87 connect(m_clipManager, SIGNAL(displayMessage(QString, int)), parent, SLOT(slotGotProgressInfo(QString,int)));
90 // init default document properties
91 m_documentProperties["zoom"] = '7';
92 m_documentProperties["verticalzoom"] = '1';
93 m_documentProperties["zonein"] = '0';
94 m_documentProperties["zoneout"] = "100";
95 m_documentProperties["enableproxy"] = QString::number((int) KdenliveSettings::enableproxy());
96 m_documentProperties["proxyparams"] = KdenliveSettings::proxyparams();
97 m_documentProperties["proxyextension"] = KdenliveSettings::proxyextension();
98 m_documentProperties["generateproxy"] = QString::number((int) KdenliveSettings::generateproxy());
99 m_documentProperties["proxyminsize"] = QString::number(KdenliveSettings::proxyminsize());
100 m_documentProperties["generateimageproxy"] = QString::number((int) KdenliveSettings::generateimageproxy());
101 m_documentProperties["proxyimageminsize"] = QString::number(KdenliveSettings::proxyimageminsize());
102 #if QT_VERSION >= 0x040700
103 m_documentProperties["documentid"] = QString::number(QDateTime::currentMSecsSinceEpoch());
105 QDateTime date = QDateTime::currentDateTime();
106 m_documentProperties["documentid"] = QString::number(date.toTime_t());
110 QMapIterator<QString, QString> i(properties);
111 while (i.hasNext()) {
113 m_documentProperties[i.key()] = i.value();
117 QMapIterator<QString, QString> j(metadata);
118 while (j.hasNext()) {
120 m_documentMetadata[j.key()] = j.value();
123 if (QLocale().decimalPoint() != QLocale::system().decimalPoint()) {
124 setlocale(LC_NUMERIC, "");
125 QLocale systemLocale = QLocale::system();
126 systemLocale.setNumberOptions(QLocale::OmitGroupSeparator);
127 QLocale::setDefault(systemLocale);
128 // locale conversion might need to be redone
129 initEffects::parseEffectFiles(setlocale(LC_NUMERIC, NULL));
134 if (!url.isEmpty()) {
136 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
138 // The file cannot be opened
139 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) {
142 //KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
149 QDomImplementation::setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
150 success = m_document.setContent(&file, false, &errorMsg, &line, &col);
155 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")));
156 if (answer == KMessageBox::Yes) {
159 else if (answer == KMessageBox::No) {
160 // Try to recover broken file produced by Kdenlive 0.9.4
161 if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
163 QString playlist = file.readAll();
164 while (!success && correction < 2) {
168 for (int j = 0; j < line && errorPos < playlist.length(); j++) {
169 errorPos = playlist.indexOf("\n", errorPos);
173 if (errorPos >= playlist.length()) break;
174 playlist.remove(errorPos, 1);
177 success = m_document.setContent(playlist, false, &errorMsg, &line, &col);
181 KMessageBox::sorry(parent, i18n("Cannot recover this project file"));
184 // Document was modified, ask for backup
185 QDomElement mlt = m_document.documentElement();
186 QDomElement info = mlt.firstChildElement("kdenlivedoc");
187 if (!info.isNull()) info.setAttribute("modified", 1);
193 parent->slotGotProgressInfo(i18n("Validating"), 0);
194 qApp->processEvents();
195 DocumentValidator validator(m_document, url);
196 success = validator.isProject();
198 // It is not a project file
199 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
200 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) {
205 * Validate the file against the current version (upgrade
206 * and recover it if needed). It is NOT a passive operation
208 // TODO: backup the document or alert the user?
209 success = validator.validate(DOCUMENTVERSION);
210 if (success) { // Let the validator handle error messages
211 parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
212 qApp->processEvents();
213 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
214 success = checkDocumentClips(infoproducers);
216 if (m_document.documentElement().attribute("modified") == "1") setModified(true);
217 parent->slotGotProgressInfo(i18n("Loading"), 0);
218 QDomElement mlt = m_document.firstChildElement("mlt");
219 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
221 // Set profile, fps, etc for the document
222 setProfilePath(infoXml.attribute("profile"));
224 // Check embedded effects
225 QDomElement customeffects = infoXml.firstChildElement("customeffects");
226 if (!customeffects.isNull() && customeffects.hasChildNodes()) {
227 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
228 qApp->processEvents();
229 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
234 QDomElement notesxml = infoXml.firstChildElement("documentnotes");
235 if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
238 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
239 if (!tracksinfo.isNull()) {
240 QDomNodeList trackslist = tracksinfo.childNodes();
241 int maxchild = trackslist.count();
242 for (int k = 0; k < maxchild; k++) {
243 e = trackslist.at(k).toElement();
244 if (e.tagName() == "trackinfo") {
245 TrackInfo projectTrack;
246 if (e.attribute("type") == "audio")
247 projectTrack.type = AUDIOTRACK;
249 projectTrack.type = VIDEOTRACK;
250 projectTrack.isMute = e.attribute("mute").toInt();
251 projectTrack.isBlind = e.attribute("blind").toInt();
252 projectTrack.isLocked = e.attribute("locked").toInt();
253 projectTrack.trackName = e.attribute("trackname");
254 projectTrack.effectsList = EffectsList(true);
255 m_tracksList.append(projectTrack);
258 mlt.removeChild(tracksinfo);
260 QStringList expandedFolders;
261 QDomNodeList folders = m_document.elementsByTagName("folder");
262 for (int i = 0; i < folders.count(); i++) {
263 e = folders.item(i).cloneNode().toElement();
264 if (e.hasAttribute("opened")) expandedFolders.append(e.attribute("id"));
265 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
267 m_documentProperties["expandedfolders"] = expandedFolders.join(";");
269 const int infomax = infoproducers.count();
270 QDomNodeList producers = m_document.elementsByTagName("producer");
271 const int max = producers.count();
273 if (!progressDialog) {
274 progressDialog = new KProgressDialog(parent, i18n("Loading project"), i18n("Adding clips"));
275 progressDialog->setAllowCancel(false);
277 progressDialog->setLabelText(i18n("Adding clips"));
279 progressDialog->progressBar()->setMaximum(infomax);
280 progressDialog->show();
281 qApp->processEvents();
283 for (int i = 0; i < infomax; i++) {
284 e = infoproducers.item(i).cloneNode().toElement();
285 QString prodId = e.attribute("id");
286 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
287 e.setTagName("producer");
288 // Get MLT's original producer properties
290 for (int j = 0; j < max; j++) {
291 QDomNode o = producers.item(j);
292 QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
293 if (origId == prodId) {
294 orig = o.cloneNode().toElement();
299 if (!addClipInfo(e, orig, prodId)) {
300 // The user manually aborted the loading.
302 emit resetProjectList();
303 m_tracksList.clear();
304 m_clipManager->clear();
309 progressDialog->progressBar()->setValue(i);
313 QDomElement markers = infoXml.firstChildElement("markers");
314 if (!markers.isNull()) {
315 QDomNodeList markerslist = markers.childNodes();
316 int maxchild = markerslist.count();
317 for (int k = 0; k < maxchild; k++) {
318 e = markerslist.at(k).toElement();
319 if (e.tagName() == "marker") {
320 CommentedTime marker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"), e.attribute("type").toInt());
321 DocClipBase *baseClip = m_clipManager->getClipById(e.attribute("id"));
322 if (baseClip) baseClip->addSnapMarker(marker);
323 else kDebug()<< " / / Warning, missing clip: "<< e.attribute("id");
326 infoXml.removeChild(markers);
329 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
330 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
331 QDomNamedNodeMap props = docproperties.attributes();
332 for (int i = 0; i < props.count(); i++)
333 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
334 docproperties = infoXml.firstChildElement("documentmetadata");
335 props = docproperties.attributes();
336 for (int i = 0; i < props.count(); i++)
337 m_documentMetadata.insert(props.item(i).nodeName(), props.item(i).nodeValue());
339 if (validator.isModified()) setModified(true);
340 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
346 KIO::NetAccess::removeTempFile(tmpFile);
350 // Something went wrong, or a new file was requested: create a new project
353 setProfilePath(profileName);
354 m_document = createEmptyDocument(tracks.x(), tracks.y());
357 // Ask to create the project directory if it does not exist
358 if (!QFile::exists(m_projectFolder.path())) {
359 int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
360 if (create == KMessageBox::Yes) {
361 QDir projectDir(m_projectFolder.path());
362 bool ok = projectDir.mkpath(m_projectFolder.path());
364 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
369 // Make sure the project folder is usable
370 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
371 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
372 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
375 // Make sure that the necessary folders exist
376 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
377 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
378 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/");
380 updateProjectFolderPlacesEntry();
382 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
383 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
384 connect(m_render, SIGNAL(addClip(const KUrl &, stringMap)), this, SLOT(slotAddClipFile(const KUrl &, stringMap)));
387 KdenliveDoc::~KdenliveDoc()
389 m_autoSaveTimer->stop();
390 delete m_commandStack;
391 kDebug() << "// DEL CLP MAN";
392 delete m_clipManager;
393 kDebug() << "// DEL CLP MAN done";
394 delete m_autoSaveTimer;
396 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
401 int KdenliveDoc::setSceneList()
403 m_render->resetProfile(KdenliveSettings::current_profile(), true);
404 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
405 // INVALID MLT Consumer, something is wrong
408 m_documentProperties.remove("position");
409 // m_document xml is now useless, clear it
414 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
416 m_tracksList.clear();
418 // Tracks are added «backwards», so we need to reverse the track numbering
419 // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
420 // Better default names for tracks: Audio 1 etc. instead of blank numbers
421 for (int i = 0; i < audiotracks; i++) {
422 TrackInfo audioTrack;
423 audioTrack.type = AUDIOTRACK;
424 audioTrack.isMute = false;
425 audioTrack.isBlind = true;
426 audioTrack.isLocked = false;
427 audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
428 audioTrack.duration = 0;
429 audioTrack.effectsList = EffectsList(true);
430 m_tracksList.append(audioTrack);
433 for (int i = 0; i < videotracks; i++) {
434 TrackInfo videoTrack;
435 videoTrack.type = VIDEOTRACK;
436 videoTrack.isMute = false;
437 videoTrack.isBlind = false;
438 videoTrack.isLocked = false;
439 videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
440 videoTrack.duration = 0;
441 videoTrack.effectsList = EffectsList(true);
442 m_tracksList.append(videoTrack);
444 return createEmptyDocument(m_tracksList);
447 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
449 // Creating new document
451 QDomElement mlt = doc.createElement("mlt");
452 mlt.setAttribute("LC_NUMERIC", "");
453 doc.appendChild(mlt);
455 // Create black producer
456 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
457 // the composite transitions with the black track are corrupted.
458 QDomElement blk = doc.createElement("producer");
459 blk.setAttribute("in", 0);
460 blk.setAttribute("out", 500);
461 blk.setAttribute("id", "black");
463 QDomElement property = doc.createElement("property");
464 property.setAttribute("name", "mlt_type");
465 QDomText value = doc.createTextNode("producer");
466 property.appendChild(value);
467 blk.appendChild(property);
469 property = doc.createElement("property");
470 property.setAttribute("name", "aspect_ratio");
471 value = doc.createTextNode(QString::number(0));
472 property.appendChild(value);
473 blk.appendChild(property);
475 property = doc.createElement("property");
476 property.setAttribute("name", "length");
477 value = doc.createTextNode(QString::number(15000));
478 property.appendChild(value);
479 blk.appendChild(property);
481 property = doc.createElement("property");
482 property.setAttribute("name", "eof");
483 value = doc.createTextNode("pause");
484 property.appendChild(value);
485 blk.appendChild(property);
487 property = doc.createElement("property");
488 property.setAttribute("name", "resource");
489 value = doc.createTextNode("black");
490 property.appendChild(value);
491 blk.appendChild(property);
493 property = doc.createElement("property");
494 property.setAttribute("name", "mlt_service");
495 value = doc.createTextNode("colour");
496 property.appendChild(value);
497 blk.appendChild(property);
499 mlt.appendChild(blk);
502 QDomElement tractor = doc.createElement("tractor");
503 tractor.setAttribute("id", "maintractor");
504 QDomElement multitrack = doc.createElement("multitrack");
505 QDomElement playlist = doc.createElement("playlist");
506 playlist.setAttribute("id", "black_track");
507 mlt.appendChild(playlist);
509 QDomElement blank0 = doc.createElement("entry");
510 blank0.setAttribute("in", "0");
511 blank0.setAttribute("out", "1");
512 blank0.setAttribute("producer", "black");
513 playlist.appendChild(blank0);
516 int total = tracks.count() + 1;
518 for (int i = 1; i < total; i++) {
519 QDomElement playlist = doc.createElement("playlist");
520 playlist.setAttribute("id", "playlist" + QString::number(i));
521 mlt.appendChild(playlist);
524 QDomElement track0 = doc.createElement("track");
525 track0.setAttribute("producer", "black_track");
526 tractor.appendChild(track0);
528 // create audio and video tracks
529 for (int i = 1; i < total; i++) {
530 QDomElement track = doc.createElement("track");
531 track.setAttribute("producer", "playlist" + QString::number(i));
532 if (tracks.at(i - 1).type == AUDIOTRACK) {
533 track.setAttribute("hide", "video");
534 } else if (tracks.at(i - 1).isBlind)
535 track.setAttribute("hide", "video");
536 if (tracks.at(i - 1).isMute)
537 track.setAttribute("hide", "audio");
538 tractor.appendChild(track);
541 for (int i = 2; i < total ; i++) {
542 QDomElement transition = doc.createElement("transition");
543 transition.setAttribute("always_active", "1");
545 QDomElement property = doc.createElement("property");
546 property.setAttribute("name", "a_track");
547 QDomText value = doc.createTextNode(QString::number(1));
548 property.appendChild(value);
549 transition.appendChild(property);
551 property = doc.createElement("property");
552 property.setAttribute("name", "b_track");
553 value = doc.createTextNode(QString::number(i));
554 property.appendChild(value);
555 transition.appendChild(property);
557 property = doc.createElement("property");
558 property.setAttribute("name", "mlt_service");
559 value = doc.createTextNode("mix");
560 property.appendChild(value);
561 transition.appendChild(property);
563 property = doc.createElement("property");
564 property.setAttribute("name", "combine");
565 value = doc.createTextNode("1");
566 property.appendChild(value);
567 transition.appendChild(property);
569 property = doc.createElement("property");
570 property.setAttribute("name", "internal_added");
571 value = doc.createTextNode("237");
572 property.appendChild(value);
573 transition.appendChild(property);
574 tractor.appendChild(transition);
576 mlt.appendChild(tractor);
581 void KdenliveDoc::syncGuides(QList <Guide *> guides)
584 QDomElement guideNode = m_guidesXml.createElement("guides");
585 m_guidesXml.appendChild(guideNode);
588 for (int i = 0; i < guides.count(); i++) {
589 e = m_guidesXml.createElement("guide");
590 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
591 e.setAttribute("comment", guides.at(i)->label());
592 guideNode.appendChild(e);
595 emit guidesUpdated();
598 QDomElement KdenliveDoc::guidesXml() const
600 return m_guidesXml.documentElement();
603 void KdenliveDoc::slotAutoSave()
605 if (m_render && m_autosave) {
606 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
607 // show error: could not open the autosave file
608 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
610 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
611 saveSceneList(m_autosave->fileName(), m_render->sceneList(), QStringList(), true);
615 void KdenliveDoc::setZoom(int horizontal, int vertical)
617 m_documentProperties["zoom"] = QString::number(horizontal);
618 m_documentProperties["verticalzoom"] = QString::number(vertical);
621 QPoint KdenliveDoc::zoom() const
623 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
626 void KdenliveDoc::setZone(int start, int end)
628 m_documentProperties["zonein"] = QString::number(start);
629 m_documentProperties["zoneout"] = QString::number(end);
632 QPoint KdenliveDoc::zone() const
634 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
637 QDomDocument KdenliveDoc::xmlSceneList(const QString &scene, const QStringList &expandedFolders)
639 QDomDocument sceneList;
640 sceneList.setContent(scene, true);
641 QDomElement mlt = sceneList.firstChildElement("mlt");
642 if (mlt.isNull() || !mlt.hasChildNodes()) {
643 //scenelist is corrupted
647 // Set playlist audio volume to 100%
648 QDomElement tractor = mlt.firstChildElement("tractor");
649 if (!tractor.isNull()) {
650 QDomNodeList props = tractor.elementsByTagName("property");
651 for (int i = 0; i < props.count(); i++) {
652 if (props.at(i).toElement().attribute("name") == "meta.volume") {
653 props.at(i).firstChild().setNodeValue("1");
659 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
660 mlt.appendChild(addedXml);
662 // check if project contains custom effects to embed them in project file
663 QDomNodeList effects = mlt.elementsByTagName("filter");
664 int maxEffects = effects.count();
665 kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
666 QMap <QString, QString> effectIds;
667 for (int i = 0; i < maxEffects; i++) {
668 QDomNode m = effects.at(i);
669 QDomNodeList params = m.childNodes();
672 for (int j = 0; j < params.count(); j++) {
673 QDomElement e = params.item(j).toElement();
674 if (e.attribute("name") == "kdenlive_id") {
675 id = e.firstChild().nodeValue();
677 if (e.attribute("name") == "tag") {
678 tag = e.firstChild().nodeValue();
680 if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
683 QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
684 addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
686 QDomElement markers = sceneList.createElement("markers");
687 addedXml.setAttribute("version", DOCUMENTVERSION);
688 addedXml.setAttribute("kdenliveversion", VERSION);
689 addedXml.setAttribute("profile", profilePath());
690 addedXml.setAttribute("projectfolder", m_projectFolder.path());
692 QDomElement docproperties = sceneList.createElement("documentproperties");
693 QMapIterator<QString, QString> i(m_documentProperties);
694 while (i.hasNext()) {
696 docproperties.setAttribute(i.key(), i.value());
698 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
699 addedXml.appendChild(docproperties);
701 QDomElement docmetadata = sceneList.createElement("documentmetadata");
702 QMapIterator<QString, QString> j(m_documentMetadata);
703 while (j.hasNext()) {
705 docmetadata.setAttribute(j.key(), j.value());
707 addedXml.appendChild(docmetadata);
709 QDomElement docnotes = sceneList.createElement("documentnotes");
710 QDomText value = sceneList.createTextNode(m_notesWidget->toHtml());
711 docnotes.appendChild(value);
712 addedXml.appendChild(docnotes);
715 QDomElement profileinfo = sceneList.createElement("profileinfo");
716 profileinfo.setAttribute("description", m_profile.description);
717 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
718 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
719 profileinfo.setAttribute("width", m_profile.width);
720 profileinfo.setAttribute("height", m_profile.height);
721 profileinfo.setAttribute("progressive", m_profile.progressive);
722 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
723 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
724 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
725 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
726 addedXml.appendChild(profileinfo);
729 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
730 foreach(const TrackInfo & info, m_tracksList) {
731 QDomElement trackinfo = sceneList.createElement("trackinfo");
732 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
733 trackinfo.setAttribute("mute", info.isMute);
734 trackinfo.setAttribute("blind", info.isBlind);
735 trackinfo.setAttribute("locked", info.isLocked);
736 trackinfo.setAttribute("trackname", info.trackName);
737 tracksinfo.appendChild(trackinfo);
739 addedXml.appendChild(tracksinfo);
741 // save project folders
742 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
744 QMapIterator<QString, QString> f(folderlist);
745 while (f.hasNext()) {
747 QDomElement folder = sceneList.createElement("folder");
748 folder.setAttribute("id", f.key());
749 folder.setAttribute("name", f.value());
750 if (expandedFolders.contains(f.key())) folder.setAttribute("opened", "1");
751 addedXml.appendChild(folder);
754 // Save project clips
756 QList <DocClipBase*> list = m_clipManager->documentClipList();
757 for (int i = 0; i < list.count(); i++) {
758 e = list.at(i)->toXML(true);
759 e.setTagName("kdenlive_producer");
760 addedXml.appendChild(sceneList.importNode(e, true));
761 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
762 for (int j = 0; j < marks.count(); j++) {
763 QDomElement marker = sceneList.createElement("marker");
764 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
765 marker.setAttribute("comment", marks.at(j).comment());
766 marker.setAttribute("id", e.attribute("id"));
767 marker.setAttribute("type", marks.at(j).markerType());
768 markers.appendChild(marker);
771 addedXml.appendChild(markers);
774 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
777 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
779 //wes.appendChild(doc.importNode(kdenliveData, true));
783 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene, const QStringList &expandedFolders, bool autosave)
785 QDomDocument sceneList = xmlSceneList(scene, expandedFolders);
786 if (sceneList.isNull()) {
787 //Make sure we don't save if scenelist is corrupted
788 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
792 // Backup current version
793 if (!autosave) backupLastSavedVersion(path);
796 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
797 kWarning() << "////// ERROR writing to file: " << path;
798 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
802 file.write(sceneList.toString().toUtf8());
803 if (file.error() != QFile::NoError) {
804 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
810 cleanupBackupFiles();
811 QFileInfo info(file);
812 QString fileName = KUrl(path).fileName().section('.', 0, -2);
813 fileName.append('-' + m_documentProperties.value("documentid"));
814 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
815 fileName.append(".kdenlive.png");
816 KUrl backupFile = m_projectFolder;
817 backupFile.addPath(".backup/");
818 backupFile.addPath(fileName);
819 emit saveTimelinePreview(backupFile.path());
824 ClipManager *KdenliveDoc::clipManager()
826 return m_clipManager;
829 KUrl KdenliveDoc::projectFolder() const
831 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
832 return m_projectFolder;
835 void KdenliveDoc::setProjectFolder(KUrl url)
837 if (url == m_projectFolder) return;
839 KStandardDirs::makeDir(url.path());
840 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
841 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
842 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);
843 m_projectFolder = url;
845 updateProjectFolderPlacesEntry();
848 void KdenliveDoc::moveProjectData(KUrl url)
850 QList <DocClipBase*> list = m_clipManager->documentClipList();
851 KUrl::List cacheUrls;
852 for (int i = 0; i < list.count(); i++) {
853 DocClipBase *clip = list.at(i);
854 if (clip->clipType() == TEXT) {
855 // the image for title clip must be moved
856 KUrl oldUrl = clip->fileURL();
857 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
858 KIO::Job *job = KIO::copy(oldUrl, newUrl);
859 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
861 QString hash = clip->getClipHash();
862 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
863 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
864 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
865 cacheUrls << oldVideoThumbUrl;
867 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
868 cacheUrls << oldAudioThumbUrl;
871 if (!cacheUrls.isEmpty()) {
872 KIO::Job *job = KIO::copy(cacheUrls, KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/"));
873 job->ui()->setWindow(kapp->activeWindow());
874 KIO::NetAccess::synchronousRun(job, 0);
878 const QString &KdenliveDoc::profilePath() const
880 return m_profile.path;
883 MltVideoProfile KdenliveDoc::mltProfile() const
888 bool KdenliveDoc::setProfilePath(QString path)
890 if (path.isEmpty()) path = KdenliveSettings::default_profile();
891 if (path.isEmpty()) path = "dv_pal";
892 m_profile = ProfilesDialog::getVideoProfile(path);
893 double current_fps = m_fps;
894 if (m_profile.path.isEmpty()) {
895 // Profile not found, use embedded profile
896 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
897 if (profileInfo.isNull()) {
898 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
899 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
901 m_profile.description = profileInfo.attribute("description");
902 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
903 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
904 m_profile.width = profileInfo.attribute("width").toInt();
905 m_profile.height = profileInfo.attribute("height").toInt();
906 m_profile.progressive = profileInfo.attribute("progressive").toInt();
907 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
908 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
909 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
910 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
911 QString existing = ProfilesDialog::existingProfile(m_profile);
912 if (!existing.isEmpty()) {
913 m_profile = ProfilesDialog::getVideoProfile(existing);
914 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
916 QString newDesc = m_profile.description;
918 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
919 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);
922 // User canceled, use default profile
923 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
925 if (newDesc != m_profile.description) {
926 // Profile description existed, was replaced by new one
927 m_profile.description = newDesc;
929 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
931 ProfilesDialog::saveProfile(m_profile);
938 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
939 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
940 KdenliveSettings::setProject_fps(m_fps);
941 m_width = m_profile.width;
942 m_height = m_profile.height;
943 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
944 m_timecode.setFormat(m_fps);
945 KdenliveSettings::setCurrent_profile(m_profile.path);
946 return (current_fps != m_fps);
949 double KdenliveDoc::dar() const
951 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
954 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
956 emit progressInfo(message, progress);
959 QUndoStack *KdenliveDoc::commandStack()
961 return m_commandStack;
965 void KdenliveDoc::setRenderer(Render *render) {
966 if (m_render) return;
968 emit progressInfo(i18n("Loading playlist..."), 0);
969 //qApp->processEvents();
971 m_render->setSceneList(m_document.toString(), m_startPos);
972 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
975 emit progressInfo(QString(), -1);
978 void KdenliveDoc::checkProjectClips(bool displayRatioChanged, bool fpsChanged)
980 if (m_render == NULL) return;
981 m_clipManager->resetProducersList(m_render->producersList(), displayRatioChanged, fpsChanged);
984 Render *KdenliveDoc::renderer()
989 void KdenliveDoc::updateClip(const QString &id)
991 emit updateClipDisplay(id);
994 int KdenliveDoc::getFramePos(QString duration)
996 return m_timecode.getFrameCount(duration);
999 QString KdenliveDoc::producerName(const QString &id)
1001 QString result = "unnamed";
1002 QDomNodeList prods = producersList();
1003 int ct = prods.count();
1004 for (int i = 0; i < ct ; i++) {
1005 QDomElement e = prods.item(i).toElement();
1006 if (e.attribute("id") != "black" && e.attribute("id") == id) {
1007 result = e.attribute("name");
1008 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
1015 QDomDocument KdenliveDoc::toXml()
1020 Timecode KdenliveDoc::timecode() const
1025 QDomNodeList KdenliveDoc::producersList()
1027 return m_document.elementsByTagName("producer");
1030 double KdenliveDoc::projectDuration() const
1033 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
1038 double KdenliveDoc::fps() const
1043 int KdenliveDoc::width() const
1048 int KdenliveDoc::height() const
1053 KUrl KdenliveDoc::url() const
1058 void KdenliveDoc::setUrl(KUrl url)
1063 void KdenliveDoc::setModified(bool mod)
1065 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
1066 m_autoSaveTimer->start(3000);
1068 if (mod == m_modified) return;
1070 emit docModified(m_modified);
1073 bool KdenliveDoc::isModified() const
1078 const QString KdenliveDoc::description() const
1080 if (m_url.isEmpty())
1081 return i18n("Untitled") + " / " + m_profile.description;
1083 return m_url.fileName() + " / " + m_profile.description;
1086 bool KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
1088 const QString producerId = clipId.section('_', 0, 0);
1089 DocClipBase *clip = m_clipManager->getClipById(producerId);
1092 elem.setAttribute("id", producerId);
1093 QString path = elem.attribute("resource");
1095 if (elem.attribute("type").toInt() == SLIDESHOW) {
1096 extension = KUrl(path).fileName();
1097 path = KUrl(path).directory();
1099 if (elem.hasAttribute("_missingsource")) {
1100 // Clip has proxy but missing original source
1102 else if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
1103 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1104 const QString size = elem.attribute("file_size");
1105 const QString hash = elem.attribute("file_hash");
1107 int action = KMessageBox::No;
1108 if (!size.isEmpty() && !hash.isEmpty()) {
1109 if (!m_searchFolder.isEmpty())
1110 newpath = searchFileRecursively(m_searchFolder, size, hash);
1112 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")));
1114 if (elem.attribute("type").toInt() == SLIDESHOW) {
1115 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")));
1116 if (res == KMessageBox::Yes)
1117 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1119 // Abort project loading
1123 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")));
1124 if (res == KMessageBox::Yes)
1125 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1127 // Abort project loading
1132 if (action == KMessageBox::Yes) {
1133 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1134 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1135 if (!m_searchFolder.isEmpty())
1136 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1137 } else if (action == KMessageBox::Cancel) {
1139 } else if (action == KMessageBox::No) {
1140 // Keep clip as placeHolder
1141 elem.setAttribute("placeholder", '1');
1143 if (!newpath.isEmpty()) {
1144 if (elem.attribute("type").toInt() == SLIDESHOW)
1145 newpath.append('/' + extension);
1146 elem.setAttribute("resource", newpath);
1147 setNewClipResource(clipId, newpath);
1151 clip = new DocClipBase(m_clipManager, elem, producerId);
1152 m_clipManager->addClip(clip);
1155 if (createClipItem) {
1156 emit addProjectClip(clip);
1162 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1164 QDomNodeList prods = m_document.elementsByTagName("producer");
1165 int maxprod = prods.count();
1166 for (int i = 0; i < maxprod; i++) {
1167 QDomNode m = prods.at(i);
1168 QString prodId = m.toElement().attribute("id");
1169 if (prodId == id || prodId.startsWith(id + '_')) {
1170 QDomNodeList params = m.childNodes();
1171 for (int j = 0; j < params.count(); j++) {
1172 QDomElement e = params.item(j).toElement();
1173 if (e.attribute("name") == "resource") {
1174 e.firstChild().setNodeValue(path);
1182 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1184 QString foundFileName;
1185 QByteArray fileData;
1186 QByteArray fileHash;
1187 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1188 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1189 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1190 if (file.open(QIODevice::ReadOnly)) {
1191 if (QString::number(file.size()) == matchSize) {
1193 * 1 MB = 1 second per 450 files (or faster)
1194 * 10 MB = 9 seconds per 450 files (or faster)
1196 if (file.size() > 1000000 * 2) {
1197 fileData = file.read(1000000);
1198 if (file.seek(file.size() - 1000000))
1199 fileData.append(file.readAll());
1201 fileData = file.readAll();
1203 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1204 if (QString(fileHash.toHex()) == matchHash)
1205 return file.fileName();
1208 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1210 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1211 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1212 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1213 if (!foundFileName.isEmpty())
1216 return foundFileName;
1219 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1221 DocClipBase *clip = m_clipManager->getClipById(clipId);
1223 if (!addClip(elem, clipId, false))
1226 QMap <QString, QString> properties;
1227 QDomNamedNodeMap attributes = elem.attributes();
1228 for (int i = 0; i < attributes.count(); i++) {
1229 QString attrname = attributes.item(i).nodeName();
1230 if (attrname != "resource")
1231 properties.insert(attrname, attributes.item(i).nodeValue());
1232 //kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1234 clip->setProperties(properties);
1235 emit addProjectClip(clip, false);
1237 if (orig != QDomElement()) {
1238 QMap<QString, QString> meta;
1239 for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1240 QString name = m.toElement().attribute("name");
1241 if (name.startsWith("meta.attr")) {
1242 if (name.endsWith(".markup")) name = name.section('.', 0, -2);
1243 meta.insert(name.section('.', 2, -1), m.firstChild().nodeValue());
1246 if (!meta.isEmpty()) {
1248 clip = m_clipManager->getClipById(clipId);
1250 clip->setMetadata(meta);
1257 void KdenliveDoc::deleteClip(const QString &clipId)
1259 emit signalDeleteProjectClip(clipId);
1262 void KdenliveDoc::slotAddClipList(const KUrl::List urls, stringMap data)
1264 m_clipManager->slotAddClipList(urls, data);
1265 //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1270 void KdenliveDoc::slotAddClipFile(const KUrl &url, stringMap data)
1272 m_clipManager->slotAddClipFile(url, data);
1273 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1277 const QString KdenliveDoc::getFreeClipId()
1279 return QString::number(m_clipManager->getFreeClipId());
1282 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1284 return m_clipManager->getClipById(clipId);
1287 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement xml, QString group, const QString &groupId)
1289 m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1291 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1294 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1296 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1298 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1301 void KdenliveDoc::slotCreateSlideshowClipFile(QMap <QString, QString> properties, QString group, const QString &groupId)
1303 m_clipManager->slotAddSlideshowClipFile(properties, group, groupId);
1305 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1308 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1310 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1311 KStandardDirs::makeDir(titlesFolder);
1312 QPointer<TitleWidget> dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1313 if (dia_ui->exec() == QDialog::Accepted) {
1314 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->duration(), dia_ui->xml().toString(), group, groupId);
1316 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1321 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1323 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1324 if (path.isEmpty()) {
1325 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1328 if (path.isEmpty()) return;
1330 //TODO: rewrite with new title system (just set resource)
1331 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1333 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1336 int KdenliveDoc::tracksCount() const
1338 return m_tracksList.count();
1341 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1343 if (ix < 0 || ix >= m_tracksList.count()) {
1344 kWarning() << "Track INFO outisde of range";
1347 return m_tracksList.at(ix);
1350 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1352 if (ix < 0 || ix >= m_tracksList.count()) {
1353 kWarning() << "SWITCH Track outisde of range";
1356 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1359 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1361 if (ix < 0 || ix >= m_tracksList.count()) {
1362 kWarning() << "Track Lock outisde of range";
1365 m_tracksList[ix].isLocked = lock;
1368 bool KdenliveDoc::isTrackLocked(int ix) const
1370 if (ix < 0 || ix >= m_tracksList.count()) {
1371 kWarning() << "Track Lock outisde of range";
1374 return m_tracksList.at(ix).isLocked;
1377 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1379 if (ix < 0 || ix >= m_tracksList.count()) {
1380 kWarning() << "SWITCH Track outisde of range";
1383 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1386 int KdenliveDoc::trackDuration(int ix)
1388 return m_tracksList.at(ix).duration;
1391 void KdenliveDoc::setTrackDuration(int ix, int duration)
1393 m_tracksList[ix].duration = duration;
1396 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1398 if (ix == -1) m_tracksList << type;
1399 else m_tracksList.insert(ix, type);
1402 void KdenliveDoc::deleteTrack(int ix)
1404 if (ix < 0 || ix >= m_tracksList.count()) {
1405 kWarning() << "Delete Track outisde of range";
1408 m_tracksList.removeAt(ix);
1411 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1413 if (ix < 0 || ix >= m_tracksList.count()) {
1414 kWarning() << "SET Track Type outisde of range";
1417 m_tracksList[ix].type = type.type;
1418 m_tracksList[ix].isMute = type.isMute;
1419 m_tracksList[ix].isBlind = type.isBlind;
1420 m_tracksList[ix].isLocked = type.isLocked;
1421 m_tracksList[ix].trackName = type.trackName;
1424 const QList <TrackInfo> KdenliveDoc::tracksList() const
1426 return m_tracksList;
1429 QPoint KdenliveDoc::getTracksCount() const
1433 foreach(const TrackInfo & info, m_tracksList) {
1434 if (info.type == VIDEOTRACK) video++;
1437 return QPoint(video, audio);
1440 void KdenliveDoc::cacheImage(const QString &fileId, const QImage &img) const
1442 img.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1445 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1447 DocumentChecker d(infoproducers, m_document);
1448 return (d.hasErrorInClips() == false);
1454 QList <QDomElement> missingClips;
1455 for (int i = 0; i < infoproducers.count(); i++) {
1456 e = infoproducers.item(i).toElement();
1457 clipType = e.attribute("type").toInt();
1458 if (clipType == COLOR) continue;
1459 if (clipType == TEXT) {
1460 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1463 id = e.attribute("id");
1464 resource = e.attribute("resource");
1465 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1466 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1467 // Missing clip found
1468 missingClips.append(e);
1470 // Check if the clip has changed
1471 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1472 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1473 e.removeAttribute("file_hash");
1477 if (missingClips.isEmpty()) return true;
1478 DocumentChecker d(missingClips, m_document);
1479 return (d.exec() == QDialog::Accepted);*/
1482 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1484 m_documentProperties[name] = value;
1487 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1489 return m_documentProperties.value(name);
1492 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1494 QMap <QString, QString> renderProperties;
1495 QMapIterator<QString, QString> i(m_documentProperties);
1496 while (i.hasNext()) {
1498 if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1500 return renderProperties;
1503 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1505 if (ix < 0 || ix >= m_tracksList.count()) {
1506 kWarning() << "Add Track effect outisde of range";
1509 effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1511 // Init parameter value & keyframes if required
1512 QDomNodeList params = effect.elementsByTagName("parameter");
1513 for (int i = 0; i < params.count(); i++) {
1514 QDomElement e = params.item(i).toElement();
1516 // Check if this effect has a variable parameter
1517 if (e.attribute("default").contains('%')) {
1518 double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1519 e.setAttribute("default", evaluatedValue);
1520 if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1521 e.setAttribute("value", evaluatedValue);
1525 if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1526 QString def = e.attribute("default");
1527 // Effect has a keyframe type parameter, we need to set the values
1528 if (e.attribute("keyframes").isEmpty()) {
1529 e.setAttribute("keyframes", "0:" + def + ';');
1530 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1535 if (effect.attribute("id") == "crop") {
1536 // default use_profile to 1 for clips with proxies to avoid problems when rendering
1537 if (e.attribute("name") == "use_profile" && getDocumentProperty("enableproxy") == "1")
1538 e.setAttribute("value", "1");
1542 m_tracksList[ix].effectsList.append(effect);
1545 void KdenliveDoc::removeTrackEffect(int ix, QDomElement effect)
1547 if (ix < 0 || ix >= m_tracksList.count()) {
1548 kWarning() << "Remove Track effect outisde of range";
1552 int toRemove = effect.attribute("kdenlive_ix").toInt();
1553 for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1554 index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix").toInt();
1555 if (toRemove == index) {
1556 m_tracksList[ix].effectsList.removeAt(toRemove);
1562 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1564 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1565 kWarning() << "Set Track effect outisde of range";
1568 if (effectIndex <= 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count()) || effect.isNull()) {
1569 kDebug() << "Invalid effect index: " << effectIndex;
1572 m_tracksList[trackIndex].effectsList.removeAt(effect.attribute("kdenlive_ix").toInt());
1573 effect.setAttribute("kdenlive_ix", effectIndex);
1574 m_tracksList[trackIndex].effectsList.insert(effect);
1575 //m_tracksList[trackIndex].effectsList.updateEffect(effect);
1578 void KdenliveDoc::enableTrackEffects(int trackIndex, QList <int> effectIndexes, bool disable)
1580 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1581 kWarning() << "Set Track effect outisde of range";
1584 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1586 for (int i = 0; i < effectIndexes.count(); i++) {
1587 effect = list.itemFromIndex(effectIndexes.at(i));
1588 if (!effect.isNull()) effect.setAttribute("disable", (int) disable);
1592 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1594 if (ix < 0 || ix >= m_tracksList.count()) {
1595 kWarning() << "Get Track effects outisde of range";
1596 return EffectsList();
1598 return m_tracksList.at(ix).effectsList;
1601 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1603 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1604 kWarning() << "Get Track effect outisde of range";
1605 return QDomElement();
1607 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1608 if (effectIndex > list.count() || effectIndex < 1 || list.itemFromIndex(effectIndex).isNull()) return QDomElement();
1609 return list.itemFromIndex(effectIndex).cloneNode().toElement();
1612 int KdenliveDoc::hasTrackEffect(int trackIndex, const QString &tag, const QString &id) const
1614 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1615 kWarning() << "Get Track effect outisde of range";
1618 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1619 return list.hasEffect(tag, id);
1622 bool KdenliveDoc::saveCustomEffects(QDomNodeList customeffects)
1625 QStringList importedEffects;
1626 int maxchild = customeffects.count();
1627 for (int i = 0; i < maxchild; i++) {
1628 e = customeffects.at(i).toElement();
1629 QString id = e.attribute("id");
1630 QString tag = e.attribute("tag");
1631 if (!id.isEmpty()) {
1632 // Check if effect exists or save it
1633 if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1635 doc.appendChild(doc.importNode(e, true));
1636 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1637 path += id + ".xml";
1638 if (!QFile::exists(path)) {
1639 importedEffects << id;
1641 if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1642 QTextStream out(&file);
1643 out << doc.toString();
1649 if (!importedEffects.isEmpty()) KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1650 return (!importedEffects.isEmpty());
1653 void KdenliveDoc::updateProjectFolderPlacesEntry()
1656 * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1657 * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1660 const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1661 KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1662 if (!bookmarkManager) return;
1663 KBookmarkGroup root = bookmarkManager->root();
1665 KBookmark bookmark = root.first();
1667 QString kdenliveName = KGlobal::mainComponent().componentName();
1668 KUrl documentLocation = m_projectFolder;
1670 bool exists = false;
1672 while (!bookmark.isNull()) {
1673 // UDI not empty indicates a device
1674 QString udi = bookmark.metaDataItem("UDI");
1675 QString appName = bookmark.metaDataItem("OnlyInApp");
1677 if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1678 if (bookmark.url() != documentLocation) {
1679 bookmark.setUrl(documentLocation);
1680 bookmarkManager->emitChanged(root);
1686 bookmark = root.next(bookmark);
1689 // if entry does not exist yet (was not found), well, create it then
1691 bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1692 // Make this user selectable ?
1693 bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1694 bookmarkManager->emitChanged(root);
1698 QStringList KdenliveDoc::getExpandedFolders()
1700 QStringList result = m_documentProperties.value("expandedfolders").split(';');
1701 // this property is only needed once when opening project, so clear it now
1702 m_documentProperties.remove("expandedfolders");
1707 double KdenliveDoc::getDisplayRatio(const QString &path)
1711 if (!file.open(QIODevice::ReadOnly)) {
1712 kWarning() << "ERROR, CANNOT READ: " << path;
1715 if (!doc.setContent(&file)) {
1716 kWarning() << "ERROR, CANNOT READ: " << path;
1721 QDomNodeList list = doc.elementsByTagName("profile");
1722 if (list.isEmpty()) return 0;
1723 QDomElement profile = list.at(0).toElement();
1724 double den = profile.attribute("display_aspect_den").toDouble();
1725 if (den > 0) return profile.attribute("display_aspect_num").toDouble() / den;
1729 void KdenliveDoc::backupLastSavedVersion(const QString &path)
1731 // Ensure backup folder exists
1732 if (path.isEmpty()) return;
1734 KUrl backupFile = m_projectFolder;
1735 backupFile.addPath(".backup/");
1736 KIO::NetAccess::mkdir(backupFile, kapp->activeWindow());
1737 QString fileName = KUrl(path).fileName().section('.', 0, -2);
1738 QFileInfo info(file);
1739 fileName.append('-' + m_documentProperties.value("documentid"));
1740 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
1741 fileName.append(".kdenlive");
1742 backupFile.addPath(fileName);
1744 if (file.exists()) {
1745 // delete previous backup if it was done less than 60 seconds ago
1746 QFile::remove(backupFile.path());
1747 if (!QFile::copy(path, backupFile.path())) {
1748 KMessageBox::information(kapp->activeWindow(), i18n("Cannot create backup copy:\n%1", backupFile.path()));
1753 void KdenliveDoc::cleanupBackupFiles()
1755 KUrl backupFile = m_projectFolder;
1756 backupFile.addPath(".backup/");
1757 QDir dir(backupFile.path());
1758 QString projectFile = url().fileName().section('.', 0, -2);
1759 projectFile.append('-' + m_documentProperties.value("documentid"));
1760 projectFile.append("-??");
1761 projectFile.append("??");
1762 projectFile.append("-??");
1763 projectFile.append("-??");
1764 projectFile.append("-??");
1765 projectFile.append("-??.kdenlive");
1768 backupFile.addPath(projectFile);
1769 filter << projectFile;
1770 dir.setNameFilters(filter);
1771 QFileInfoList resultList = dir.entryInfoList(QDir::Files, QDir::Time);
1773 QDateTime d = QDateTime::currentDateTime();
1774 QStringList hourList;
1775 QStringList dayList;
1776 QStringList weekList;
1777 QStringList oldList;
1778 for (int i = 0; i < resultList.count(); i++) {
1779 if (d.secsTo(resultList.at(i).lastModified()) < 3600) {
1780 // files created in the last hour
1781 hourList.append(resultList.at(i).absoluteFilePath());
1783 else if (d.secsTo(resultList.at(i).lastModified()) < 43200) {
1784 // files created in the day
1785 dayList.append(resultList.at(i).absoluteFilePath());
1787 else if (d.daysTo(resultList.at(i).lastModified()) < 8) {
1788 // files created in the week
1789 weekList.append(resultList.at(i).absoluteFilePath());
1793 oldList.append(resultList.at(i).absoluteFilePath());
1796 if (hourList.count() > 20) {
1797 int step = hourList.count() / 10;
1798 for (int i = 0; i < hourList.count(); i += step) {
1799 kDebug()<<"REMOVE AT: "<<i<<", COUNT: "<<hourList.count();
1800 hourList.removeAt(i);
1803 } else hourList.clear();
1804 if (dayList.count() > 20) {
1805 int step = dayList.count() / 10;
1806 for (int i = 0; i < dayList.count(); i += step) {
1807 dayList.removeAt(i);
1810 } else dayList.clear();
1811 if (weekList.count() > 20) {
1812 int step = weekList.count() / 10;
1813 for (int i = 0; i < weekList.count(); i += step) {
1814 weekList.removeAt(i);
1817 } else weekList.clear();
1818 if (oldList.count() > 20) {
1819 int step = oldList.count() / 10;
1820 for (int i = 0; i < oldList.count(); i += step) {
1821 oldList.removeAt(i);
1824 } else oldList.clear();
1827 while (hourList.count() > 0) {
1828 f = hourList.takeFirst();
1830 QFile::remove(f + ".png");
1832 while (dayList.count() > 0) {
1833 f = dayList.takeFirst();
1835 QFile::remove(f + ".png");
1837 while (weekList.count() > 0) {
1838 f = weekList.takeFirst();
1840 QFile::remove(f + ".png");
1842 while (oldList.count() > 0) {
1843 f = oldList.takeFirst();
1845 QFile::remove(f + ".png");
1849 const QMap <QString, QString> KdenliveDoc::metadata() const
1851 return m_documentMetadata;
1854 void KdenliveDoc::setMetadata(const QMap <QString, QString> meta)
1857 m_documentMetadata = meta;
1860 #include "kdenlivedoc.moc"