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.87;
57 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) :
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());
84 #if QT_VERSION >= 0x040700
85 m_documentProperties["documentid"] = QString::number(QDateTime::currentMSecsSinceEpoch());
87 QDateTime date = QDateTime::currentDateTime();
88 m_documentProperties["documentid"] = QString::number(date.toTime_t());
92 QMapIterator<QString, QString> i(properties);
95 m_documentProperties[i.key()] = i.value();
100 if (!url.isEmpty()) {
102 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
104 // The file cannot be opened
105 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) {
108 //KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
113 QDomImplementation impl;
114 impl.setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
115 success = m_document.setContent(&file, false, &errorMsg);
117 KIO::NetAccess::removeTempFile(tmpFile);
121 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) {
124 //KMessageBox::error(parent, errorMsg);
127 parent->slotGotProgressInfo(i18n("Validating"), 0);
128 qApp->processEvents();
129 DocumentValidator validator(m_document);
130 success = validator.isProject();
132 // It is not a project file
133 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
134 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) {
139 * Validate the file against the current version (upgrade
140 * and recover it if needed). It is NOT a passive operation
142 // TODO: backup the document or alert the user?
143 success = validator.validate(DOCUMENTVERSION);
144 if (success) { // Let the validator handle error messages
145 parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
146 qApp->processEvents();
147 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
148 success = checkDocumentClips(infoproducers);
150 if (m_document.documentElement().attribute("modified") == "1") setModified(true);
151 parent->slotGotProgressInfo(i18n("Loading"), 0);
152 QDomElement mlt = m_document.firstChildElement("mlt");
153 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
155 // Set profile, fps, etc for the document
156 setProfilePath(infoXml.attribute("profile"));
158 // Check embedded effects
159 QDomElement customeffects = infoXml.firstChildElement("customeffects");
160 if (!customeffects.isNull() && customeffects.hasChildNodes()) {
161 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
162 qApp->processEvents();
163 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
168 QDomElement notesxml = infoXml.firstChildElement("documentnotes");
169 if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
172 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
173 if (!tracksinfo.isNull()) {
174 QDomNodeList trackslist = tracksinfo.childNodes();
175 int maxchild = trackslist.count();
176 for (int k = 0; k < maxchild; k++) {
177 e = trackslist.at(k).toElement();
178 if (e.tagName() == "trackinfo") {
179 TrackInfo projectTrack;
180 if (e.attribute("type") == "audio")
181 projectTrack.type = AUDIOTRACK;
183 projectTrack.type = VIDEOTRACK;
184 projectTrack.isMute = e.attribute("mute").toInt();
185 projectTrack.isBlind = e.attribute("blind").toInt();
186 projectTrack.isLocked = e.attribute("locked").toInt();
187 projectTrack.trackName = e.attribute("trackname");
188 m_tracksList.append(projectTrack);
191 mlt.removeChild(tracksinfo);
193 QStringList expandedFolders;
194 QDomNodeList folders = m_document.elementsByTagName("folder");
195 for (int i = 0; i < folders.count(); i++) {
196 e = folders.item(i).cloneNode().toElement();
197 if (e.hasAttribute("opened")) expandedFolders.append(e.attribute("id"));
198 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
200 m_documentProperties["expandedfolders"] = expandedFolders.join(";");
202 const int infomax = infoproducers.count();
203 QDomNodeList producers = m_document.elementsByTagName("producer");
204 const int max = producers.count();
206 if (!progressDialog) {
207 progressDialog = new KProgressDialog(parent, i18n("Loading project"), i18n("Adding clips"));
208 progressDialog->setAllowCancel(false);
210 progressDialog->setLabelText(i18n("Adding clips"));
212 progressDialog->progressBar()->setMaximum(infomax);
213 progressDialog->show();
214 qApp->processEvents();
216 for (int i = 0; i < infomax; i++) {
217 e = infoproducers.item(i).cloneNode().toElement();
218 QString prodId = e.attribute("id");
219 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
220 e.setTagName("producer");
221 // Get MLT's original producer properties
223 for (int j = 0; j < max; j++) {
224 QDomNode o = producers.item(j);
225 QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
226 if (origId == prodId) {
227 orig = o.cloneNode().toElement();
232 if (!addClipInfo(e, orig, prodId)) {
233 // The user manually aborted the loading.
235 emit resetProjectList();
236 m_tracksList.clear();
237 m_clipManager->clear();
242 progressDialog->progressBar()->setValue(i);
246 QDomElement markers = infoXml.firstChildElement("markers");
247 if (!markers.isNull()) {
248 QDomNodeList markerslist = markers.childNodes();
249 int maxchild = markerslist.count();
250 for (int k = 0; k < maxchild; k++) {
251 e = markerslist.at(k).toElement();
252 if (e.tagName() == "marker")
253 m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
255 infoXml.removeChild(markers);
258 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
259 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
260 QDomNamedNodeMap props = docproperties.attributes();
261 for (int i = 0; i < props.count(); i++)
262 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
264 if (validator.isModified()) setModified(true);
265 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
274 // Something went wrong, or a new file was requested: create a new project
277 setProfilePath(profileName);
278 m_document = createEmptyDocument(tracks.x(), tracks.y());
281 // Ask to create the project directory if it does not exist
282 if (!QFile::exists(m_projectFolder.path())) {
283 int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
284 if (create == KMessageBox::Yes) {
285 QDir projectDir(m_projectFolder.path());
286 bool ok = projectDir.mkpath(m_projectFolder.path());
288 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
293 // Make sure the project folder is usable
294 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
295 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
296 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
299 // Make sure that the necessary folders exist
300 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
301 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
302 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/");
303 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/");
305 updateProjectFolderPlacesEntry();
307 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
308 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
311 KdenliveDoc::~KdenliveDoc()
313 m_autoSaveTimer->stop();
314 delete m_commandStack;
315 kDebug() << "// DEL CLP MAN";
316 delete m_clipManager;
317 kDebug() << "// DEL CLP MAN done";
318 delete m_autoSaveTimer;
320 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
325 int KdenliveDoc::setSceneList()
327 m_render->resetProfile(KdenliveSettings::current_profile(), true);
328 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
329 // INVALID MLT Consumer, something is wrong
332 m_documentProperties.remove("position");
333 // m_document xml is now useless, clear it
338 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
340 m_tracksList.clear();
342 // Tracks are added «backwards», so we need to reverse the track numbering
343 // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
344 // Better default names for tracks: Audio 1 etc. instead of blank numbers
345 for (int i = 0; i < audiotracks; i++) {
346 TrackInfo audioTrack;
347 audioTrack.type = AUDIOTRACK;
348 audioTrack.isMute = false;
349 audioTrack.isBlind = true;
350 audioTrack.isLocked = false;
351 audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
352 audioTrack.duration = 0;
353 m_tracksList.append(audioTrack);
356 for (int i = 0; i < videotracks; i++) {
357 TrackInfo videoTrack;
358 videoTrack.type = VIDEOTRACK;
359 videoTrack.isMute = false;
360 videoTrack.isBlind = false;
361 videoTrack.isLocked = false;
362 videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
363 videoTrack.duration = 0;
364 m_tracksList.append(videoTrack);
366 return createEmptyDocument(m_tracksList);
369 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
371 // Creating new document
373 QDomElement mlt = doc.createElement("mlt");
374 mlt.setAttribute("LC_NUMERIC", "");
375 doc.appendChild(mlt);
377 // Create black producer
378 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
379 // the composite transitions with the black track are corrupted.
380 QDomElement blk = doc.createElement("producer");
381 blk.setAttribute("in", 0);
382 blk.setAttribute("out", 500);
383 blk.setAttribute("id", "black");
385 QDomElement property = doc.createElement("property");
386 property.setAttribute("name", "mlt_type");
387 QDomText value = doc.createTextNode("producer");
388 property.appendChild(value);
389 blk.appendChild(property);
391 property = doc.createElement("property");
392 property.setAttribute("name", "aspect_ratio");
393 value = doc.createTextNode(QString::number(0));
394 property.appendChild(value);
395 blk.appendChild(property);
397 property = doc.createElement("property");
398 property.setAttribute("name", "length");
399 value = doc.createTextNode(QString::number(15000));
400 property.appendChild(value);
401 blk.appendChild(property);
403 property = doc.createElement("property");
404 property.setAttribute("name", "eof");
405 value = doc.createTextNode("pause");
406 property.appendChild(value);
407 blk.appendChild(property);
409 property = doc.createElement("property");
410 property.setAttribute("name", "resource");
411 value = doc.createTextNode("black");
412 property.appendChild(value);
413 blk.appendChild(property);
415 property = doc.createElement("property");
416 property.setAttribute("name", "mlt_service");
417 value = doc.createTextNode("colour");
418 property.appendChild(value);
419 blk.appendChild(property);
421 mlt.appendChild(blk);
424 QDomElement tractor = doc.createElement("tractor");
425 tractor.setAttribute("id", "maintractor");
426 QDomElement multitrack = doc.createElement("multitrack");
427 QDomElement playlist = doc.createElement("playlist");
428 playlist.setAttribute("id", "black_track");
429 mlt.appendChild(playlist);
431 QDomElement blank0 = doc.createElement("entry");
432 blank0.setAttribute("in", "0");
433 blank0.setAttribute("out", "1");
434 blank0.setAttribute("producer", "black");
435 playlist.appendChild(blank0);
438 int total = tracks.count() + 1;
440 for (int i = 1; i < total; i++) {
441 QDomElement playlist = doc.createElement("playlist");
442 playlist.setAttribute("id", "playlist" + QString::number(i));
443 mlt.appendChild(playlist);
446 QDomElement track0 = doc.createElement("track");
447 track0.setAttribute("producer", "black_track");
448 tractor.appendChild(track0);
450 // create audio and video tracks
451 for (int i = 1; i < total; i++) {
452 QDomElement track = doc.createElement("track");
453 track.setAttribute("producer", "playlist" + QString::number(i));
454 if (tracks.at(i - 1).type == AUDIOTRACK) {
455 track.setAttribute("hide", "video");
456 } else if (tracks.at(i - 1).isBlind)
457 track.setAttribute("hide", "video");
458 if (tracks.at(i - 1).isMute)
459 track.setAttribute("hide", "audio");
460 tractor.appendChild(track);
463 for (int i = 2; i < total ; i++) {
464 QDomElement transition = doc.createElement("transition");
465 transition.setAttribute("always_active", "1");
467 QDomElement property = doc.createElement("property");
468 property.setAttribute("name", "a_track");
469 QDomText value = doc.createTextNode(QString::number(1));
470 property.appendChild(value);
471 transition.appendChild(property);
473 property = doc.createElement("property");
474 property.setAttribute("name", "b_track");
475 value = doc.createTextNode(QString::number(i));
476 property.appendChild(value);
477 transition.appendChild(property);
479 property = doc.createElement("property");
480 property.setAttribute("name", "mlt_service");
481 value = doc.createTextNode("mix");
482 property.appendChild(value);
483 transition.appendChild(property);
485 property = doc.createElement("property");
486 property.setAttribute("name", "combine");
487 value = doc.createTextNode("1");
488 property.appendChild(value);
489 transition.appendChild(property);
491 property = doc.createElement("property");
492 property.setAttribute("name", "internal_added");
493 value = doc.createTextNode("237");
494 property.appendChild(value);
495 transition.appendChild(property);
496 tractor.appendChild(transition);
498 mlt.appendChild(tractor);
503 void KdenliveDoc::syncGuides(QList <Guide *> guides)
506 QDomElement guideNode = m_guidesXml.createElement("guides");
507 m_guidesXml.appendChild(guideNode);
510 for (int i = 0; i < guides.count(); i++) {
511 e = m_guidesXml.createElement("guide");
512 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
513 e.setAttribute("comment", guides.at(i)->label());
514 guideNode.appendChild(e);
517 emit guidesUpdated();
520 QDomElement KdenliveDoc::guidesXml() const
522 return m_guidesXml.documentElement();
525 void KdenliveDoc::slotAutoSave()
527 if (m_render && m_autosave) {
528 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
529 // show error: could not open the autosave file
530 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
532 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
533 saveSceneList(m_autosave->fileName(), m_render->sceneList(), QStringList(), true);
537 void KdenliveDoc::setZoom(int horizontal, int vertical)
539 m_documentProperties["zoom"] = QString::number(horizontal);
540 m_documentProperties["verticalzoom"] = QString::number(vertical);
543 QPoint KdenliveDoc::zoom() const
545 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
548 void KdenliveDoc::setZone(int start, int end)
550 m_documentProperties["zonein"] = QString::number(start);
551 m_documentProperties["zoneout"] = QString::number(end);
554 QPoint KdenliveDoc::zone() const
556 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
559 QDomDocument KdenliveDoc::xmlSceneList(const QString &scene, const QStringList expandedFolders)
561 QDomDocument sceneList;
562 sceneList.setContent(scene, true);
563 QDomElement mlt = sceneList.firstChildElement("mlt");
564 if (mlt.isNull() || !mlt.hasChildNodes()) {
565 //scenelist is corrupted
569 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
570 mlt.appendChild(addedXml);
572 // check if project contains custom effects to embed them in project file
573 QDomNodeList effects = mlt.elementsByTagName("filter");
574 int maxEffects = effects.count();
575 kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
576 QMap <QString, QString> effectIds;
577 for (int i = 0; i < maxEffects; i++) {
578 QDomNode m = effects.at(i);
579 QDomNodeList params = m.childNodes();
582 for (int j = 0; j < params.count(); j++) {
583 QDomElement e = params.item(j).toElement();
584 if (e.attribute("name") == "kdenlive_id") {
585 id = e.firstChild().nodeValue();
587 if (e.attribute("name") == "tag") {
588 tag = e.firstChild().nodeValue();
590 if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
593 QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
594 addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
596 QDomElement markers = sceneList.createElement("markers");
597 addedXml.setAttribute("version", DOCUMENTVERSION);
598 addedXml.setAttribute("kdenliveversion", VERSION);
599 addedXml.setAttribute("profile", profilePath());
600 addedXml.setAttribute("projectfolder", m_projectFolder.path());
602 QDomElement docproperties = sceneList.createElement("documentproperties");
603 QMapIterator<QString, QString> i(m_documentProperties);
604 while (i.hasNext()) {
606 docproperties.setAttribute(i.key(), i.value());
608 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
609 addedXml.appendChild(docproperties);
611 QDomElement docnotes = sceneList.createElement("documentnotes");
612 QDomText value = sceneList.createTextNode(m_notesWidget->toHtml());
613 docnotes.appendChild(value);
614 addedXml.appendChild(docnotes);
617 QDomElement profileinfo = sceneList.createElement("profileinfo");
618 profileinfo.setAttribute("description", m_profile.description);
619 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
620 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
621 profileinfo.setAttribute("width", m_profile.width);
622 profileinfo.setAttribute("height", m_profile.height);
623 profileinfo.setAttribute("progressive", m_profile.progressive);
624 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
625 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
626 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
627 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
628 addedXml.appendChild(profileinfo);
631 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
632 foreach(const TrackInfo & info, m_tracksList) {
633 QDomElement trackinfo = sceneList.createElement("trackinfo");
634 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
635 trackinfo.setAttribute("mute", info.isMute);
636 trackinfo.setAttribute("blind", info.isBlind);
637 trackinfo.setAttribute("locked", info.isLocked);
638 trackinfo.setAttribute("trackname", info.trackName);
639 tracksinfo.appendChild(trackinfo);
641 addedXml.appendChild(tracksinfo);
643 // save project folders
644 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
646 QMapIterator<QString, QString> f(folderlist);
647 while (f.hasNext()) {
649 QDomElement folder = sceneList.createElement("folder");
650 folder.setAttribute("id", f.key());
651 folder.setAttribute("name", f.value());
652 if (expandedFolders.contains(f.key())) folder.setAttribute("opened", "1");
653 addedXml.appendChild(folder);
656 // Save project clips
658 QList <DocClipBase*> list = m_clipManager->documentClipList();
659 for (int i = 0; i < list.count(); i++) {
660 e = list.at(i)->toXML();
661 e.setTagName("kdenlive_producer");
662 addedXml.appendChild(sceneList.importNode(e, true));
663 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
664 for (int j = 0; j < marks.count(); j++) {
665 QDomElement marker = sceneList.createElement("marker");
666 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
667 marker.setAttribute("comment", marks.at(j).comment());
668 marker.setAttribute("id", e.attribute("id"));
669 markers.appendChild(marker);
672 addedXml.appendChild(markers);
675 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
678 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
680 //wes.appendChild(doc.importNode(kdenliveData, true));
684 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene, const QStringList expandedFolders, bool autosave)
686 QDomDocument sceneList = xmlSceneList(scene, expandedFolders);
687 if (sceneList.isNull()) {
688 //Make sure we don't save if scenelist is corrupted
689 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
693 // Backup current version
694 if (!autosave) backupLastSavedVersion(path);
697 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
698 kWarning() << "////// ERROR writing to file: " << path;
699 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
703 file.write(sceneList.toString().toUtf8());
704 if (file.error() != QFile::NoError) {
705 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
711 cleanupBackupFiles();
712 QFileInfo info(file);
713 QString fileName = KUrl(path).fileName().section('.', 0, -2);
714 fileName.append("-" + m_documentProperties.value("documentid"));
715 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
716 fileName.append(".kdenlive.png");
717 KUrl backupFile = m_projectFolder;
718 backupFile.addPath(".backup/");
719 backupFile.addPath(fileName);
720 emit saveTimelinePreview(backupFile.path());
725 ClipManager *KdenliveDoc::clipManager()
727 return m_clipManager;
730 KUrl KdenliveDoc::projectFolder() const
732 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
733 return m_projectFolder;
736 void KdenliveDoc::setProjectFolder(KUrl url)
738 if (url == m_projectFolder) return;
740 KStandardDirs::makeDir(url.path());
741 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
742 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
743 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);
744 m_projectFolder = url;
746 updateProjectFolderPlacesEntry();
749 void KdenliveDoc::moveProjectData(KUrl url)
751 QList <DocClipBase*> list = m_clipManager->documentClipList();
752 //TODO: Also move ladspa effects files
753 for (int i = 0; i < list.count(); i++) {
754 DocClipBase *clip = list.at(i);
755 if (clip->clipType() == TEXT) {
756 // the image for title clip must be moved
757 KUrl oldUrl = clip->fileURL();
758 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
759 KIO::Job *job = KIO::copy(oldUrl, newUrl);
760 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
762 QString hash = clip->getClipHash();
763 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
764 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
765 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
766 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
767 KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
768 KIO::NetAccess::synchronousRun(job, 0);
770 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
771 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
772 KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
773 if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
778 const QString &KdenliveDoc::profilePath() const
780 return m_profile.path;
783 MltVideoProfile KdenliveDoc::mltProfile() const
788 bool KdenliveDoc::setProfilePath(QString path)
790 if (path.isEmpty()) path = KdenliveSettings::default_profile();
791 if (path.isEmpty()) path = "dv_pal";
792 m_profile = ProfilesDialog::getVideoProfile(path);
793 double current_fps = m_fps;
794 if (m_profile.path.isEmpty()) {
795 // Profile not found, use embedded profile
796 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
797 if (profileInfo.isNull()) {
798 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
799 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
801 m_profile.description = profileInfo.attribute("description");
802 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
803 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
804 m_profile.width = profileInfo.attribute("width").toInt();
805 m_profile.height = profileInfo.attribute("height").toInt();
806 m_profile.progressive = profileInfo.attribute("progressive").toInt();
807 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
808 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
809 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
810 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
811 QString existing = ProfilesDialog::existingProfile(m_profile);
812 if (!existing.isEmpty()) {
813 m_profile = ProfilesDialog::getVideoProfile(existing);
814 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
816 QString newDesc = m_profile.description;
818 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
819 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);
822 // User canceled, use default profile
823 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
825 if (newDesc != m_profile.description) {
826 // Profile description existed, was replaced by new one
827 m_profile.description = newDesc;
829 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
831 ProfilesDialog::saveProfile(m_profile);
838 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
839 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
840 KdenliveSettings::setProject_fps(m_fps);
841 m_width = m_profile.width;
842 m_height = m_profile.height;
843 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
844 m_timecode.setFormat(m_fps);
845 KdenliveSettings::setCurrent_profile(m_profile.path);
846 return (current_fps != m_fps);
849 double KdenliveDoc::dar() const
851 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
854 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
856 emit progressInfo(message, progress);
859 QUndoStack *KdenliveDoc::commandStack()
861 return m_commandStack;
865 void KdenliveDoc::setRenderer(Render *render) {
866 if (m_render) return;
868 emit progressInfo(i18n("Loading playlist..."), 0);
869 //qApp->processEvents();
871 m_render->setSceneList(m_document.toString(), m_startPos);
872 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
875 emit progressInfo(QString(), -1);
878 void KdenliveDoc::checkProjectClips(bool displayRatioChanged, bool fpsChanged)
880 if (m_render == NULL) return;
881 m_clipManager->resetProducersList(m_render->producersList(), displayRatioChanged, fpsChanged);
884 Render *KdenliveDoc::renderer()
889 void KdenliveDoc::updateClip(const QString id)
891 emit updateClipDisplay(id);
894 int KdenliveDoc::getFramePos(QString duration)
896 return m_timecode.getFrameCount(duration);
899 QString KdenliveDoc::producerName(const QString &id)
901 QString result = "unnamed";
902 QDomNodeList prods = producersList();
903 int ct = prods.count();
904 for (int i = 0; i < ct ; i++) {
905 QDomElement e = prods.item(i).toElement();
906 if (e.attribute("id") != "black" && e.attribute("id") == id) {
907 result = e.attribute("name");
908 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
915 QDomDocument KdenliveDoc::toXml()
920 Timecode KdenliveDoc::timecode() const
925 QDomNodeList KdenliveDoc::producersList()
927 return m_document.elementsByTagName("producer");
930 double KdenliveDoc::projectDuration() const
933 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
938 double KdenliveDoc::fps() const
943 int KdenliveDoc::width() const
948 int KdenliveDoc::height() const
953 KUrl KdenliveDoc::url() const
958 void KdenliveDoc::setUrl(KUrl url)
963 void KdenliveDoc::setModified(bool mod)
965 if (isReadOnly()) return;
966 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
967 m_autoSaveTimer->start(3000);
969 if (mod == m_modified) return;
971 emit docModified(m_modified);
974 bool KdenliveDoc::isModified() const
979 const QString KdenliveDoc::description() const
982 return i18n("Untitled") + " / " + m_profile.description;
984 return m_url.fileName() + " / " + m_profile.description;
987 bool KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
989 const QString producerId = clipId.section('_', 0, 0);
990 DocClipBase *clip = m_clipManager->getClipById(producerId);
993 elem.setAttribute("id", producerId);
994 QString path = elem.attribute("resource");
996 if (elem.attribute("type").toInt() == SLIDESHOW) {
997 extension = KUrl(path).fileName();
998 path = KUrl(path).directory();
1001 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
1002 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1003 const QString size = elem.attribute("file_size");
1004 const QString hash = elem.attribute("file_hash");
1006 int action = KMessageBox::No;
1007 if (!size.isEmpty() && !hash.isEmpty()) {
1008 if (!m_searchFolder.isEmpty())
1009 newpath = searchFileRecursively(m_searchFolder, size, hash);
1011 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")));
1013 if (elem.attribute("type").toInt() == SLIDESHOW) {
1014 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")));
1015 if (res == KMessageBox::Yes)
1016 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1018 // Abort project loading
1022 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")));
1023 if (res == KMessageBox::Yes)
1024 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1026 // Abort project loading
1031 if (action == KMessageBox::Yes) {
1032 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1033 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1034 if (!m_searchFolder.isEmpty())
1035 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1036 } else if (action == KMessageBox::Cancel) {
1038 } else if (action == KMessageBox::No) {
1039 // Keep clip as placeHolder
1040 elem.setAttribute("placeholder", '1');
1042 if (!newpath.isEmpty()) {
1043 if (elem.attribute("type").toInt() == SLIDESHOW)
1044 newpath.append('/' + extension);
1045 elem.setAttribute("resource", newpath);
1046 setNewClipResource(clipId, newpath);
1050 clip = new DocClipBase(m_clipManager, elem, producerId);
1051 m_clipManager->addClip(clip);
1054 if (createClipItem) {
1055 emit addProjectClip(clip);
1061 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1063 QDomNodeList prods = m_document.elementsByTagName("producer");
1064 int maxprod = prods.count();
1065 for (int i = 0; i < maxprod; i++) {
1066 QDomNode m = prods.at(i);
1067 QString prodId = m.toElement().attribute("id");
1068 if (prodId == id || prodId.startsWith(id + '_')) {
1069 QDomNodeList params = m.childNodes();
1070 for (int j = 0; j < params.count(); j++) {
1071 QDomElement e = params.item(j).toElement();
1072 if (e.attribute("name") == "resource") {
1073 e.firstChild().setNodeValue(path);
1081 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1083 QString foundFileName;
1084 QByteArray fileData;
1085 QByteArray fileHash;
1086 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1087 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1088 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1089 if (file.open(QIODevice::ReadOnly)) {
1090 if (QString::number(file.size()) == matchSize) {
1092 * 1 MB = 1 second per 450 files (or faster)
1093 * 10 MB = 9 seconds per 450 files (or faster)
1095 if (file.size() > 1000000 * 2) {
1096 fileData = file.read(1000000);
1097 if (file.seek(file.size() - 1000000))
1098 fileData.append(file.readAll());
1100 fileData = file.readAll();
1102 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1103 if (QString(fileHash.toHex()) == matchHash)
1104 return file.fileName();
1107 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1109 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1110 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1111 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1112 if (!foundFileName.isEmpty())
1115 return foundFileName;
1118 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1120 DocClipBase *clip = m_clipManager->getClipById(clipId);
1122 if (!addClip(elem, clipId, false))
1125 QMap <QString, QString> properties;
1126 QDomNamedNodeMap attributes = elem.attributes();
1127 for (int i = 0; i < attributes.count(); i++) {
1128 QString attrname = attributes.item(i).nodeName();
1129 if (attrname != "resource")
1130 properties.insert(attrname, attributes.item(i).nodeValue());
1131 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1133 clip->setProperties(properties);
1134 emit addProjectClip(clip, false);
1136 if (orig != QDomElement()) {
1137 QMap<QString, QString> meta;
1138 for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1139 QString name = m.toElement().attribute("name");
1140 if (name.startsWith("meta.attr"))
1141 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1143 if (!meta.isEmpty()) {
1145 clip = m_clipManager->getClipById(clipId);
1147 clip->setMetadata(meta);
1154 void KdenliveDoc::deleteClip(const QString &clipId)
1156 emit signalDeleteProjectClip(clipId);
1159 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1161 m_clipManager->slotAddClipList(urls, group, groupId);
1162 //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1167 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1169 m_clipManager->slotAddClipFile(url, group, groupId);
1170 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1174 const QString KdenliveDoc::getFreeClipId()
1176 return QString::number(m_clipManager->getFreeClipId());
1179 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1181 return m_clipManager->getClipById(clipId);
1184 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement xml, QString group, const QString &groupId)
1186 m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1188 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1191 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1193 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1195 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1198 void KdenliveDoc::slotCreateSlideshowClipFile(const QString name, const QString path, int count, const QString duration,
1199 const bool loop, const bool crop, const bool fade,
1200 const QString &luma_duration, const QString &luma_file, const int softness,
1201 const QString &animation, QString group, const QString &groupId)
1203 m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop,
1204 crop, fade, luma_duration,
1205 luma_file, softness,
1206 animation, group, groupId);
1208 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1211 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1213 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1214 KStandardDirs::makeDir(titlesFolder);
1215 TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1216 if (dia_ui->exec() == QDialog::Accepted) {
1217 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->outPoint(), dia_ui->xml().toString(), group, groupId);
1219 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1224 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1226 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1227 if (path.isEmpty()) {
1228 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1231 if (path.isEmpty()) return;
1233 //TODO: rewrite with new title system (just set resource)
1234 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1236 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1239 int KdenliveDoc::tracksCount() const
1241 return m_tracksList.count();
1244 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1246 if (ix < 0 || ix >= m_tracksList.count()) {
1247 kWarning() << "Track INFO outisde of range";
1250 return m_tracksList.at(ix);
1253 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1255 if (ix < 0 || ix >= m_tracksList.count()) {
1256 kWarning() << "SWITCH Track outisde of range";
1259 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1262 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1264 if (ix < 0 || ix >= m_tracksList.count()) {
1265 kWarning() << "Track Lock outisde of range";
1268 m_tracksList[ix].isLocked = lock;
1271 bool KdenliveDoc::isTrackLocked(int ix) const
1273 if (ix < 0 || ix >= m_tracksList.count()) {
1274 kWarning() << "Track Lock outisde of range";
1277 return m_tracksList.at(ix).isLocked;
1280 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1282 if (ix < 0 || ix >= m_tracksList.count()) {
1283 kWarning() << "SWITCH Track outisde of range";
1286 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1289 int KdenliveDoc::trackDuration(int ix)
1291 return m_tracksList.at(ix).duration;
1294 void KdenliveDoc::setTrackDuration(int ix, int duration)
1296 m_tracksList[ix].duration = duration;
1299 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1301 if (ix == -1) m_tracksList << type;
1302 else m_tracksList.insert(ix, type);
1305 void KdenliveDoc::deleteTrack(int ix)
1307 if (ix < 0 || ix >= m_tracksList.count()) {
1308 kWarning() << "Delete Track outisde of range";
1311 m_tracksList.removeAt(ix);
1314 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1316 if (ix < 0 || ix >= m_tracksList.count()) {
1317 kWarning() << "SET Track Type outisde of range";
1320 m_tracksList[ix].type = type.type;
1321 m_tracksList[ix].isMute = type.isMute;
1322 m_tracksList[ix].isBlind = type.isBlind;
1323 m_tracksList[ix].isLocked = type.isLocked;
1324 m_tracksList[ix].trackName = type.trackName;
1327 const QList <TrackInfo> KdenliveDoc::tracksList() const
1329 return m_tracksList;
1332 QPoint KdenliveDoc::getTracksCount() const
1336 foreach(const TrackInfo & info, m_tracksList) {
1337 if (info.type == VIDEOTRACK) video++;
1340 return QPoint(video, audio);
1343 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1345 pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1348 QString KdenliveDoc::getLadspaFile() const
1351 QString counter = QString::number(ct).rightJustified(5, '0', false);
1352 while (QFile::exists(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa")) {
1354 counter = QString::number(ct).rightJustified(5, '0', false);
1356 return m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa";
1359 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1361 DocumentChecker d(infoproducers, m_document);
1362 return (d.hasErrorInClips() == false);
1368 QList <QDomElement> missingClips;
1369 for (int i = 0; i < infoproducers.count(); i++) {
1370 e = infoproducers.item(i).toElement();
1371 clipType = e.attribute("type").toInt();
1372 if (clipType == COLOR) continue;
1373 if (clipType == TEXT) {
1374 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1377 id = e.attribute("id");
1378 resource = e.attribute("resource");
1379 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1380 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1381 // Missing clip found
1382 missingClips.append(e);
1384 // Check if the clip has changed
1385 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1386 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1387 e.removeAttribute("file_hash");
1391 if (missingClips.isEmpty()) return true;
1392 DocumentChecker d(missingClips, m_document);
1393 return (d.exec() == QDialog::Accepted);*/
1396 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1398 m_documentProperties[name] = value;
1401 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1403 return m_documentProperties.value(name);
1406 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1408 QMap <QString, QString> renderProperties;
1409 QMapIterator<QString, QString> i(m_documentProperties);
1410 while (i.hasNext()) {
1412 if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1414 return renderProperties;
1417 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1419 if (ix < 0 || ix >= m_tracksList.count()) {
1420 kWarning() << "Add Track effect outisde of range";
1423 effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1425 // Init parameter value & keyframes if required
1426 QDomNodeList params = effect.elementsByTagName("parameter");
1427 for (int i = 0; i < params.count(); i++) {
1428 QDomElement e = params.item(i).toElement();
1430 // Check if this effect has a variable parameter
1431 if (e.attribute("default").contains('%')) {
1432 double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1433 e.setAttribute("default", evaluatedValue);
1434 if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1435 e.setAttribute("value", evaluatedValue);
1439 if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1440 QString def = e.attribute("default");
1441 // Effect has a keyframe type parameter, we need to set the values
1442 if (e.attribute("keyframes").isEmpty()) {
1443 e.setAttribute("keyframes", "0:" + def + ';');
1444 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1449 if (effect.attribute("id") == "crop") {
1450 // default use_profile to 1 for clips with proxies to avoid problems when rendering
1451 if (e.attribute("name") == "use_profile" && getDocumentProperty("enableproxy") == "1")
1452 e.setAttribute("value", "1");
1456 m_tracksList[ix].effectsList.append(effect);
1459 void KdenliveDoc::removeTrackEffect(int ix, QDomElement effect)
1461 if (ix < 0 || ix >= m_tracksList.count()) {
1462 kWarning() << "Remove Track effect outisde of range";
1466 QString toRemove = effect.attribute("kdenlive_ix");
1467 for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1468 index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix");
1469 if (toRemove == index) {
1470 m_tracksList[ix].effectsList.removeAt(i);
1472 } else if (index.toInt() > toRemove.toInt()) {
1473 m_tracksList[ix].effectsList.item(i).setAttribute("kdenlive_ix", index.toInt() - 1);
1478 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1480 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1481 kWarning() << "Set Track effect outisde of range";
1484 if (effectIndex < 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count() - 1) || effect.isNull()) {
1485 kDebug() << "Invalid effect index: " << effectIndex;
1488 effect.setAttribute("kdenlive_ix", effectIndex + 1);
1489 m_tracksList[trackIndex].effectsList.replace(effectIndex, effect);
1492 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1494 if (ix < 0 || ix >= m_tracksList.count()) {
1495 kWarning() << "Get Track effects outisde of range";
1496 return EffectsList();
1498 return m_tracksList.at(ix).effectsList;
1501 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1503 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1504 kWarning() << "Get Track effect outisde of range";
1505 return QDomElement();
1507 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1508 if (effectIndex > list.count() - 1 || effectIndex < 0 || list.at(effectIndex).isNull()) return QDomElement();
1509 return list.at(effectIndex).cloneNode().toElement();
1512 bool KdenliveDoc::saveCustomEffects(QDomNodeList customeffects)
1515 QStringList importedEffects;
1516 int maxchild = customeffects.count();
1517 for (int i = 0; i < maxchild; i++) {
1518 e = customeffects.at(i).toElement();
1519 QString id = e.attribute("id");
1520 QString tag = e.attribute("tag");
1521 if (!id.isEmpty()) {
1522 // Check if effect exists or save it
1523 if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1525 doc.appendChild(doc.importNode(e, true));
1526 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1527 path += id + ".xml";
1528 if (!QFile::exists(path)) {
1529 importedEffects << id;
1531 if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1532 QTextStream out(&file);
1533 out << doc.toString();
1539 if (!importedEffects.isEmpty()) KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1540 return (!importedEffects.isEmpty());
1543 void KdenliveDoc::updateProjectFolderPlacesEntry()
1546 * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1547 * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1550 const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1551 KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1552 KBookmarkGroup root = bookmarkManager->root();
1553 KBookmark bookmark = root.first();
1555 QString kdenliveName = KGlobal::mainComponent().componentName();
1556 KUrl documentLocation = m_projectFolder;
1558 bool exists = false;
1560 while (!bookmark.isNull()) {
1561 // UDI not empty indicates a device
1562 QString udi = bookmark.metaDataItem("UDI");
1563 QString appName = bookmark.metaDataItem("OnlyInApp");
1565 if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1566 if (bookmark.url() != documentLocation) {
1567 bookmark.setUrl(documentLocation);
1568 bookmarkManager->emitChanged(root);
1574 bookmark = root.next(bookmark);
1577 // if entry does not exist yet (was not found), well, create it then
1579 bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1580 // Make this user selectable ?
1581 bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1582 bookmarkManager->emitChanged(root);
1586 QStringList KdenliveDoc::getExpandedFolders()
1588 QStringList result = m_documentProperties.value("expandedfolders").split(';');
1589 // this property is only needed once when opening project, so clear it now
1590 m_documentProperties.remove("expandedfolders");
1595 double KdenliveDoc::getDisplayRatio(const QString &path)
1599 if (!file.open(QIODevice::ReadOnly)) {
1600 kWarning() << "ERROR, CANNOT READ: " << path;
1603 if (!doc.setContent(&file)) {
1604 kWarning() << "ERROR, CANNOT READ: " << path;
1609 QDomNodeList list = doc.elementsByTagName("profile");
1610 if (list.isEmpty()) return 0;
1611 QDomElement profile = list.at(0).toElement();
1612 double den = profile.attribute("display_aspect_den").toDouble();
1613 if (den > 0) return profile.attribute("display_aspect_num").toDouble() / den;
1617 void KdenliveDoc::backupLastSavedVersion(const QString &path)
1619 // Ensure backup folder exists
1620 if (path.isEmpty()) return;
1622 KUrl backupFile = m_projectFolder;
1623 backupFile.addPath(".backup/");
1624 KIO::NetAccess::mkdir(backupFile, kapp->activeWindow());
1625 QString fileName = KUrl(path).fileName().section('.', 0, -2);
1626 QFileInfo info(file);
1627 fileName.append("-" + m_documentProperties.value("documentid"));
1628 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
1629 fileName.append(".kdenlive");
1630 backupFile.addPath(fileName);
1632 if (file.exists()) {
1633 // delete previous backup if it was done less than 60 seconds ago
1634 QFile::remove(backupFile.path());
1635 if (!QFile::copy(path, backupFile.path())) {
1636 KMessageBox::information(kapp->activeWindow(), i18n("Cannot create backup copy:\n%1", backupFile.path()));
1641 bool KdenliveDoc::isReadOnly() const
1643 return m_documentProperties.contains("readonly");
1646 void KdenliveDoc::cleanupBackupFiles()
1648 KUrl backupFile = m_projectFolder;
1649 backupFile.addPath(".backup/");
1650 QDir dir(backupFile.path());
1651 QString projectFile = url().fileName().section('.', 0, -2);
1652 projectFile.append("-" + m_documentProperties.value("documentid"));
1653 projectFile.append("-??");
1654 projectFile.append("??");
1655 projectFile.append("-??");
1656 projectFile.append("-??");
1657 projectFile.append("-??");
1658 projectFile.append("-??.kdenlive");
1661 backupFile.addPath(projectFile);
1662 filter << projectFile;
1663 dir.setNameFilters(filter);
1664 QFileInfoList resultList = dir.entryInfoList(QDir::Files, QDir::Time);
1666 QDateTime d = QDateTime::currentDateTime();
1667 QStringList hourList;
1668 QStringList dayList;
1669 QStringList weekList;
1670 QStringList oldList;
1671 for (int i = 0; i < resultList.count(); i++) {
1672 if (d.secsTo(resultList.at(i).lastModified()) < 3600) {
1673 // files created in the last hour
1674 hourList.append(resultList.at(i).absoluteFilePath());
1676 else if (d.secsTo(resultList.at(i).lastModified()) < 43200) {
1677 // files created in the day
1678 dayList.append(resultList.at(i).absoluteFilePath());
1680 else if (d.daysTo(resultList.at(i).lastModified()) < 8) {
1681 // files created in the week
1682 weekList.append(resultList.at(i).absoluteFilePath());
1686 oldList.append(resultList.at(i).absoluteFilePath());
1689 if (hourList.count() > 20) {
1690 int step = hourList.count() / 10;
1691 for (int i = 0; i < hourList.count(); i += step) {
1692 kDebug()<<"REMOVE AT: "<<i<<", COUNT: "<<hourList.count();
1693 hourList.removeAt(i);
1696 } else hourList.clear();
1697 if (dayList.count() > 20) {
1698 int step = dayList.count() / 10;
1699 for (int i = 0; i < dayList.count(); i += step) {
1700 dayList.removeAt(i);
1703 } else dayList.clear();
1704 if (weekList.count() > 20) {
1705 int step = weekList.count() / 10;
1706 for (int i = 0; i < weekList.count(); i += step) {
1707 weekList.removeAt(i);
1710 } else weekList.clear();
1711 if (oldList.count() > 20) {
1712 int step = oldList.count() / 10;
1713 for (int i = 0; i < oldList.count(); i += step) {
1714 oldList.removeAt(i);
1717 } else oldList.clear();
1720 while (hourList.count() > 0) {
1721 f = hourList.takeFirst();
1723 QFile::remove(f + ".png");
1725 while (dayList.count() > 0) {
1726 f = dayList.takeFirst();
1728 QFile::remove(f + ".png");
1730 while (weekList.count() > 0) {
1731 f = weekList.takeFirst();
1733 QFile::remove(f + ".png");
1735 while (oldList.count() > 0) {
1736 f = oldList.takeFirst();
1738 QFile::remove(f + ".png");
1742 #include "kdenlivedoc.moc"