1 /***************************************************************************
2 * Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org) *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
18 ***************************************************************************/
21 #include "kdenlivedoc.h"
22 #include "docclipbase.h"
23 #include "profilesdialog.h"
24 #include "kdenlivesettings.h"
26 #include "clipmanager.h"
27 #include "titlewidget.h"
28 #include "mainwindow.h"
29 #include "documentchecker.h"
30 #include "documentvalidator.h"
31 #include "kdenlive-config.h"
32 #include "initeffects.h"
35 #include <KStandardDirs>
36 #include <KMessageBox>
37 #include <KProgressDialog>
39 #include <KFileDialog>
40 #include <KIO/NetAccess>
41 #include <KIO/CopyJob>
42 #include <KApplication>
44 #include <KBookmarkManager>
46 #include <KStandardDirs>
48 #include <QCryptographicHash>
50 #include <QInputDialog>
51 #include <QDomImplementation>
53 #include <mlt++/Mlt.h>
55 const double DOCUMENTVERSION = 0.85;
57 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, QString profileName, QMap <QString, QString> properties, const QPoint tracks, Render *render, KTextEdit *notes, MainWindow *parent, KProgressDialog *progressDialog) :
63 m_commandStack(new QUndoStack(undoGroup)),
65 m_projectFolder(projectFolder)
67 m_clipManager = new ClipManager(this);
68 m_autoSaveTimer = new QTimer(this);
69 m_autoSaveTimer->setSingleShot(true);
72 // init default document properties
73 m_documentProperties["zoom"] = "7";
74 m_documentProperties["verticalzoom"] = "1";
75 m_documentProperties["zonein"] = "0";
76 m_documentProperties["zoneout"] = "100";
77 m_documentProperties["enableproxy"] = QString::number((int) KdenliveSettings::enableproxy());
78 m_documentProperties["proxyparams"] = KdenliveSettings::proxyparams();
79 m_documentProperties["proxyextension"] = KdenliveSettings::proxyextension();
80 m_documentProperties["generateproxy"] = QString::number((int) KdenliveSettings::generateproxy());
81 m_documentProperties["proxyminsize"] = QString::number(KdenliveSettings::proxyminsize());
82 m_documentProperties["generateimageproxy"] = QString::number((int) KdenliveSettings::generateimageproxy());
83 m_documentProperties["proxyimageminsize"] = QString::number(KdenliveSettings::proxyimageminsize());
86 QMapIterator<QString, QString> i(properties);
89 m_documentProperties[i.key()] = i.value();
94 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
95 if (!success) // The file cannot be opened
96 KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
100 QDomImplementation impl;
101 impl.setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
102 success = m_document.setContent(&file, false, &errorMsg);
104 KIO::NetAccess::removeTempFile(tmpFile);
106 if (!success) // It is corrupted
107 KMessageBox::error(parent, errorMsg);
109 parent->slotGotProgressInfo(i18n("Validating"), 0);
110 qApp->processEvents();
111 DocumentValidator validator(m_document);
112 success = validator.isProject();
114 // It is not a project file
115 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
118 * Validate the file against the current version (upgrade
119 * and recover it if needed). It is NOT a passive operation
121 // TODO: backup the document or alert the user?
122 success = validator.validate(DOCUMENTVERSION);
123 if (success) { // Let the validator handle error messages
124 parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
125 qApp->processEvents();
126 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
127 success = checkDocumentClips(infoproducers);
129 if (m_document.documentElement().attribute("modified") == "1") setModified(true);
130 parent->slotGotProgressInfo(i18n("Loading"), 0);
131 QDomElement mlt = m_document.firstChildElement("mlt");
132 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
134 // Check embedded effects
135 QDomElement customeffects = infoXml.firstChildElement("customeffects");
136 if (!customeffects.isNull() && customeffects.hasChildNodes()) {
137 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
138 qApp->processEvents();
139 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
144 QDomElement notesxml = infoXml.firstChildElement("documentnotes");
145 if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
148 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
149 if (!tracksinfo.isNull()) {
150 QDomNodeList trackslist = tracksinfo.childNodes();
151 int maxchild = trackslist.count();
152 for (int k = 0; k < maxchild; k++) {
153 e = trackslist.at(k).toElement();
154 if (e.tagName() == "trackinfo") {
155 TrackInfo projectTrack;
156 if (e.attribute("type") == "audio")
157 projectTrack.type = AUDIOTRACK;
159 projectTrack.type = VIDEOTRACK;
160 projectTrack.isMute = e.attribute("mute").toInt();
161 projectTrack.isBlind = e.attribute("blind").toInt();
162 projectTrack.isLocked = e.attribute("locked").toInt();
163 projectTrack.trackName = e.attribute("trackname");
164 m_tracksList.append(projectTrack);
167 mlt.removeChild(tracksinfo);
169 QStringList expandedFolders;
170 QDomNodeList folders = m_document.elementsByTagName("folder");
171 for (int i = 0; i < folders.count(); i++) {
172 e = folders.item(i).cloneNode().toElement();
173 if (e.hasAttribute("opened")) expandedFolders.append(e.attribute("id"));
174 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
176 m_documentProperties["expandedfolders"] = expandedFolders.join(";");
178 const int infomax = infoproducers.count();
179 QDomNodeList producers = m_document.elementsByTagName("producer");
180 const int max = producers.count();
182 if (!progressDialog) {
183 progressDialog = new KProgressDialog(parent, i18n("Loading project"), i18n("Adding clips"));
184 progressDialog->setAllowCancel(false);
186 progressDialog->setLabelText(i18n("Adding clips"));
188 progressDialog->progressBar()->setMaximum(infomax);
189 progressDialog->show();
190 qApp->processEvents();
192 for (int i = 0; i < infomax; i++) {
193 e = infoproducers.item(i).cloneNode().toElement();
194 QString prodId = e.attribute("id");
195 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
196 e.setTagName("producer");
197 // Get MLT's original producer properties
199 for (int j = 0; j < max; j++) {
200 QDomNode o = producers.item(j);
201 QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
202 if (origId == prodId) {
203 orig = o.cloneNode().toElement();
208 if (!addClipInfo(e, orig, prodId)) {
209 // The user manually aborted the loading.
211 emit resetProjectList();
212 m_tracksList.clear();
213 m_clipManager->clear();
218 progressDialog->progressBar()->setValue(i);
222 QDomElement markers = infoXml.firstChildElement("markers");
223 if (!markers.isNull()) {
224 QDomNodeList markerslist = markers.childNodes();
225 int maxchild = markerslist.count();
226 for (int k = 0; k < maxchild; k++) {
227 e = markerslist.at(k).toElement();
228 if (e.tagName() == "marker")
229 m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
231 infoXml.removeChild(markers);
234 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
235 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
236 QDomNamedNodeMap props = docproperties.attributes();
237 for (int i = 0; i < props.count(); i++)
238 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
239 setProfilePath(infoXml.attribute("profile"));
240 if (validator.isModified()) setModified(true);
241 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
250 // Something went wrong, or a new file was requested: create a new project
253 setProfilePath(profileName);
254 m_document = createEmptyDocument(tracks.x(), tracks.y());
257 // Set the video profile (empty == default)
258 KdenliveSettings::setCurrent_profile(profilePath());
260 // Ask to create the project directory if it does not exist
261 if (!QFile::exists(m_projectFolder.path())) {
262 int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
263 if (create == KMessageBox::Yes) {
264 QDir projectDir(m_projectFolder.path());
265 bool ok = projectDir.mkpath(m_projectFolder.path());
267 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
272 // Make sure the project folder is usable
273 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
274 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
275 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
278 // Make sure that the necessary folders exist
279 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
280 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
281 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/");
282 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/");
284 updateProjectFolderPlacesEntry();
286 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
287 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
290 KdenliveDoc::~KdenliveDoc()
292 m_autoSaveTimer->stop();
293 delete m_commandStack;
294 kDebug() << "// DEL CLP MAN";
295 delete m_clipManager;
296 kDebug() << "// DEL CLP MAN done";
297 delete m_autoSaveTimer;
299 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
304 int KdenliveDoc::setSceneList()
306 m_render->resetProfile(KdenliveSettings::current_profile());
307 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
308 // INVALID MLT Consumer, something is wrong
311 m_documentProperties.remove("position");
312 // m_document xml is now useless, clear it
317 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
319 m_tracksList.clear();
321 // Tracks are added «backwards», so we need to reverse the track numbering
322 // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
323 // Better default names for tracks: Audio 1 etc. instead of blank numbers
324 for (int i = 0; i < audiotracks; i++) {
325 TrackInfo audioTrack;
326 audioTrack.type = AUDIOTRACK;
327 audioTrack.isMute = false;
328 audioTrack.isBlind = true;
329 audioTrack.isLocked = false;
330 audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
331 audioTrack.duration = 0;
332 m_tracksList.append(audioTrack);
335 for (int i = 0; i < videotracks; i++) {
336 TrackInfo videoTrack;
337 videoTrack.type = VIDEOTRACK;
338 videoTrack.isMute = false;
339 videoTrack.isBlind = false;
340 videoTrack.isLocked = false;
341 videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
342 videoTrack.duration = 0;
343 m_tracksList.append(videoTrack);
345 return createEmptyDocument(m_tracksList);
348 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
350 // Creating new document
352 QDomElement mlt = doc.createElement("mlt");
353 doc.appendChild(mlt);
356 // Create black producer
357 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
358 // the composite transitions with the black track are corrupted.
359 QDomElement blk = doc.createElement("producer");
360 blk.setAttribute("in", 0);
361 blk.setAttribute("out", 500);
362 blk.setAttribute("id", "black");
364 QDomElement property = doc.createElement("property");
365 property.setAttribute("name", "mlt_type");
366 QDomText value = doc.createTextNode("producer");
367 property.appendChild(value);
368 blk.appendChild(property);
370 property = doc.createElement("property");
371 property.setAttribute("name", "aspect_ratio");
372 value = doc.createTextNode(QString::number(0.0));
373 property.appendChild(value);
374 blk.appendChild(property);
376 property = doc.createElement("property");
377 property.setAttribute("name", "length");
378 value = doc.createTextNode(QString::number(15000));
379 property.appendChild(value);
380 blk.appendChild(property);
382 property = doc.createElement("property");
383 property.setAttribute("name", "eof");
384 value = doc.createTextNode("pause");
385 property.appendChild(value);
386 blk.appendChild(property);
388 property = doc.createElement("property");
389 property.setAttribute("name", "resource");
390 value = doc.createTextNode("black");
391 property.appendChild(value);
392 blk.appendChild(property);
394 property = doc.createElement("property");
395 property.setAttribute("name", "mlt_service");
396 value = doc.createTextNode("colour");
397 property.appendChild(value);
398 blk.appendChild(property);
400 mlt.appendChild(blk);
403 QDomElement tractor = doc.createElement("tractor");
404 tractor.setAttribute("id", "maintractor");
405 QDomElement multitrack = doc.createElement("multitrack");
406 QDomElement playlist = doc.createElement("playlist");
407 playlist.setAttribute("id", "black_track");
408 mlt.appendChild(playlist);
410 QDomElement blank0 = doc.createElement("entry");
411 blank0.setAttribute("in", "0");
412 blank0.setAttribute("out", "1");
413 blank0.setAttribute("producer", "black");
414 playlist.appendChild(blank0);
417 int total = tracks.count() + 1;
419 for (int i = 1; i < total; i++) {
420 QDomElement playlist = doc.createElement("playlist");
421 playlist.setAttribute("id", "playlist" + QString::number(i));
422 mlt.appendChild(playlist);
425 QDomElement track0 = doc.createElement("track");
426 track0.setAttribute("producer", "black_track");
427 tractor.appendChild(track0);
429 // create audio and video tracks
430 for (int i = 1; i < total; i++) {
431 QDomElement track = doc.createElement("track");
432 track.setAttribute("producer", "playlist" + QString::number(i));
433 if (tracks.at(i - 1).type == AUDIOTRACK) {
434 track.setAttribute("hide", "video");
435 } else if (tracks.at(i - 1).isBlind)
436 track.setAttribute("hide", "video");
437 if (tracks.at(i - 1).isMute)
438 track.setAttribute("hide", "audio");
439 tractor.appendChild(track);
442 for (int i = 2; i < total ; i++) {
443 QDomElement transition = doc.createElement("transition");
444 transition.setAttribute("always_active", "1");
446 QDomElement property = doc.createElement("property");
447 property.setAttribute("name", "a_track");
448 QDomText value = doc.createTextNode(QString::number(1));
449 property.appendChild(value);
450 transition.appendChild(property);
452 property = doc.createElement("property");
453 property.setAttribute("name", "b_track");
454 value = doc.createTextNode(QString::number(i));
455 property.appendChild(value);
456 transition.appendChild(property);
458 property = doc.createElement("property");
459 property.setAttribute("name", "mlt_service");
460 value = doc.createTextNode("mix");
461 property.appendChild(value);
462 transition.appendChild(property);
464 property = doc.createElement("property");
465 property.setAttribute("name", "combine");
466 value = doc.createTextNode("1");
467 property.appendChild(value);
468 transition.appendChild(property);
470 property = doc.createElement("property");
471 property.setAttribute("name", "internal_added");
472 value = doc.createTextNode("237");
473 property.appendChild(value);
474 transition.appendChild(property);
475 tractor.appendChild(transition);
477 mlt.appendChild(tractor);
482 void KdenliveDoc::syncGuides(QList <Guide *> guides)
485 QDomElement guideNode = m_guidesXml.createElement("guides");
486 m_guidesXml.appendChild(guideNode);
489 for (int i = 0; i < guides.count(); i++) {
490 e = m_guidesXml.createElement("guide");
491 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
492 e.setAttribute("comment", guides.at(i)->label());
493 guideNode.appendChild(e);
496 emit guidesUpdated();
499 QDomElement KdenliveDoc::guidesXml() const
501 return m_guidesXml.documentElement();
504 void KdenliveDoc::slotAutoSave()
506 if (m_render && m_autosave) {
507 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
508 // show error: could not open the autosave file
509 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
511 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
512 saveSceneList(m_autosave->fileName(), m_render->sceneList(), QStringList());
516 void KdenliveDoc::setZoom(int horizontal, int vertical)
518 m_documentProperties["zoom"] = QString::number(horizontal);
519 m_documentProperties["verticalzoom"] = QString::number(vertical);
522 QPoint KdenliveDoc::zoom() const
524 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
527 void KdenliveDoc::setZone(int start, int end)
529 m_documentProperties["zonein"] = QString::number(start);
530 m_documentProperties["zoneout"] = QString::number(end);
533 QPoint KdenliveDoc::zone() const
535 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
538 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene, const QStringList expandedFolders)
540 QDomDocument sceneList;
541 sceneList.setContent(scene, true);
542 QDomElement mlt = sceneList.firstChildElement("mlt");
543 if (mlt.isNull() || !mlt.hasChildNodes()) {
544 //Make sure we don't save if scenelist is corrupted
545 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
549 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
550 mlt.appendChild(addedXml);
552 // check if project contains custom effects to embed them in project file
553 QDomNodeList effects = mlt.elementsByTagName("filter");
554 int maxEffects = effects.count();
555 kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
556 QMap <QString, QString> effectIds;
557 for (int i = 0; i < maxEffects; i++) {
558 QDomNode m = effects.at(i);
559 QDomNodeList params = m.childNodes();
562 for (int j = 0; j < params.count(); j++) {
563 QDomElement e = params.item(j).toElement();
564 if (e.attribute("name") == "kdenlive_id") {
565 id = e.firstChild().nodeValue();
567 if (e.attribute("name") == "tag") {
568 tag = e.firstChild().nodeValue();
570 if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
573 QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
574 addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
576 QDomElement markers = sceneList.createElement("markers");
577 addedXml.setAttribute("version", DOCUMENTVERSION);
578 addedXml.setAttribute("kdenliveversion", VERSION);
579 addedXml.setAttribute("profile", profilePath());
580 addedXml.setAttribute("projectfolder", m_projectFolder.path());
582 QDomElement docproperties = sceneList.createElement("documentproperties");
583 QMapIterator<QString, QString> i(m_documentProperties);
584 while (i.hasNext()) {
586 docproperties.setAttribute(i.key(), i.value());
588 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
589 addedXml.appendChild(docproperties);
591 QDomElement docnotes = sceneList.createElement("documentnotes");
592 QDomText value = sceneList.createTextNode(m_notesWidget->toPlainText());
593 docnotes.appendChild(value);
594 addedXml.appendChild(docnotes);
597 QDomElement profileinfo = sceneList.createElement("profileinfo");
598 profileinfo.setAttribute("description", m_profile.description);
599 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
600 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
601 profileinfo.setAttribute("width", m_profile.width);
602 profileinfo.setAttribute("height", m_profile.height);
603 profileinfo.setAttribute("progressive", m_profile.progressive);
604 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
605 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
606 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
607 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
608 addedXml.appendChild(profileinfo);
611 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
612 foreach(const TrackInfo & info, m_tracksList) {
613 QDomElement trackinfo = sceneList.createElement("trackinfo");
614 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
615 trackinfo.setAttribute("mute", info.isMute);
616 trackinfo.setAttribute("blind", info.isBlind);
617 trackinfo.setAttribute("locked", info.isLocked);
618 trackinfo.setAttribute("trackname", info.trackName);
619 tracksinfo.appendChild(trackinfo);
621 addedXml.appendChild(tracksinfo);
623 // save project folders
624 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
626 QMapIterator<QString, QString> f(folderlist);
627 while (f.hasNext()) {
629 QDomElement folder = sceneList.createElement("folder");
630 folder.setAttribute("id", f.key());
631 folder.setAttribute("name", f.value());
632 if (expandedFolders.contains(f.key())) folder.setAttribute("opened", "1");
633 addedXml.appendChild(folder);
636 // Save project clips
638 QList <DocClipBase*> list = m_clipManager->documentClipList();
639 for (int i = 0; i < list.count(); i++) {
640 e = list.at(i)->toXML();
641 e.setTagName("kdenlive_producer");
642 addedXml.appendChild(sceneList.importNode(e, true));
643 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
644 for (int j = 0; j < marks.count(); j++) {
645 QDomElement marker = sceneList.createElement("marker");
646 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
647 marker.setAttribute("comment", marks.at(j).comment());
648 marker.setAttribute("id", e.attribute("id"));
649 markers.appendChild(marker);
652 addedXml.appendChild(markers);
655 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
658 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
660 //wes.appendChild(doc.importNode(kdenliveData, true));
663 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
664 kWarning() << "////// ERROR writing to file: " << path;
665 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
669 file.write(sceneList.toString().toUtf8());
670 if (file.error() != QFile::NoError) {
671 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
679 ClipManager *KdenliveDoc::clipManager()
681 return m_clipManager;
684 KUrl KdenliveDoc::projectFolder() const
686 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
687 return m_projectFolder;
690 void KdenliveDoc::setProjectFolder(KUrl url)
692 if (url == m_projectFolder) return;
694 KStandardDirs::makeDir(url.path());
695 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
696 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
697 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);
698 m_projectFolder = url;
700 updateProjectFolderPlacesEntry();
703 void KdenliveDoc::moveProjectData(KUrl url)
705 QList <DocClipBase*> list = m_clipManager->documentClipList();
706 //TODO: Also move ladspa effects files
707 for (int i = 0; i < list.count(); i++) {
708 DocClipBase *clip = list.at(i);
709 if (clip->clipType() == TEXT) {
710 // the image for title clip must be moved
711 KUrl oldUrl = clip->fileURL();
712 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
713 KIO::Job *job = KIO::copy(oldUrl, newUrl);
714 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
716 QString hash = clip->getClipHash();
717 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
718 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
719 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
720 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
721 KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
722 KIO::NetAccess::synchronousRun(job, 0);
724 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
725 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
726 KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
727 if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
732 const QString &KdenliveDoc::profilePath() const
734 return m_profile.path;
737 MltVideoProfile KdenliveDoc::mltProfile() const
742 bool KdenliveDoc::setProfilePath(QString path)
744 if (path.isEmpty()) path = KdenliveSettings::default_profile();
745 if (path.isEmpty()) path = "dv_pal";
746 m_profile = ProfilesDialog::getVideoProfile(path);
747 double current_fps = m_fps;
748 if (m_profile.path.isEmpty()) {
749 // Profile not found, use embedded profile
750 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
751 if (profileInfo.isNull()) {
752 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
753 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
755 m_profile.description = profileInfo.attribute("description");
756 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
757 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
758 m_profile.width = profileInfo.attribute("width").toInt();
759 m_profile.height = profileInfo.attribute("height").toInt();
760 m_profile.progressive = profileInfo.attribute("progressive").toInt();
761 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
762 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
763 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
764 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
765 QString existing = ProfilesDialog::existingProfile(m_profile);
766 if (!existing.isEmpty()) {
767 m_profile = ProfilesDialog::getVideoProfile(existing);
768 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
770 QString newDesc = m_profile.description;
772 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
773 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);
776 // User canceled, use default profile
777 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
779 if (newDesc != m_profile.description) {
780 // Profile description existed, was replaced by new one
781 m_profile.description = newDesc;
783 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
785 ProfilesDialog::saveProfile(m_profile);
792 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
793 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
794 KdenliveSettings::setProject_fps(m_fps);
795 m_width = m_profile.width;
796 m_height = m_profile.height;
797 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
798 m_timecode.setFormat(m_fps);
799 return (current_fps != m_fps);
802 double KdenliveDoc::dar() const
804 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
807 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
809 emit progressInfo(message, progress);
812 QUndoStack *KdenliveDoc::commandStack()
814 return m_commandStack;
818 void KdenliveDoc::setRenderer(Render *render) {
819 if (m_render) return;
821 emit progressInfo(i18n("Loading playlist..."), 0);
822 //qApp->processEvents();
824 m_render->setSceneList(m_document.toString(), m_startPos);
825 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
828 emit progressInfo(QString(), -1);
831 void KdenliveDoc::checkProjectClips()
833 if (m_render == NULL) return;
834 m_clipManager->resetProducersList(m_render->producersList());
837 Render *KdenliveDoc::renderer()
842 void KdenliveDoc::updateClip(const QString id)
844 emit updateClipDisplay(id);
847 int KdenliveDoc::getFramePos(QString duration)
849 return m_timecode.getFrameCount(duration);
852 QString KdenliveDoc::producerName(const QString &id)
854 QString result = "unnamed";
855 QDomNodeList prods = producersList();
856 int ct = prods.count();
857 for (int i = 0; i < ct ; i++) {
858 QDomElement e = prods.item(i).toElement();
859 if (e.attribute("id") != "black" && e.attribute("id") == id) {
860 result = e.attribute("name");
861 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
868 QDomDocument KdenliveDoc::toXml()
873 Timecode KdenliveDoc::timecode() const
878 QDomNodeList KdenliveDoc::producersList()
880 return m_document.elementsByTagName("producer");
883 double KdenliveDoc::projectDuration() const
886 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
891 double KdenliveDoc::fps() const
896 int KdenliveDoc::width() const
901 int KdenliveDoc::height() const
906 KUrl KdenliveDoc::url() const
911 void KdenliveDoc::setUrl(KUrl url)
916 void KdenliveDoc::setModified(bool mod)
918 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
919 m_autoSaveTimer->start(3000);
921 if (mod == m_modified) return;
923 emit docModified(m_modified);
926 bool KdenliveDoc::isModified() const
931 const QString KdenliveDoc::description() const
934 return i18n("Untitled") + " / " + m_profile.description;
936 return m_url.fileName() + " / " + m_profile.description;
939 bool KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
941 const QString producerId = clipId.section('_', 0, 0);
942 DocClipBase *clip = m_clipManager->getClipById(producerId);
945 elem.setAttribute("id", producerId);
946 QString path = elem.attribute("resource");
948 if (elem.attribute("type").toInt() == SLIDESHOW) {
949 extension = KUrl(path).fileName();
950 path = KUrl(path).directory();
953 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
954 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
955 const QString size = elem.attribute("file_size");
956 const QString hash = elem.attribute("file_hash");
958 int action = KMessageBox::No;
959 if (!size.isEmpty() && !hash.isEmpty()) {
960 if (!m_searchFolder.isEmpty())
961 newpath = searchFileRecursively(m_searchFolder, size, hash);
963 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")));
965 if (elem.attribute("type").toInt() == SLIDESHOW) {
966 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")));
967 if (res == KMessageBox::Yes)
968 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
970 // Abort project loading
974 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")));
975 if (res == KMessageBox::Yes)
976 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
978 // Abort project loading
983 if (action == KMessageBox::Yes) {
984 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
985 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
986 if (!m_searchFolder.isEmpty())
987 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
988 } else if (action == KMessageBox::Cancel) {
990 } else if (action == KMessageBox::No) {
991 // Keep clip as placeHolder
992 elem.setAttribute("placeholder", '1');
994 if (!newpath.isEmpty()) {
995 if (elem.attribute("type").toInt() == SLIDESHOW)
996 newpath.append('/' + extension);
997 elem.setAttribute("resource", newpath);
998 setNewClipResource(clipId, newpath);
1002 clip = new DocClipBase(m_clipManager, elem, producerId);
1003 m_clipManager->addClip(clip);
1006 if (createClipItem) {
1007 emit addProjectClip(clip);
1013 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1015 QDomNodeList prods = m_document.elementsByTagName("producer");
1016 int maxprod = prods.count();
1017 for (int i = 0; i < maxprod; i++) {
1018 QDomNode m = prods.at(i);
1019 QString prodId = m.toElement().attribute("id");
1020 if (prodId == id || prodId.startsWith(id + '_')) {
1021 QDomNodeList params = m.childNodes();
1022 for (int j = 0; j < params.count(); j++) {
1023 QDomElement e = params.item(j).toElement();
1024 if (e.attribute("name") == "resource") {
1025 e.firstChild().setNodeValue(path);
1033 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1035 QString foundFileName;
1036 QByteArray fileData;
1037 QByteArray fileHash;
1038 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1039 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1040 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1041 if (file.open(QIODevice::ReadOnly)) {
1042 if (QString::number(file.size()) == matchSize) {
1044 * 1 MB = 1 second per 450 files (or faster)
1045 * 10 MB = 9 seconds per 450 files (or faster)
1047 if (file.size() > 1000000 * 2) {
1048 fileData = file.read(1000000);
1049 if (file.seek(file.size() - 1000000))
1050 fileData.append(file.readAll());
1052 fileData = file.readAll();
1054 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1055 if (QString(fileHash.toHex()) == matchHash)
1056 return file.fileName();
1059 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1061 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1062 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1063 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1064 if (!foundFileName.isEmpty())
1067 return foundFileName;
1070 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1072 DocClipBase *clip = m_clipManager->getClipById(clipId);
1074 if (!addClip(elem, clipId, false))
1077 QMap <QString, QString> properties;
1078 QDomNamedNodeMap attributes = elem.attributes();
1079 for (int i = 0; i < attributes.count(); i++) {
1080 QString attrname = attributes.item(i).nodeName();
1081 if (attrname != "resource")
1082 properties.insert(attrname, attributes.item(i).nodeValue());
1083 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1085 clip->setProperties(properties);
1086 emit addProjectClip(clip, false);
1088 if (orig != QDomElement()) {
1089 QMap<QString, QString> meta;
1090 for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1091 QString name = m.toElement().attribute("name");
1092 if (name.startsWith("meta.attr"))
1093 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1095 if (!meta.isEmpty()) {
1097 clip = m_clipManager->getClipById(clipId);
1099 clip->setMetadata(meta);
1106 void KdenliveDoc::deleteClip(const QString &clipId)
1108 emit signalDeleteProjectClip(clipId);
1111 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1113 m_clipManager->slotAddClipList(urls, group, groupId);
1114 //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1119 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1121 m_clipManager->slotAddClipFile(url, group, groupId);
1122 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1126 const QString KdenliveDoc::getFreeClipId()
1128 return QString::number(m_clipManager->getFreeClipId());
1131 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1133 return m_clipManager->getClipById(clipId);
1136 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement xml, QString group, const QString &groupId)
1138 m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1140 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1143 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1145 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1147 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1150 void KdenliveDoc::slotCreateSlideshowClipFile(const QString name, const QString path, int count, const QString duration,
1151 const bool loop, const bool crop, const bool fade,
1152 const QString &luma_duration, const QString &luma_file, const int softness,
1153 const QString &animation, QString group, const QString &groupId)
1155 m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop,
1156 crop, fade, luma_duration,
1157 luma_file, softness,
1158 animation, group, groupId);
1160 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1163 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1165 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1166 KStandardDirs::makeDir(titlesFolder);
1167 TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1168 if (dia_ui->exec() == QDialog::Accepted) {
1169 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->outPoint(), dia_ui->xml().toString(), group, groupId);
1171 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1176 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1178 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1179 if (path.isEmpty()) {
1180 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1183 if (path.isEmpty()) return;
1185 //TODO: rewrite with new title system (just set resource)
1186 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1188 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1191 int KdenliveDoc::tracksCount() const
1193 return m_tracksList.count();
1196 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1198 if (ix < 0 || ix >= m_tracksList.count()) {
1199 kWarning() << "Track INFO outisde of range";
1202 return m_tracksList.at(ix);
1205 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1207 if (ix < 0 || ix >= m_tracksList.count()) {
1208 kWarning() << "SWITCH Track outisde of range";
1211 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1214 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1216 if (ix < 0 || ix >= m_tracksList.count()) {
1217 kWarning() << "Track Lock outisde of range";
1220 m_tracksList[ix].isLocked = lock;
1223 bool KdenliveDoc::isTrackLocked(int ix) const
1225 if (ix < 0 || ix >= m_tracksList.count()) {
1226 kWarning() << "Track Lock outisde of range";
1229 return m_tracksList.at(ix).isLocked;
1232 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1234 if (ix < 0 || ix >= m_tracksList.count()) {
1235 kWarning() << "SWITCH Track outisde of range";
1238 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1241 int KdenliveDoc::trackDuration(int ix)
1243 return m_tracksList.at(ix).duration;
1246 void KdenliveDoc::setTrackDuration(int ix, int duration)
1248 m_tracksList[ix].duration = duration;
1251 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1253 if (ix == -1) m_tracksList << type;
1254 else m_tracksList.insert(ix, type);
1257 void KdenliveDoc::deleteTrack(int ix)
1259 if (ix < 0 || ix >= m_tracksList.count()) {
1260 kWarning() << "Delete Track outisde of range";
1263 m_tracksList.removeAt(ix);
1266 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1268 if (ix < 0 || ix >= m_tracksList.count()) {
1269 kWarning() << "SET Track Type outisde of range";
1272 m_tracksList[ix].type = type.type;
1273 m_tracksList[ix].isMute = type.isMute;
1274 m_tracksList[ix].isBlind = type.isBlind;
1275 m_tracksList[ix].isLocked = type.isLocked;
1276 m_tracksList[ix].trackName = type.trackName;
1279 const QList <TrackInfo> KdenliveDoc::tracksList() const
1281 return m_tracksList;
1284 QPoint KdenliveDoc::getTracksCount() const
1288 foreach(const TrackInfo & info, m_tracksList) {
1289 if (info.type == VIDEOTRACK) video++;
1292 return QPoint(video, audio);
1295 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1297 pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1300 QString KdenliveDoc::getLadspaFile() const
1303 QString counter = QString::number(ct).rightJustified(5, '0', false);
1304 while (QFile::exists(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa")) {
1306 counter = QString::number(ct).rightJustified(5, '0', false);
1308 return m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa";
1311 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1313 DocumentChecker d(infoproducers, m_document);
1314 return (d.hasMissingClips() == false);
1320 QList <QDomElement> missingClips;
1321 for (int i = 0; i < infoproducers.count(); i++) {
1322 e = infoproducers.item(i).toElement();
1323 clipType = e.attribute("type").toInt();
1324 if (clipType == COLOR) continue;
1325 if (clipType == TEXT) {
1326 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1329 id = e.attribute("id");
1330 resource = e.attribute("resource");
1331 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1332 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1333 // Missing clip found
1334 missingClips.append(e);
1336 // Check if the clip has changed
1337 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1338 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1339 e.removeAttribute("file_hash");
1343 if (missingClips.isEmpty()) return true;
1344 DocumentChecker d(missingClips, m_document);
1345 return (d.exec() == QDialog::Accepted);*/
1348 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1350 m_documentProperties[name] = value;
1353 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1355 return m_documentProperties.value(name);
1358 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1360 QMap <QString, QString> renderProperties;
1361 QMapIterator<QString, QString> i(m_documentProperties);
1362 while (i.hasNext()) {
1364 if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1366 return renderProperties;
1369 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1371 if (ix < 0 || ix >= m_tracksList.count()) {
1372 kWarning() << "Add Track effect outisde of range";
1375 effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1377 // Init parameter value & keyframes if required
1378 QDomNodeList params = effect.elementsByTagName("parameter");
1379 for (int i = 0; i < params.count(); i++) {
1380 QDomElement e = params.item(i).toElement();
1382 // Check if this effect has a variable parameter
1383 if (e.attribute("default").startsWith('%')) {
1384 double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1385 e.setAttribute("default", evaluatedValue);
1386 if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1387 e.setAttribute("value", evaluatedValue);
1391 if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1392 QString def = e.attribute("default");
1393 // Effect has a keyframe type parameter, we need to set the values
1394 if (e.attribute("keyframes").isEmpty()) {
1395 e.setAttribute("keyframes", "0:" + def + ';');
1396 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1402 m_tracksList[ix].effectsList.append(effect);
1405 void KdenliveDoc::removeTrackEffect(int ix, QDomElement effect)
1407 if (ix < 0 || ix >= m_tracksList.count()) {
1408 kWarning() << "Remove Track effect outisde of range";
1412 QString toRemove = effect.attribute("kdenlive_ix");
1413 for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1414 index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix");
1415 if (toRemove == index) {
1416 m_tracksList[ix].effectsList.removeAt(i);
1418 } else if (index.toInt() > toRemove.toInt()) {
1419 m_tracksList[ix].effectsList.item(i).setAttribute("kdenlive_ix", index.toInt() - 1);
1424 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1426 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1427 kWarning() << "Set Track effect outisde of range";
1430 if (effectIndex < 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count() - 1) || effect.isNull()) {
1431 kDebug() << "Invalid effect index: " << effectIndex;
1434 effect.setAttribute("kdenlive_ix", effectIndex + 1);
1435 m_tracksList[trackIndex].effectsList.replace(effectIndex, effect);
1438 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1440 if (ix < 0 || ix >= m_tracksList.count()) {
1441 kWarning() << "Get Track effects outisde of range";
1442 return EffectsList();
1444 return m_tracksList.at(ix).effectsList;
1447 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1449 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1450 kWarning() << "Get Track effect outisde of range";
1451 return QDomElement();
1453 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1454 if (effectIndex > list.count() - 1 || effectIndex < 0 || list.at(effectIndex).isNull()) return QDomElement();
1455 return list.at(effectIndex).cloneNode().toElement();
1458 bool KdenliveDoc::saveCustomEffects(QDomNodeList customeffects)
1461 QStringList importedEffects;
1462 int maxchild = customeffects.count();
1463 for (int i = 0; i < maxchild; i++) {
1464 e = customeffects.at(i).toElement();
1465 QString id = e.attribute("id");
1466 QString tag = e.attribute("tag");
1467 if (!id.isEmpty()) {
1468 // Check if effect exists or save it
1469 if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1471 doc.appendChild(doc.importNode(e, true));
1472 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1473 path += id + ".xml";
1474 if (!QFile::exists(path)) {
1475 importedEffects << id;
1477 if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1478 QTextStream out(&file);
1479 out << doc.toString();
1485 if (!importedEffects.isEmpty()) KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1486 return (!importedEffects.isEmpty());
1489 void KdenliveDoc::updateProjectFolderPlacesEntry()
1492 * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1493 * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1496 const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1497 KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1498 KBookmarkGroup root = bookmarkManager->root();
1499 KBookmark bookmark = root.first();
1501 QString kdenliveName = KGlobal::mainComponent().componentName();
1502 KUrl documentLocation = m_projectFolder;
1504 bool exists = false;
1506 while (!bookmark.isNull()) {
1507 // UDI not empty indicates a device
1508 QString udi = bookmark.metaDataItem("UDI");
1509 QString appName = bookmark.metaDataItem("OnlyInApp");
1511 if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1512 if (bookmark.url() != documentLocation) {
1513 bookmark.setUrl(documentLocation);
1514 bookmarkManager->emitChanged(root);
1520 bookmark = root.next(bookmark);
1523 // if entry does not exist yet (was not found), well, create it then
1525 bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1526 // Make this user selectable ?
1527 bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1528 bookmarkManager->emitChanged(root);
1532 QStringList KdenliveDoc::getExpandedFolders()
1534 QStringList result = m_documentProperties.value("expandedfolders").split(';');
1535 // this property is only needed once when opening project, so clear it now
1536 m_documentProperties.remove("expandedfolders");
1540 #include "kdenlivedoc.moc"