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.88;
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();
98 if (QLocale() != QLocale::system()) {
99 QLocale::setDefault(QLocale::system());
100 // locale conversion might need to be redone
101 initEffects::parseEffectFiles();
106 if (!url.isEmpty()) {
108 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
110 // The file cannot be opened
111 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) {
114 //KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
119 QDomImplementation impl;
120 impl.setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
121 success = m_document.setContent(&file, false, &errorMsg);
123 KIO::NetAccess::removeTempFile(tmpFile);
127 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) {
130 //KMessageBox::error(parent, errorMsg);
133 parent->slotGotProgressInfo(i18n("Validating"), 0);
134 qApp->processEvents();
135 DocumentValidator validator(m_document);
136 success = validator.isProject();
138 // It is not a project file
139 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
140 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) {
145 * Validate the file against the current version (upgrade
146 * and recover it if needed). It is NOT a passive operation
148 // TODO: backup the document or alert the user?
149 success = validator.validate(DOCUMENTVERSION);
150 if (success) { // Let the validator handle error messages
151 parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
152 qApp->processEvents();
153 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
154 success = checkDocumentClips(infoproducers);
156 if (m_document.documentElement().attribute("modified") == "1") setModified(true);
157 parent->slotGotProgressInfo(i18n("Loading"), 0);
158 QDomElement mlt = m_document.firstChildElement("mlt");
159 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
161 // Set profile, fps, etc for the document
162 setProfilePath(infoXml.attribute("profile"));
164 // Check embedded effects
165 QDomElement customeffects = infoXml.firstChildElement("customeffects");
166 if (!customeffects.isNull() && customeffects.hasChildNodes()) {
167 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
168 qApp->processEvents();
169 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
174 QDomElement notesxml = infoXml.firstChildElement("documentnotes");
175 if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
178 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
179 if (!tracksinfo.isNull()) {
180 QDomNodeList trackslist = tracksinfo.childNodes();
181 int maxchild = trackslist.count();
182 for (int k = 0; k < maxchild; k++) {
183 e = trackslist.at(k).toElement();
184 if (e.tagName() == "trackinfo") {
185 TrackInfo projectTrack;
186 if (e.attribute("type") == "audio")
187 projectTrack.type = AUDIOTRACK;
189 projectTrack.type = VIDEOTRACK;
190 projectTrack.isMute = e.attribute("mute").toInt();
191 projectTrack.isBlind = e.attribute("blind").toInt();
192 projectTrack.isLocked = e.attribute("locked").toInt();
193 projectTrack.trackName = e.attribute("trackname");
194 m_tracksList.append(projectTrack);
197 mlt.removeChild(tracksinfo);
199 QStringList expandedFolders;
200 QDomNodeList folders = m_document.elementsByTagName("folder");
201 for (int i = 0; i < folders.count(); i++) {
202 e = folders.item(i).cloneNode().toElement();
203 if (e.hasAttribute("opened")) expandedFolders.append(e.attribute("id"));
204 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
206 m_documentProperties["expandedfolders"] = expandedFolders.join(";");
208 const int infomax = infoproducers.count();
209 QDomNodeList producers = m_document.elementsByTagName("producer");
210 const int max = producers.count();
212 if (!progressDialog) {
213 progressDialog = new KProgressDialog(parent, i18n("Loading project"), i18n("Adding clips"));
214 progressDialog->setAllowCancel(false);
216 progressDialog->setLabelText(i18n("Adding clips"));
218 progressDialog->progressBar()->setMaximum(infomax);
219 progressDialog->show();
220 qApp->processEvents();
222 for (int i = 0; i < infomax; i++) {
223 e = infoproducers.item(i).cloneNode().toElement();
224 QString prodId = e.attribute("id");
225 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
226 e.setTagName("producer");
227 // Get MLT's original producer properties
229 for (int j = 0; j < max; j++) {
230 QDomNode o = producers.item(j);
231 QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
232 if (origId == prodId) {
233 orig = o.cloneNode().toElement();
238 if (!addClipInfo(e, orig, prodId)) {
239 // The user manually aborted the loading.
241 emit resetProjectList();
242 m_tracksList.clear();
243 m_clipManager->clear();
248 progressDialog->progressBar()->setValue(i);
252 QDomElement markers = infoXml.firstChildElement("markers");
253 if (!markers.isNull()) {
254 QDomNodeList markerslist = markers.childNodes();
255 int maxchild = markerslist.count();
256 for (int k = 0; k < maxchild; k++) {
257 e = markerslist.at(k).toElement();
258 if (e.tagName() == "marker")
259 m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
261 infoXml.removeChild(markers);
264 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
265 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
266 QDomNamedNodeMap props = docproperties.attributes();
267 for (int i = 0; i < props.count(); i++)
268 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
270 if (validator.isModified()) setModified(true);
271 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
280 // Something went wrong, or a new file was requested: create a new project
283 setProfilePath(profileName);
284 m_document = createEmptyDocument(tracks.x(), tracks.y());
287 // Ask to create the project directory if it does not exist
288 if (!QFile::exists(m_projectFolder.path())) {
289 int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
290 if (create == KMessageBox::Yes) {
291 QDir projectDir(m_projectFolder.path());
292 bool ok = projectDir.mkpath(m_projectFolder.path());
294 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
299 // Make sure the project folder is usable
300 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
301 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
302 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
305 // Make sure that the necessary folders exist
306 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
307 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
308 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/");
310 updateProjectFolderPlacesEntry();
312 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
313 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
316 KdenliveDoc::~KdenliveDoc()
318 m_autoSaveTimer->stop();
319 delete m_commandStack;
320 kDebug() << "// DEL CLP MAN";
321 delete m_clipManager;
322 kDebug() << "// DEL CLP MAN done";
323 delete m_autoSaveTimer;
325 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
330 int KdenliveDoc::setSceneList()
332 m_render->resetProfile(KdenliveSettings::current_profile(), true);
333 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
334 // INVALID MLT Consumer, something is wrong
337 m_documentProperties.remove("position");
338 // m_document xml is now useless, clear it
343 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
345 m_tracksList.clear();
347 // Tracks are added «backwards», so we need to reverse the track numbering
348 // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
349 // Better default names for tracks: Audio 1 etc. instead of blank numbers
350 for (int i = 0; i < audiotracks; i++) {
351 TrackInfo audioTrack;
352 audioTrack.type = AUDIOTRACK;
353 audioTrack.isMute = false;
354 audioTrack.isBlind = true;
355 audioTrack.isLocked = false;
356 audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
357 audioTrack.duration = 0;
358 m_tracksList.append(audioTrack);
361 for (int i = 0; i < videotracks; i++) {
362 TrackInfo videoTrack;
363 videoTrack.type = VIDEOTRACK;
364 videoTrack.isMute = false;
365 videoTrack.isBlind = false;
366 videoTrack.isLocked = false;
367 videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
368 videoTrack.duration = 0;
369 m_tracksList.append(videoTrack);
371 return createEmptyDocument(m_tracksList);
374 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
376 // Creating new document
378 QDomElement mlt = doc.createElement("mlt");
379 mlt.setAttribute("LC_NUMERIC", "");
380 doc.appendChild(mlt);
382 // Create black producer
383 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
384 // the composite transitions with the black track are corrupted.
385 QDomElement blk = doc.createElement("producer");
386 blk.setAttribute("in", 0);
387 blk.setAttribute("out", 500);
388 blk.setAttribute("id", "black");
390 QDomElement property = doc.createElement("property");
391 property.setAttribute("name", "mlt_type");
392 QDomText value = doc.createTextNode("producer");
393 property.appendChild(value);
394 blk.appendChild(property);
396 property = doc.createElement("property");
397 property.setAttribute("name", "aspect_ratio");
398 value = doc.createTextNode(QString::number(0));
399 property.appendChild(value);
400 blk.appendChild(property);
402 property = doc.createElement("property");
403 property.setAttribute("name", "length");
404 value = doc.createTextNode(QString::number(15000));
405 property.appendChild(value);
406 blk.appendChild(property);
408 property = doc.createElement("property");
409 property.setAttribute("name", "eof");
410 value = doc.createTextNode("pause");
411 property.appendChild(value);
412 blk.appendChild(property);
414 property = doc.createElement("property");
415 property.setAttribute("name", "resource");
416 value = doc.createTextNode("black");
417 property.appendChild(value);
418 blk.appendChild(property);
420 property = doc.createElement("property");
421 property.setAttribute("name", "mlt_service");
422 value = doc.createTextNode("colour");
423 property.appendChild(value);
424 blk.appendChild(property);
426 mlt.appendChild(blk);
429 QDomElement tractor = doc.createElement("tractor");
430 tractor.setAttribute("id", "maintractor");
431 QDomElement multitrack = doc.createElement("multitrack");
432 QDomElement playlist = doc.createElement("playlist");
433 playlist.setAttribute("id", "black_track");
434 mlt.appendChild(playlist);
436 QDomElement blank0 = doc.createElement("entry");
437 blank0.setAttribute("in", "0");
438 blank0.setAttribute("out", "1");
439 blank0.setAttribute("producer", "black");
440 playlist.appendChild(blank0);
443 int total = tracks.count() + 1;
445 for (int i = 1; i < total; i++) {
446 QDomElement playlist = doc.createElement("playlist");
447 playlist.setAttribute("id", "playlist" + QString::number(i));
448 mlt.appendChild(playlist);
451 QDomElement track0 = doc.createElement("track");
452 track0.setAttribute("producer", "black_track");
453 tractor.appendChild(track0);
455 // create audio and video tracks
456 for (int i = 1; i < total; i++) {
457 QDomElement track = doc.createElement("track");
458 track.setAttribute("producer", "playlist" + QString::number(i));
459 if (tracks.at(i - 1).type == AUDIOTRACK) {
460 track.setAttribute("hide", "video");
461 } else if (tracks.at(i - 1).isBlind)
462 track.setAttribute("hide", "video");
463 if (tracks.at(i - 1).isMute)
464 track.setAttribute("hide", "audio");
465 tractor.appendChild(track);
468 for (int i = 2; i < total ; i++) {
469 QDomElement transition = doc.createElement("transition");
470 transition.setAttribute("always_active", "1");
472 QDomElement property = doc.createElement("property");
473 property.setAttribute("name", "a_track");
474 QDomText value = doc.createTextNode(QString::number(1));
475 property.appendChild(value);
476 transition.appendChild(property);
478 property = doc.createElement("property");
479 property.setAttribute("name", "b_track");
480 value = doc.createTextNode(QString::number(i));
481 property.appendChild(value);
482 transition.appendChild(property);
484 property = doc.createElement("property");
485 property.setAttribute("name", "mlt_service");
486 value = doc.createTextNode("mix");
487 property.appendChild(value);
488 transition.appendChild(property);
490 property = doc.createElement("property");
491 property.setAttribute("name", "combine");
492 value = doc.createTextNode("1");
493 property.appendChild(value);
494 transition.appendChild(property);
496 property = doc.createElement("property");
497 property.setAttribute("name", "internal_added");
498 value = doc.createTextNode("237");
499 property.appendChild(value);
500 transition.appendChild(property);
501 tractor.appendChild(transition);
503 mlt.appendChild(tractor);
508 void KdenliveDoc::syncGuides(QList <Guide *> guides)
511 QDomElement guideNode = m_guidesXml.createElement("guides");
512 m_guidesXml.appendChild(guideNode);
515 for (int i = 0; i < guides.count(); i++) {
516 e = m_guidesXml.createElement("guide");
517 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
518 e.setAttribute("comment", guides.at(i)->label());
519 guideNode.appendChild(e);
522 emit guidesUpdated();
525 QDomElement KdenliveDoc::guidesXml() const
527 return m_guidesXml.documentElement();
530 void KdenliveDoc::slotAutoSave()
532 if (m_render && m_autosave) {
533 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
534 // show error: could not open the autosave file
535 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
537 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
538 saveSceneList(m_autosave->fileName(), m_render->sceneList(), QStringList(), true);
542 void KdenliveDoc::setZoom(int horizontal, int vertical)
544 m_documentProperties["zoom"] = QString::number(horizontal);
545 m_documentProperties["verticalzoom"] = QString::number(vertical);
548 QPoint KdenliveDoc::zoom() const
550 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
553 void KdenliveDoc::setZone(int start, int end)
555 m_documentProperties["zonein"] = QString::number(start);
556 m_documentProperties["zoneout"] = QString::number(end);
559 QPoint KdenliveDoc::zone() const
561 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
564 QDomDocument KdenliveDoc::xmlSceneList(const QString &scene, const QStringList expandedFolders)
566 QDomDocument sceneList;
567 sceneList.setContent(scene, true);
568 QDomElement mlt = sceneList.firstChildElement("mlt");
569 if (mlt.isNull() || !mlt.hasChildNodes()) {
570 //scenelist is corrupted
574 // Set playlist audio volume to 100%
575 QDomElement tractor = mlt.firstChildElement("tractor");
576 if (!tractor.isNull()) {
577 QDomNodeList props = tractor.elementsByTagName("property");
578 for (int i = 0; i < props.count(); i++) {
579 if (props.at(i).toElement().attribute("name") == "meta.volume") {
580 props.at(i).firstChild().setNodeValue("1");
586 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
587 mlt.appendChild(addedXml);
589 // check if project contains custom effects to embed them in project file
590 QDomNodeList effects = mlt.elementsByTagName("filter");
591 int maxEffects = effects.count();
592 kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
593 QMap <QString, QString> effectIds;
594 for (int i = 0; i < maxEffects; i++) {
595 QDomNode m = effects.at(i);
596 QDomNodeList params = m.childNodes();
599 for (int j = 0; j < params.count(); j++) {
600 QDomElement e = params.item(j).toElement();
601 if (e.attribute("name") == "kdenlive_id") {
602 id = e.firstChild().nodeValue();
604 if (e.attribute("name") == "tag") {
605 tag = e.firstChild().nodeValue();
607 if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
610 QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
611 addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
613 QDomElement markers = sceneList.createElement("markers");
614 addedXml.setAttribute("version", DOCUMENTVERSION);
615 addedXml.setAttribute("kdenliveversion", VERSION);
616 addedXml.setAttribute("profile", profilePath());
617 addedXml.setAttribute("projectfolder", m_projectFolder.path());
619 QDomElement docproperties = sceneList.createElement("documentproperties");
620 QMapIterator<QString, QString> i(m_documentProperties);
621 while (i.hasNext()) {
623 docproperties.setAttribute(i.key(), i.value());
625 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
626 addedXml.appendChild(docproperties);
628 QDomElement docnotes = sceneList.createElement("documentnotes");
629 QDomText value = sceneList.createTextNode(m_notesWidget->toHtml());
630 docnotes.appendChild(value);
631 addedXml.appendChild(docnotes);
634 QDomElement profileinfo = sceneList.createElement("profileinfo");
635 profileinfo.setAttribute("description", m_profile.description);
636 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
637 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
638 profileinfo.setAttribute("width", m_profile.width);
639 profileinfo.setAttribute("height", m_profile.height);
640 profileinfo.setAttribute("progressive", m_profile.progressive);
641 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
642 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
643 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
644 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
645 addedXml.appendChild(profileinfo);
648 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
649 foreach(const TrackInfo & info, m_tracksList) {
650 QDomElement trackinfo = sceneList.createElement("trackinfo");
651 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
652 trackinfo.setAttribute("mute", info.isMute);
653 trackinfo.setAttribute("blind", info.isBlind);
654 trackinfo.setAttribute("locked", info.isLocked);
655 trackinfo.setAttribute("trackname", info.trackName);
656 tracksinfo.appendChild(trackinfo);
658 addedXml.appendChild(tracksinfo);
660 // save project folders
661 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
663 QMapIterator<QString, QString> f(folderlist);
664 while (f.hasNext()) {
666 QDomElement folder = sceneList.createElement("folder");
667 folder.setAttribute("id", f.key());
668 folder.setAttribute("name", f.value());
669 if (expandedFolders.contains(f.key())) folder.setAttribute("opened", "1");
670 addedXml.appendChild(folder);
673 // Save project clips
675 QList <DocClipBase*> list = m_clipManager->documentClipList();
676 for (int i = 0; i < list.count(); i++) {
677 e = list.at(i)->toXML();
678 e.setTagName("kdenlive_producer");
679 addedXml.appendChild(sceneList.importNode(e, true));
680 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
681 for (int j = 0; j < marks.count(); j++) {
682 QDomElement marker = sceneList.createElement("marker");
683 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
684 marker.setAttribute("comment", marks.at(j).comment());
685 marker.setAttribute("id", e.attribute("id"));
686 markers.appendChild(marker);
689 addedXml.appendChild(markers);
692 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
695 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
697 //wes.appendChild(doc.importNode(kdenliveData, true));
701 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene, const QStringList expandedFolders, bool autosave)
703 QDomDocument sceneList = xmlSceneList(scene, expandedFolders);
704 if (sceneList.isNull()) {
705 //Make sure we don't save if scenelist is corrupted
706 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
710 // Backup current version
711 if (!autosave) backupLastSavedVersion(path);
714 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
715 kWarning() << "////// ERROR writing to file: " << path;
716 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
720 file.write(sceneList.toString().toUtf8());
721 if (file.error() != QFile::NoError) {
722 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
728 cleanupBackupFiles();
729 QFileInfo info(file);
730 QString fileName = KUrl(path).fileName().section('.', 0, -2);
731 fileName.append("-" + m_documentProperties.value("documentid"));
732 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
733 fileName.append(".kdenlive.png");
734 KUrl backupFile = m_projectFolder;
735 backupFile.addPath(".backup/");
736 backupFile.addPath(fileName);
737 emit saveTimelinePreview(backupFile.path());
742 ClipManager *KdenliveDoc::clipManager()
744 return m_clipManager;
747 KUrl KdenliveDoc::projectFolder() const
749 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
750 return m_projectFolder;
753 void KdenliveDoc::setProjectFolder(KUrl url)
755 if (url == m_projectFolder) return;
757 KStandardDirs::makeDir(url.path());
758 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
759 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
760 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);
761 m_projectFolder = url;
763 updateProjectFolderPlacesEntry();
766 void KdenliveDoc::moveProjectData(KUrl url)
768 QList <DocClipBase*> list = m_clipManager->documentClipList();
769 for (int i = 0; i < list.count(); i++) {
770 DocClipBase *clip = list.at(i);
771 if (clip->clipType() == TEXT) {
772 // the image for title clip must be moved
773 KUrl oldUrl = clip->fileURL();
774 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
775 KIO::Job *job = KIO::copy(oldUrl, newUrl);
776 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
778 QString hash = clip->getClipHash();
779 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
780 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
781 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
782 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
783 KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
784 KIO::NetAccess::synchronousRun(job, 0);
786 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
787 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
788 KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
789 if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
794 const QString &KdenliveDoc::profilePath() const
796 return m_profile.path;
799 MltVideoProfile KdenliveDoc::mltProfile() const
804 bool KdenliveDoc::setProfilePath(QString path)
806 if (path.isEmpty()) path = KdenliveSettings::default_profile();
807 if (path.isEmpty()) path = "dv_pal";
808 m_profile = ProfilesDialog::getVideoProfile(path);
809 double current_fps = m_fps;
810 if (m_profile.path.isEmpty()) {
811 // Profile not found, use embedded profile
812 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
813 if (profileInfo.isNull()) {
814 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
815 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
817 m_profile.description = profileInfo.attribute("description");
818 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
819 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
820 m_profile.width = profileInfo.attribute("width").toInt();
821 m_profile.height = profileInfo.attribute("height").toInt();
822 m_profile.progressive = profileInfo.attribute("progressive").toInt();
823 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
824 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
825 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
826 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
827 QString existing = ProfilesDialog::existingProfile(m_profile);
828 if (!existing.isEmpty()) {
829 m_profile = ProfilesDialog::getVideoProfile(existing);
830 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
832 QString newDesc = m_profile.description;
834 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
835 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);
838 // User canceled, use default profile
839 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
841 if (newDesc != m_profile.description) {
842 // Profile description existed, was replaced by new one
843 m_profile.description = newDesc;
845 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
847 ProfilesDialog::saveProfile(m_profile);
854 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
855 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
856 KdenliveSettings::setProject_fps(m_fps);
857 m_width = m_profile.width;
858 m_height = m_profile.height;
859 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
860 m_timecode.setFormat(m_fps);
861 KdenliveSettings::setCurrent_profile(m_profile.path);
862 return (current_fps != m_fps);
865 double KdenliveDoc::dar() const
867 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
870 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
872 emit progressInfo(message, progress);
875 QUndoStack *KdenliveDoc::commandStack()
877 return m_commandStack;
881 void KdenliveDoc::setRenderer(Render *render) {
882 if (m_render) return;
884 emit progressInfo(i18n("Loading playlist..."), 0);
885 //qApp->processEvents();
887 m_render->setSceneList(m_document.toString(), m_startPos);
888 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
891 emit progressInfo(QString(), -1);
894 void KdenliveDoc::checkProjectClips(bool displayRatioChanged, bool fpsChanged)
896 if (m_render == NULL) return;
897 m_clipManager->resetProducersList(m_render->producersList(), displayRatioChanged, fpsChanged);
900 Render *KdenliveDoc::renderer()
905 void KdenliveDoc::updateClip(const QString id)
907 emit updateClipDisplay(id);
910 int KdenliveDoc::getFramePos(QString duration)
912 return m_timecode.getFrameCount(duration);
915 QString KdenliveDoc::producerName(const QString &id)
917 QString result = "unnamed";
918 QDomNodeList prods = producersList();
919 int ct = prods.count();
920 for (int i = 0; i < ct ; i++) {
921 QDomElement e = prods.item(i).toElement();
922 if (e.attribute("id") != "black" && e.attribute("id") == id) {
923 result = e.attribute("name");
924 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
931 QDomDocument KdenliveDoc::toXml()
936 Timecode KdenliveDoc::timecode() const
941 QDomNodeList KdenliveDoc::producersList()
943 return m_document.elementsByTagName("producer");
946 double KdenliveDoc::projectDuration() const
949 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
954 double KdenliveDoc::fps() const
959 int KdenliveDoc::width() const
964 int KdenliveDoc::height() const
969 KUrl KdenliveDoc::url() const
974 void KdenliveDoc::setUrl(KUrl url)
979 void KdenliveDoc::setModified(bool mod)
981 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
982 m_autoSaveTimer->start(3000);
984 if (mod == m_modified) return;
986 emit docModified(m_modified);
989 bool KdenliveDoc::isModified() const
994 const QString KdenliveDoc::description() const
997 return i18n("Untitled") + " / " + m_profile.description;
999 return m_url.fileName() + " / " + m_profile.description;
1002 bool KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
1004 const QString producerId = clipId.section('_', 0, 0);
1005 DocClipBase *clip = m_clipManager->getClipById(producerId);
1008 elem.setAttribute("id", producerId);
1009 QString path = elem.attribute("resource");
1011 if (elem.attribute("type").toInt() == SLIDESHOW) {
1012 extension = KUrl(path).fileName();
1013 path = KUrl(path).directory();
1016 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
1017 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1018 const QString size = elem.attribute("file_size");
1019 const QString hash = elem.attribute("file_hash");
1021 int action = KMessageBox::No;
1022 if (!size.isEmpty() && !hash.isEmpty()) {
1023 if (!m_searchFolder.isEmpty())
1024 newpath = searchFileRecursively(m_searchFolder, size, hash);
1026 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")));
1028 if (elem.attribute("type").toInt() == SLIDESHOW) {
1029 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")));
1030 if (res == KMessageBox::Yes)
1031 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1033 // Abort project loading
1037 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")));
1038 if (res == KMessageBox::Yes)
1039 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1041 // Abort project loading
1046 if (action == KMessageBox::Yes) {
1047 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1048 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1049 if (!m_searchFolder.isEmpty())
1050 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1051 } else if (action == KMessageBox::Cancel) {
1053 } else if (action == KMessageBox::No) {
1054 // Keep clip as placeHolder
1055 elem.setAttribute("placeholder", '1');
1057 if (!newpath.isEmpty()) {
1058 if (elem.attribute("type").toInt() == SLIDESHOW)
1059 newpath.append('/' + extension);
1060 elem.setAttribute("resource", newpath);
1061 setNewClipResource(clipId, newpath);
1065 clip = new DocClipBase(m_clipManager, elem, producerId);
1066 m_clipManager->addClip(clip);
1069 if (createClipItem) {
1070 emit addProjectClip(clip);
1076 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1078 QDomNodeList prods = m_document.elementsByTagName("producer");
1079 int maxprod = prods.count();
1080 for (int i = 0; i < maxprod; i++) {
1081 QDomNode m = prods.at(i);
1082 QString prodId = m.toElement().attribute("id");
1083 if (prodId == id || prodId.startsWith(id + '_')) {
1084 QDomNodeList params = m.childNodes();
1085 for (int j = 0; j < params.count(); j++) {
1086 QDomElement e = params.item(j).toElement();
1087 if (e.attribute("name") == "resource") {
1088 e.firstChild().setNodeValue(path);
1096 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1098 QString foundFileName;
1099 QByteArray fileData;
1100 QByteArray fileHash;
1101 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1102 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1103 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1104 if (file.open(QIODevice::ReadOnly)) {
1105 if (QString::number(file.size()) == matchSize) {
1107 * 1 MB = 1 second per 450 files (or faster)
1108 * 10 MB = 9 seconds per 450 files (or faster)
1110 if (file.size() > 1000000 * 2) {
1111 fileData = file.read(1000000);
1112 if (file.seek(file.size() - 1000000))
1113 fileData.append(file.readAll());
1115 fileData = file.readAll();
1117 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1118 if (QString(fileHash.toHex()) == matchHash)
1119 return file.fileName();
1122 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1124 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1125 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1126 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1127 if (!foundFileName.isEmpty())
1130 return foundFileName;
1133 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1135 DocClipBase *clip = m_clipManager->getClipById(clipId);
1137 if (!addClip(elem, clipId, false))
1140 QMap <QString, QString> properties;
1141 QDomNamedNodeMap attributes = elem.attributes();
1142 for (int i = 0; i < attributes.count(); i++) {
1143 QString attrname = attributes.item(i).nodeName();
1144 if (attrname != "resource")
1145 properties.insert(attrname, attributes.item(i).nodeValue());
1146 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1148 clip->setProperties(properties);
1149 emit addProjectClip(clip, false);
1151 if (orig != QDomElement()) {
1152 QMap<QString, QString> meta;
1153 for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1154 QString name = m.toElement().attribute("name");
1155 if (name.startsWith("meta.attr"))
1156 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1158 if (!meta.isEmpty()) {
1160 clip = m_clipManager->getClipById(clipId);
1162 clip->setMetadata(meta);
1169 void KdenliveDoc::deleteClip(const QString &clipId)
1171 emit signalDeleteProjectClip(clipId);
1174 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1176 m_clipManager->slotAddClipList(urls, group, groupId);
1177 //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1182 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1184 m_clipManager->slotAddClipFile(url, group, groupId);
1185 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1189 const QString KdenliveDoc::getFreeClipId()
1191 return QString::number(m_clipManager->getFreeClipId());
1194 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1196 return m_clipManager->getClipById(clipId);
1199 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement xml, QString group, const QString &groupId)
1201 m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1203 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1206 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1208 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1210 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1213 void KdenliveDoc::slotCreateSlideshowClipFile(const QString name, const QString path, int count, const QString duration,
1214 const bool loop, const bool crop, const bool fade,
1215 const QString &luma_duration, const QString &luma_file, const int softness,
1216 const QString &animation, QString group, const QString &groupId)
1218 m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop,
1219 crop, fade, luma_duration,
1220 luma_file, softness,
1221 animation, group, groupId);
1223 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1226 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1228 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1229 KStandardDirs::makeDir(titlesFolder);
1230 TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1231 if (dia_ui->exec() == QDialog::Accepted) {
1232 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->outPoint(), dia_ui->xml().toString(), group, groupId);
1234 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1239 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1241 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1242 if (path.isEmpty()) {
1243 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1246 if (path.isEmpty()) return;
1248 //TODO: rewrite with new title system (just set resource)
1249 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1251 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1254 int KdenliveDoc::tracksCount() const
1256 return m_tracksList.count();
1259 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1261 if (ix < 0 || ix >= m_tracksList.count()) {
1262 kWarning() << "Track INFO outisde of range";
1265 return m_tracksList.at(ix);
1268 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1270 if (ix < 0 || ix >= m_tracksList.count()) {
1271 kWarning() << "SWITCH Track outisde of range";
1274 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1277 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1279 if (ix < 0 || ix >= m_tracksList.count()) {
1280 kWarning() << "Track Lock outisde of range";
1283 m_tracksList[ix].isLocked = lock;
1286 bool KdenliveDoc::isTrackLocked(int ix) const
1288 if (ix < 0 || ix >= m_tracksList.count()) {
1289 kWarning() << "Track Lock outisde of range";
1292 return m_tracksList.at(ix).isLocked;
1295 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1297 if (ix < 0 || ix >= m_tracksList.count()) {
1298 kWarning() << "SWITCH Track outisde of range";
1301 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1304 int KdenliveDoc::trackDuration(int ix)
1306 return m_tracksList.at(ix).duration;
1309 void KdenliveDoc::setTrackDuration(int ix, int duration)
1311 m_tracksList[ix].duration = duration;
1314 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1316 if (ix == -1) m_tracksList << type;
1317 else m_tracksList.insert(ix, type);
1320 void KdenliveDoc::deleteTrack(int ix)
1322 if (ix < 0 || ix >= m_tracksList.count()) {
1323 kWarning() << "Delete Track outisde of range";
1326 m_tracksList.removeAt(ix);
1329 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1331 if (ix < 0 || ix >= m_tracksList.count()) {
1332 kWarning() << "SET Track Type outisde of range";
1335 m_tracksList[ix].type = type.type;
1336 m_tracksList[ix].isMute = type.isMute;
1337 m_tracksList[ix].isBlind = type.isBlind;
1338 m_tracksList[ix].isLocked = type.isLocked;
1339 m_tracksList[ix].trackName = type.trackName;
1342 const QList <TrackInfo> KdenliveDoc::tracksList() const
1344 return m_tracksList;
1347 QPoint KdenliveDoc::getTracksCount() const
1351 foreach(const TrackInfo & info, m_tracksList) {
1352 if (info.type == VIDEOTRACK) video++;
1355 return QPoint(video, audio);
1358 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1360 pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1363 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1365 DocumentChecker d(infoproducers, m_document);
1366 return (d.hasErrorInClips() == false);
1372 QList <QDomElement> missingClips;
1373 for (int i = 0; i < infoproducers.count(); i++) {
1374 e = infoproducers.item(i).toElement();
1375 clipType = e.attribute("type").toInt();
1376 if (clipType == COLOR) continue;
1377 if (clipType == TEXT) {
1378 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1381 id = e.attribute("id");
1382 resource = e.attribute("resource");
1383 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1384 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1385 // Missing clip found
1386 missingClips.append(e);
1388 // Check if the clip has changed
1389 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1390 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1391 e.removeAttribute("file_hash");
1395 if (missingClips.isEmpty()) return true;
1396 DocumentChecker d(missingClips, m_document);
1397 return (d.exec() == QDialog::Accepted);*/
1400 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1402 m_documentProperties[name] = value;
1405 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1407 return m_documentProperties.value(name);
1410 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1412 QMap <QString, QString> renderProperties;
1413 QMapIterator<QString, QString> i(m_documentProperties);
1414 while (i.hasNext()) {
1416 if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1418 return renderProperties;
1421 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1423 if (ix < 0 || ix >= m_tracksList.count()) {
1424 kWarning() << "Add Track effect outisde of range";
1427 effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1429 // Init parameter value & keyframes if required
1430 QDomNodeList params = effect.elementsByTagName("parameter");
1431 for (int i = 0; i < params.count(); i++) {
1432 QDomElement e = params.item(i).toElement();
1434 // Check if this effect has a variable parameter
1435 if (e.attribute("default").contains('%')) {
1436 double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1437 e.setAttribute("default", evaluatedValue);
1438 if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1439 e.setAttribute("value", evaluatedValue);
1443 if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1444 QString def = e.attribute("default");
1445 // Effect has a keyframe type parameter, we need to set the values
1446 if (e.attribute("keyframes").isEmpty()) {
1447 e.setAttribute("keyframes", "0:" + def + ';');
1448 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1453 if (effect.attribute("id") == "crop") {
1454 // default use_profile to 1 for clips with proxies to avoid problems when rendering
1455 if (e.attribute("name") == "use_profile" && getDocumentProperty("enableproxy") == "1")
1456 e.setAttribute("value", "1");
1460 m_tracksList[ix].effectsList.append(effect);
1463 void KdenliveDoc::removeTrackEffect(int ix, QDomElement effect)
1465 if (ix < 0 || ix >= m_tracksList.count()) {
1466 kWarning() << "Remove Track effect outisde of range";
1470 QString toRemove = effect.attribute("kdenlive_ix");
1471 for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1472 index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix");
1473 if (toRemove == index) {
1474 m_tracksList[ix].effectsList.removeAt(i);
1476 } else if (index.toInt() > toRemove.toInt()) {
1477 m_tracksList[ix].effectsList.item(i).setAttribute("kdenlive_ix", index.toInt() - 1);
1482 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1484 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1485 kWarning() << "Set Track effect outisde of range";
1488 if (effectIndex < 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count() - 1) || effect.isNull()) {
1489 kDebug() << "Invalid effect index: " << effectIndex;
1492 effect.setAttribute("kdenlive_ix", effectIndex + 1);
1493 m_tracksList[trackIndex].effectsList.replace(effectIndex, effect);
1496 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1498 if (ix < 0 || ix >= m_tracksList.count()) {
1499 kWarning() << "Get Track effects outisde of range";
1500 return EffectsList();
1502 return m_tracksList.at(ix).effectsList;
1505 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1507 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1508 kWarning() << "Get Track effect outisde of range";
1509 return QDomElement();
1511 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1512 if (effectIndex > list.count() - 1 || effectIndex < 0 || list.at(effectIndex).isNull()) return QDomElement();
1513 return list.at(effectIndex).cloneNode().toElement();
1516 bool KdenliveDoc::saveCustomEffects(QDomNodeList customeffects)
1519 QStringList importedEffects;
1520 int maxchild = customeffects.count();
1521 for (int i = 0; i < maxchild; i++) {
1522 e = customeffects.at(i).toElement();
1523 QString id = e.attribute("id");
1524 QString tag = e.attribute("tag");
1525 if (!id.isEmpty()) {
1526 // Check if effect exists or save it
1527 if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1529 doc.appendChild(doc.importNode(e, true));
1530 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1531 path += id + ".xml";
1532 if (!QFile::exists(path)) {
1533 importedEffects << id;
1535 if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1536 QTextStream out(&file);
1537 out << doc.toString();
1543 if (!importedEffects.isEmpty()) KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1544 return (!importedEffects.isEmpty());
1547 void KdenliveDoc::updateProjectFolderPlacesEntry()
1550 * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1551 * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1554 const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1555 KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1556 KBookmarkGroup root = bookmarkManager->root();
1557 KBookmark bookmark = root.first();
1559 QString kdenliveName = KGlobal::mainComponent().componentName();
1560 KUrl documentLocation = m_projectFolder;
1562 bool exists = false;
1564 while (!bookmark.isNull()) {
1565 // UDI not empty indicates a device
1566 QString udi = bookmark.metaDataItem("UDI");
1567 QString appName = bookmark.metaDataItem("OnlyInApp");
1569 if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1570 if (bookmark.url() != documentLocation) {
1571 bookmark.setUrl(documentLocation);
1572 bookmarkManager->emitChanged(root);
1578 bookmark = root.next(bookmark);
1581 // if entry does not exist yet (was not found), well, create it then
1583 bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1584 // Make this user selectable ?
1585 bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1586 bookmarkManager->emitChanged(root);
1590 QStringList KdenliveDoc::getExpandedFolders()
1592 QStringList result = m_documentProperties.value("expandedfolders").split(';');
1593 // this property is only needed once when opening project, so clear it now
1594 m_documentProperties.remove("expandedfolders");
1599 double KdenliveDoc::getDisplayRatio(const QString &path)
1603 if (!file.open(QIODevice::ReadOnly)) {
1604 kWarning() << "ERROR, CANNOT READ: " << path;
1607 if (!doc.setContent(&file)) {
1608 kWarning() << "ERROR, CANNOT READ: " << path;
1613 QDomNodeList list = doc.elementsByTagName("profile");
1614 if (list.isEmpty()) return 0;
1615 QDomElement profile = list.at(0).toElement();
1616 double den = profile.attribute("display_aspect_den").toDouble();
1617 if (den > 0) return profile.attribute("display_aspect_num").toDouble() / den;
1621 void KdenliveDoc::backupLastSavedVersion(const QString &path)
1623 // Ensure backup folder exists
1624 if (path.isEmpty()) return;
1626 KUrl backupFile = m_projectFolder;
1627 backupFile.addPath(".backup/");
1628 KIO::NetAccess::mkdir(backupFile, kapp->activeWindow());
1629 QString fileName = KUrl(path).fileName().section('.', 0, -2);
1630 QFileInfo info(file);
1631 fileName.append("-" + m_documentProperties.value("documentid"));
1632 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
1633 fileName.append(".kdenlive");
1634 backupFile.addPath(fileName);
1636 if (file.exists()) {
1637 // delete previous backup if it was done less than 60 seconds ago
1638 QFile::remove(backupFile.path());
1639 if (!QFile::copy(path, backupFile.path())) {
1640 KMessageBox::information(kapp->activeWindow(), i18n("Cannot create backup copy:\n%1", backupFile.path()));
1645 void KdenliveDoc::cleanupBackupFiles()
1647 KUrl backupFile = m_projectFolder;
1648 backupFile.addPath(".backup/");
1649 QDir dir(backupFile.path());
1650 QString projectFile = url().fileName().section('.', 0, -2);
1651 projectFile.append("-" + m_documentProperties.value("documentid"));
1652 projectFile.append("-??");
1653 projectFile.append("??");
1654 projectFile.append("-??");
1655 projectFile.append("-??");
1656 projectFile.append("-??");
1657 projectFile.append("-??.kdenlive");
1660 backupFile.addPath(projectFile);
1661 filter << projectFile;
1662 dir.setNameFilters(filter);
1663 QFileInfoList resultList = dir.entryInfoList(QDir::Files, QDir::Time);
1665 QDateTime d = QDateTime::currentDateTime();
1666 QStringList hourList;
1667 QStringList dayList;
1668 QStringList weekList;
1669 QStringList oldList;
1670 for (int i = 0; i < resultList.count(); i++) {
1671 if (d.secsTo(resultList.at(i).lastModified()) < 3600) {
1672 // files created in the last hour
1673 hourList.append(resultList.at(i).absoluteFilePath());
1675 else if (d.secsTo(resultList.at(i).lastModified()) < 43200) {
1676 // files created in the day
1677 dayList.append(resultList.at(i).absoluteFilePath());
1679 else if (d.daysTo(resultList.at(i).lastModified()) < 8) {
1680 // files created in the week
1681 weekList.append(resultList.at(i).absoluteFilePath());
1685 oldList.append(resultList.at(i).absoluteFilePath());
1688 if (hourList.count() > 20) {
1689 int step = hourList.count() / 10;
1690 for (int i = 0; i < hourList.count(); i += step) {
1691 kDebug()<<"REMOVE AT: "<<i<<", COUNT: "<<hourList.count();
1692 hourList.removeAt(i);
1695 } else hourList.clear();
1696 if (dayList.count() > 20) {
1697 int step = dayList.count() / 10;
1698 for (int i = 0; i < dayList.count(); i += step) {
1699 dayList.removeAt(i);
1702 } else dayList.clear();
1703 if (weekList.count() > 20) {
1704 int step = weekList.count() / 10;
1705 for (int i = 0; i < weekList.count(); i += step) {
1706 weekList.removeAt(i);
1709 } else weekList.clear();
1710 if (oldList.count() > 20) {
1711 int step = oldList.count() / 10;
1712 for (int i = 0; i < oldList.count(); i += step) {
1713 oldList.removeAt(i);
1716 } else oldList.clear();
1719 while (hourList.count() > 0) {
1720 f = hourList.takeFirst();
1722 QFile::remove(f + ".png");
1724 while (dayList.count() > 0) {
1725 f = dayList.takeFirst();
1727 QFile::remove(f + ".png");
1729 while (weekList.count() > 0) {
1730 f = weekList.takeFirst();
1732 QFile::remove(f + ".png");
1734 while (oldList.count() > 0) {
1735 f = oldList.takeFirst();
1737 QFile::remove(f + ".png");
1741 #include "kdenlivedoc.moc"