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 "config-kdenlive.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, QMap <QString, QString> metadata, 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);
86 connect(m_clipManager, SIGNAL(displayMessage(QString, int)), parent, SLOT(slotGotProgressInfo(QString,int)));
89 // init default document properties
90 m_documentProperties["zoom"] = '7';
91 m_documentProperties["verticalzoom"] = '1';
92 m_documentProperties["zonein"] = '0';
93 m_documentProperties["zoneout"] = "100";
94 m_documentProperties["enableproxy"] = QString::number((int) KdenliveSettings::enableproxy());
95 m_documentProperties["proxyparams"] = KdenliveSettings::proxyparams();
96 m_documentProperties["proxyextension"] = KdenliveSettings::proxyextension();
97 m_documentProperties["generateproxy"] = QString::number((int) KdenliveSettings::generateproxy());
98 m_documentProperties["proxyminsize"] = QString::number(KdenliveSettings::proxyminsize());
99 m_documentProperties["generateimageproxy"] = QString::number((int) KdenliveSettings::generateimageproxy());
100 m_documentProperties["proxyimageminsize"] = QString::number(KdenliveSettings::proxyimageminsize());
101 #if QT_VERSION >= 0x040700
102 m_documentProperties["documentid"] = QString::number(QDateTime::currentMSecsSinceEpoch());
104 QDateTime date = QDateTime::currentDateTime();
105 m_documentProperties["documentid"] = QString::number(date.toTime_t());
109 QMapIterator<QString, QString> i(properties);
110 while (i.hasNext()) {
112 m_documentProperties[i.key()] = i.value();
116 QMapIterator<QString, QString> j(metadata);
117 while (j.hasNext()) {
119 m_documentMetadata[j.key()] = j.value();
122 if (QLocale().decimalPoint() != QLocale::system().decimalPoint()) {
123 setlocale(LC_NUMERIC, "");
124 QLocale systemLocale = QLocale::system();
125 systemLocale.setNumberOptions(QLocale::OmitGroupSeparator);
126 QLocale::setDefault(systemLocale);
127 // locale conversion might need to be redone
128 initEffects::parseEffectFiles(setlocale(LC_NUMERIC, NULL));
133 if (!url.isEmpty()) {
135 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
137 // The file cannot be opened
138 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) {
141 //KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
148 QDomImplementation::setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
149 success = m_document.setContent(&file, false, &errorMsg, &line, &col);
151 KIO::NetAccess::removeTempFile(tmpFile);
155 if (KMessageBox::warningContinueCancel(parent, i18n("Cannot open the project file, error is:\n%1 (line %2, col %3)\nDo you want to open a backup file?", errorMsg, line, col), i18n("Error opening file"), KGuiItem(i18n("Open Backup"))) == KMessageBox::Continue) {
158 //KMessageBox::error(parent, errorMsg);
161 parent->slotGotProgressInfo(i18n("Validating"), 0);
162 qApp->processEvents();
163 DocumentValidator validator(m_document, url);
164 success = validator.isProject();
166 // It is not a project file
167 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
168 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) {
173 * Validate the file against the current version (upgrade
174 * and recover it if needed). It is NOT a passive operation
176 // TODO: backup the document or alert the user?
177 success = validator.validate(DOCUMENTVERSION);
178 if (success) { // Let the validator handle error messages
179 parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
180 qApp->processEvents();
181 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
182 success = checkDocumentClips(infoproducers);
184 if (m_document.documentElement().attribute("modified") == "1") setModified(true);
185 parent->slotGotProgressInfo(i18n("Loading"), 0);
186 QDomElement mlt = m_document.firstChildElement("mlt");
187 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
189 // Set profile, fps, etc for the document
190 setProfilePath(infoXml.attribute("profile"));
192 // Check embedded effects
193 QDomElement customeffects = infoXml.firstChildElement("customeffects");
194 if (!customeffects.isNull() && customeffects.hasChildNodes()) {
195 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
196 qApp->processEvents();
197 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
202 QDomElement notesxml = infoXml.firstChildElement("documentnotes");
203 if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
206 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
207 if (!tracksinfo.isNull()) {
208 QDomNodeList trackslist = tracksinfo.childNodes();
209 int maxchild = trackslist.count();
210 for (int k = 0; k < maxchild; k++) {
211 e = trackslist.at(k).toElement();
212 if (e.tagName() == "trackinfo") {
213 TrackInfo projectTrack;
214 if (e.attribute("type") == "audio")
215 projectTrack.type = AUDIOTRACK;
217 projectTrack.type = VIDEOTRACK;
218 projectTrack.isMute = e.attribute("mute").toInt();
219 projectTrack.isBlind = e.attribute("blind").toInt();
220 projectTrack.isLocked = e.attribute("locked").toInt();
221 projectTrack.trackName = e.attribute("trackname");
222 projectTrack.effectsList = EffectsList(true);
223 m_tracksList.append(projectTrack);
226 mlt.removeChild(tracksinfo);
228 QStringList expandedFolders;
229 QDomNodeList folders = m_document.elementsByTagName("folder");
230 for (int i = 0; i < folders.count(); i++) {
231 e = folders.item(i).cloneNode().toElement();
232 if (e.hasAttribute("opened")) expandedFolders.append(e.attribute("id"));
233 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
235 m_documentProperties["expandedfolders"] = expandedFolders.join(";");
237 const int infomax = infoproducers.count();
238 QDomNodeList producers = m_document.elementsByTagName("producer");
239 const int max = producers.count();
241 if (!progressDialog) {
242 progressDialog = new KProgressDialog(parent, i18n("Loading project"), i18n("Adding clips"));
243 progressDialog->setAllowCancel(false);
245 progressDialog->setLabelText(i18n("Adding clips"));
247 progressDialog->progressBar()->setMaximum(infomax);
248 progressDialog->show();
249 qApp->processEvents();
251 for (int i = 0; i < infomax; i++) {
252 e = infoproducers.item(i).cloneNode().toElement();
253 QString prodId = e.attribute("id");
254 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
255 e.setTagName("producer");
256 // Get MLT's original producer properties
258 for (int j = 0; j < max; j++) {
259 QDomNode o = producers.item(j);
260 QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
261 if (origId == prodId) {
262 orig = o.cloneNode().toElement();
267 if (!addClipInfo(e, orig, prodId)) {
268 // The user manually aborted the loading.
270 emit resetProjectList();
271 m_tracksList.clear();
272 m_clipManager->clear();
277 progressDialog->progressBar()->setValue(i);
281 QDomElement markers = infoXml.firstChildElement("markers");
282 if (!markers.isNull()) {
283 QDomNodeList markerslist = markers.childNodes();
284 int maxchild = markerslist.count();
285 for (int k = 0; k < maxchild; k++) {
286 e = markerslist.at(k).toElement();
287 if (e.tagName() == "marker") {
288 CommentedTime marker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"), e.attribute("type").toInt());
289 DocClipBase *baseClip = m_clipManager->getClipById(e.attribute("id"));
290 if (baseClip) baseClip->addSnapMarker(marker);
291 else kDebug()<< " / / Warning, missing clip: "<< e.attribute("id");
294 infoXml.removeChild(markers);
297 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
298 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
299 QDomNamedNodeMap props = docproperties.attributes();
300 for (int i = 0; i < props.count(); i++)
301 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
302 docproperties = infoXml.firstChildElement("documentmetadata");
303 props = docproperties.attributes();
304 for (int i = 0; i < props.count(); i++)
305 m_documentMetadata.insert(props.item(i).nodeName(), props.item(i).nodeValue());
307 if (validator.isModified()) setModified(true);
308 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
317 // Something went wrong, or a new file was requested: create a new project
320 setProfilePath(profileName);
321 m_document = createEmptyDocument(tracks.x(), tracks.y());
324 // Ask to create the project directory if it does not exist
325 if (!QFile::exists(m_projectFolder.path())) {
326 int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
327 if (create == KMessageBox::Yes) {
328 QDir projectDir(m_projectFolder.path());
329 bool ok = projectDir.mkpath(m_projectFolder.path());
331 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
336 // Make sure the project folder is usable
337 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
338 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
339 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
342 // Make sure that the necessary folders exist
343 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
344 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
345 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/");
347 updateProjectFolderPlacesEntry();
349 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
350 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
351 connect(m_render, SIGNAL(addClip(const KUrl &, stringMap)), this, SLOT(slotAddClipFile(const KUrl &, stringMap)));
354 KdenliveDoc::~KdenliveDoc()
356 m_autoSaveTimer->stop();
357 delete m_commandStack;
358 kDebug() << "// DEL CLP MAN";
359 delete m_clipManager;
360 kDebug() << "// DEL CLP MAN done";
361 delete m_autoSaveTimer;
363 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
368 int KdenliveDoc::setSceneList()
370 m_render->resetProfile(KdenliveSettings::current_profile(), true);
371 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
372 // INVALID MLT Consumer, something is wrong
375 m_documentProperties.remove("position");
376 // m_document xml is now useless, clear it
381 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
383 m_tracksList.clear();
385 // Tracks are added «backwards», so we need to reverse the track numbering
386 // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
387 // Better default names for tracks: Audio 1 etc. instead of blank numbers
388 for (int i = 0; i < audiotracks; i++) {
389 TrackInfo audioTrack;
390 audioTrack.type = AUDIOTRACK;
391 audioTrack.isMute = false;
392 audioTrack.isBlind = true;
393 audioTrack.isLocked = false;
394 audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
395 audioTrack.duration = 0;
396 audioTrack.effectsList = EffectsList(true);
397 m_tracksList.append(audioTrack);
400 for (int i = 0; i < videotracks; i++) {
401 TrackInfo videoTrack;
402 videoTrack.type = VIDEOTRACK;
403 videoTrack.isMute = false;
404 videoTrack.isBlind = false;
405 videoTrack.isLocked = false;
406 videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
407 videoTrack.duration = 0;
408 videoTrack.effectsList = EffectsList(true);
409 m_tracksList.append(videoTrack);
411 return createEmptyDocument(m_tracksList);
414 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
416 // Creating new document
418 QDomElement mlt = doc.createElement("mlt");
419 mlt.setAttribute("LC_NUMERIC", "");
420 doc.appendChild(mlt);
422 // Create black producer
423 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
424 // the composite transitions with the black track are corrupted.
425 QDomElement blk = doc.createElement("producer");
426 blk.setAttribute("in", 0);
427 blk.setAttribute("out", 500);
428 blk.setAttribute("id", "black");
430 QDomElement property = doc.createElement("property");
431 property.setAttribute("name", "mlt_type");
432 QDomText value = doc.createTextNode("producer");
433 property.appendChild(value);
434 blk.appendChild(property);
436 property = doc.createElement("property");
437 property.setAttribute("name", "aspect_ratio");
438 value = doc.createTextNode(QString::number(0));
439 property.appendChild(value);
440 blk.appendChild(property);
442 property = doc.createElement("property");
443 property.setAttribute("name", "length");
444 value = doc.createTextNode(QString::number(15000));
445 property.appendChild(value);
446 blk.appendChild(property);
448 property = doc.createElement("property");
449 property.setAttribute("name", "eof");
450 value = doc.createTextNode("pause");
451 property.appendChild(value);
452 blk.appendChild(property);
454 property = doc.createElement("property");
455 property.setAttribute("name", "resource");
456 value = doc.createTextNode("black");
457 property.appendChild(value);
458 blk.appendChild(property);
460 property = doc.createElement("property");
461 property.setAttribute("name", "mlt_service");
462 value = doc.createTextNode("colour");
463 property.appendChild(value);
464 blk.appendChild(property);
466 mlt.appendChild(blk);
469 QDomElement tractor = doc.createElement("tractor");
470 tractor.setAttribute("id", "maintractor");
471 QDomElement multitrack = doc.createElement("multitrack");
472 QDomElement playlist = doc.createElement("playlist");
473 playlist.setAttribute("id", "black_track");
474 mlt.appendChild(playlist);
476 QDomElement blank0 = doc.createElement("entry");
477 blank0.setAttribute("in", "0");
478 blank0.setAttribute("out", "1");
479 blank0.setAttribute("producer", "black");
480 playlist.appendChild(blank0);
483 int total = tracks.count() + 1;
485 for (int i = 1; i < total; i++) {
486 QDomElement playlist = doc.createElement("playlist");
487 playlist.setAttribute("id", "playlist" + QString::number(i));
488 mlt.appendChild(playlist);
491 QDomElement track0 = doc.createElement("track");
492 track0.setAttribute("producer", "black_track");
493 tractor.appendChild(track0);
495 // create audio and video tracks
496 for (int i = 1; i < total; i++) {
497 QDomElement track = doc.createElement("track");
498 track.setAttribute("producer", "playlist" + QString::number(i));
499 if (tracks.at(i - 1).type == AUDIOTRACK) {
500 track.setAttribute("hide", "video");
501 } else if (tracks.at(i - 1).isBlind)
502 track.setAttribute("hide", "video");
503 if (tracks.at(i - 1).isMute)
504 track.setAttribute("hide", "audio");
505 tractor.appendChild(track);
508 for (int i = 2; i < total ; i++) {
509 QDomElement transition = doc.createElement("transition");
510 transition.setAttribute("always_active", "1");
512 QDomElement property = doc.createElement("property");
513 property.setAttribute("name", "a_track");
514 QDomText value = doc.createTextNode(QString::number(1));
515 property.appendChild(value);
516 transition.appendChild(property);
518 property = doc.createElement("property");
519 property.setAttribute("name", "b_track");
520 value = doc.createTextNode(QString::number(i));
521 property.appendChild(value);
522 transition.appendChild(property);
524 property = doc.createElement("property");
525 property.setAttribute("name", "mlt_service");
526 value = doc.createTextNode("mix");
527 property.appendChild(value);
528 transition.appendChild(property);
530 property = doc.createElement("property");
531 property.setAttribute("name", "combine");
532 value = doc.createTextNode("1");
533 property.appendChild(value);
534 transition.appendChild(property);
536 property = doc.createElement("property");
537 property.setAttribute("name", "internal_added");
538 value = doc.createTextNode("237");
539 property.appendChild(value);
540 transition.appendChild(property);
541 tractor.appendChild(transition);
543 mlt.appendChild(tractor);
548 void KdenliveDoc::syncGuides(QList <Guide *> guides)
551 QDomElement guideNode = m_guidesXml.createElement("guides");
552 m_guidesXml.appendChild(guideNode);
555 for (int i = 0; i < guides.count(); i++) {
556 e = m_guidesXml.createElement("guide");
557 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
558 e.setAttribute("comment", guides.at(i)->label());
559 guideNode.appendChild(e);
562 emit guidesUpdated();
565 QDomElement KdenliveDoc::guidesXml() const
567 return m_guidesXml.documentElement();
570 void KdenliveDoc::slotAutoSave()
572 if (m_render && m_autosave) {
573 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
574 // show error: could not open the autosave file
575 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
577 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
578 saveSceneList(m_autosave->fileName(), m_render->sceneList(), QStringList(), true);
582 void KdenliveDoc::setZoom(int horizontal, int vertical)
584 m_documentProperties["zoom"] = QString::number(horizontal);
585 m_documentProperties["verticalzoom"] = QString::number(vertical);
588 QPoint KdenliveDoc::zoom() const
590 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
593 void KdenliveDoc::setZone(int start, int end)
595 m_documentProperties["zonein"] = QString::number(start);
596 m_documentProperties["zoneout"] = QString::number(end);
599 QPoint KdenliveDoc::zone() const
601 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
604 QDomDocument KdenliveDoc::xmlSceneList(const QString &scene, const QStringList &expandedFolders)
606 QDomDocument sceneList;
607 sceneList.setContent(scene, true);
608 QDomElement mlt = sceneList.firstChildElement("mlt");
609 if (mlt.isNull() || !mlt.hasChildNodes()) {
610 //scenelist is corrupted
614 // Set playlist audio volume to 100%
615 QDomElement tractor = mlt.firstChildElement("tractor");
616 if (!tractor.isNull()) {
617 QDomNodeList props = tractor.elementsByTagName("property");
618 for (int i = 0; i < props.count(); i++) {
619 if (props.at(i).toElement().attribute("name") == "meta.volume") {
620 props.at(i).firstChild().setNodeValue("1");
626 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
627 mlt.appendChild(addedXml);
629 // check if project contains custom effects to embed them in project file
630 QDomNodeList effects = mlt.elementsByTagName("filter");
631 int maxEffects = effects.count();
632 kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
633 QMap <QString, QString> effectIds;
634 for (int i = 0; i < maxEffects; i++) {
635 QDomNode m = effects.at(i);
636 QDomNodeList params = m.childNodes();
639 for (int j = 0; j < params.count(); j++) {
640 QDomElement e = params.item(j).toElement();
641 if (e.attribute("name") == "kdenlive_id") {
642 id = e.firstChild().nodeValue();
644 if (e.attribute("name") == "tag") {
645 tag = e.firstChild().nodeValue();
647 if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
650 QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
651 addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
653 QDomElement markers = sceneList.createElement("markers");
654 addedXml.setAttribute("version", DOCUMENTVERSION);
655 addedXml.setAttribute("kdenliveversion", VERSION);
656 addedXml.setAttribute("profile", profilePath());
657 addedXml.setAttribute("projectfolder", m_projectFolder.path());
659 QDomElement docproperties = sceneList.createElement("documentproperties");
660 QMapIterator<QString, QString> i(m_documentProperties);
661 while (i.hasNext()) {
663 docproperties.setAttribute(i.key(), i.value());
665 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
666 addedXml.appendChild(docproperties);
668 QDomElement docmetadata = sceneList.createElement("documentmetadata");
669 QMapIterator<QString, QString> j(m_documentMetadata);
670 while (j.hasNext()) {
672 docmetadata.setAttribute(j.key(), j.value());
674 addedXml.appendChild(docmetadata);
676 QDomElement docnotes = sceneList.createElement("documentnotes");
677 QDomText value = sceneList.createTextNode(m_notesWidget->toHtml());
678 docnotes.appendChild(value);
679 addedXml.appendChild(docnotes);
682 QDomElement profileinfo = sceneList.createElement("profileinfo");
683 profileinfo.setAttribute("description", m_profile.description);
684 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
685 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
686 profileinfo.setAttribute("width", m_profile.width);
687 profileinfo.setAttribute("height", m_profile.height);
688 profileinfo.setAttribute("progressive", m_profile.progressive);
689 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
690 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
691 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
692 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
693 addedXml.appendChild(profileinfo);
696 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
697 foreach(const TrackInfo & info, m_tracksList) {
698 QDomElement trackinfo = sceneList.createElement("trackinfo");
699 if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
700 trackinfo.setAttribute("mute", info.isMute);
701 trackinfo.setAttribute("blind", info.isBlind);
702 trackinfo.setAttribute("locked", info.isLocked);
703 trackinfo.setAttribute("trackname", info.trackName);
704 tracksinfo.appendChild(trackinfo);
706 addedXml.appendChild(tracksinfo);
708 // save project folders
709 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
711 QMapIterator<QString, QString> f(folderlist);
712 while (f.hasNext()) {
714 QDomElement folder = sceneList.createElement("folder");
715 folder.setAttribute("id", f.key());
716 folder.setAttribute("name", f.value());
717 if (expandedFolders.contains(f.key())) folder.setAttribute("opened", "1");
718 addedXml.appendChild(folder);
721 // Save project clips
723 QList <DocClipBase*> list = m_clipManager->documentClipList();
724 for (int i = 0; i < list.count(); i++) {
725 e = list.at(i)->toXML(true);
726 e.setTagName("kdenlive_producer");
727 addedXml.appendChild(sceneList.importNode(e, true));
728 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
729 for (int j = 0; j < marks.count(); j++) {
730 QDomElement marker = sceneList.createElement("marker");
731 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
732 marker.setAttribute("comment", marks.at(j).comment());
733 marker.setAttribute("id", e.attribute("id"));
734 marker.setAttribute("type", marks.at(j).markerType());
735 markers.appendChild(marker);
738 addedXml.appendChild(markers);
741 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
744 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
746 //wes.appendChild(doc.importNode(kdenliveData, true));
750 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene, const QStringList &expandedFolders, bool autosave)
752 QDomDocument sceneList = xmlSceneList(scene, expandedFolders);
753 if (sceneList.isNull()) {
754 //Make sure we don't save if scenelist is corrupted
755 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
759 // Backup current version
760 if (!autosave) backupLastSavedVersion(path);
763 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
764 kWarning() << "////// ERROR writing to file: " << path;
765 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
769 file.write(sceneList.toString().toUtf8());
770 if (file.error() != QFile::NoError) {
771 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
777 cleanupBackupFiles();
778 QFileInfo info(file);
779 QString fileName = KUrl(path).fileName().section('.', 0, -2);
780 fileName.append('-' + m_documentProperties.value("documentid"));
781 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
782 fileName.append(".kdenlive.png");
783 KUrl backupFile = m_projectFolder;
784 backupFile.addPath(".backup/");
785 backupFile.addPath(fileName);
786 emit saveTimelinePreview(backupFile.path());
791 ClipManager *KdenliveDoc::clipManager()
793 return m_clipManager;
796 KUrl KdenliveDoc::projectFolder() const
798 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
799 return m_projectFolder;
802 void KdenliveDoc::setProjectFolder(KUrl url)
804 if (url == m_projectFolder) return;
806 KStandardDirs::makeDir(url.path());
807 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
808 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
809 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?", m_projectFolder.path(), url.path())) == KMessageBox::Yes) moveProjectData(url);
810 m_projectFolder = url;
812 updateProjectFolderPlacesEntry();
815 void KdenliveDoc::moveProjectData(KUrl url)
817 QList <DocClipBase*> list = m_clipManager->documentClipList();
818 KUrl::List cacheUrls;
819 for (int i = 0; i < list.count(); i++) {
820 DocClipBase *clip = list.at(i);
821 if (clip->clipType() == TEXT) {
822 // the image for title clip must be moved
823 KUrl oldUrl = clip->fileURL();
824 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
825 KIO::Job *job = KIO::copy(oldUrl, newUrl);
826 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
828 QString hash = clip->getClipHash();
829 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
830 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
831 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
832 cacheUrls << oldVideoThumbUrl;
834 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
835 cacheUrls << oldAudioThumbUrl;
838 if (!cacheUrls.isEmpty()) {
839 KIO::Job *job = KIO::copy(cacheUrls, KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/"));
840 job->ui()->setWindow(kapp->activeWindow());
841 KIO::NetAccess::synchronousRun(job, 0);
845 const QString &KdenliveDoc::profilePath() const
847 return m_profile.path;
850 MltVideoProfile KdenliveDoc::mltProfile() const
855 bool KdenliveDoc::setProfilePath(QString path)
857 if (path.isEmpty()) path = KdenliveSettings::default_profile();
858 if (path.isEmpty()) path = "dv_pal";
859 m_profile = ProfilesDialog::getVideoProfile(path);
860 double current_fps = m_fps;
861 if (m_profile.path.isEmpty()) {
862 // Profile not found, use embedded profile
863 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
864 if (profileInfo.isNull()) {
865 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
866 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
868 m_profile.description = profileInfo.attribute("description");
869 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
870 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
871 m_profile.width = profileInfo.attribute("width").toInt();
872 m_profile.height = profileInfo.attribute("height").toInt();
873 m_profile.progressive = profileInfo.attribute("progressive").toInt();
874 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
875 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
876 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
877 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
878 QString existing = ProfilesDialog::existingProfile(m_profile);
879 if (!existing.isEmpty()) {
880 m_profile = ProfilesDialog::getVideoProfile(existing);
881 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
883 QString newDesc = m_profile.description;
885 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
886 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);
889 // User canceled, use default profile
890 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
892 if (newDesc != m_profile.description) {
893 // Profile description existed, was replaced by new one
894 m_profile.description = newDesc;
896 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
898 ProfilesDialog::saveProfile(m_profile);
905 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
906 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
907 KdenliveSettings::setProject_fps(m_fps);
908 m_width = m_profile.width;
909 m_height = m_profile.height;
910 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
911 m_timecode.setFormat(m_fps);
912 KdenliveSettings::setCurrent_profile(m_profile.path);
913 return (current_fps != m_fps);
916 double KdenliveDoc::dar() const
918 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
921 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
923 emit progressInfo(message, progress);
926 QUndoStack *KdenliveDoc::commandStack()
928 return m_commandStack;
932 void KdenliveDoc::setRenderer(Render *render) {
933 if (m_render) return;
935 emit progressInfo(i18n("Loading playlist..."), 0);
936 //qApp->processEvents();
938 m_render->setSceneList(m_document.toString(), m_startPos);
939 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
942 emit progressInfo(QString(), -1);
945 void KdenliveDoc::checkProjectClips(bool displayRatioChanged, bool fpsChanged)
947 if (m_render == NULL) return;
948 m_clipManager->resetProducersList(m_render->producersList(), displayRatioChanged, fpsChanged);
951 Render *KdenliveDoc::renderer()
956 void KdenliveDoc::updateClip(const QString &id)
958 emit updateClipDisplay(id);
961 int KdenliveDoc::getFramePos(QString duration)
963 return m_timecode.getFrameCount(duration);
966 QString KdenliveDoc::producerName(const QString &id)
968 QString result = "unnamed";
969 QDomNodeList prods = producersList();
970 int ct = prods.count();
971 for (int i = 0; i < ct ; i++) {
972 QDomElement e = prods.item(i).toElement();
973 if (e.attribute("id") != "black" && e.attribute("id") == id) {
974 result = e.attribute("name");
975 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
982 QDomDocument KdenliveDoc::toXml()
987 Timecode KdenliveDoc::timecode() const
992 QDomNodeList KdenliveDoc::producersList()
994 return m_document.elementsByTagName("producer");
997 double KdenliveDoc::projectDuration() const
1000 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
1005 double KdenliveDoc::fps() const
1010 int KdenliveDoc::width() const
1015 int KdenliveDoc::height() const
1020 KUrl KdenliveDoc::url() const
1025 void KdenliveDoc::setUrl(KUrl url)
1030 void KdenliveDoc::setModified(bool mod)
1032 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
1033 m_autoSaveTimer->start(3000);
1035 if (mod == m_modified) return;
1037 emit docModified(m_modified);
1040 bool KdenliveDoc::isModified() const
1045 const QString KdenliveDoc::description() const
1047 if (m_url.isEmpty())
1048 return i18n("Untitled") + " / " + m_profile.description;
1050 return m_url.fileName() + " / " + m_profile.description;
1053 bool KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
1055 const QString producerId = clipId.section('_', 0, 0);
1056 DocClipBase *clip = m_clipManager->getClipById(producerId);
1059 elem.setAttribute("id", producerId);
1060 QString path = elem.attribute("resource");
1062 if (elem.attribute("type").toInt() == SLIDESHOW) {
1063 extension = KUrl(path).fileName();
1064 path = KUrl(path).directory();
1066 if (elem.hasAttribute("_missingsource")) {
1067 // Clip has proxy but missing original source
1069 else if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
1070 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1071 const QString size = elem.attribute("file_size");
1072 const QString hash = elem.attribute("file_hash");
1074 int action = KMessageBox::No;
1075 if (!size.isEmpty() && !hash.isEmpty()) {
1076 if (!m_searchFolder.isEmpty())
1077 newpath = searchFileRecursively(m_searchFolder, size, hash);
1079 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")));
1081 if (elem.attribute("type").toInt() == SLIDESHOW) {
1082 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")));
1083 if (res == KMessageBox::Yes)
1084 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1086 // Abort project loading
1090 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")));
1091 if (res == KMessageBox::Yes)
1092 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1094 // Abort project loading
1099 if (action == KMessageBox::Yes) {
1100 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1101 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1102 if (!m_searchFolder.isEmpty())
1103 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1104 } else if (action == KMessageBox::Cancel) {
1106 } else if (action == KMessageBox::No) {
1107 // Keep clip as placeHolder
1108 elem.setAttribute("placeholder", '1');
1110 if (!newpath.isEmpty()) {
1111 if (elem.attribute("type").toInt() == SLIDESHOW)
1112 newpath.append('/' + extension);
1113 elem.setAttribute("resource", newpath);
1114 setNewClipResource(clipId, newpath);
1118 clip = new DocClipBase(m_clipManager, elem, producerId);
1119 m_clipManager->addClip(clip);
1122 if (createClipItem) {
1123 emit addProjectClip(clip);
1129 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1131 QDomNodeList prods = m_document.elementsByTagName("producer");
1132 int maxprod = prods.count();
1133 for (int i = 0; i < maxprod; i++) {
1134 QDomNode m = prods.at(i);
1135 QString prodId = m.toElement().attribute("id");
1136 if (prodId == id || prodId.startsWith(id + '_')) {
1137 QDomNodeList params = m.childNodes();
1138 for (int j = 0; j < params.count(); j++) {
1139 QDomElement e = params.item(j).toElement();
1140 if (e.attribute("name") == "resource") {
1141 e.firstChild().setNodeValue(path);
1149 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1151 QString foundFileName;
1152 QByteArray fileData;
1153 QByteArray fileHash;
1154 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1155 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1156 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1157 if (file.open(QIODevice::ReadOnly)) {
1158 if (QString::number(file.size()) == matchSize) {
1160 * 1 MB = 1 second per 450 files (or faster)
1161 * 10 MB = 9 seconds per 450 files (or faster)
1163 if (file.size() > 1000000 * 2) {
1164 fileData = file.read(1000000);
1165 if (file.seek(file.size() - 1000000))
1166 fileData.append(file.readAll());
1168 fileData = file.readAll();
1170 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1171 if (QString(fileHash.toHex()) == matchHash)
1172 return file.fileName();
1175 kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1177 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1178 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1179 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1180 if (!foundFileName.isEmpty())
1183 return foundFileName;
1186 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1188 DocClipBase *clip = m_clipManager->getClipById(clipId);
1190 if (!addClip(elem, clipId, false))
1193 QMap <QString, QString> properties;
1194 QDomNamedNodeMap attributes = elem.attributes();
1195 for (int i = 0; i < attributes.count(); i++) {
1196 QString attrname = attributes.item(i).nodeName();
1197 if (attrname != "resource")
1198 properties.insert(attrname, attributes.item(i).nodeValue());
1199 //kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1201 clip->setProperties(properties);
1202 emit addProjectClip(clip, false);
1204 if (orig != QDomElement()) {
1205 QMap<QString, QString> meta;
1206 for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1207 QString name = m.toElement().attribute("name");
1208 if (name.startsWith("meta.attr")) {
1209 if (name.endsWith(".markup")) name = name.section('.', 0, -2);
1210 meta.insert(name.section('.', 2, -1), m.firstChild().nodeValue());
1213 if (!meta.isEmpty()) {
1215 clip = m_clipManager->getClipById(clipId);
1217 clip->setMetadata(meta);
1224 void KdenliveDoc::deleteClip(const QString &clipId)
1226 emit signalDeleteProjectClip(clipId);
1229 void KdenliveDoc::slotAddClipList(const KUrl::List urls, stringMap data)
1231 m_clipManager->slotAddClipList(urls, data);
1232 //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1237 void KdenliveDoc::slotAddClipFile(const KUrl &url, stringMap data)
1239 m_clipManager->slotAddClipFile(url, data);
1240 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1244 const QString KdenliveDoc::getFreeClipId()
1246 return QString::number(m_clipManager->getFreeClipId());
1249 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1251 return m_clipManager->getClipById(clipId);
1254 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement xml, QString group, const QString &groupId)
1256 m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1258 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1261 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1263 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1265 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1268 void KdenliveDoc::slotCreateSlideshowClipFile(QMap <QString, QString> properties, QString group, const QString &groupId)
1270 m_clipManager->slotAddSlideshowClipFile(properties, group, groupId);
1272 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1275 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1277 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1278 KStandardDirs::makeDir(titlesFolder);
1279 QPointer<TitleWidget> dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1280 if (dia_ui->exec() == QDialog::Accepted) {
1281 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->duration(), dia_ui->xml().toString(), group, groupId);
1283 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1288 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1290 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1291 if (path.isEmpty()) {
1292 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1295 if (path.isEmpty()) return;
1297 //TODO: rewrite with new title system (just set resource)
1298 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1300 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1303 int KdenliveDoc::tracksCount() const
1305 return m_tracksList.count();
1308 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1310 if (ix < 0 || ix >= m_tracksList.count()) {
1311 kWarning() << "Track INFO outisde of range";
1314 return m_tracksList.at(ix);
1317 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1319 if (ix < 0 || ix >= m_tracksList.count()) {
1320 kWarning() << "SWITCH Track outisde of range";
1323 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1326 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1328 if (ix < 0 || ix >= m_tracksList.count()) {
1329 kWarning() << "Track Lock outisde of range";
1332 m_tracksList[ix].isLocked = lock;
1335 bool KdenliveDoc::isTrackLocked(int ix) const
1337 if (ix < 0 || ix >= m_tracksList.count()) {
1338 kWarning() << "Track Lock outisde of range";
1341 return m_tracksList.at(ix).isLocked;
1344 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1346 if (ix < 0 || ix >= m_tracksList.count()) {
1347 kWarning() << "SWITCH Track outisde of range";
1350 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1353 int KdenliveDoc::trackDuration(int ix)
1355 return m_tracksList.at(ix).duration;
1358 void KdenliveDoc::setTrackDuration(int ix, int duration)
1360 m_tracksList[ix].duration = duration;
1363 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1365 if (ix == -1) m_tracksList << type;
1366 else m_tracksList.insert(ix, type);
1369 void KdenliveDoc::deleteTrack(int ix)
1371 if (ix < 0 || ix >= m_tracksList.count()) {
1372 kWarning() << "Delete Track outisde of range";
1375 m_tracksList.removeAt(ix);
1378 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1380 if (ix < 0 || ix >= m_tracksList.count()) {
1381 kWarning() << "SET Track Type outisde of range";
1384 m_tracksList[ix].type = type.type;
1385 m_tracksList[ix].isMute = type.isMute;
1386 m_tracksList[ix].isBlind = type.isBlind;
1387 m_tracksList[ix].isLocked = type.isLocked;
1388 m_tracksList[ix].trackName = type.trackName;
1391 const QList <TrackInfo> KdenliveDoc::tracksList() const
1393 return m_tracksList;
1396 QPoint KdenliveDoc::getTracksCount() const
1400 foreach(const TrackInfo & info, m_tracksList) {
1401 if (info.type == VIDEOTRACK) video++;
1404 return QPoint(video, audio);
1407 void KdenliveDoc::cacheImage(const QString &fileId, const QImage &img) const
1409 img.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1412 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1414 DocumentChecker d(infoproducers, m_document);
1415 return (d.hasErrorInClips() == false);
1421 QList <QDomElement> missingClips;
1422 for (int i = 0; i < infoproducers.count(); i++) {
1423 e = infoproducers.item(i).toElement();
1424 clipType = e.attribute("type").toInt();
1425 if (clipType == COLOR) continue;
1426 if (clipType == TEXT) {
1427 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1430 id = e.attribute("id");
1431 resource = e.attribute("resource");
1432 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1433 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1434 // Missing clip found
1435 missingClips.append(e);
1437 // Check if the clip has changed
1438 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1439 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1440 e.removeAttribute("file_hash");
1444 if (missingClips.isEmpty()) return true;
1445 DocumentChecker d(missingClips, m_document);
1446 return (d.exec() == QDialog::Accepted);*/
1449 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1451 m_documentProperties[name] = value;
1454 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1456 return m_documentProperties.value(name);
1459 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1461 QMap <QString, QString> renderProperties;
1462 QMapIterator<QString, QString> i(m_documentProperties);
1463 while (i.hasNext()) {
1465 if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1467 return renderProperties;
1470 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1472 if (ix < 0 || ix >= m_tracksList.count()) {
1473 kWarning() << "Add Track effect outisde of range";
1476 effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1478 // Init parameter value & keyframes if required
1479 QDomNodeList params = effect.elementsByTagName("parameter");
1480 for (int i = 0; i < params.count(); i++) {
1481 QDomElement e = params.item(i).toElement();
1483 // Check if this effect has a variable parameter
1484 if (e.attribute("default").contains('%')) {
1485 double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1486 e.setAttribute("default", evaluatedValue);
1487 if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1488 e.setAttribute("value", evaluatedValue);
1492 if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1493 QString def = e.attribute("default");
1494 // Effect has a keyframe type parameter, we need to set the values
1495 if (e.attribute("keyframes").isEmpty()) {
1496 e.setAttribute("keyframes", "0:" + def + ';');
1497 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1502 if (effect.attribute("id") == "crop") {
1503 // default use_profile to 1 for clips with proxies to avoid problems when rendering
1504 if (e.attribute("name") == "use_profile" && getDocumentProperty("enableproxy") == "1")
1505 e.setAttribute("value", "1");
1509 m_tracksList[ix].effectsList.append(effect);
1512 void KdenliveDoc::removeTrackEffect(int ix, QDomElement effect)
1514 if (ix < 0 || ix >= m_tracksList.count()) {
1515 kWarning() << "Remove Track effect outisde of range";
1519 int toRemove = effect.attribute("kdenlive_ix").toInt();
1520 for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1521 index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix").toInt();
1522 if (toRemove == index) {
1523 m_tracksList[ix].effectsList.removeAt(toRemove);
1529 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1531 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1532 kWarning() << "Set Track effect outisde of range";
1535 if (effectIndex <= 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count()) || effect.isNull()) {
1536 kDebug() << "Invalid effect index: " << effectIndex;
1539 m_tracksList[trackIndex].effectsList.removeAt(effect.attribute("kdenlive_ix").toInt());
1540 effect.setAttribute("kdenlive_ix", effectIndex);
1541 m_tracksList[trackIndex].effectsList.insert(effect);
1542 //m_tracksList[trackIndex].effectsList.updateEffect(effect);
1545 void KdenliveDoc::enableTrackEffects(int trackIndex, QList <int> effectIndexes, bool disable)
1547 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1548 kWarning() << "Set Track effect outisde of range";
1551 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1553 for (int i = 0; i < effectIndexes.count(); i++) {
1554 effect = list.itemFromIndex(effectIndexes.at(i));
1555 if (!effect.isNull()) effect.setAttribute("disable", (int) disable);
1559 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1561 if (ix < 0 || ix >= m_tracksList.count()) {
1562 kWarning() << "Get Track effects outisde of range";
1563 return EffectsList();
1565 return m_tracksList.at(ix).effectsList;
1568 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1570 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1571 kWarning() << "Get Track effect outisde of range";
1572 return QDomElement();
1574 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1575 if (effectIndex > list.count() || effectIndex < 1 || list.itemFromIndex(effectIndex).isNull()) return QDomElement();
1576 return list.itemFromIndex(effectIndex).cloneNode().toElement();
1579 int KdenliveDoc::hasTrackEffect(int trackIndex, const QString &tag, const QString &id) const
1581 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1582 kWarning() << "Get Track effect outisde of range";
1585 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1586 return list.hasEffect(tag, id);
1589 bool KdenliveDoc::saveCustomEffects(QDomNodeList customeffects)
1592 QStringList importedEffects;
1593 int maxchild = customeffects.count();
1594 for (int i = 0; i < maxchild; i++) {
1595 e = customeffects.at(i).toElement();
1596 QString id = e.attribute("id");
1597 QString tag = e.attribute("tag");
1598 if (!id.isEmpty()) {
1599 // Check if effect exists or save it
1600 if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1602 doc.appendChild(doc.importNode(e, true));
1603 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1604 path += id + ".xml";
1605 if (!QFile::exists(path)) {
1606 importedEffects << id;
1608 if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1609 QTextStream out(&file);
1610 out << doc.toString();
1616 if (!importedEffects.isEmpty()) KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1617 return (!importedEffects.isEmpty());
1620 void KdenliveDoc::updateProjectFolderPlacesEntry()
1623 * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1624 * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1627 const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1628 KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1629 if (!bookmarkManager) return;
1630 KBookmarkGroup root = bookmarkManager->root();
1632 KBookmark bookmark = root.first();
1634 QString kdenliveName = KGlobal::mainComponent().componentName();
1635 KUrl documentLocation = m_projectFolder;
1637 bool exists = false;
1639 while (!bookmark.isNull()) {
1640 // UDI not empty indicates a device
1641 QString udi = bookmark.metaDataItem("UDI");
1642 QString appName = bookmark.metaDataItem("OnlyInApp");
1644 if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1645 if (bookmark.url() != documentLocation) {
1646 bookmark.setUrl(documentLocation);
1647 bookmarkManager->emitChanged(root);
1653 bookmark = root.next(bookmark);
1656 // if entry does not exist yet (was not found), well, create it then
1658 bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1659 // Make this user selectable ?
1660 bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1661 bookmarkManager->emitChanged(root);
1665 QStringList KdenliveDoc::getExpandedFolders()
1667 QStringList result = m_documentProperties.value("expandedfolders").split(';');
1668 // this property is only needed once when opening project, so clear it now
1669 m_documentProperties.remove("expandedfolders");
1674 double KdenliveDoc::getDisplayRatio(const QString &path)
1678 if (!file.open(QIODevice::ReadOnly)) {
1679 kWarning() << "ERROR, CANNOT READ: " << path;
1682 if (!doc.setContent(&file)) {
1683 kWarning() << "ERROR, CANNOT READ: " << path;
1688 QDomNodeList list = doc.elementsByTagName("profile");
1689 if (list.isEmpty()) return 0;
1690 QDomElement profile = list.at(0).toElement();
1691 double den = profile.attribute("display_aspect_den").toDouble();
1692 if (den > 0) return profile.attribute("display_aspect_num").toDouble() / den;
1696 void KdenliveDoc::backupLastSavedVersion(const QString &path)
1698 // Ensure backup folder exists
1699 if (path.isEmpty()) return;
1701 KUrl backupFile = m_projectFolder;
1702 backupFile.addPath(".backup/");
1703 KIO::NetAccess::mkdir(backupFile, kapp->activeWindow());
1704 QString fileName = KUrl(path).fileName().section('.', 0, -2);
1705 QFileInfo info(file);
1706 fileName.append('-' + m_documentProperties.value("documentid"));
1707 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
1708 fileName.append(".kdenlive");
1709 backupFile.addPath(fileName);
1711 if (file.exists()) {
1712 // delete previous backup if it was done less than 60 seconds ago
1713 QFile::remove(backupFile.path());
1714 if (!QFile::copy(path, backupFile.path())) {
1715 KMessageBox::information(kapp->activeWindow(), i18n("Cannot create backup copy:\n%1", backupFile.path()));
1720 void KdenliveDoc::cleanupBackupFiles()
1722 KUrl backupFile = m_projectFolder;
1723 backupFile.addPath(".backup/");
1724 QDir dir(backupFile.path());
1725 QString projectFile = url().fileName().section('.', 0, -2);
1726 projectFile.append('-' + m_documentProperties.value("documentid"));
1727 projectFile.append("-??");
1728 projectFile.append("??");
1729 projectFile.append("-??");
1730 projectFile.append("-??");
1731 projectFile.append("-??");
1732 projectFile.append("-??.kdenlive");
1735 backupFile.addPath(projectFile);
1736 filter << projectFile;
1737 dir.setNameFilters(filter);
1738 QFileInfoList resultList = dir.entryInfoList(QDir::Files, QDir::Time);
1740 QDateTime d = QDateTime::currentDateTime();
1741 QStringList hourList;
1742 QStringList dayList;
1743 QStringList weekList;
1744 QStringList oldList;
1745 for (int i = 0; i < resultList.count(); i++) {
1746 if (d.secsTo(resultList.at(i).lastModified()) < 3600) {
1747 // files created in the last hour
1748 hourList.append(resultList.at(i).absoluteFilePath());
1750 else if (d.secsTo(resultList.at(i).lastModified()) < 43200) {
1751 // files created in the day
1752 dayList.append(resultList.at(i).absoluteFilePath());
1754 else if (d.daysTo(resultList.at(i).lastModified()) < 8) {
1755 // files created in the week
1756 weekList.append(resultList.at(i).absoluteFilePath());
1760 oldList.append(resultList.at(i).absoluteFilePath());
1763 if (hourList.count() > 20) {
1764 int step = hourList.count() / 10;
1765 for (int i = 0; i < hourList.count(); i += step) {
1766 kDebug()<<"REMOVE AT: "<<i<<", COUNT: "<<hourList.count();
1767 hourList.removeAt(i);
1770 } else hourList.clear();
1771 if (dayList.count() > 20) {
1772 int step = dayList.count() / 10;
1773 for (int i = 0; i < dayList.count(); i += step) {
1774 dayList.removeAt(i);
1777 } else dayList.clear();
1778 if (weekList.count() > 20) {
1779 int step = weekList.count() / 10;
1780 for (int i = 0; i < weekList.count(); i += step) {
1781 weekList.removeAt(i);
1784 } else weekList.clear();
1785 if (oldList.count() > 20) {
1786 int step = oldList.count() / 10;
1787 for (int i = 0; i < oldList.count(); i += step) {
1788 oldList.removeAt(i);
1791 } else oldList.clear();
1794 while (hourList.count() > 0) {
1795 f = hourList.takeFirst();
1797 QFile::remove(f + ".png");
1799 while (dayList.count() > 0) {
1800 f = dayList.takeFirst();
1802 QFile::remove(f + ".png");
1804 while (weekList.count() > 0) {
1805 f = weekList.takeFirst();
1807 QFile::remove(f + ".png");
1809 while (oldList.count() > 0) {
1810 f = oldList.takeFirst();
1812 QFile::remove(f + ".png");
1816 const QMap <QString, QString> KdenliveDoc::metadata() const
1818 return m_documentMetadata;
1821 void KdenliveDoc::setMetadata(const QMap <QString, QString> meta)
1823 m_documentMetadata = meta;
1826 #include "kdenlivedoc.moc"