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, 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();
115 if (QLocale().decimalPoint() != QLocale::system().decimalPoint()) {
116 setlocale(LC_NUMERIC, "");
117 QLocale systemLocale = QLocale::system();
118 systemLocale.setNumberOptions(QLocale::OmitGroupSeparator);
119 QLocale::setDefault(systemLocale);
120 // locale conversion might need to be redone
121 initEffects::parseEffectFiles();
126 if (!url.isEmpty()) {
128 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
130 // The file cannot be opened
131 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) {
134 //KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
139 QDomImplementation impl;
140 impl.setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
141 success = m_document.setContent(&file, false, &errorMsg);
143 KIO::NetAccess::removeTempFile(tmpFile);
147 if (KMessageBox::warningContinueCancel(parent, i18n("Cannot open the project file, error is:\n%1\nDo you want to open a backup file?", errorMsg), i18n("Error opening file"), KGuiItem(i18n("Open Backup"))) == KMessageBox::Continue) {
150 //KMessageBox::error(parent, errorMsg);
153 parent->slotGotProgressInfo(i18n("Validating"), 0);
154 qApp->processEvents();
155 DocumentValidator validator(m_document);
156 success = validator.isProject();
158 // It is not a project file
159 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
160 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) {
165 * Validate the file against the current version (upgrade
166 * and recover it if needed). It is NOT a passive operation
168 // TODO: backup the document or alert the user?
169 success = validator.validate(DOCUMENTVERSION);
170 if (success) { // Let the validator handle error messages
171 parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
172 qApp->processEvents();
173 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
174 success = checkDocumentClips(infoproducers);
176 if (m_document.documentElement().attribute("modified") == "1") setModified(true);
177 parent->slotGotProgressInfo(i18n("Loading"), 0);
178 QDomElement mlt = m_document.firstChildElement("mlt");
179 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
181 // Set profile, fps, etc for the document
182 setProfilePath(infoXml.attribute("profile"));
184 // Check embedded effects
185 QDomElement customeffects = infoXml.firstChildElement("customeffects");
186 if (!customeffects.isNull() && customeffects.hasChildNodes()) {
187 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
188 qApp->processEvents();
189 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
194 QDomElement notesxml = infoXml.firstChildElement("documentnotes");
195 if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
198 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
199 if (!tracksinfo.isNull()) {
200 QDomNodeList trackslist = tracksinfo.childNodes();
201 int maxchild = trackslist.count();
202 for (int k = 0; k < maxchild; k++) {
203 e = trackslist.at(k).toElement();
204 if (e.tagName() == "trackinfo") {
205 TrackInfo projectTrack;
206 if (e.attribute("type") == "audio")
207 projectTrack.type = AUDIOTRACK;
209 projectTrack.type = VIDEOTRACK;
210 projectTrack.isMute = e.attribute("mute").toInt();
211 projectTrack.isBlind = e.attribute("blind").toInt();
212 projectTrack.isLocked = e.attribute("locked").toInt();
213 projectTrack.trackName = e.attribute("trackname");
214 m_tracksList.append(projectTrack);
217 mlt.removeChild(tracksinfo);
219 QStringList expandedFolders;
220 QDomNodeList folders = m_document.elementsByTagName("folder");
221 for (int i = 0; i < folders.count(); i++) {
222 e = folders.item(i).cloneNode().toElement();
223 if (e.hasAttribute("opened")) expandedFolders.append(e.attribute("id"));
224 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
226 m_documentProperties["expandedfolders"] = expandedFolders.join(";");
228 const int infomax = infoproducers.count();
229 QDomNodeList producers = m_document.elementsByTagName("producer");
230 const int max = producers.count();
232 if (!progressDialog) {
233 progressDialog = new KProgressDialog(parent, i18n("Loading project"), i18n("Adding clips"));
234 progressDialog->setAllowCancel(false);
236 progressDialog->setLabelText(i18n("Adding clips"));
238 progressDialog->progressBar()->setMaximum(infomax);
239 progressDialog->show();
240 qApp->processEvents();
242 for (int i = 0; i < infomax; i++) {
243 e = infoproducers.item(i).cloneNode().toElement();
244 QString prodId = e.attribute("id");
245 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
246 e.setTagName("producer");
247 // Get MLT's original producer properties
249 for (int j = 0; j < max; j++) {
250 QDomNode o = producers.item(j);
251 QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
252 if (origId == prodId) {
253 orig = o.cloneNode().toElement();
258 if (!addClipInfo(e, orig, prodId)) {
259 // The user manually aborted the loading.
261 emit resetProjectList();
262 m_tracksList.clear();
263 m_clipManager->clear();
268 progressDialog->progressBar()->setValue(i);
272 QDomElement markers = infoXml.firstChildElement("markers");
273 if (!markers.isNull()) {
274 QDomNodeList markerslist = markers.childNodes();
275 int maxchild = markerslist.count();
276 for (int k = 0; k < maxchild; k++) {
277 e = markerslist.at(k).toElement();
278 if (e.tagName() == "marker")
279 m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
281 infoXml.removeChild(markers);
284 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
285 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
286 QDomNamedNodeMap props = docproperties.attributes();
287 for (int i = 0; i < props.count(); i++)
288 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
290 if (validator.isModified()) setModified(true);
291 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
300 // Something went wrong, or a new file was requested: create a new project
303 setProfilePath(profileName);
304 m_document = createEmptyDocument(tracks.x(), tracks.y());
307 // Ask to create the project directory if it does not exist
308 if (!QFile::exists(m_projectFolder.path())) {
309 int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
310 if (create == KMessageBox::Yes) {
311 QDir projectDir(m_projectFolder.path());
312 bool ok = projectDir.mkpath(m_projectFolder.path());
314 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
319 // Make sure the project folder is usable
320 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
321 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
322 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
325 // Make sure that the necessary folders exist
326 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
327 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
328 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/");
330 updateProjectFolderPlacesEntry();
332 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
333 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
336 KdenliveDoc::~KdenliveDoc()
338 m_autoSaveTimer->stop();
339 delete m_commandStack;
340 kDebug() << "// DEL CLP MAN";
341 delete m_clipManager;
342 kDebug() << "// DEL CLP MAN done";
343 delete m_autoSaveTimer;
345 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
350 int KdenliveDoc::setSceneList()
352 m_render->resetProfile(KdenliveSettings::current_profile(), true);
353 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
354 // INVALID MLT Consumer, something is wrong
357 m_documentProperties.remove("position");
358 // m_document xml is now useless, clear it
363 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
365 m_tracksList.clear();
367 // Tracks are added «backwards», so we need to reverse the track numbering
368 // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
369 // Better default names for tracks: Audio 1 etc. instead of blank numbers
370 for (int i = 0; i < audiotracks; i++) {
371 TrackInfo audioTrack;
372 audioTrack.type = AUDIOTRACK;
373 audioTrack.isMute = false;
374 audioTrack.isBlind = true;
375 audioTrack.isLocked = false;
376 audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
377 audioTrack.duration = 0;
378 m_tracksList.append(audioTrack);
381 for (int i = 0; i < videotracks; i++) {
382 TrackInfo videoTrack;
383 videoTrack.type = VIDEOTRACK;
384 videoTrack.isMute = false;
385 videoTrack.isBlind = false;
386 videoTrack.isLocked = false;
387 videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
388 videoTrack.duration = 0;
389 m_tracksList.append(videoTrack);
391 return createEmptyDocument(m_tracksList);
394 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
396 // Creating new document
398 QDomElement mlt = doc.createElement("mlt");
399 mlt.setAttribute("LC_NUMERIC", "");
400 doc.appendChild(mlt);
402 // Create black producer
403 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
404 // the composite transitions with the black track are corrupted.
405 QDomElement blk = doc.createElement("producer");
406 blk.setAttribute("in", 0);
407 blk.setAttribute("out", 500);
408 blk.setAttribute("id", "black");
410 QDomElement property = doc.createElement("property");
411 property.setAttribute("name", "mlt_type");
412 QDomText value = doc.createTextNode("producer");
413 property.appendChild(value);
414 blk.appendChild(property);
416 property = doc.createElement("property");
417 property.setAttribute("name", "aspect_ratio");
418 value = doc.createTextNode(QString::number(0));
419 property.appendChild(value);
420 blk.appendChild(property);
422 property = doc.createElement("property");
423 property.setAttribute("name", "length");
424 value = doc.createTextNode(QString::number(15000));
425 property.appendChild(value);
426 blk.appendChild(property);
428 property = doc.createElement("property");
429 property.setAttribute("name", "eof");
430 value = doc.createTextNode("pause");
431 property.appendChild(value);
432 blk.appendChild(property);
434 property = doc.createElement("property");
435 property.setAttribute("name", "resource");
436 value = doc.createTextNode("black");
437 property.appendChild(value);
438 blk.appendChild(property);
440 property = doc.createElement("property");
441 property.setAttribute("name", "mlt_service");
442 value = doc.createTextNode("colour");
443 property.appendChild(value);
444 blk.appendChild(property);
446 mlt.appendChild(blk);
449 QDomElement tractor = doc.createElement("tractor");
450 tractor.setAttribute("id", "maintractor");
451 QDomElement multitrack = doc.createElement("multitrack");
452 QDomElement playlist = doc.createElement("playlist");
453 playlist.setAttribute("id", "black_track");
454 mlt.appendChild(playlist);
456 QDomElement blank0 = doc.createElement("entry");
457 blank0.setAttribute("in", "0");
458 blank0.setAttribute("out", "1");
459 blank0.setAttribute("producer", "black");
460 playlist.appendChild(blank0);
463 int total = tracks.count() + 1;
465 for (int i = 1; i < total; i++) {
466 QDomElement playlist = doc.createElement("playlist");
467 playlist.setAttribute("id", "playlist" + QString::number(i));
468 mlt.appendChild(playlist);
471 QDomElement track0 = doc.createElement("track");
472 track0.setAttribute("producer", "black_track");
473 tractor.appendChild(track0);
475 // create audio and video tracks
476 for (int i = 1; i < total; i++) {
477 QDomElement track = doc.createElement("track");
478 track.setAttribute("producer", "playlist" + QString::number(i));
479 if (tracks.at(i - 1).type == AUDIOTRACK) {
480 track.setAttribute("hide", "video");
481 } else if (tracks.at(i - 1).isBlind)
482 track.setAttribute("hide", "video");
483 if (tracks.at(i - 1).isMute)
484 track.setAttribute("hide", "audio");
485 tractor.appendChild(track);
488 for (int i = 2; i < total ; i++) {
489 QDomElement transition = doc.createElement("transition");
490 transition.setAttribute("always_active", "1");
492 QDomElement property = doc.createElement("property");
493 property.setAttribute("name", "a_track");
494 QDomText value = doc.createTextNode(QString::number(1));
495 property.appendChild(value);
496 transition.appendChild(property);
498 property = doc.createElement("property");
499 property.setAttribute("name", "b_track");
500 value = doc.createTextNode(QString::number(i));
501 property.appendChild(value);
502 transition.appendChild(property);
504 property = doc.createElement("property");
505 property.setAttribute("name", "mlt_service");
506 value = doc.createTextNode("mix");
507 property.appendChild(value);
508 transition.appendChild(property);
510 property = doc.createElement("property");
511 property.setAttribute("name", "combine");
512 value = doc.createTextNode("1");
513 property.appendChild(value);
514 transition.appendChild(property);
516 property = doc.createElement("property");
517 property.setAttribute("name", "internal_added");
518 value = doc.createTextNode("237");
519 property.appendChild(value);
520 transition.appendChild(property);
521 tractor.appendChild(transition);
523 mlt.appendChild(tractor);
528 void KdenliveDoc::syncGuides(QList <Guide *> guides)
531 QDomElement guideNode = m_guidesXml.createElement("guides");
532 m_guidesXml.appendChild(guideNode);
535 for (int i = 0; i < guides.count(); i++) {
536 e = m_guidesXml.createElement("guide");
537 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
538 e.setAttribute("comment", guides.at(i)->label());
539 guideNode.appendChild(e);
542 emit guidesUpdated();
545 QDomElement KdenliveDoc::guidesXml() const
547 return m_guidesXml.documentElement();
550 void KdenliveDoc::slotAutoSave()
552 if (m_render && m_autosave) {
553 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
554 // show error: could not open the autosave file
555 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
557 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
558 saveSceneList(m_autosave->fileName(), m_render->sceneList(), QStringList(), true);
562 void KdenliveDoc::setZoom(int horizontal, int vertical)
564 m_documentProperties["zoom"] = QString::number(horizontal);
565 m_documentProperties["verticalzoom"] = QString::number(vertical);
568 QPoint KdenliveDoc::zoom() const
570 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
573 void KdenliveDoc::setZone(int start, int end)
575 m_documentProperties["zonein"] = QString::number(start);
576 m_documentProperties["zoneout"] = QString::number(end);
579 QPoint KdenliveDoc::zone() const
581 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
584 QDomDocument KdenliveDoc::xmlSceneList(const QString &scene, const QStringList &expandedFolders)
586 QDomDocument sceneList;
587 sceneList.setContent(scene, true);
588 QDomElement mlt = sceneList.firstChildElement("mlt");
589 if (mlt.isNull() || !mlt.hasChildNodes()) {
590 //scenelist is corrupted
594 // Set playlist audio volume to 100%
595 QDomElement tractor = mlt.firstChildElement("tractor");
596 if (!tractor.isNull()) {
597 QDomNodeList props = tractor.elementsByTagName("property");
598 for (int i = 0; i < props.count(); i++) {
599 if (props.at(i).toElement().attribute("name") == "meta.volume") {
600 props.at(i).firstChild().setNodeValue("1");
606 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
607 mlt.appendChild(addedXml);
609 // check if project contains custom effects to embed them in project file
610 QDomNodeList effects = mlt.elementsByTagName("filter");
611 int maxEffects = effects.count();
612 kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
613 QMap <QString, QString> effectIds;
614 for (int i = 0; i < maxEffects; i++) {
615 QDomNode m = effects.at(i);
616 QDomNodeList params = m.childNodes();
619 for (int j = 0; j < params.count(); j++) {
620 QDomElement e = params.item(j).toElement();
621 if (e.attribute("name") == "kdenlive_id") {
622 id = e.firstChild().nodeValue();
624 if (e.attribute("name") == "tag") {
625 tag = e.firstChild().nodeValue();
627 if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
630 QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
631 addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
633 QDomElement markers = sceneList.createElement("markers");
634 addedXml.setAttribute("version", DOCUMENTVERSION);
635 addedXml.setAttribute("kdenliveversion", VERSION);
636 addedXml.setAttribute("profile", profilePath());
637 addedXml.setAttribute("projectfolder", m_projectFolder.path());
639 QDomElement docproperties = sceneList.createElement("documentproperties");
640 QMapIterator<QString, QString> i(m_documentProperties);
641 while (i.hasNext()) {
643 docproperties.setAttribute(i.key(), i.value());
645 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
646 addedXml.appendChild(docproperties);
648 QDomElement docnotes = sceneList.createElement("documentnotes");
649 QDomText value = sceneList.createTextNode(m_notesWidget->toHtml());
650 docnotes.appendChild(value);
651 addedXml.appendChild(docnotes);
654 QDomElement profileinfo = sceneList.createElement("profileinfo");
655 profileinfo.setAttribute("description", m_profile.description);
656 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
657 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
658 profileinfo.setAttribute("width", m_profile.width);
659 profileinfo.setAttribute("height", m_profile.height);
660 profileinfo.setAttribute("progressive", m_profile.progressive);
661 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
662 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
663 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
664 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
665 addedXml.appendChild(profileinfo);
668 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
669 foreach(const TrackInfo & info, m_tracksList) {
670 QDomElement trackinfo = sceneList.createElement("trackinfo");
671 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
672 trackinfo.setAttribute("mute", info.isMute);
673 trackinfo.setAttribute("blind", info.isBlind);
674 trackinfo.setAttribute("locked", info.isLocked);
675 trackinfo.setAttribute("trackname", info.trackName);
676 tracksinfo.appendChild(trackinfo);
678 addedXml.appendChild(tracksinfo);
680 // save project folders
681 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
683 QMapIterator<QString, QString> f(folderlist);
684 while (f.hasNext()) {
686 QDomElement folder = sceneList.createElement("folder");
687 folder.setAttribute("id", f.key());
688 folder.setAttribute("name", f.value());
689 if (expandedFolders.contains(f.key())) folder.setAttribute("opened", "1");
690 addedXml.appendChild(folder);
693 // Save project clips
695 QList <DocClipBase*> list = m_clipManager->documentClipList();
696 for (int i = 0; i < list.count(); i++) {
697 e = list.at(i)->toXML();
698 e.setTagName("kdenlive_producer");
699 addedXml.appendChild(sceneList.importNode(e, true));
700 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
701 for (int j = 0; j < marks.count(); j++) {
702 QDomElement marker = sceneList.createElement("marker");
703 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
704 marker.setAttribute("comment", marks.at(j).comment());
705 marker.setAttribute("id", e.attribute("id"));
706 markers.appendChild(marker);
709 addedXml.appendChild(markers);
712 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
715 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
717 //wes.appendChild(doc.importNode(kdenliveData, true));
721 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene, const QStringList &expandedFolders, bool autosave)
723 QDomDocument sceneList = xmlSceneList(scene, expandedFolders);
724 if (sceneList.isNull()) {
725 //Make sure we don't save if scenelist is corrupted
726 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
730 // Backup current version
731 if (!autosave) backupLastSavedVersion(path);
734 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
735 kWarning() << "////// ERROR writing to file: " << path;
736 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
740 file.write(sceneList.toString().toUtf8());
741 if (file.error() != QFile::NoError) {
742 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
748 cleanupBackupFiles();
749 QFileInfo info(file);
750 QString fileName = KUrl(path).fileName().section('.', 0, -2);
751 fileName.append("-" + m_documentProperties.value("documentid"));
752 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
753 fileName.append(".kdenlive.png");
754 KUrl backupFile = m_projectFolder;
755 backupFile.addPath(".backup/");
756 backupFile.addPath(fileName);
757 emit saveTimelinePreview(backupFile.path());
762 ClipManager *KdenliveDoc::clipManager()
764 return m_clipManager;
767 KUrl KdenliveDoc::projectFolder() const
769 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
770 return m_projectFolder;
773 void KdenliveDoc::setProjectFolder(KUrl url)
775 if (url == m_projectFolder) return;
777 KStandardDirs::makeDir(url.path());
778 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
779 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
780 if (KMessageBox::questionYesNo(kapp->activeWindow(), i18n("You have changed the project folder. Do you want to copy the cached data from %1 to the new folder %2?").arg(m_projectFolder.path(), url.path())) == KMessageBox::Yes) moveProjectData(url);
781 m_projectFolder = url;
783 updateProjectFolderPlacesEntry();
786 void KdenliveDoc::moveProjectData(KUrl url)
788 QList <DocClipBase*> list = m_clipManager->documentClipList();
789 KUrl::List cacheUrls;
790 for (int i = 0; i < list.count(); i++) {
791 DocClipBase *clip = list.at(i);
792 if (clip->clipType() == TEXT) {
793 // the image for title clip must be moved
794 KUrl oldUrl = clip->fileURL();
795 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
796 KIO::Job *job = KIO::copy(oldUrl, newUrl);
797 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
799 QString hash = clip->getClipHash();
800 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
801 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
802 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
803 cacheUrls << oldVideoThumbUrl;
805 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
806 cacheUrls << oldAudioThumbUrl;
809 if (!cacheUrls.isEmpty()) {
810 KIO::Job *job = KIO::copy(cacheUrls, KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/"));
811 job->ui()->setWindow(kapp->activeWindow());
812 KIO::NetAccess::synchronousRun(job, 0);
816 const QString &KdenliveDoc::profilePath() const
818 return m_profile.path;
821 MltVideoProfile KdenliveDoc::mltProfile() const
826 bool KdenliveDoc::setProfilePath(QString path)
828 if (path.isEmpty()) path = KdenliveSettings::default_profile();
829 if (path.isEmpty()) path = "dv_pal";
830 m_profile = ProfilesDialog::getVideoProfile(path);
831 double current_fps = m_fps;
832 if (m_profile.path.isEmpty()) {
833 // Profile not found, use embedded profile
834 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
835 if (profileInfo.isNull()) {
836 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
837 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
839 m_profile.description = profileInfo.attribute("description");
840 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
841 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
842 m_profile.width = profileInfo.attribute("width").toInt();
843 m_profile.height = profileInfo.attribute("height").toInt();
844 m_profile.progressive = profileInfo.attribute("progressive").toInt();
845 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
846 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
847 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
848 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
849 QString existing = ProfilesDialog::existingProfile(m_profile);
850 if (!existing.isEmpty()) {
851 m_profile = ProfilesDialog::getVideoProfile(existing);
852 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
854 QString newDesc = m_profile.description;
856 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
857 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);
860 // User canceled, use default profile
861 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
863 if (newDesc != m_profile.description) {
864 // Profile description existed, was replaced by new one
865 m_profile.description = newDesc;
867 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
869 ProfilesDialog::saveProfile(m_profile);
876 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
877 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
878 KdenliveSettings::setProject_fps(m_fps);
879 m_width = m_profile.width;
880 m_height = m_profile.height;
881 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
882 m_timecode.setFormat(m_fps);
883 KdenliveSettings::setCurrent_profile(m_profile.path);
884 return (current_fps != m_fps);
887 double KdenliveDoc::dar() const
889 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
892 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
894 emit progressInfo(message, progress);
897 QUndoStack *KdenliveDoc::commandStack()
899 return m_commandStack;
903 void KdenliveDoc::setRenderer(Render *render) {
904 if (m_render) return;
906 emit progressInfo(i18n("Loading playlist..."), 0);
907 //qApp->processEvents();
909 m_render->setSceneList(m_document.toString(), m_startPos);
910 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
913 emit progressInfo(QString(), -1);
916 void KdenliveDoc::checkProjectClips(bool displayRatioChanged, bool fpsChanged)
918 if (m_render == NULL) return;
919 m_clipManager->resetProducersList(m_render->producersList(), displayRatioChanged, fpsChanged);
922 Render *KdenliveDoc::renderer()
927 void KdenliveDoc::updateClip(const QString &id)
929 emit updateClipDisplay(id);
932 int KdenliveDoc::getFramePos(QString duration)
934 return m_timecode.getFrameCount(duration);
937 QString KdenliveDoc::producerName(const QString &id)
939 QString result = "unnamed";
940 QDomNodeList prods = producersList();
941 int ct = prods.count();
942 for (int i = 0; i < ct ; i++) {
943 QDomElement e = prods.item(i).toElement();
944 if (e.attribute("id") != "black" && e.attribute("id") == id) {
945 result = e.attribute("name");
946 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
953 QDomDocument KdenliveDoc::toXml()
958 Timecode KdenliveDoc::timecode() const
963 QDomNodeList KdenliveDoc::producersList()
965 return m_document.elementsByTagName("producer");
968 double KdenliveDoc::projectDuration() const
971 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
976 double KdenliveDoc::fps() const
981 int KdenliveDoc::width() const
986 int KdenliveDoc::height() const
991 KUrl KdenliveDoc::url() const
996 void KdenliveDoc::setUrl(KUrl url)
1001 void KdenliveDoc::setModified(bool mod)
1003 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
1004 m_autoSaveTimer->start(3000);
1006 if (mod == m_modified) return;
1008 emit docModified(m_modified);
1011 bool KdenliveDoc::isModified() const
1016 const QString KdenliveDoc::description() const
1018 if (m_url.isEmpty())
1019 return i18n("Untitled") + " / " + m_profile.description;
1021 return m_url.fileName() + " / " + m_profile.description;
1024 bool KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
1026 const QString producerId = clipId.section('_', 0, 0);
1027 DocClipBase *clip = m_clipManager->getClipById(producerId);
1030 elem.setAttribute("id", producerId);
1031 QString path = elem.attribute("resource");
1033 if (elem.attribute("type").toInt() == SLIDESHOW) {
1034 extension = KUrl(path).fileName();
1035 path = KUrl(path).directory();
1038 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
1039 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1040 const QString size = elem.attribute("file_size");
1041 const QString hash = elem.attribute("file_hash");
1043 int action = KMessageBox::No;
1044 if (!size.isEmpty() && !hash.isEmpty()) {
1045 if (!m_searchFolder.isEmpty())
1046 newpath = searchFileRecursively(m_searchFolder, size, hash);
1048 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")));
1050 if (elem.attribute("type").toInt() == SLIDESHOW) {
1051 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")));
1052 if (res == KMessageBox::Yes)
1053 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1055 // Abort project loading
1059 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")));
1060 if (res == KMessageBox::Yes)
1061 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1063 // Abort project loading
1068 if (action == KMessageBox::Yes) {
1069 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1070 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1071 if (!m_searchFolder.isEmpty())
1072 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1073 } else if (action == KMessageBox::Cancel) {
1075 } else if (action == KMessageBox::No) {
1076 // Keep clip as placeHolder
1077 elem.setAttribute("placeholder", '1');
1079 if (!newpath.isEmpty()) {
1080 if (elem.attribute("type").toInt() == SLIDESHOW)
1081 newpath.append('/' + extension);
1082 elem.setAttribute("resource", newpath);
1083 setNewClipResource(clipId, newpath);
1087 clip = new DocClipBase(m_clipManager, elem, producerId);
1088 m_clipManager->addClip(clip);
1091 if (createClipItem) {
1092 emit addProjectClip(clip);
1098 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1100 QDomNodeList prods = m_document.elementsByTagName("producer");
1101 int maxprod = prods.count();
1102 for (int i = 0; i < maxprod; i++) {
1103 QDomNode m = prods.at(i);
1104 QString prodId = m.toElement().attribute("id");
1105 if (prodId == id || prodId.startsWith(id + '_')) {
1106 QDomNodeList params = m.childNodes();
1107 for (int j = 0; j < params.count(); j++) {
1108 QDomElement e = params.item(j).toElement();
1109 if (e.attribute("name") == "resource") {
1110 e.firstChild().setNodeValue(path);
1118 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1120 QString foundFileName;
1121 QByteArray fileData;
1122 QByteArray fileHash;
1123 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1124 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1125 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1126 if (file.open(QIODevice::ReadOnly)) {
1127 if (QString::number(file.size()) == matchSize) {
1129 * 1 MB = 1 second per 450 files (or faster)
1130 * 10 MB = 9 seconds per 450 files (or faster)
1132 if (file.size() > 1000000 * 2) {
1133 fileData = file.read(1000000);
1134 if (file.seek(file.size() - 1000000))
1135 fileData.append(file.readAll());
1137 fileData = file.readAll();
1139 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1140 if (QString(fileHash.toHex()) == matchHash)
1141 return file.fileName();
1144 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1146 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1147 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1148 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1149 if (!foundFileName.isEmpty())
1152 return foundFileName;
1155 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1157 DocClipBase *clip = m_clipManager->getClipById(clipId);
1159 if (!addClip(elem, clipId, false))
1162 QMap <QString, QString> properties;
1163 QDomNamedNodeMap attributes = elem.attributes();
1164 for (int i = 0; i < attributes.count(); i++) {
1165 QString attrname = attributes.item(i).nodeName();
1166 if (attrname != "resource")
1167 properties.insert(attrname, attributes.item(i).nodeValue());
1168 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1170 clip->setProperties(properties);
1171 emit addProjectClip(clip, false);
1173 if (orig != QDomElement()) {
1174 QMap<QString, QString> meta;
1175 for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1176 QString name = m.toElement().attribute("name");
1177 if (name.startsWith("meta.attr"))
1178 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1180 if (!meta.isEmpty()) {
1182 clip = m_clipManager->getClipById(clipId);
1184 clip->setMetadata(meta);
1191 void KdenliveDoc::deleteClip(const QString &clipId)
1193 emit signalDeleteProjectClip(clipId);
1196 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString &group, const QString &groupId)
1198 m_clipManager->slotAddClipList(urls, group, groupId);
1199 //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1204 void KdenliveDoc::slotAddClipFile(const KUrl &url, const QString &group, const QString &groupId, const QString &comment)
1206 m_clipManager->slotAddClipFile(url, group, groupId, comment);
1207 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1211 const QString KdenliveDoc::getFreeClipId()
1213 return QString::number(m_clipManager->getFreeClipId());
1216 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1218 return m_clipManager->getClipById(clipId);
1221 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement xml, QString group, const QString &groupId)
1223 m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1225 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1228 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1230 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1232 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1235 void KdenliveDoc::slotCreateSlideshowClipFile(const QString &name, const QString &path, int count, const QString &duration,
1236 const bool loop, const bool crop, const bool fade,
1237 const QString &luma_duration, const QString &luma_file, const int softness,
1238 const QString &animation, QString group, const QString &groupId)
1240 m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop,
1241 crop, fade, luma_duration,
1242 luma_file, softness,
1243 animation, group, groupId);
1245 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1248 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1250 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1251 KStandardDirs::makeDir(titlesFolder);
1252 TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1253 if (dia_ui->exec() == QDialog::Accepted) {
1254 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->outPoint(), dia_ui->xml().toString(), group, groupId);
1256 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1261 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1263 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1264 if (path.isEmpty()) {
1265 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1268 if (path.isEmpty()) return;
1270 //TODO: rewrite with new title system (just set resource)
1271 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1273 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1276 int KdenliveDoc::tracksCount() const
1278 return m_tracksList.count();
1281 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1283 if (ix < 0 || ix >= m_tracksList.count()) {
1284 kWarning() << "Track INFO outisde of range";
1287 return m_tracksList.at(ix);
1290 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1292 if (ix < 0 || ix >= m_tracksList.count()) {
1293 kWarning() << "SWITCH Track outisde of range";
1296 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1299 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1301 if (ix < 0 || ix >= m_tracksList.count()) {
1302 kWarning() << "Track Lock outisde of range";
1305 m_tracksList[ix].isLocked = lock;
1308 bool KdenliveDoc::isTrackLocked(int ix) const
1310 if (ix < 0 || ix >= m_tracksList.count()) {
1311 kWarning() << "Track Lock outisde of range";
1314 return m_tracksList.at(ix).isLocked;
1317 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1319 if (ix < 0 || ix >= m_tracksList.count()) {
1320 kWarning() << "SWITCH Track outisde of range";
1323 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1326 int KdenliveDoc::trackDuration(int ix)
1328 return m_tracksList.at(ix).duration;
1331 void KdenliveDoc::setTrackDuration(int ix, int duration)
1333 m_tracksList[ix].duration = duration;
1336 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1338 if (ix == -1) m_tracksList << type;
1339 else m_tracksList.insert(ix, type);
1342 void KdenliveDoc::deleteTrack(int ix)
1344 if (ix < 0 || ix >= m_tracksList.count()) {
1345 kWarning() << "Delete Track outisde of range";
1348 m_tracksList.removeAt(ix);
1351 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1353 if (ix < 0 || ix >= m_tracksList.count()) {
1354 kWarning() << "SET Track Type outisde of range";
1357 m_tracksList[ix].type = type.type;
1358 m_tracksList[ix].isMute = type.isMute;
1359 m_tracksList[ix].isBlind = type.isBlind;
1360 m_tracksList[ix].isLocked = type.isLocked;
1361 m_tracksList[ix].trackName = type.trackName;
1364 const QList <TrackInfo> KdenliveDoc::tracksList() const
1366 return m_tracksList;
1369 QPoint KdenliveDoc::getTracksCount() const
1373 foreach(const TrackInfo & info, m_tracksList) {
1374 if (info.type == VIDEOTRACK) video++;
1377 return QPoint(video, audio);
1380 void KdenliveDoc::cacheImage(const QString &fileId, const QImage &img) const
1382 img.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1385 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1387 DocumentChecker d(infoproducers, m_document);
1388 return (d.hasErrorInClips() == false);
1394 QList <QDomElement> missingClips;
1395 for (int i = 0; i < infoproducers.count(); i++) {
1396 e = infoproducers.item(i).toElement();
1397 clipType = e.attribute("type").toInt();
1398 if (clipType == COLOR) continue;
1399 if (clipType == TEXT) {
1400 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1403 id = e.attribute("id");
1404 resource = e.attribute("resource");
1405 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1406 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1407 // Missing clip found
1408 missingClips.append(e);
1410 // Check if the clip has changed
1411 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1412 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1413 e.removeAttribute("file_hash");
1417 if (missingClips.isEmpty()) return true;
1418 DocumentChecker d(missingClips, m_document);
1419 return (d.exec() == QDialog::Accepted);*/
1422 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1424 m_documentProperties[name] = value;
1427 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1429 return m_documentProperties.value(name);
1432 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1434 QMap <QString, QString> renderProperties;
1435 QMapIterator<QString, QString> i(m_documentProperties);
1436 while (i.hasNext()) {
1438 if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1440 return renderProperties;
1443 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1445 if (ix < 0 || ix >= m_tracksList.count()) {
1446 kWarning() << "Add Track effect outisde of range";
1449 effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1451 // Init parameter value & keyframes if required
1452 QDomNodeList params = effect.elementsByTagName("parameter");
1453 for (int i = 0; i < params.count(); i++) {
1454 QDomElement e = params.item(i).toElement();
1456 // Check if this effect has a variable parameter
1457 if (e.attribute("default").contains('%')) {
1458 double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1459 e.setAttribute("default", evaluatedValue);
1460 if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1461 e.setAttribute("value", evaluatedValue);
1465 if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1466 QString def = e.attribute("default");
1467 // Effect has a keyframe type parameter, we need to set the values
1468 if (e.attribute("keyframes").isEmpty()) {
1469 e.setAttribute("keyframes", "0:" + def + ';');
1470 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1475 if (effect.attribute("id") == "crop") {
1476 // default use_profile to 1 for clips with proxies to avoid problems when rendering
1477 if (e.attribute("name") == "use_profile" && getDocumentProperty("enableproxy") == "1")
1478 e.setAttribute("value", "1");
1482 m_tracksList[ix].effectsList.append(effect);
1485 void KdenliveDoc::removeTrackEffect(int ix, QDomElement effect)
1487 if (ix < 0 || ix >= m_tracksList.count()) {
1488 kWarning() << "Remove Track effect outisde of range";
1492 QString toRemove = effect.attribute("kdenlive_ix");
1493 for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1494 index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix");
1495 if (toRemove == index) {
1496 m_tracksList[ix].effectsList.removeAt(i);
1498 } else if (index.toInt() > toRemove.toInt()) {
1499 m_tracksList[ix].effectsList.item(i).setAttribute("kdenlive_ix", index.toInt() - 1);
1504 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1506 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1507 kWarning() << "Set Track effect outisde of range";
1510 if (effectIndex < 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count() - 1) || effect.isNull()) {
1511 kDebug() << "Invalid effect index: " << effectIndex;
1514 effect.setAttribute("kdenlive_ix", effectIndex + 1);
1515 m_tracksList[trackIndex].effectsList.replace(effectIndex, effect);
1518 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1520 if (ix < 0 || ix >= m_tracksList.count()) {
1521 kWarning() << "Get Track effects outisde of range";
1522 return EffectsList();
1524 return m_tracksList.at(ix).effectsList;
1527 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1529 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1530 kWarning() << "Get Track effect outisde of range";
1531 return QDomElement();
1533 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1534 if (effectIndex > list.count() - 1 || effectIndex < 0 || list.at(effectIndex).isNull()) return QDomElement();
1535 return list.at(effectIndex).cloneNode().toElement();
1538 bool KdenliveDoc::saveCustomEffects(QDomNodeList customeffects)
1541 QStringList importedEffects;
1542 int maxchild = customeffects.count();
1543 for (int i = 0; i < maxchild; i++) {
1544 e = customeffects.at(i).toElement();
1545 QString id = e.attribute("id");
1546 QString tag = e.attribute("tag");
1547 if (!id.isEmpty()) {
1548 // Check if effect exists or save it
1549 if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1551 doc.appendChild(doc.importNode(e, true));
1552 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1553 path += id + ".xml";
1554 if (!QFile::exists(path)) {
1555 importedEffects << id;
1557 if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1558 QTextStream out(&file);
1559 out << doc.toString();
1565 if (!importedEffects.isEmpty()) KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1566 return (!importedEffects.isEmpty());
1569 void KdenliveDoc::updateProjectFolderPlacesEntry()
1572 * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1573 * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1576 const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1577 KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1578 if (!bookmarkManager) return;
1579 KBookmarkGroup root = bookmarkManager->root();
1581 KBookmark bookmark = root.first();
1583 QString kdenliveName = KGlobal::mainComponent().componentName();
1584 KUrl documentLocation = m_projectFolder;
1586 bool exists = false;
1588 while (!bookmark.isNull()) {
1589 // UDI not empty indicates a device
1590 QString udi = bookmark.metaDataItem("UDI");
1591 QString appName = bookmark.metaDataItem("OnlyInApp");
1593 if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1594 if (bookmark.url() != documentLocation) {
1595 bookmark.setUrl(documentLocation);
1596 bookmarkManager->emitChanged(root);
1602 bookmark = root.next(bookmark);
1605 // if entry does not exist yet (was not found), well, create it then
1607 bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1608 // Make this user selectable ?
1609 bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1610 bookmarkManager->emitChanged(root);
1614 QStringList KdenliveDoc::getExpandedFolders()
1616 QStringList result = m_documentProperties.value("expandedfolders").split(';');
1617 // this property is only needed once when opening project, so clear it now
1618 m_documentProperties.remove("expandedfolders");
1623 double KdenliveDoc::getDisplayRatio(const QString &path)
1627 if (!file.open(QIODevice::ReadOnly)) {
1628 kWarning() << "ERROR, CANNOT READ: " << path;
1631 if (!doc.setContent(&file)) {
1632 kWarning() << "ERROR, CANNOT READ: " << path;
1637 QDomNodeList list = doc.elementsByTagName("profile");
1638 if (list.isEmpty()) return 0;
1639 QDomElement profile = list.at(0).toElement();
1640 double den = profile.attribute("display_aspect_den").toDouble();
1641 if (den > 0) return profile.attribute("display_aspect_num").toDouble() / den;
1645 void KdenliveDoc::backupLastSavedVersion(const QString &path)
1647 // Ensure backup folder exists
1648 if (path.isEmpty()) return;
1650 KUrl backupFile = m_projectFolder;
1651 backupFile.addPath(".backup/");
1652 KIO::NetAccess::mkdir(backupFile, kapp->activeWindow());
1653 QString fileName = KUrl(path).fileName().section('.', 0, -2);
1654 QFileInfo info(file);
1655 fileName.append("-" + m_documentProperties.value("documentid"));
1656 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
1657 fileName.append(".kdenlive");
1658 backupFile.addPath(fileName);
1660 if (file.exists()) {
1661 // delete previous backup if it was done less than 60 seconds ago
1662 QFile::remove(backupFile.path());
1663 if (!QFile::copy(path, backupFile.path())) {
1664 KMessageBox::information(kapp->activeWindow(), i18n("Cannot create backup copy:\n%1", backupFile.path()));
1669 void KdenliveDoc::cleanupBackupFiles()
1671 KUrl backupFile = m_projectFolder;
1672 backupFile.addPath(".backup/");
1673 QDir dir(backupFile.path());
1674 QString projectFile = url().fileName().section('.', 0, -2);
1675 projectFile.append("-" + m_documentProperties.value("documentid"));
1676 projectFile.append("-??");
1677 projectFile.append("??");
1678 projectFile.append("-??");
1679 projectFile.append("-??");
1680 projectFile.append("-??");
1681 projectFile.append("-??.kdenlive");
1684 backupFile.addPath(projectFile);
1685 filter << projectFile;
1686 dir.setNameFilters(filter);
1687 QFileInfoList resultList = dir.entryInfoList(QDir::Files, QDir::Time);
1689 QDateTime d = QDateTime::currentDateTime();
1690 QStringList hourList;
1691 QStringList dayList;
1692 QStringList weekList;
1693 QStringList oldList;
1694 for (int i = 0; i < resultList.count(); i++) {
1695 if (d.secsTo(resultList.at(i).lastModified()) < 3600) {
1696 // files created in the last hour
1697 hourList.append(resultList.at(i).absoluteFilePath());
1699 else if (d.secsTo(resultList.at(i).lastModified()) < 43200) {
1700 // files created in the day
1701 dayList.append(resultList.at(i).absoluteFilePath());
1703 else if (d.daysTo(resultList.at(i).lastModified()) < 8) {
1704 // files created in the week
1705 weekList.append(resultList.at(i).absoluteFilePath());
1709 oldList.append(resultList.at(i).absoluteFilePath());
1712 if (hourList.count() > 20) {
1713 int step = hourList.count() / 10;
1714 for (int i = 0; i < hourList.count(); i += step) {
1715 kDebug()<<"REMOVE AT: "<<i<<", COUNT: "<<hourList.count();
1716 hourList.removeAt(i);
1719 } else hourList.clear();
1720 if (dayList.count() > 20) {
1721 int step = dayList.count() / 10;
1722 for (int i = 0; i < dayList.count(); i += step) {
1723 dayList.removeAt(i);
1726 } else dayList.clear();
1727 if (weekList.count() > 20) {
1728 int step = weekList.count() / 10;
1729 for (int i = 0; i < weekList.count(); i += step) {
1730 weekList.removeAt(i);
1733 } else weekList.clear();
1734 if (oldList.count() > 20) {
1735 int step = oldList.count() / 10;
1736 for (int i = 0; i < oldList.count(); i += step) {
1737 oldList.removeAt(i);
1740 } else oldList.clear();
1743 while (hourList.count() > 0) {
1744 f = hourList.takeFirst();
1746 QFile::remove(f + ".png");
1748 while (dayList.count() > 0) {
1749 f = dayList.takeFirst();
1751 QFile::remove(f + ".png");
1753 while (weekList.count() > 0) {
1754 f = weekList.takeFirst();
1756 QFile::remove(f + ".png");
1758 while (oldList.count() > 0) {
1759 f = oldList.takeFirst();
1761 QFile::remove(f + ".png");
1765 #include "kdenlivedoc.moc"