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 <KIO/JobUiDelegate>
43 #include <KApplication>
45 #include <KBookmarkManager>
47 #include <KStandardDirs>
49 #include <QCryptographicHash>
51 #include <QInputDialog>
52 #include <QDomImplementation>
54 #include <mlt++/Mlt.h>
56 const double DOCUMENTVERSION = 0.88;
58 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) :
64 m_commandStack(new QUndoStack(undoGroup)),
66 m_projectFolder(projectFolder)
68 m_clipManager = new ClipManager(this);
69 m_autoSaveTimer = new QTimer(this);
70 m_autoSaveTimer->setSingleShot(true);
73 // init default document properties
74 m_documentProperties["zoom"] = "7";
75 m_documentProperties["verticalzoom"] = "1";
76 m_documentProperties["zonein"] = "0";
77 m_documentProperties["zoneout"] = "100";
78 m_documentProperties["enableproxy"] = QString::number((int) KdenliveSettings::enableproxy());
79 m_documentProperties["proxyparams"] = KdenliveSettings::proxyparams();
80 m_documentProperties["proxyextension"] = KdenliveSettings::proxyextension();
81 m_documentProperties["generateproxy"] = QString::number((int) KdenliveSettings::generateproxy());
82 m_documentProperties["proxyminsize"] = QString::number(KdenliveSettings::proxyminsize());
83 m_documentProperties["generateimageproxy"] = QString::number((int) KdenliveSettings::generateimageproxy());
84 m_documentProperties["proxyimageminsize"] = QString::number(KdenliveSettings::proxyimageminsize());
85 #if QT_VERSION >= 0x040700
86 m_documentProperties["documentid"] = QString::number(QDateTime::currentMSecsSinceEpoch());
88 QDateTime date = QDateTime::currentDateTime();
89 m_documentProperties["documentid"] = QString::number(date.toTime_t());
93 QMapIterator<QString, QString> i(properties);
96 m_documentProperties[i.key()] = i.value();
99 if (QLocale() != QLocale::system()) {
100 QLocale::setDefault(QLocale::system());
101 // locale conversion might need to be redone
102 initEffects::parseEffectFiles();
107 if (!url.isEmpty()) {
109 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
111 // The file cannot be opened
112 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) {
115 //KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
120 QDomImplementation impl;
121 impl.setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
122 success = m_document.setContent(&file, false, &errorMsg);
124 KIO::NetAccess::removeTempFile(tmpFile);
128 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) {
131 //KMessageBox::error(parent, errorMsg);
134 parent->slotGotProgressInfo(i18n("Validating"), 0);
135 qApp->processEvents();
136 DocumentValidator validator(m_document);
137 success = validator.isProject();
139 // It is not a project file
140 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
141 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) {
146 * Validate the file against the current version (upgrade
147 * and recover it if needed). It is NOT a passive operation
149 // TODO: backup the document or alert the user?
150 success = validator.validate(DOCUMENTVERSION);
151 if (success) { // Let the validator handle error messages
152 parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
153 qApp->processEvents();
154 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
155 success = checkDocumentClips(infoproducers);
157 if (m_document.documentElement().attribute("modified") == "1") setModified(true);
158 parent->slotGotProgressInfo(i18n("Loading"), 0);
159 QDomElement mlt = m_document.firstChildElement("mlt");
160 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
162 // Set profile, fps, etc for the document
163 setProfilePath(infoXml.attribute("profile"));
165 // Check embedded effects
166 QDomElement customeffects = infoXml.firstChildElement("customeffects");
167 if (!customeffects.isNull() && customeffects.hasChildNodes()) {
168 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
169 qApp->processEvents();
170 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
175 QDomElement notesxml = infoXml.firstChildElement("documentnotes");
176 if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
179 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
180 if (!tracksinfo.isNull()) {
181 QDomNodeList trackslist = tracksinfo.childNodes();
182 int maxchild = trackslist.count();
183 for (int k = 0; k < maxchild; k++) {
184 e = trackslist.at(k).toElement();
185 if (e.tagName() == "trackinfo") {
186 TrackInfo projectTrack;
187 if (e.attribute("type") == "audio")
188 projectTrack.type = AUDIOTRACK;
190 projectTrack.type = VIDEOTRACK;
191 projectTrack.isMute = e.attribute("mute").toInt();
192 projectTrack.isBlind = e.attribute("blind").toInt();
193 projectTrack.isLocked = e.attribute("locked").toInt();
194 projectTrack.trackName = e.attribute("trackname");
195 m_tracksList.append(projectTrack);
198 mlt.removeChild(tracksinfo);
200 QStringList expandedFolders;
201 QDomNodeList folders = m_document.elementsByTagName("folder");
202 for (int i = 0; i < folders.count(); i++) {
203 e = folders.item(i).cloneNode().toElement();
204 if (e.hasAttribute("opened")) expandedFolders.append(e.attribute("id"));
205 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
207 m_documentProperties["expandedfolders"] = expandedFolders.join(";");
209 const int infomax = infoproducers.count();
210 QDomNodeList producers = m_document.elementsByTagName("producer");
211 const int max = producers.count();
213 if (!progressDialog) {
214 progressDialog = new KProgressDialog(parent, i18n("Loading project"), i18n("Adding clips"));
215 progressDialog->setAllowCancel(false);
217 progressDialog->setLabelText(i18n("Adding clips"));
219 progressDialog->progressBar()->setMaximum(infomax);
220 progressDialog->show();
221 qApp->processEvents();
223 for (int i = 0; i < infomax; i++) {
224 e = infoproducers.item(i).cloneNode().toElement();
225 QString prodId = e.attribute("id");
226 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
227 e.setTagName("producer");
228 // Get MLT's original producer properties
230 for (int j = 0; j < max; j++) {
231 QDomNode o = producers.item(j);
232 QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
233 if (origId == prodId) {
234 orig = o.cloneNode().toElement();
239 if (!addClipInfo(e, orig, prodId)) {
240 // The user manually aborted the loading.
242 emit resetProjectList();
243 m_tracksList.clear();
244 m_clipManager->clear();
249 progressDialog->progressBar()->setValue(i);
253 QDomElement markers = infoXml.firstChildElement("markers");
254 if (!markers.isNull()) {
255 QDomNodeList markerslist = markers.childNodes();
256 int maxchild = markerslist.count();
257 for (int k = 0; k < maxchild; k++) {
258 e = markerslist.at(k).toElement();
259 if (e.tagName() == "marker")
260 m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
262 infoXml.removeChild(markers);
265 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
266 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
267 QDomNamedNodeMap props = docproperties.attributes();
268 for (int i = 0; i < props.count(); i++)
269 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
271 if (validator.isModified()) setModified(true);
272 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
281 // Something went wrong, or a new file was requested: create a new project
284 setProfilePath(profileName);
285 m_document = createEmptyDocument(tracks.x(), tracks.y());
288 // Ask to create the project directory if it does not exist
289 if (!QFile::exists(m_projectFolder.path())) {
290 int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
291 if (create == KMessageBox::Yes) {
292 QDir projectDir(m_projectFolder.path());
293 bool ok = projectDir.mkpath(m_projectFolder.path());
295 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
300 // Make sure the project folder is usable
301 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
302 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
303 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
306 // Make sure that the necessary folders exist
307 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
308 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
309 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/");
311 updateProjectFolderPlacesEntry();
313 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
314 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
317 KdenliveDoc::~KdenliveDoc()
319 m_autoSaveTimer->stop();
320 delete m_commandStack;
321 kDebug() << "// DEL CLP MAN";
322 delete m_clipManager;
323 kDebug() << "// DEL CLP MAN done";
324 delete m_autoSaveTimer;
326 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
331 int KdenliveDoc::setSceneList()
333 m_render->resetProfile(KdenliveSettings::current_profile(), true);
334 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
335 // INVALID MLT Consumer, something is wrong
338 m_documentProperties.remove("position");
339 // m_document xml is now useless, clear it
344 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
346 m_tracksList.clear();
348 // Tracks are added «backwards», so we need to reverse the track numbering
349 // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
350 // Better default names for tracks: Audio 1 etc. instead of blank numbers
351 for (int i = 0; i < audiotracks; i++) {
352 TrackInfo audioTrack;
353 audioTrack.type = AUDIOTRACK;
354 audioTrack.isMute = false;
355 audioTrack.isBlind = true;
356 audioTrack.isLocked = false;
357 audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
358 audioTrack.duration = 0;
359 m_tracksList.append(audioTrack);
362 for (int i = 0; i < videotracks; i++) {
363 TrackInfo videoTrack;
364 videoTrack.type = VIDEOTRACK;
365 videoTrack.isMute = false;
366 videoTrack.isBlind = false;
367 videoTrack.isLocked = false;
368 videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
369 videoTrack.duration = 0;
370 m_tracksList.append(videoTrack);
372 return createEmptyDocument(m_tracksList);
375 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
377 // Creating new document
379 QDomElement mlt = doc.createElement("mlt");
380 mlt.setAttribute("LC_NUMERIC", "");
381 doc.appendChild(mlt);
383 // Create black producer
384 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
385 // the composite transitions with the black track are corrupted.
386 QDomElement blk = doc.createElement("producer");
387 blk.setAttribute("in", 0);
388 blk.setAttribute("out", 500);
389 blk.setAttribute("id", "black");
391 QDomElement property = doc.createElement("property");
392 property.setAttribute("name", "mlt_type");
393 QDomText value = doc.createTextNode("producer");
394 property.appendChild(value);
395 blk.appendChild(property);
397 property = doc.createElement("property");
398 property.setAttribute("name", "aspect_ratio");
399 value = doc.createTextNode(QString::number(0));
400 property.appendChild(value);
401 blk.appendChild(property);
403 property = doc.createElement("property");
404 property.setAttribute("name", "length");
405 value = doc.createTextNode(QString::number(15000));
406 property.appendChild(value);
407 blk.appendChild(property);
409 property = doc.createElement("property");
410 property.setAttribute("name", "eof");
411 value = doc.createTextNode("pause");
412 property.appendChild(value);
413 blk.appendChild(property);
415 property = doc.createElement("property");
416 property.setAttribute("name", "resource");
417 value = doc.createTextNode("black");
418 property.appendChild(value);
419 blk.appendChild(property);
421 property = doc.createElement("property");
422 property.setAttribute("name", "mlt_service");
423 value = doc.createTextNode("colour");
424 property.appendChild(value);
425 blk.appendChild(property);
427 mlt.appendChild(blk);
430 QDomElement tractor = doc.createElement("tractor");
431 tractor.setAttribute("id", "maintractor");
432 QDomElement multitrack = doc.createElement("multitrack");
433 QDomElement playlist = doc.createElement("playlist");
434 playlist.setAttribute("id", "black_track");
435 mlt.appendChild(playlist);
437 QDomElement blank0 = doc.createElement("entry");
438 blank0.setAttribute("in", "0");
439 blank0.setAttribute("out", "1");
440 blank0.setAttribute("producer", "black");
441 playlist.appendChild(blank0);
444 int total = tracks.count() + 1;
446 for (int i = 1; i < total; i++) {
447 QDomElement playlist = doc.createElement("playlist");
448 playlist.setAttribute("id", "playlist" + QString::number(i));
449 mlt.appendChild(playlist);
452 QDomElement track0 = doc.createElement("track");
453 track0.setAttribute("producer", "black_track");
454 tractor.appendChild(track0);
456 // create audio and video tracks
457 for (int i = 1; i < total; i++) {
458 QDomElement track = doc.createElement("track");
459 track.setAttribute("producer", "playlist" + QString::number(i));
460 if (tracks.at(i - 1).type == AUDIOTRACK) {
461 track.setAttribute("hide", "video");
462 } else if (tracks.at(i - 1).isBlind)
463 track.setAttribute("hide", "video");
464 if (tracks.at(i - 1).isMute)
465 track.setAttribute("hide", "audio");
466 tractor.appendChild(track);
469 for (int i = 2; i < total ; i++) {
470 QDomElement transition = doc.createElement("transition");
471 transition.setAttribute("always_active", "1");
473 QDomElement property = doc.createElement("property");
474 property.setAttribute("name", "a_track");
475 QDomText value = doc.createTextNode(QString::number(1));
476 property.appendChild(value);
477 transition.appendChild(property);
479 property = doc.createElement("property");
480 property.setAttribute("name", "b_track");
481 value = doc.createTextNode(QString::number(i));
482 property.appendChild(value);
483 transition.appendChild(property);
485 property = doc.createElement("property");
486 property.setAttribute("name", "mlt_service");
487 value = doc.createTextNode("mix");
488 property.appendChild(value);
489 transition.appendChild(property);
491 property = doc.createElement("property");
492 property.setAttribute("name", "combine");
493 value = doc.createTextNode("1");
494 property.appendChild(value);
495 transition.appendChild(property);
497 property = doc.createElement("property");
498 property.setAttribute("name", "internal_added");
499 value = doc.createTextNode("237");
500 property.appendChild(value);
501 transition.appendChild(property);
502 tractor.appendChild(transition);
504 mlt.appendChild(tractor);
509 void KdenliveDoc::syncGuides(QList <Guide *> guides)
512 QDomElement guideNode = m_guidesXml.createElement("guides");
513 m_guidesXml.appendChild(guideNode);
516 for (int i = 0; i < guides.count(); i++) {
517 e = m_guidesXml.createElement("guide");
518 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
519 e.setAttribute("comment", guides.at(i)->label());
520 guideNode.appendChild(e);
523 emit guidesUpdated();
526 QDomElement KdenliveDoc::guidesXml() const
528 return m_guidesXml.documentElement();
531 void KdenliveDoc::slotAutoSave()
533 if (m_render && m_autosave) {
534 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
535 // show error: could not open the autosave file
536 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
538 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
539 saveSceneList(m_autosave->fileName(), m_render->sceneList(), QStringList(), true);
543 void KdenliveDoc::setZoom(int horizontal, int vertical)
545 m_documentProperties["zoom"] = QString::number(horizontal);
546 m_documentProperties["verticalzoom"] = QString::number(vertical);
549 QPoint KdenliveDoc::zoom() const
551 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
554 void KdenliveDoc::setZone(int start, int end)
556 m_documentProperties["zonein"] = QString::number(start);
557 m_documentProperties["zoneout"] = QString::number(end);
560 QPoint KdenliveDoc::zone() const
562 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
565 QDomDocument KdenliveDoc::xmlSceneList(const QString &scene, const QStringList expandedFolders)
567 QDomDocument sceneList;
568 sceneList.setContent(scene, true);
569 QDomElement mlt = sceneList.firstChildElement("mlt");
570 if (mlt.isNull() || !mlt.hasChildNodes()) {
571 //scenelist is corrupted
575 // Set playlist audio volume to 100%
576 QDomElement tractor = mlt.firstChildElement("tractor");
577 if (!tractor.isNull()) {
578 QDomNodeList props = tractor.elementsByTagName("property");
579 for (int i = 0; i < props.count(); i++) {
580 if (props.at(i).toElement().attribute("name") == "meta.volume") {
581 props.at(i).firstChild().setNodeValue("1");
587 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
588 mlt.appendChild(addedXml);
590 // check if project contains custom effects to embed them in project file
591 QDomNodeList effects = mlt.elementsByTagName("filter");
592 int maxEffects = effects.count();
593 kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
594 QMap <QString, QString> effectIds;
595 for (int i = 0; i < maxEffects; i++) {
596 QDomNode m = effects.at(i);
597 QDomNodeList params = m.childNodes();
600 for (int j = 0; j < params.count(); j++) {
601 QDomElement e = params.item(j).toElement();
602 if (e.attribute("name") == "kdenlive_id") {
603 id = e.firstChild().nodeValue();
605 if (e.attribute("name") == "tag") {
606 tag = e.firstChild().nodeValue();
608 if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
611 QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
612 addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
614 QDomElement markers = sceneList.createElement("markers");
615 addedXml.setAttribute("version", DOCUMENTVERSION);
616 addedXml.setAttribute("kdenliveversion", VERSION);
617 addedXml.setAttribute("profile", profilePath());
618 addedXml.setAttribute("projectfolder", m_projectFolder.path());
620 QDomElement docproperties = sceneList.createElement("documentproperties");
621 QMapIterator<QString, QString> i(m_documentProperties);
622 while (i.hasNext()) {
624 docproperties.setAttribute(i.key(), i.value());
626 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
627 addedXml.appendChild(docproperties);
629 QDomElement docnotes = sceneList.createElement("documentnotes");
630 QDomText value = sceneList.createTextNode(m_notesWidget->toHtml());
631 docnotes.appendChild(value);
632 addedXml.appendChild(docnotes);
635 QDomElement profileinfo = sceneList.createElement("profileinfo");
636 profileinfo.setAttribute("description", m_profile.description);
637 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
638 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
639 profileinfo.setAttribute("width", m_profile.width);
640 profileinfo.setAttribute("height", m_profile.height);
641 profileinfo.setAttribute("progressive", m_profile.progressive);
642 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
643 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
644 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
645 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
646 addedXml.appendChild(profileinfo);
649 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
650 foreach(const TrackInfo & info, m_tracksList) {
651 QDomElement trackinfo = sceneList.createElement("trackinfo");
652 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
653 trackinfo.setAttribute("mute", info.isMute);
654 trackinfo.setAttribute("blind", info.isBlind);
655 trackinfo.setAttribute("locked", info.isLocked);
656 trackinfo.setAttribute("trackname", info.trackName);
657 tracksinfo.appendChild(trackinfo);
659 addedXml.appendChild(tracksinfo);
661 // save project folders
662 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
664 QMapIterator<QString, QString> f(folderlist);
665 while (f.hasNext()) {
667 QDomElement folder = sceneList.createElement("folder");
668 folder.setAttribute("id", f.key());
669 folder.setAttribute("name", f.value());
670 if (expandedFolders.contains(f.key())) folder.setAttribute("opened", "1");
671 addedXml.appendChild(folder);
674 // Save project clips
676 QList <DocClipBase*> list = m_clipManager->documentClipList();
677 for (int i = 0; i < list.count(); i++) {
678 e = list.at(i)->toXML();
679 e.setTagName("kdenlive_producer");
680 addedXml.appendChild(sceneList.importNode(e, true));
681 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
682 for (int j = 0; j < marks.count(); j++) {
683 QDomElement marker = sceneList.createElement("marker");
684 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
685 marker.setAttribute("comment", marks.at(j).comment());
686 marker.setAttribute("id", e.attribute("id"));
687 markers.appendChild(marker);
690 addedXml.appendChild(markers);
693 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
696 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
698 //wes.appendChild(doc.importNode(kdenliveData, true));
702 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene, const QStringList expandedFolders, bool autosave)
704 QDomDocument sceneList = xmlSceneList(scene, expandedFolders);
705 if (sceneList.isNull()) {
706 //Make sure we don't save if scenelist is corrupted
707 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
711 // Backup current version
712 if (!autosave) backupLastSavedVersion(path);
715 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
716 kWarning() << "////// ERROR writing to file: " << path;
717 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
721 file.write(sceneList.toString().toUtf8());
722 if (file.error() != QFile::NoError) {
723 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
729 cleanupBackupFiles();
730 QFileInfo info(file);
731 QString fileName = KUrl(path).fileName().section('.', 0, -2);
732 fileName.append("-" + m_documentProperties.value("documentid"));
733 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
734 fileName.append(".kdenlive.png");
735 KUrl backupFile = m_projectFolder;
736 backupFile.addPath(".backup/");
737 backupFile.addPath(fileName);
738 emit saveTimelinePreview(backupFile.path());
743 ClipManager *KdenliveDoc::clipManager()
745 return m_clipManager;
748 KUrl KdenliveDoc::projectFolder() const
750 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
751 return m_projectFolder;
754 void KdenliveDoc::setProjectFolder(KUrl url)
756 if (url == m_projectFolder) return;
758 KStandardDirs::makeDir(url.path());
759 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
760 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
761 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);
762 m_projectFolder = url;
764 updateProjectFolderPlacesEntry();
767 void KdenliveDoc::moveProjectData(KUrl url)
769 QList <DocClipBase*> list = m_clipManager->documentClipList();
770 KUrl::List cacheUrls;
771 for (int i = 0; i < list.count(); i++) {
772 DocClipBase *clip = list.at(i);
773 if (clip->clipType() == TEXT) {
774 // the image for title clip must be moved
775 KUrl oldUrl = clip->fileURL();
776 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
777 KIO::Job *job = KIO::copy(oldUrl, newUrl);
778 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
780 QString hash = clip->getClipHash();
781 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
782 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
783 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
784 cacheUrls << oldVideoThumbUrl;
786 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
787 cacheUrls << oldAudioThumbUrl;
790 if (!cacheUrls.isEmpty()) {
791 KIO::Job *job = KIO::copy(cacheUrls, KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/"));
792 job->ui()->setWindow(kapp->activeWindow());
793 KIO::NetAccess::synchronousRun(job, 0);
797 const QString &KdenliveDoc::profilePath() const
799 return m_profile.path;
802 MltVideoProfile KdenliveDoc::mltProfile() const
807 bool KdenliveDoc::setProfilePath(QString path)
809 if (path.isEmpty()) path = KdenliveSettings::default_profile();
810 if (path.isEmpty()) path = "dv_pal";
811 m_profile = ProfilesDialog::getVideoProfile(path);
812 double current_fps = m_fps;
813 if (m_profile.path.isEmpty()) {
814 // Profile not found, use embedded profile
815 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
816 if (profileInfo.isNull()) {
817 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
818 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
820 m_profile.description = profileInfo.attribute("description");
821 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
822 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
823 m_profile.width = profileInfo.attribute("width").toInt();
824 m_profile.height = profileInfo.attribute("height").toInt();
825 m_profile.progressive = profileInfo.attribute("progressive").toInt();
826 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
827 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
828 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
829 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
830 QString existing = ProfilesDialog::existingProfile(m_profile);
831 if (!existing.isEmpty()) {
832 m_profile = ProfilesDialog::getVideoProfile(existing);
833 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
835 QString newDesc = m_profile.description;
837 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
838 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);
841 // User canceled, use default profile
842 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
844 if (newDesc != m_profile.description) {
845 // Profile description existed, was replaced by new one
846 m_profile.description = newDesc;
848 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
850 ProfilesDialog::saveProfile(m_profile);
857 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
858 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
859 KdenliveSettings::setProject_fps(m_fps);
860 m_width = m_profile.width;
861 m_height = m_profile.height;
862 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
863 m_timecode.setFormat(m_fps);
864 KdenliveSettings::setCurrent_profile(m_profile.path);
865 return (current_fps != m_fps);
868 double KdenliveDoc::dar() const
870 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
873 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
875 emit progressInfo(message, progress);
878 QUndoStack *KdenliveDoc::commandStack()
880 return m_commandStack;
884 void KdenliveDoc::setRenderer(Render *render) {
885 if (m_render) return;
887 emit progressInfo(i18n("Loading playlist..."), 0);
888 //qApp->processEvents();
890 m_render->setSceneList(m_document.toString(), m_startPos);
891 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
894 emit progressInfo(QString(), -1);
897 void KdenliveDoc::checkProjectClips(bool displayRatioChanged, bool fpsChanged)
899 if (m_render == NULL) return;
900 m_clipManager->resetProducersList(m_render->producersList(), displayRatioChanged, fpsChanged);
903 Render *KdenliveDoc::renderer()
908 void KdenliveDoc::updateClip(const QString id)
910 emit updateClipDisplay(id);
913 int KdenliveDoc::getFramePos(QString duration)
915 return m_timecode.getFrameCount(duration);
918 QString KdenliveDoc::producerName(const QString &id)
920 QString result = "unnamed";
921 QDomNodeList prods = producersList();
922 int ct = prods.count();
923 for (int i = 0; i < ct ; i++) {
924 QDomElement e = prods.item(i).toElement();
925 if (e.attribute("id") != "black" && e.attribute("id") == id) {
926 result = e.attribute("name");
927 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
934 QDomDocument KdenliveDoc::toXml()
939 Timecode KdenliveDoc::timecode() const
944 QDomNodeList KdenliveDoc::producersList()
946 return m_document.elementsByTagName("producer");
949 double KdenliveDoc::projectDuration() const
952 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
957 double KdenliveDoc::fps() const
962 int KdenliveDoc::width() const
967 int KdenliveDoc::height() const
972 KUrl KdenliveDoc::url() const
977 void KdenliveDoc::setUrl(KUrl url)
982 void KdenliveDoc::setModified(bool mod)
984 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
985 m_autoSaveTimer->start(3000);
987 if (mod == m_modified) return;
989 emit docModified(m_modified);
992 bool KdenliveDoc::isModified() const
997 const QString KdenliveDoc::description() const
1000 return i18n("Untitled") + " / " + m_profile.description;
1002 return m_url.fileName() + " / " + m_profile.description;
1005 bool KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
1007 const QString producerId = clipId.section('_', 0, 0);
1008 DocClipBase *clip = m_clipManager->getClipById(producerId);
1011 elem.setAttribute("id", producerId);
1012 QString path = elem.attribute("resource");
1014 if (elem.attribute("type").toInt() == SLIDESHOW) {
1015 extension = KUrl(path).fileName();
1016 path = KUrl(path).directory();
1019 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
1020 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1021 const QString size = elem.attribute("file_size");
1022 const QString hash = elem.attribute("file_hash");
1024 int action = KMessageBox::No;
1025 if (!size.isEmpty() && !hash.isEmpty()) {
1026 if (!m_searchFolder.isEmpty())
1027 newpath = searchFileRecursively(m_searchFolder, size, hash);
1029 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")));
1031 if (elem.attribute("type").toInt() == SLIDESHOW) {
1032 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")));
1033 if (res == KMessageBox::Yes)
1034 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1036 // Abort project loading
1040 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")));
1041 if (res == KMessageBox::Yes)
1042 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1044 // Abort project loading
1049 if (action == KMessageBox::Yes) {
1050 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1051 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1052 if (!m_searchFolder.isEmpty())
1053 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1054 } else if (action == KMessageBox::Cancel) {
1056 } else if (action == KMessageBox::No) {
1057 // Keep clip as placeHolder
1058 elem.setAttribute("placeholder", '1');
1060 if (!newpath.isEmpty()) {
1061 if (elem.attribute("type").toInt() == SLIDESHOW)
1062 newpath.append('/' + extension);
1063 elem.setAttribute("resource", newpath);
1064 setNewClipResource(clipId, newpath);
1068 clip = new DocClipBase(m_clipManager, elem, producerId);
1069 m_clipManager->addClip(clip);
1072 if (createClipItem) {
1073 emit addProjectClip(clip);
1079 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1081 QDomNodeList prods = m_document.elementsByTagName("producer");
1082 int maxprod = prods.count();
1083 for (int i = 0; i < maxprod; i++) {
1084 QDomNode m = prods.at(i);
1085 QString prodId = m.toElement().attribute("id");
1086 if (prodId == id || prodId.startsWith(id + '_')) {
1087 QDomNodeList params = m.childNodes();
1088 for (int j = 0; j < params.count(); j++) {
1089 QDomElement e = params.item(j).toElement();
1090 if (e.attribute("name") == "resource") {
1091 e.firstChild().setNodeValue(path);
1099 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1101 QString foundFileName;
1102 QByteArray fileData;
1103 QByteArray fileHash;
1104 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1105 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1106 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1107 if (file.open(QIODevice::ReadOnly)) {
1108 if (QString::number(file.size()) == matchSize) {
1110 * 1 MB = 1 second per 450 files (or faster)
1111 * 10 MB = 9 seconds per 450 files (or faster)
1113 if (file.size() > 1000000 * 2) {
1114 fileData = file.read(1000000);
1115 if (file.seek(file.size() - 1000000))
1116 fileData.append(file.readAll());
1118 fileData = file.readAll();
1120 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1121 if (QString(fileHash.toHex()) == matchHash)
1122 return file.fileName();
1125 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1127 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1128 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1129 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1130 if (!foundFileName.isEmpty())
1133 return foundFileName;
1136 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1138 DocClipBase *clip = m_clipManager->getClipById(clipId);
1140 if (!addClip(elem, clipId, false))
1143 QMap <QString, QString> properties;
1144 QDomNamedNodeMap attributes = elem.attributes();
1145 for (int i = 0; i < attributes.count(); i++) {
1146 QString attrname = attributes.item(i).nodeName();
1147 if (attrname != "resource")
1148 properties.insert(attrname, attributes.item(i).nodeValue());
1149 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1151 clip->setProperties(properties);
1152 emit addProjectClip(clip, false);
1154 if (orig != QDomElement()) {
1155 QMap<QString, QString> meta;
1156 for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1157 QString name = m.toElement().attribute("name");
1158 if (name.startsWith("meta.attr"))
1159 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1161 if (!meta.isEmpty()) {
1163 clip = m_clipManager->getClipById(clipId);
1165 clip->setMetadata(meta);
1172 void KdenliveDoc::deleteClip(const QString &clipId)
1174 emit signalDeleteProjectClip(clipId);
1177 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1179 m_clipManager->slotAddClipList(urls, group, groupId);
1180 //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1185 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1187 m_clipManager->slotAddClipFile(url, group, groupId);
1188 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1192 const QString KdenliveDoc::getFreeClipId()
1194 return QString::number(m_clipManager->getFreeClipId());
1197 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1199 return m_clipManager->getClipById(clipId);
1202 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement xml, QString group, const QString &groupId)
1204 m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1206 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1209 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1211 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1213 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1216 void KdenliveDoc::slotCreateSlideshowClipFile(const QString name, const QString path, int count, const QString duration,
1217 const bool loop, const bool crop, const bool fade,
1218 const QString &luma_duration, const QString &luma_file, const int softness,
1219 const QString &animation, QString group, const QString &groupId)
1221 m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop,
1222 crop, fade, luma_duration,
1223 luma_file, softness,
1224 animation, group, groupId);
1226 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1229 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1231 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1232 KStandardDirs::makeDir(titlesFolder);
1233 TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1234 if (dia_ui->exec() == QDialog::Accepted) {
1235 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->outPoint(), dia_ui->xml().toString(), group, groupId);
1237 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1242 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1244 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1245 if (path.isEmpty()) {
1246 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1249 if (path.isEmpty()) return;
1251 //TODO: rewrite with new title system (just set resource)
1252 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1254 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1257 int KdenliveDoc::tracksCount() const
1259 return m_tracksList.count();
1262 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1264 if (ix < 0 || ix >= m_tracksList.count()) {
1265 kWarning() << "Track INFO outisde of range";
1268 return m_tracksList.at(ix);
1271 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1273 if (ix < 0 || ix >= m_tracksList.count()) {
1274 kWarning() << "SWITCH Track outisde of range";
1277 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1280 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1282 if (ix < 0 || ix >= m_tracksList.count()) {
1283 kWarning() << "Track Lock outisde of range";
1286 m_tracksList[ix].isLocked = lock;
1289 bool KdenliveDoc::isTrackLocked(int ix) const
1291 if (ix < 0 || ix >= m_tracksList.count()) {
1292 kWarning() << "Track Lock outisde of range";
1295 return m_tracksList.at(ix).isLocked;
1298 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1300 if (ix < 0 || ix >= m_tracksList.count()) {
1301 kWarning() << "SWITCH Track outisde of range";
1304 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1307 int KdenliveDoc::trackDuration(int ix)
1309 return m_tracksList.at(ix).duration;
1312 void KdenliveDoc::setTrackDuration(int ix, int duration)
1314 m_tracksList[ix].duration = duration;
1317 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1319 if (ix == -1) m_tracksList << type;
1320 else m_tracksList.insert(ix, type);
1323 void KdenliveDoc::deleteTrack(int ix)
1325 if (ix < 0 || ix >= m_tracksList.count()) {
1326 kWarning() << "Delete Track outisde of range";
1329 m_tracksList.removeAt(ix);
1332 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1334 if (ix < 0 || ix >= m_tracksList.count()) {
1335 kWarning() << "SET Track Type outisde of range";
1338 m_tracksList[ix].type = type.type;
1339 m_tracksList[ix].isMute = type.isMute;
1340 m_tracksList[ix].isBlind = type.isBlind;
1341 m_tracksList[ix].isLocked = type.isLocked;
1342 m_tracksList[ix].trackName = type.trackName;
1345 const QList <TrackInfo> KdenliveDoc::tracksList() const
1347 return m_tracksList;
1350 QPoint KdenliveDoc::getTracksCount() const
1354 foreach(const TrackInfo & info, m_tracksList) {
1355 if (info.type == VIDEOTRACK) video++;
1358 return QPoint(video, audio);
1361 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1363 pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1366 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1368 DocumentChecker d(infoproducers, m_document);
1369 return (d.hasErrorInClips() == false);
1375 QList <QDomElement> missingClips;
1376 for (int i = 0; i < infoproducers.count(); i++) {
1377 e = infoproducers.item(i).toElement();
1378 clipType = e.attribute("type").toInt();
1379 if (clipType == COLOR) continue;
1380 if (clipType == TEXT) {
1381 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1384 id = e.attribute("id");
1385 resource = e.attribute("resource");
1386 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1387 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1388 // Missing clip found
1389 missingClips.append(e);
1391 // Check if the clip has changed
1392 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1393 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1394 e.removeAttribute("file_hash");
1398 if (missingClips.isEmpty()) return true;
1399 DocumentChecker d(missingClips, m_document);
1400 return (d.exec() == QDialog::Accepted);*/
1403 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1405 m_documentProperties[name] = value;
1408 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1410 return m_documentProperties.value(name);
1413 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1415 QMap <QString, QString> renderProperties;
1416 QMapIterator<QString, QString> i(m_documentProperties);
1417 while (i.hasNext()) {
1419 if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1421 return renderProperties;
1424 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1426 if (ix < 0 || ix >= m_tracksList.count()) {
1427 kWarning() << "Add Track effect outisde of range";
1430 effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1432 // Init parameter value & keyframes if required
1433 QDomNodeList params = effect.elementsByTagName("parameter");
1434 for (int i = 0; i < params.count(); i++) {
1435 QDomElement e = params.item(i).toElement();
1437 // Check if this effect has a variable parameter
1438 if (e.attribute("default").contains('%')) {
1439 double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1440 e.setAttribute("default", evaluatedValue);
1441 if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1442 e.setAttribute("value", evaluatedValue);
1446 if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1447 QString def = e.attribute("default");
1448 // Effect has a keyframe type parameter, we need to set the values
1449 if (e.attribute("keyframes").isEmpty()) {
1450 e.setAttribute("keyframes", "0:" + def + ';');
1451 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1456 if (effect.attribute("id") == "crop") {
1457 // default use_profile to 1 for clips with proxies to avoid problems when rendering
1458 if (e.attribute("name") == "use_profile" && getDocumentProperty("enableproxy") == "1")
1459 e.setAttribute("value", "1");
1463 m_tracksList[ix].effectsList.append(effect);
1466 void KdenliveDoc::removeTrackEffect(int ix, QDomElement effect)
1468 if (ix < 0 || ix >= m_tracksList.count()) {
1469 kWarning() << "Remove Track effect outisde of range";
1473 QString toRemove = effect.attribute("kdenlive_ix");
1474 for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1475 index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix");
1476 if (toRemove == index) {
1477 m_tracksList[ix].effectsList.removeAt(i);
1479 } else if (index.toInt() > toRemove.toInt()) {
1480 m_tracksList[ix].effectsList.item(i).setAttribute("kdenlive_ix", index.toInt() - 1);
1485 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1487 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1488 kWarning() << "Set Track effect outisde of range";
1491 if (effectIndex < 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count() - 1) || effect.isNull()) {
1492 kDebug() << "Invalid effect index: " << effectIndex;
1495 effect.setAttribute("kdenlive_ix", effectIndex + 1);
1496 m_tracksList[trackIndex].effectsList.replace(effectIndex, effect);
1499 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1501 if (ix < 0 || ix >= m_tracksList.count()) {
1502 kWarning() << "Get Track effects outisde of range";
1503 return EffectsList();
1505 return m_tracksList.at(ix).effectsList;
1508 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1510 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1511 kWarning() << "Get Track effect outisde of range";
1512 return QDomElement();
1514 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1515 if (effectIndex > list.count() - 1 || effectIndex < 0 || list.at(effectIndex).isNull()) return QDomElement();
1516 return list.at(effectIndex).cloneNode().toElement();
1519 bool KdenliveDoc::saveCustomEffects(QDomNodeList customeffects)
1522 QStringList importedEffects;
1523 int maxchild = customeffects.count();
1524 for (int i = 0; i < maxchild; i++) {
1525 e = customeffects.at(i).toElement();
1526 QString id = e.attribute("id");
1527 QString tag = e.attribute("tag");
1528 if (!id.isEmpty()) {
1529 // Check if effect exists or save it
1530 if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1532 doc.appendChild(doc.importNode(e, true));
1533 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1534 path += id + ".xml";
1535 if (!QFile::exists(path)) {
1536 importedEffects << id;
1538 if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1539 QTextStream out(&file);
1540 out << doc.toString();
1546 if (!importedEffects.isEmpty()) KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1547 return (!importedEffects.isEmpty());
1550 void KdenliveDoc::updateProjectFolderPlacesEntry()
1553 * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1554 * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1557 const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1558 KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1559 KBookmarkGroup root = bookmarkManager->root();
1560 KBookmark bookmark = root.first();
1562 QString kdenliveName = KGlobal::mainComponent().componentName();
1563 KUrl documentLocation = m_projectFolder;
1565 bool exists = false;
1567 while (!bookmark.isNull()) {
1568 // UDI not empty indicates a device
1569 QString udi = bookmark.metaDataItem("UDI");
1570 QString appName = bookmark.metaDataItem("OnlyInApp");
1572 if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1573 if (bookmark.url() != documentLocation) {
1574 bookmark.setUrl(documentLocation);
1575 bookmarkManager->emitChanged(root);
1581 bookmark = root.next(bookmark);
1584 // if entry does not exist yet (was not found), well, create it then
1586 bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1587 // Make this user selectable ?
1588 bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1589 bookmarkManager->emitChanged(root);
1593 QStringList KdenliveDoc::getExpandedFolders()
1595 QStringList result = m_documentProperties.value("expandedfolders").split(';');
1596 // this property is only needed once when opening project, so clear it now
1597 m_documentProperties.remove("expandedfolders");
1602 double KdenliveDoc::getDisplayRatio(const QString &path)
1606 if (!file.open(QIODevice::ReadOnly)) {
1607 kWarning() << "ERROR, CANNOT READ: " << path;
1610 if (!doc.setContent(&file)) {
1611 kWarning() << "ERROR, CANNOT READ: " << path;
1616 QDomNodeList list = doc.elementsByTagName("profile");
1617 if (list.isEmpty()) return 0;
1618 QDomElement profile = list.at(0).toElement();
1619 double den = profile.attribute("display_aspect_den").toDouble();
1620 if (den > 0) return profile.attribute("display_aspect_num").toDouble() / den;
1624 void KdenliveDoc::backupLastSavedVersion(const QString &path)
1626 // Ensure backup folder exists
1627 if (path.isEmpty()) return;
1629 KUrl backupFile = m_projectFolder;
1630 backupFile.addPath(".backup/");
1631 KIO::NetAccess::mkdir(backupFile, kapp->activeWindow());
1632 QString fileName = KUrl(path).fileName().section('.', 0, -2);
1633 QFileInfo info(file);
1634 fileName.append("-" + m_documentProperties.value("documentid"));
1635 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
1636 fileName.append(".kdenlive");
1637 backupFile.addPath(fileName);
1639 if (file.exists()) {
1640 // delete previous backup if it was done less than 60 seconds ago
1641 QFile::remove(backupFile.path());
1642 if (!QFile::copy(path, backupFile.path())) {
1643 KMessageBox::information(kapp->activeWindow(), i18n("Cannot create backup copy:\n%1", backupFile.path()));
1648 void KdenliveDoc::cleanupBackupFiles()
1650 KUrl backupFile = m_projectFolder;
1651 backupFile.addPath(".backup/");
1652 QDir dir(backupFile.path());
1653 QString projectFile = url().fileName().section('.', 0, -2);
1654 projectFile.append("-" + m_documentProperties.value("documentid"));
1655 projectFile.append("-??");
1656 projectFile.append("??");
1657 projectFile.append("-??");
1658 projectFile.append("-??");
1659 projectFile.append("-??");
1660 projectFile.append("-??.kdenlive");
1663 backupFile.addPath(projectFile);
1664 filter << projectFile;
1665 dir.setNameFilters(filter);
1666 QFileInfoList resultList = dir.entryInfoList(QDir::Files, QDir::Time);
1668 QDateTime d = QDateTime::currentDateTime();
1669 QStringList hourList;
1670 QStringList dayList;
1671 QStringList weekList;
1672 QStringList oldList;
1673 for (int i = 0; i < resultList.count(); i++) {
1674 if (d.secsTo(resultList.at(i).lastModified()) < 3600) {
1675 // files created in the last hour
1676 hourList.append(resultList.at(i).absoluteFilePath());
1678 else if (d.secsTo(resultList.at(i).lastModified()) < 43200) {
1679 // files created in the day
1680 dayList.append(resultList.at(i).absoluteFilePath());
1682 else if (d.daysTo(resultList.at(i).lastModified()) < 8) {
1683 // files created in the week
1684 weekList.append(resultList.at(i).absoluteFilePath());
1688 oldList.append(resultList.at(i).absoluteFilePath());
1691 if (hourList.count() > 20) {
1692 int step = hourList.count() / 10;
1693 for (int i = 0; i < hourList.count(); i += step) {
1694 kDebug()<<"REMOVE AT: "<<i<<", COUNT: "<<hourList.count();
1695 hourList.removeAt(i);
1698 } else hourList.clear();
1699 if (dayList.count() > 20) {
1700 int step = dayList.count() / 10;
1701 for (int i = 0; i < dayList.count(); i += step) {
1702 dayList.removeAt(i);
1705 } else dayList.clear();
1706 if (weekList.count() > 20) {
1707 int step = weekList.count() / 10;
1708 for (int i = 0; i < weekList.count(); i += step) {
1709 weekList.removeAt(i);
1712 } else weekList.clear();
1713 if (oldList.count() > 20) {
1714 int step = oldList.count() / 10;
1715 for (int i = 0; i < oldList.count(); i += step) {
1716 oldList.removeAt(i);
1719 } else oldList.clear();
1722 while (hourList.count() > 0) {
1723 f = hourList.takeFirst();
1725 QFile::remove(f + ".png");
1727 while (dayList.count() > 0) {
1728 f = dayList.takeFirst();
1730 QFile::remove(f + ".png");
1732 while (weekList.count() > 0) {
1733 f = weekList.takeFirst();
1735 QFile::remove(f + ".png");
1737 while (oldList.count() > 0) {
1738 f = oldList.takeFirst();
1740 QFile::remove(f + ".png");
1744 #include "kdenlivedoc.moc"