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>
59 const double DOCUMENTVERSION = 0.88;
61 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, QString profileName, QMap <QString, QString> properties, const QPoint &tracks, Render *render, KTextEdit *notes, bool *openBackup, MainWindow *parent, KProgressDialog *progressDialog) :
67 m_commandStack(new QUndoStack(undoGroup)),
69 m_projectFolder(projectFolder)
71 // init m_profile struct
72 m_profile.frame_rate_num = 0;
73 m_profile.frame_rate_den = 0;
76 m_profile.progressive = 0;
77 m_profile.sample_aspect_num = 0;
78 m_profile.sample_aspect_den = 0;
79 m_profile.display_aspect_num = 0;
80 m_profile.display_aspect_den = 0;
81 m_profile.colorspace = 0;
83 m_clipManager = new ClipManager(this);
84 m_autoSaveTimer = new QTimer(this);
85 m_autoSaveTimer->setSingleShot(true);
88 // init default document properties
89 m_documentProperties["zoom"] = "7";
90 m_documentProperties["verticalzoom"] = "1";
91 m_documentProperties["zonein"] = "0";
92 m_documentProperties["zoneout"] = "100";
93 m_documentProperties["enableproxy"] = QString::number((int) KdenliveSettings::enableproxy());
94 m_documentProperties["proxyparams"] = KdenliveSettings::proxyparams();
95 m_documentProperties["proxyextension"] = KdenliveSettings::proxyextension();
96 m_documentProperties["generateproxy"] = QString::number((int) KdenliveSettings::generateproxy());
97 m_documentProperties["proxyminsize"] = QString::number(KdenliveSettings::proxyminsize());
98 m_documentProperties["generateimageproxy"] = QString::number((int) KdenliveSettings::generateimageproxy());
99 m_documentProperties["proxyimageminsize"] = QString::number(KdenliveSettings::proxyimageminsize());
100 #if QT_VERSION >= 0x040700
101 m_documentProperties["documentid"] = QString::number(QDateTime::currentMSecsSinceEpoch());
103 QDateTime date = QDateTime::currentDateTime();
104 m_documentProperties["documentid"] = QString::number(date.toTime_t());
108 QMapIterator<QString, QString> i(properties);
109 while (i.hasNext()) {
111 m_documentProperties[i.key()] = i.value();
114 if (QLocale().decimalPoint() != QLocale::system().decimalPoint()) {
115 setlocale(LC_NUMERIC, "");
116 QLocale systemLocale = QLocale::system();
117 systemLocale.setNumberOptions(QLocale::OmitGroupSeparator);
118 QLocale::setDefault(systemLocale);
119 // locale conversion might need to be redone
120 initEffects::parseEffectFiles();
125 if (!url.isEmpty()) {
127 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
129 // The file cannot be opened
130 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) {
133 //KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
138 QDomImplementation impl;
139 impl.setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
140 success = m_document.setContent(&file, false, &errorMsg);
142 KIO::NetAccess::removeTempFile(tmpFile);
146 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) {
149 //KMessageBox::error(parent, errorMsg);
152 parent->slotGotProgressInfo(i18n("Validating"), 0);
153 qApp->processEvents();
154 DocumentValidator validator(m_document);
155 success = validator.isProject();
157 // It is not a project file
158 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
159 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) {
164 * Validate the file against the current version (upgrade
165 * and recover it if needed). It is NOT a passive operation
167 // TODO: backup the document or alert the user?
168 success = validator.validate(DOCUMENTVERSION);
169 if (success) { // Let the validator handle error messages
170 parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
171 qApp->processEvents();
172 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
173 success = checkDocumentClips(infoproducers);
175 if (m_document.documentElement().attribute("modified") == "1") setModified(true);
176 parent->slotGotProgressInfo(i18n("Loading"), 0);
177 QDomElement mlt = m_document.firstChildElement("mlt");
178 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
180 // Set profile, fps, etc for the document
181 setProfilePath(infoXml.attribute("profile"));
183 // Check embedded effects
184 QDomElement customeffects = infoXml.firstChildElement("customeffects");
185 if (!customeffects.isNull() && customeffects.hasChildNodes()) {
186 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
187 qApp->processEvents();
188 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
193 QDomElement notesxml = infoXml.firstChildElement("documentnotes");
194 if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
197 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
198 if (!tracksinfo.isNull()) {
199 QDomNodeList trackslist = tracksinfo.childNodes();
200 int maxchild = trackslist.count();
201 for (int k = 0; k < maxchild; k++) {
202 e = trackslist.at(k).toElement();
203 if (e.tagName() == "trackinfo") {
204 TrackInfo projectTrack;
205 if (e.attribute("type") == "audio")
206 projectTrack.type = AUDIOTRACK;
208 projectTrack.type = VIDEOTRACK;
209 projectTrack.isMute = e.attribute("mute").toInt();
210 projectTrack.isBlind = e.attribute("blind").toInt();
211 projectTrack.isLocked = e.attribute("locked").toInt();
212 projectTrack.trackName = e.attribute("trackname");
213 m_tracksList.append(projectTrack);
216 mlt.removeChild(tracksinfo);
218 QStringList expandedFolders;
219 QDomNodeList folders = m_document.elementsByTagName("folder");
220 for (int i = 0; i < folders.count(); i++) {
221 e = folders.item(i).cloneNode().toElement();
222 if (e.hasAttribute("opened")) expandedFolders.append(e.attribute("id"));
223 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
225 m_documentProperties["expandedfolders"] = expandedFolders.join(";");
227 const int infomax = infoproducers.count();
228 QDomNodeList producers = m_document.elementsByTagName("producer");
229 const int max = producers.count();
231 if (!progressDialog) {
232 progressDialog = new KProgressDialog(parent, i18n("Loading project"), i18n("Adding clips"));
233 progressDialog->setAllowCancel(false);
235 progressDialog->setLabelText(i18n("Adding clips"));
237 progressDialog->progressBar()->setMaximum(infomax);
238 progressDialog->show();
239 qApp->processEvents();
241 for (int i = 0; i < infomax; i++) {
242 e = infoproducers.item(i).cloneNode().toElement();
243 QString prodId = e.attribute("id");
244 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
245 e.setTagName("producer");
246 // Get MLT's original producer properties
248 for (int j = 0; j < max; j++) {
249 QDomNode o = producers.item(j);
250 QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
251 if (origId == prodId) {
252 orig = o.cloneNode().toElement();
257 if (!addClipInfo(e, orig, prodId)) {
258 // The user manually aborted the loading.
260 emit resetProjectList();
261 m_tracksList.clear();
262 m_clipManager->clear();
267 progressDialog->progressBar()->setValue(i);
271 QDomElement markers = infoXml.firstChildElement("markers");
272 if (!markers.isNull()) {
273 QDomNodeList markerslist = markers.childNodes();
274 int maxchild = markerslist.count();
275 for (int k = 0; k < maxchild; k++) {
276 e = markerslist.at(k).toElement();
277 if (e.tagName() == "marker")
278 m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
280 infoXml.removeChild(markers);
283 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
284 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
285 QDomNamedNodeMap props = docproperties.attributes();
286 for (int i = 0; i < props.count(); i++)
287 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
289 if (validator.isModified()) setModified(true);
290 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
299 // Something went wrong, or a new file was requested: create a new project
302 setProfilePath(profileName);
303 m_document = createEmptyDocument(tracks.x(), tracks.y());
306 // Ask to create the project directory if it does not exist
307 if (!QFile::exists(m_projectFolder.path())) {
308 int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
309 if (create == KMessageBox::Yes) {
310 QDir projectDir(m_projectFolder.path());
311 bool ok = projectDir.mkpath(m_projectFolder.path());
313 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
318 // Make sure the project folder is usable
319 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
320 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
321 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
324 // Make sure that the necessary folders exist
325 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
326 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
327 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/");
329 updateProjectFolderPlacesEntry();
331 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
332 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
335 KdenliveDoc::~KdenliveDoc()
337 m_autoSaveTimer->stop();
338 delete m_commandStack;
339 kDebug() << "// DEL CLP MAN";
340 delete m_clipManager;
341 kDebug() << "// DEL CLP MAN done";
342 delete m_autoSaveTimer;
344 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
349 int KdenliveDoc::setSceneList()
351 m_render->resetProfile(KdenliveSettings::current_profile(), true);
352 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
353 // INVALID MLT Consumer, something is wrong
356 m_documentProperties.remove("position");
357 // m_document xml is now useless, clear it
362 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
364 m_tracksList.clear();
366 // Tracks are added «backwards», so we need to reverse the track numbering
367 // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
368 // Better default names for tracks: Audio 1 etc. instead of blank numbers
369 for (int i = 0; i < audiotracks; i++) {
370 TrackInfo audioTrack;
371 audioTrack.type = AUDIOTRACK;
372 audioTrack.isMute = false;
373 audioTrack.isBlind = true;
374 audioTrack.isLocked = false;
375 audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
376 audioTrack.duration = 0;
377 m_tracksList.append(audioTrack);
380 for (int i = 0; i < videotracks; i++) {
381 TrackInfo videoTrack;
382 videoTrack.type = VIDEOTRACK;
383 videoTrack.isMute = false;
384 videoTrack.isBlind = false;
385 videoTrack.isLocked = false;
386 videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
387 videoTrack.duration = 0;
388 m_tracksList.append(videoTrack);
390 return createEmptyDocument(m_tracksList);
393 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
395 // Creating new document
397 QDomElement mlt = doc.createElement("mlt");
398 mlt.setAttribute("LC_NUMERIC", "");
399 doc.appendChild(mlt);
401 // Create black producer
402 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
403 // the composite transitions with the black track are corrupted.
404 QDomElement blk = doc.createElement("producer");
405 blk.setAttribute("in", 0);
406 blk.setAttribute("out", 500);
407 blk.setAttribute("id", "black");
409 QDomElement property = doc.createElement("property");
410 property.setAttribute("name", "mlt_type");
411 QDomText value = doc.createTextNode("producer");
412 property.appendChild(value);
413 blk.appendChild(property);
415 property = doc.createElement("property");
416 property.setAttribute("name", "aspect_ratio");
417 value = doc.createTextNode(QString::number(0));
418 property.appendChild(value);
419 blk.appendChild(property);
421 property = doc.createElement("property");
422 property.setAttribute("name", "length");
423 value = doc.createTextNode(QString::number(15000));
424 property.appendChild(value);
425 blk.appendChild(property);
427 property = doc.createElement("property");
428 property.setAttribute("name", "eof");
429 value = doc.createTextNode("pause");
430 property.appendChild(value);
431 blk.appendChild(property);
433 property = doc.createElement("property");
434 property.setAttribute("name", "resource");
435 value = doc.createTextNode("black");
436 property.appendChild(value);
437 blk.appendChild(property);
439 property = doc.createElement("property");
440 property.setAttribute("name", "mlt_service");
441 value = doc.createTextNode("colour");
442 property.appendChild(value);
443 blk.appendChild(property);
445 mlt.appendChild(blk);
448 QDomElement tractor = doc.createElement("tractor");
449 tractor.setAttribute("id", "maintractor");
450 QDomElement multitrack = doc.createElement("multitrack");
451 QDomElement playlist = doc.createElement("playlist");
452 playlist.setAttribute("id", "black_track");
453 mlt.appendChild(playlist);
455 QDomElement blank0 = doc.createElement("entry");
456 blank0.setAttribute("in", "0");
457 blank0.setAttribute("out", "1");
458 blank0.setAttribute("producer", "black");
459 playlist.appendChild(blank0);
462 int total = tracks.count() + 1;
464 for (int i = 1; i < total; i++) {
465 QDomElement playlist = doc.createElement("playlist");
466 playlist.setAttribute("id", "playlist" + QString::number(i));
467 mlt.appendChild(playlist);
470 QDomElement track0 = doc.createElement("track");
471 track0.setAttribute("producer", "black_track");
472 tractor.appendChild(track0);
474 // create audio and video tracks
475 for (int i = 1; i < total; i++) {
476 QDomElement track = doc.createElement("track");
477 track.setAttribute("producer", "playlist" + QString::number(i));
478 if (tracks.at(i - 1).type == AUDIOTRACK) {
479 track.setAttribute("hide", "video");
480 } else if (tracks.at(i - 1).isBlind)
481 track.setAttribute("hide", "video");
482 if (tracks.at(i - 1).isMute)
483 track.setAttribute("hide", "audio");
484 tractor.appendChild(track);
487 for (int i = 2; i < total ; i++) {
488 QDomElement transition = doc.createElement("transition");
489 transition.setAttribute("always_active", "1");
491 QDomElement property = doc.createElement("property");
492 property.setAttribute("name", "a_track");
493 QDomText value = doc.createTextNode(QString::number(1));
494 property.appendChild(value);
495 transition.appendChild(property);
497 property = doc.createElement("property");
498 property.setAttribute("name", "b_track");
499 value = doc.createTextNode(QString::number(i));
500 property.appendChild(value);
501 transition.appendChild(property);
503 property = doc.createElement("property");
504 property.setAttribute("name", "mlt_service");
505 value = doc.createTextNode("mix");
506 property.appendChild(value);
507 transition.appendChild(property);
509 property = doc.createElement("property");
510 property.setAttribute("name", "combine");
511 value = doc.createTextNode("1");
512 property.appendChild(value);
513 transition.appendChild(property);
515 property = doc.createElement("property");
516 property.setAttribute("name", "internal_added");
517 value = doc.createTextNode("237");
518 property.appendChild(value);
519 transition.appendChild(property);
520 tractor.appendChild(transition);
522 mlt.appendChild(tractor);
527 void KdenliveDoc::syncGuides(QList <Guide *> guides)
530 QDomElement guideNode = m_guidesXml.createElement("guides");
531 m_guidesXml.appendChild(guideNode);
534 for (int i = 0; i < guides.count(); i++) {
535 e = m_guidesXml.createElement("guide");
536 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
537 e.setAttribute("comment", guides.at(i)->label());
538 guideNode.appendChild(e);
541 emit guidesUpdated();
544 QDomElement KdenliveDoc::guidesXml() const
546 return m_guidesXml.documentElement();
549 void KdenliveDoc::slotAutoSave()
551 if (m_render && m_autosave) {
552 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
553 // show error: could not open the autosave file
554 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
556 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
557 saveSceneList(m_autosave->fileName(), m_render->sceneList(), QStringList(), true);
561 void KdenliveDoc::setZoom(int horizontal, int vertical)
563 m_documentProperties["zoom"] = QString::number(horizontal);
564 m_documentProperties["verticalzoom"] = QString::number(vertical);
567 QPoint KdenliveDoc::zoom() const
569 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
572 void KdenliveDoc::setZone(int start, int end)
574 m_documentProperties["zonein"] = QString::number(start);
575 m_documentProperties["zoneout"] = QString::number(end);
578 QPoint KdenliveDoc::zone() const
580 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
583 QDomDocument KdenliveDoc::xmlSceneList(const QString &scene, const QStringList &expandedFolders)
585 QDomDocument sceneList;
586 sceneList.setContent(scene, true);
587 QDomElement mlt = sceneList.firstChildElement("mlt");
588 if (mlt.isNull() || !mlt.hasChildNodes()) {
589 //scenelist is corrupted
593 // Set playlist audio volume to 100%
594 QDomElement tractor = mlt.firstChildElement("tractor");
595 if (!tractor.isNull()) {
596 QDomNodeList props = tractor.elementsByTagName("property");
597 for (int i = 0; i < props.count(); i++) {
598 if (props.at(i).toElement().attribute("name") == "meta.volume") {
599 props.at(i).firstChild().setNodeValue("1");
605 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
606 mlt.appendChild(addedXml);
608 // check if project contains custom effects to embed them in project file
609 QDomNodeList effects = mlt.elementsByTagName("filter");
610 int maxEffects = effects.count();
611 kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
612 QMap <QString, QString> effectIds;
613 for (int i = 0; i < maxEffects; i++) {
614 QDomNode m = effects.at(i);
615 QDomNodeList params = m.childNodes();
618 for (int j = 0; j < params.count(); j++) {
619 QDomElement e = params.item(j).toElement();
620 if (e.attribute("name") == "kdenlive_id") {
621 id = e.firstChild().nodeValue();
623 if (e.attribute("name") == "tag") {
624 tag = e.firstChild().nodeValue();
626 if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
629 QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
630 addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
632 QDomElement markers = sceneList.createElement("markers");
633 addedXml.setAttribute("version", DOCUMENTVERSION);
634 addedXml.setAttribute("kdenliveversion", VERSION);
635 addedXml.setAttribute("profile", profilePath());
636 addedXml.setAttribute("projectfolder", m_projectFolder.path());
638 QDomElement docproperties = sceneList.createElement("documentproperties");
639 QMapIterator<QString, QString> i(m_documentProperties);
640 while (i.hasNext()) {
642 docproperties.setAttribute(i.key(), i.value());
644 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
645 addedXml.appendChild(docproperties);
647 QDomElement docnotes = sceneList.createElement("documentnotes");
648 QDomText value = sceneList.createTextNode(m_notesWidget->toHtml());
649 docnotes.appendChild(value);
650 addedXml.appendChild(docnotes);
653 QDomElement profileinfo = sceneList.createElement("profileinfo");
654 profileinfo.setAttribute("description", m_profile.description);
655 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
656 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
657 profileinfo.setAttribute("width", m_profile.width);
658 profileinfo.setAttribute("height", m_profile.height);
659 profileinfo.setAttribute("progressive", m_profile.progressive);
660 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
661 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
662 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
663 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
664 addedXml.appendChild(profileinfo);
667 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
668 foreach(const TrackInfo & info, m_tracksList) {
669 QDomElement trackinfo = sceneList.createElement("trackinfo");
670 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
671 trackinfo.setAttribute("mute", info.isMute);
672 trackinfo.setAttribute("blind", info.isBlind);
673 trackinfo.setAttribute("locked", info.isLocked);
674 trackinfo.setAttribute("trackname", info.trackName);
675 tracksinfo.appendChild(trackinfo);
677 addedXml.appendChild(tracksinfo);
679 // save project folders
680 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
682 QMapIterator<QString, QString> f(folderlist);
683 while (f.hasNext()) {
685 QDomElement folder = sceneList.createElement("folder");
686 folder.setAttribute("id", f.key());
687 folder.setAttribute("name", f.value());
688 if (expandedFolders.contains(f.key())) folder.setAttribute("opened", "1");
689 addedXml.appendChild(folder);
692 // Save project clips
694 QList <DocClipBase*> list = m_clipManager->documentClipList();
695 for (int i = 0; i < list.count(); i++) {
696 e = list.at(i)->toXML();
697 e.setTagName("kdenlive_producer");
698 addedXml.appendChild(sceneList.importNode(e, true));
699 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
700 for (int j = 0; j < marks.count(); j++) {
701 QDomElement marker = sceneList.createElement("marker");
702 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
703 marker.setAttribute("comment", marks.at(j).comment());
704 marker.setAttribute("id", e.attribute("id"));
705 markers.appendChild(marker);
708 addedXml.appendChild(markers);
711 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
714 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
716 //wes.appendChild(doc.importNode(kdenliveData, true));
720 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene, const QStringList &expandedFolders, bool autosave)
722 QDomDocument sceneList = xmlSceneList(scene, expandedFolders);
723 if (sceneList.isNull()) {
724 //Make sure we don't save if scenelist is corrupted
725 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
729 // Backup current version
730 if (!autosave) backupLastSavedVersion(path);
733 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
734 kWarning() << "////// ERROR writing to file: " << path;
735 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
739 file.write(sceneList.toString().toUtf8());
740 if (file.error() != QFile::NoError) {
741 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
747 cleanupBackupFiles();
748 QFileInfo info(file);
749 QString fileName = KUrl(path).fileName().section('.', 0, -2);
750 fileName.append("-" + m_documentProperties.value("documentid"));
751 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
752 fileName.append(".kdenlive.png");
753 KUrl backupFile = m_projectFolder;
754 backupFile.addPath(".backup/");
755 backupFile.addPath(fileName);
756 emit saveTimelinePreview(backupFile.path());
761 ClipManager *KdenliveDoc::clipManager()
763 return m_clipManager;
766 KUrl KdenliveDoc::projectFolder() const
768 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
769 return m_projectFolder;
772 void KdenliveDoc::setProjectFolder(KUrl url)
774 if (url == m_projectFolder) return;
776 KStandardDirs::makeDir(url.path());
777 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
778 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
779 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);
780 m_projectFolder = url;
782 updateProjectFolderPlacesEntry();
785 void KdenliveDoc::moveProjectData(KUrl url)
787 QList <DocClipBase*> list = m_clipManager->documentClipList();
788 KUrl::List cacheUrls;
789 for (int i = 0; i < list.count(); i++) {
790 DocClipBase *clip = list.at(i);
791 if (clip->clipType() == TEXT) {
792 // the image for title clip must be moved
793 KUrl oldUrl = clip->fileURL();
794 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
795 KIO::Job *job = KIO::copy(oldUrl, newUrl);
796 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
798 QString hash = clip->getClipHash();
799 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
800 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
801 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
802 cacheUrls << oldVideoThumbUrl;
804 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
805 cacheUrls << oldAudioThumbUrl;
808 if (!cacheUrls.isEmpty()) {
809 KIO::Job *job = KIO::copy(cacheUrls, KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/"));
810 job->ui()->setWindow(kapp->activeWindow());
811 KIO::NetAccess::synchronousRun(job, 0);
815 const QString &KdenliveDoc::profilePath() const
817 return m_profile.path;
820 MltVideoProfile KdenliveDoc::mltProfile() const
825 bool KdenliveDoc::setProfilePath(QString path)
827 if (path.isEmpty()) path = KdenliveSettings::default_profile();
828 if (path.isEmpty()) path = "dv_pal";
829 m_profile = ProfilesDialog::getVideoProfile(path);
830 double current_fps = m_fps;
831 if (m_profile.path.isEmpty()) {
832 // Profile not found, use embedded profile
833 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
834 if (profileInfo.isNull()) {
835 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
836 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
838 m_profile.description = profileInfo.attribute("description");
839 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
840 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
841 m_profile.width = profileInfo.attribute("width").toInt();
842 m_profile.height = profileInfo.attribute("height").toInt();
843 m_profile.progressive = profileInfo.attribute("progressive").toInt();
844 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
845 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
846 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
847 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
848 QString existing = ProfilesDialog::existingProfile(m_profile);
849 if (!existing.isEmpty()) {
850 m_profile = ProfilesDialog::getVideoProfile(existing);
851 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
853 QString newDesc = m_profile.description;
855 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
856 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);
859 // User canceled, use default profile
860 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
862 if (newDesc != m_profile.description) {
863 // Profile description existed, was replaced by new one
864 m_profile.description = newDesc;
866 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
868 ProfilesDialog::saveProfile(m_profile);
875 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
876 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
877 KdenliveSettings::setProject_fps(m_fps);
878 m_width = m_profile.width;
879 m_height = m_profile.height;
880 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
881 m_timecode.setFormat(m_fps);
882 KdenliveSettings::setCurrent_profile(m_profile.path);
883 return (current_fps != m_fps);
886 double KdenliveDoc::dar() const
888 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
891 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
893 emit progressInfo(message, progress);
896 QUndoStack *KdenliveDoc::commandStack()
898 return m_commandStack;
902 void KdenliveDoc::setRenderer(Render *render) {
903 if (m_render) return;
905 emit progressInfo(i18n("Loading playlist..."), 0);
906 //qApp->processEvents();
908 m_render->setSceneList(m_document.toString(), m_startPos);
909 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
912 emit progressInfo(QString(), -1);
915 void KdenliveDoc::checkProjectClips(bool displayRatioChanged, bool fpsChanged)
917 if (m_render == NULL) return;
918 m_clipManager->resetProducersList(m_render->producersList(), displayRatioChanged, fpsChanged);
921 Render *KdenliveDoc::renderer()
926 void KdenliveDoc::updateClip(const QString &id)
928 emit updateClipDisplay(id);
931 int KdenliveDoc::getFramePos(QString duration)
933 return m_timecode.getFrameCount(duration);
936 QString KdenliveDoc::producerName(const QString &id)
938 QString result = "unnamed";
939 QDomNodeList prods = producersList();
940 int ct = prods.count();
941 for (int i = 0; i < ct ; i++) {
942 QDomElement e = prods.item(i).toElement();
943 if (e.attribute("id") != "black" && e.attribute("id") == id) {
944 result = e.attribute("name");
945 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
952 QDomDocument KdenliveDoc::toXml()
957 Timecode KdenliveDoc::timecode() const
962 QDomNodeList KdenliveDoc::producersList()
964 return m_document.elementsByTagName("producer");
967 double KdenliveDoc::projectDuration() const
970 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
975 double KdenliveDoc::fps() const
980 int KdenliveDoc::width() const
985 int KdenliveDoc::height() const
990 KUrl KdenliveDoc::url() const
995 void KdenliveDoc::setUrl(KUrl url)
1000 void KdenliveDoc::setModified(bool mod)
1002 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
1003 m_autoSaveTimer->start(3000);
1005 if (mod == m_modified) return;
1007 emit docModified(m_modified);
1010 bool KdenliveDoc::isModified() const
1015 const QString KdenliveDoc::description() const
1017 if (m_url.isEmpty())
1018 return i18n("Untitled") + " / " + m_profile.description;
1020 return m_url.fileName() + " / " + m_profile.description;
1023 bool KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
1025 const QString producerId = clipId.section('_', 0, 0);
1026 DocClipBase *clip = m_clipManager->getClipById(producerId);
1029 elem.setAttribute("id", producerId);
1030 QString path = elem.attribute("resource");
1032 if (elem.attribute("type").toInt() == SLIDESHOW) {
1033 extension = KUrl(path).fileName();
1034 path = KUrl(path).directory();
1037 if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
1038 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1039 const QString size = elem.attribute("file_size");
1040 const QString hash = elem.attribute("file_hash");
1042 int action = KMessageBox::No;
1043 if (!size.isEmpty() && !hash.isEmpty()) {
1044 if (!m_searchFolder.isEmpty())
1045 newpath = searchFileRecursively(m_searchFolder, size, hash);
1047 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")));
1049 if (elem.attribute("type").toInt() == SLIDESHOW) {
1050 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")));
1051 if (res == KMessageBox::Yes)
1052 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1054 // Abort project loading
1058 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")));
1059 if (res == KMessageBox::Yes)
1060 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1062 // Abort project loading
1067 if (action == KMessageBox::Yes) {
1068 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1069 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1070 if (!m_searchFolder.isEmpty())
1071 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1072 } else if (action == KMessageBox::Cancel) {
1074 } else if (action == KMessageBox::No) {
1075 // Keep clip as placeHolder
1076 elem.setAttribute("placeholder", '1');
1078 if (!newpath.isEmpty()) {
1079 if (elem.attribute("type").toInt() == SLIDESHOW)
1080 newpath.append('/' + extension);
1081 elem.setAttribute("resource", newpath);
1082 setNewClipResource(clipId, newpath);
1086 clip = new DocClipBase(m_clipManager, elem, producerId);
1087 m_clipManager->addClip(clip);
1090 if (createClipItem) {
1091 emit addProjectClip(clip);
1097 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1099 QDomNodeList prods = m_document.elementsByTagName("producer");
1100 int maxprod = prods.count();
1101 for (int i = 0; i < maxprod; i++) {
1102 QDomNode m = prods.at(i);
1103 QString prodId = m.toElement().attribute("id");
1104 if (prodId == id || prodId.startsWith(id + '_')) {
1105 QDomNodeList params = m.childNodes();
1106 for (int j = 0; j < params.count(); j++) {
1107 QDomElement e = params.item(j).toElement();
1108 if (e.attribute("name") == "resource") {
1109 e.firstChild().setNodeValue(path);
1117 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1119 QString foundFileName;
1120 QByteArray fileData;
1121 QByteArray fileHash;
1122 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1123 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1124 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1125 if (file.open(QIODevice::ReadOnly)) {
1126 if (QString::number(file.size()) == matchSize) {
1128 * 1 MB = 1 second per 450 files (or faster)
1129 * 10 MB = 9 seconds per 450 files (or faster)
1131 if (file.size() > 1000000 * 2) {
1132 fileData = file.read(1000000);
1133 if (file.seek(file.size() - 1000000))
1134 fileData.append(file.readAll());
1136 fileData = file.readAll();
1138 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1139 if (QString(fileHash.toHex()) == matchHash)
1140 return file.fileName();
1143 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1145 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1146 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1147 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1148 if (!foundFileName.isEmpty())
1151 return foundFileName;
1154 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1156 DocClipBase *clip = m_clipManager->getClipById(clipId);
1158 if (!addClip(elem, clipId, false))
1161 QMap <QString, QString> properties;
1162 QDomNamedNodeMap attributes = elem.attributes();
1163 for (int i = 0; i < attributes.count(); i++) {
1164 QString attrname = attributes.item(i).nodeName();
1165 if (attrname != "resource")
1166 properties.insert(attrname, attributes.item(i).nodeValue());
1167 kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1169 clip->setProperties(properties);
1170 emit addProjectClip(clip, false);
1172 if (orig != QDomElement()) {
1173 QMap<QString, QString> meta;
1174 for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1175 QString name = m.toElement().attribute("name");
1176 if (name.startsWith("meta.attr"))
1177 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1179 if (!meta.isEmpty()) {
1181 clip = m_clipManager->getClipById(clipId);
1183 clip->setMetadata(meta);
1190 void KdenliveDoc::deleteClip(const QString &clipId)
1192 emit signalDeleteProjectClip(clipId);
1195 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString &group, const QString &groupId)
1197 m_clipManager->slotAddClipList(urls, group, groupId);
1198 //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1203 void KdenliveDoc::slotAddClipFile(const KUrl &url, const QString &group, const QString &groupId)
1205 m_clipManager->slotAddClipFile(url, group, groupId);
1206 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1210 const QString KdenliveDoc::getFreeClipId()
1212 return QString::number(m_clipManager->getFreeClipId());
1215 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1217 return m_clipManager->getClipById(clipId);
1220 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement xml, QString group, const QString &groupId)
1222 m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1224 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1227 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1229 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1231 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1234 void KdenliveDoc::slotCreateSlideshowClipFile(const QString &name, const QString &path, int count, const QString &duration,
1235 const bool loop, const bool crop, const bool fade,
1236 const QString &luma_duration, const QString &luma_file, const int softness,
1237 const QString &animation, QString group, const QString &groupId)
1239 m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop,
1240 crop, fade, luma_duration,
1241 luma_file, softness,
1242 animation, group, groupId);
1244 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1247 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1249 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1250 KStandardDirs::makeDir(titlesFolder);
1251 TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1252 if (dia_ui->exec() == QDialog::Accepted) {
1253 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->outPoint(), dia_ui->xml().toString(), group, groupId);
1255 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1260 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1262 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1263 if (path.isEmpty()) {
1264 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1267 if (path.isEmpty()) return;
1269 //TODO: rewrite with new title system (just set resource)
1270 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1272 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1275 int KdenliveDoc::tracksCount() const
1277 return m_tracksList.count();
1280 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1282 if (ix < 0 || ix >= m_tracksList.count()) {
1283 kWarning() << "Track INFO outisde of range";
1286 return m_tracksList.at(ix);
1289 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1291 if (ix < 0 || ix >= m_tracksList.count()) {
1292 kWarning() << "SWITCH Track outisde of range";
1295 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1298 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1300 if (ix < 0 || ix >= m_tracksList.count()) {
1301 kWarning() << "Track Lock outisde of range";
1304 m_tracksList[ix].isLocked = lock;
1307 bool KdenliveDoc::isTrackLocked(int ix) const
1309 if (ix < 0 || ix >= m_tracksList.count()) {
1310 kWarning() << "Track Lock outisde of range";
1313 return m_tracksList.at(ix).isLocked;
1316 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1318 if (ix < 0 || ix >= m_tracksList.count()) {
1319 kWarning() << "SWITCH Track outisde of range";
1322 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1325 int KdenliveDoc::trackDuration(int ix)
1327 return m_tracksList.at(ix).duration;
1330 void KdenliveDoc::setTrackDuration(int ix, int duration)
1332 m_tracksList[ix].duration = duration;
1335 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1337 if (ix == -1) m_tracksList << type;
1338 else m_tracksList.insert(ix, type);
1341 void KdenliveDoc::deleteTrack(int ix)
1343 if (ix < 0 || ix >= m_tracksList.count()) {
1344 kWarning() << "Delete Track outisde of range";
1347 m_tracksList.removeAt(ix);
1350 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1352 if (ix < 0 || ix >= m_tracksList.count()) {
1353 kWarning() << "SET Track Type outisde of range";
1356 m_tracksList[ix].type = type.type;
1357 m_tracksList[ix].isMute = type.isMute;
1358 m_tracksList[ix].isBlind = type.isBlind;
1359 m_tracksList[ix].isLocked = type.isLocked;
1360 m_tracksList[ix].trackName = type.trackName;
1363 const QList <TrackInfo> KdenliveDoc::tracksList() const
1365 return m_tracksList;
1368 QPoint KdenliveDoc::getTracksCount() const
1372 foreach(const TrackInfo & info, m_tracksList) {
1373 if (info.type == VIDEOTRACK) video++;
1376 return QPoint(video, audio);
1379 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1381 pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1384 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1386 DocumentChecker d(infoproducers, m_document);
1387 return (d.hasErrorInClips() == false);
1393 QList <QDomElement> missingClips;
1394 for (int i = 0; i < infoproducers.count(); i++) {
1395 e = infoproducers.item(i).toElement();
1396 clipType = e.attribute("type").toInt();
1397 if (clipType == COLOR) continue;
1398 if (clipType == TEXT) {
1399 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1402 id = e.attribute("id");
1403 resource = e.attribute("resource");
1404 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1405 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1406 // Missing clip found
1407 missingClips.append(e);
1409 // Check if the clip has changed
1410 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1411 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1412 e.removeAttribute("file_hash");
1416 if (missingClips.isEmpty()) return true;
1417 DocumentChecker d(missingClips, m_document);
1418 return (d.exec() == QDialog::Accepted);*/
1421 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1423 m_documentProperties[name] = value;
1426 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1428 return m_documentProperties.value(name);
1431 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1433 QMap <QString, QString> renderProperties;
1434 QMapIterator<QString, QString> i(m_documentProperties);
1435 while (i.hasNext()) {
1437 if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1439 return renderProperties;
1442 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1444 if (ix < 0 || ix >= m_tracksList.count()) {
1445 kWarning() << "Add Track effect outisde of range";
1448 effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1450 // Init parameter value & keyframes if required
1451 QDomNodeList params = effect.elementsByTagName("parameter");
1452 for (int i = 0; i < params.count(); i++) {
1453 QDomElement e = params.item(i).toElement();
1455 // Check if this effect has a variable parameter
1456 if (e.attribute("default").contains('%')) {
1457 double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1458 e.setAttribute("default", evaluatedValue);
1459 if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1460 e.setAttribute("value", evaluatedValue);
1464 if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1465 QString def = e.attribute("default");
1466 // Effect has a keyframe type parameter, we need to set the values
1467 if (e.attribute("keyframes").isEmpty()) {
1468 e.setAttribute("keyframes", "0:" + def + ';');
1469 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1474 if (effect.attribute("id") == "crop") {
1475 // default use_profile to 1 for clips with proxies to avoid problems when rendering
1476 if (e.attribute("name") == "use_profile" && getDocumentProperty("enableproxy") == "1")
1477 e.setAttribute("value", "1");
1481 m_tracksList[ix].effectsList.append(effect);
1484 void KdenliveDoc::removeTrackEffect(int ix, QDomElement effect)
1486 if (ix < 0 || ix >= m_tracksList.count()) {
1487 kWarning() << "Remove Track effect outisde of range";
1491 QString toRemove = effect.attribute("kdenlive_ix");
1492 for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1493 index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix");
1494 if (toRemove == index) {
1495 m_tracksList[ix].effectsList.removeAt(i);
1497 } else if (index.toInt() > toRemove.toInt()) {
1498 m_tracksList[ix].effectsList.item(i).setAttribute("kdenlive_ix", index.toInt() - 1);
1503 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1505 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1506 kWarning() << "Set Track effect outisde of range";
1509 if (effectIndex < 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count() - 1) || effect.isNull()) {
1510 kDebug() << "Invalid effect index: " << effectIndex;
1513 effect.setAttribute("kdenlive_ix", effectIndex + 1);
1514 m_tracksList[trackIndex].effectsList.replace(effectIndex, effect);
1517 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1519 if (ix < 0 || ix >= m_tracksList.count()) {
1520 kWarning() << "Get Track effects outisde of range";
1521 return EffectsList();
1523 return m_tracksList.at(ix).effectsList;
1526 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1528 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1529 kWarning() << "Get Track effect outisde of range";
1530 return QDomElement();
1532 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1533 if (effectIndex > list.count() - 1 || effectIndex < 0 || list.at(effectIndex).isNull()) return QDomElement();
1534 return list.at(effectIndex).cloneNode().toElement();
1537 bool KdenliveDoc::saveCustomEffects(QDomNodeList customeffects)
1540 QStringList importedEffects;
1541 int maxchild = customeffects.count();
1542 for (int i = 0; i < maxchild; i++) {
1543 e = customeffects.at(i).toElement();
1544 QString id = e.attribute("id");
1545 QString tag = e.attribute("tag");
1546 if (!id.isEmpty()) {
1547 // Check if effect exists or save it
1548 if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1550 doc.appendChild(doc.importNode(e, true));
1551 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1552 path += id + ".xml";
1553 if (!QFile::exists(path)) {
1554 importedEffects << id;
1556 if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1557 QTextStream out(&file);
1558 out << doc.toString();
1564 if (!importedEffects.isEmpty()) KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1565 return (!importedEffects.isEmpty());
1568 void KdenliveDoc::updateProjectFolderPlacesEntry()
1571 * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1572 * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1575 const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1576 KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1577 KBookmarkGroup root = bookmarkManager->root();
1578 KBookmark bookmark = root.first();
1580 QString kdenliveName = KGlobal::mainComponent().componentName();
1581 KUrl documentLocation = m_projectFolder;
1583 bool exists = false;
1585 while (!bookmark.isNull()) {
1586 // UDI not empty indicates a device
1587 QString udi = bookmark.metaDataItem("UDI");
1588 QString appName = bookmark.metaDataItem("OnlyInApp");
1590 if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1591 if (bookmark.url() != documentLocation) {
1592 bookmark.setUrl(documentLocation);
1593 bookmarkManager->emitChanged(root);
1599 bookmark = root.next(bookmark);
1602 // if entry does not exist yet (was not found), well, create it then
1604 bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1605 // Make this user selectable ?
1606 bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1607 bookmarkManager->emitChanged(root);
1611 QStringList KdenliveDoc::getExpandedFolders()
1613 QStringList result = m_documentProperties.value("expandedfolders").split(';');
1614 // this property is only needed once when opening project, so clear it now
1615 m_documentProperties.remove("expandedfolders");
1620 double KdenliveDoc::getDisplayRatio(const QString &path)
1624 if (!file.open(QIODevice::ReadOnly)) {
1625 kWarning() << "ERROR, CANNOT READ: " << path;
1628 if (!doc.setContent(&file)) {
1629 kWarning() << "ERROR, CANNOT READ: " << path;
1634 QDomNodeList list = doc.elementsByTagName("profile");
1635 if (list.isEmpty()) return 0;
1636 QDomElement profile = list.at(0).toElement();
1637 double den = profile.attribute("display_aspect_den").toDouble();
1638 if (den > 0) return profile.attribute("display_aspect_num").toDouble() / den;
1642 void KdenliveDoc::backupLastSavedVersion(const QString &path)
1644 // Ensure backup folder exists
1645 if (path.isEmpty()) return;
1647 KUrl backupFile = m_projectFolder;
1648 backupFile.addPath(".backup/");
1649 KIO::NetAccess::mkdir(backupFile, kapp->activeWindow());
1650 QString fileName = KUrl(path).fileName().section('.', 0, -2);
1651 QFileInfo info(file);
1652 fileName.append("-" + m_documentProperties.value("documentid"));
1653 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
1654 fileName.append(".kdenlive");
1655 backupFile.addPath(fileName);
1657 if (file.exists()) {
1658 // delete previous backup if it was done less than 60 seconds ago
1659 QFile::remove(backupFile.path());
1660 if (!QFile::copy(path, backupFile.path())) {
1661 KMessageBox::information(kapp->activeWindow(), i18n("Cannot create backup copy:\n%1", backupFile.path()));
1666 void KdenliveDoc::cleanupBackupFiles()
1668 KUrl backupFile = m_projectFolder;
1669 backupFile.addPath(".backup/");
1670 QDir dir(backupFile.path());
1671 QString projectFile = url().fileName().section('.', 0, -2);
1672 projectFile.append("-" + m_documentProperties.value("documentid"));
1673 projectFile.append("-??");
1674 projectFile.append("??");
1675 projectFile.append("-??");
1676 projectFile.append("-??");
1677 projectFile.append("-??");
1678 projectFile.append("-??.kdenlive");
1681 backupFile.addPath(projectFile);
1682 filter << projectFile;
1683 dir.setNameFilters(filter);
1684 QFileInfoList resultList = dir.entryInfoList(QDir::Files, QDir::Time);
1686 QDateTime d = QDateTime::currentDateTime();
1687 QStringList hourList;
1688 QStringList dayList;
1689 QStringList weekList;
1690 QStringList oldList;
1691 for (int i = 0; i < resultList.count(); i++) {
1692 if (d.secsTo(resultList.at(i).lastModified()) < 3600) {
1693 // files created in the last hour
1694 hourList.append(resultList.at(i).absoluteFilePath());
1696 else if (d.secsTo(resultList.at(i).lastModified()) < 43200) {
1697 // files created in the day
1698 dayList.append(resultList.at(i).absoluteFilePath());
1700 else if (d.daysTo(resultList.at(i).lastModified()) < 8) {
1701 // files created in the week
1702 weekList.append(resultList.at(i).absoluteFilePath());
1706 oldList.append(resultList.at(i).absoluteFilePath());
1709 if (hourList.count() > 20) {
1710 int step = hourList.count() / 10;
1711 for (int i = 0; i < hourList.count(); i += step) {
1712 kDebug()<<"REMOVE AT: "<<i<<", COUNT: "<<hourList.count();
1713 hourList.removeAt(i);
1716 } else hourList.clear();
1717 if (dayList.count() > 20) {
1718 int step = dayList.count() / 10;
1719 for (int i = 0; i < dayList.count(); i += step) {
1720 dayList.removeAt(i);
1723 } else dayList.clear();
1724 if (weekList.count() > 20) {
1725 int step = weekList.count() / 10;
1726 for (int i = 0; i < weekList.count(); i += step) {
1727 weekList.removeAt(i);
1730 } else weekList.clear();
1731 if (oldList.count() > 20) {
1732 int step = oldList.count() / 10;
1733 for (int i = 0; i < oldList.count(); i += step) {
1734 oldList.removeAt(i);
1737 } else oldList.clear();
1740 while (hourList.count() > 0) {
1741 f = hourList.takeFirst();
1743 QFile::remove(f + ".png");
1745 while (dayList.count() > 0) {
1746 f = dayList.takeFirst();
1748 QFile::remove(f + ".png");
1750 while (weekList.count() > 0) {
1751 f = weekList.takeFirst();
1753 QFile::remove(f + ".png");
1755 while (oldList.count() > 0) {
1756 f = oldList.takeFirst();
1758 QFile::remove(f + ".png");
1762 #include "kdenlivedoc.moc"