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 "widgets/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>
38 #include <KLocalizedString>
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>
57 #include <mlt++/Mlt.h>
62 const double DOCUMENTVERSION = 0.88;
64 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, const QString &profileName, const QMap <QString, QString>& properties, const QMap <QString, QString>& metadata, const QPoint &tracks, Render *render, KTextEdit *notes, bool *openBackup, QGLWidget *glContext, MainWindow *parent, KProgressDialog *progressDialog) :
70 m_commandStack(new QUndoStack(undoGroup)),
72 m_projectFolder(projectFolder)
74 // init m_profile struct
75 m_profile.frame_rate_num = 0;
76 m_profile.frame_rate_den = 0;
79 m_profile.progressive = 0;
80 m_profile.sample_aspect_num = 0;
81 m_profile.sample_aspect_den = 0;
82 m_profile.display_aspect_num = 0;
83 m_profile.display_aspect_den = 0;
84 m_profile.colorspace = 0;
86 m_clipManager = new ClipManager(this, glContext);
87 m_autoSaveTimer = new QTimer(this);
88 m_autoSaveTimer->setSingleShot(true);
89 connect(m_clipManager, SIGNAL(displayMessage(QString,int)), parent, SLOT(slotGotProgressInfo(QString,int)));
92 // init default document properties
93 m_documentProperties["zoom"] = '7';
94 m_documentProperties["verticalzoom"] = '1';
95 m_documentProperties["zonein"] = '0';
96 m_documentProperties["zoneout"] = "100";
97 m_documentProperties["enableproxy"] = QString::number((int) KdenliveSettings::enableproxy());
98 m_documentProperties["proxyparams"] = KdenliveSettings::proxyparams();
99 m_documentProperties["proxyextension"] = KdenliveSettings::proxyextension();
100 m_documentProperties["generateproxy"] = QString::number((int) KdenliveSettings::generateproxy());
101 m_documentProperties["proxyminsize"] = QString::number(KdenliveSettings::proxyminsize());
102 m_documentProperties["generateimageproxy"] = QString::number((int) KdenliveSettings::generateimageproxy());
103 m_documentProperties["proxyimageminsize"] = QString::number(KdenliveSettings::proxyimageminsize());
104 #if QT_VERSION >= 0x040700
105 m_documentProperties["documentid"] = QString::number(QDateTime::currentMSecsSinceEpoch());
107 QDateTime date = QDateTime::currentDateTime();
108 m_documentProperties["documentid"] = QString::number(date.toTime_t());
112 QMapIterator<QString, QString> i(properties);
113 while (i.hasNext()) {
115 m_documentProperties[i.key()] = i.value();
119 QMapIterator<QString, QString> j(metadata);
120 while (j.hasNext()) {
122 m_documentMetadata[j.key()] = j.value();
125 if (QLocale().decimalPoint() != QLocale::system().decimalPoint()) {
126 setlocale(LC_NUMERIC, "");
127 QLocale systemLocale = QLocale::system();
128 systemLocale.setNumberOptions(QLocale::OmitGroupSeparator);
129 QLocale::setDefault(systemLocale);
130 // locale conversion might need to be redone
131 initEffects::parseEffectFiles(setlocale(LC_NUMERIC, NULL));
136 if (!url.isEmpty()) {
138 success = KIO::NetAccess::download(url.path(), tmpFile, parent);
140 // The file cannot be opened
141 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) {
144 //KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
151 QDomImplementation::setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
152 success = m_document.setContent(&file, false, &errorMsg, &line, &col);
157 int answer = KMessageBox::warningYesNoCancel (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")), KGuiItem(i18n("Recover")));
158 if (answer == KMessageBox::Yes) {
161 else if (answer == KMessageBox::No) {
162 // Try to recover broken file produced by Kdenlive 0.9.4
163 if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
165 QString playlist = file.readAll();
166 while (!success && correction < 2) {
170 for (int j = 0; j < line && errorPos < playlist.length(); j++) {
171 errorPos = playlist.indexOf("\n", errorPos);
175 if (errorPos >= playlist.length()) break;
176 playlist.remove(errorPos, 1);
179 success = m_document.setContent(playlist, false, &errorMsg, &line, &col);
183 KMessageBox::sorry(parent, i18n("Cannot recover this project file"));
186 // Document was modified, ask for backup
187 QDomElement mlt = m_document.documentElement();
188 QDomElement info = mlt.firstChildElement("kdenlivedoc");
189 if (!info.isNull()) info.setAttribute("modified", 1);
195 parent->slotGotProgressInfo(i18n("Validating"), 0);
196 qApp->processEvents();
197 DocumentValidator validator(m_document, url);
198 success = validator.isProject();
200 // It is not a project file
201 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
202 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) {
207 * Validate the file against the current version (upgrade
208 * and recover it if needed). It is NOT a passive operation
210 // TODO: backup the document or alert the user?
211 success = validator.validate(DOCUMENTVERSION);
212 if (success) { // Let the validator handle error messages
213 parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
214 qApp->processEvents();
215 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
216 success = checkDocumentClips(infoproducers);
218 if (m_document.documentElement().attribute("modified") == "1") setModified(true);
219 parent->slotGotProgressInfo(i18n("Loading"), 0);
220 QDomElement mlt = m_document.firstChildElement("mlt");
221 QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
223 // Set profile, fps, etc for the document
224 setProfilePath(infoXml.attribute("profile"));
226 // Check embedded effects
227 QDomElement customeffects = infoXml.firstChildElement("customeffects");
228 if (!customeffects.isNull() && customeffects.hasChildNodes()) {
229 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
230 qApp->processEvents();
231 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
236 QDomElement notesxml = infoXml.firstChildElement("documentnotes");
237 if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
240 QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
241 if (!tracksinfo.isNull()) {
242 QDomNodeList trackslist = tracksinfo.childNodes();
243 int maxchild = trackslist.count();
244 for (int k = 0; k < maxchild; k++) {
245 e = trackslist.at(k).toElement();
246 if (e.tagName() == "trackinfo") {
247 TrackInfo projectTrack;
248 if (e.attribute("type") == "audio")
249 projectTrack.type = AudioTrack;
251 projectTrack.type = VideoTrack;
252 projectTrack.isMute = e.attribute("mute").toInt();
253 projectTrack.isBlind = e.attribute("blind").toInt();
254 projectTrack.isLocked = e.attribute("locked").toInt();
255 projectTrack.trackName = e.attribute("trackname");
256 projectTrack.effectsList = EffectsList(true);
257 m_tracksList.append(projectTrack);
260 mlt.removeChild(tracksinfo);
262 QStringList expandedFolders;
263 QDomNodeList folders = m_document.elementsByTagName("folder");
264 for (int i = 0; i < folders.count(); ++i) {
265 e = folders.item(i).cloneNode().toElement();
266 if (e.hasAttribute("opened")) expandedFolders.append(e.attribute("id"));
267 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
269 m_documentProperties["expandedfolders"] = expandedFolders.join(";");
271 const int infomax = infoproducers.count();
272 QDomNodeList producers = m_document.elementsByTagName("producer");
273 const int max = producers.count();
275 if (!progressDialog) {
276 progressDialog = new KProgressDialog(parent, i18n("Loading project"), i18n("Adding clips"));
277 progressDialog->setAllowCancel(false);
279 progressDialog->setLabelText(i18n("Adding clips"));
281 progressDialog->progressBar()->setMaximum(infomax);
282 progressDialog->show();
283 qApp->processEvents();
285 for (int i = 0; i < infomax; ++i) {
286 e = infoproducers.item(i).cloneNode().toElement();
287 QString prodId = e.attribute("id");
288 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
289 e.setTagName("producer");
290 // Get MLT's original producer properties
292 for (int j = 0; j < max; j++) {
293 QDomNode o = producers.item(j);
294 QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
295 if (origId == prodId) {
296 orig = o.cloneNode().toElement();
301 if (!addClipInfo(e, orig, prodId)) {
302 // The user manually aborted the loading.
304 emit resetProjectList();
305 m_tracksList.clear();
306 m_clipManager->clear();
311 progressDialog->progressBar()->setValue(i);
315 QDomElement markers = infoXml.firstChildElement("markers");
316 if (!markers.isNull()) {
317 QDomNodeList markerslist = markers.childNodes();
318 int maxchild = markerslist.count();
319 for (int k = 0; k < maxchild; k++) {
320 e = markerslist.at(k).toElement();
321 if (e.tagName() == "marker") {
322 CommentedTime marker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"), e.attribute("type").toInt());
323 DocClipBase *baseClip = m_clipManager->getClipById(e.attribute("id"));
324 if (baseClip) baseClip->addSnapMarker(marker);
325 else kDebug()<< " / / Warning, missing clip: "<< e.attribute("id");
328 infoXml.removeChild(markers);
331 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
332 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
333 QDomNamedNodeMap props = docproperties.attributes();
334 for (int i = 0; i < props.count(); ++i)
335 m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
336 docproperties = infoXml.firstChildElement("documentmetadata");
337 props = docproperties.attributes();
338 for (int i = 0; i < props.count(); ++i)
339 m_documentMetadata.insert(props.item(i).nodeName(), props.item(i).nodeValue());
341 if (validator.isModified()) setModified(true);
342 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
348 KIO::NetAccess::removeTempFile(tmpFile);
352 // Something went wrong, or a new file was requested: create a new project
355 setProfilePath(profileName);
356 m_document = createEmptyDocument(tracks.x(), tracks.y());
359 // Ask to create the project directory if it does not exist
360 if (!QFile::exists(m_projectFolder.path())) {
361 int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
362 if (create == KMessageBox::Yes) {
363 QDir projectDir(m_projectFolder.path());
364 bool ok = projectDir.mkpath(m_projectFolder.path());
366 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
371 // Make sure the project folder is usable
372 if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
373 KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
374 m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
377 // Make sure that the necessary folders exist
378 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
379 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
380 KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/");
382 updateProjectFolderPlacesEntry();
384 //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
385 connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
386 connect(m_render, SIGNAL(addClip(KUrl,stringMap)), this, SLOT(slotAddClipFile(KUrl,stringMap)));
389 KdenliveDoc::~KdenliveDoc()
391 m_autoSaveTimer->stop();
392 delete m_commandStack;
393 kDebug() << "// DEL CLP MAN";
394 delete m_clipManager;
395 kDebug() << "// DEL CLP MAN done";
396 delete m_autoSaveTimer;
398 if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
403 int KdenliveDoc::setSceneList()
405 m_render->resetProfile(KdenliveSettings::current_profile(), true);
406 if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
407 // INVALID MLT Consumer, something is wrong
410 m_documentProperties.remove("position");
411 // m_document xml is now useless, clear it
416 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
418 m_tracksList.clear();
420 // Tracks are added «backwards», so we need to reverse the track numbering
421 // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
422 // Better default names for tracks: Audio 1 etc. instead of blank numbers
423 for (int i = 0; i < audiotracks; ++i) {
424 TrackInfo audioTrack;
425 audioTrack.type = AudioTrack;
426 audioTrack.isMute = false;
427 audioTrack.isBlind = true;
428 audioTrack.isLocked = false;
429 audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
430 audioTrack.duration = 0;
431 audioTrack.effectsList = EffectsList(true);
432 m_tracksList.append(audioTrack);
435 for (int i = 0; i < videotracks; ++i) {
436 TrackInfo videoTrack;
437 videoTrack.type = VideoTrack;
438 videoTrack.isMute = false;
439 videoTrack.isBlind = false;
440 videoTrack.isLocked = false;
441 videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
442 videoTrack.duration = 0;
443 videoTrack.effectsList = EffectsList(true);
444 m_tracksList.append(videoTrack);
446 return createEmptyDocument(m_tracksList);
449 QDomDocument KdenliveDoc::createEmptyDocument(const QList <TrackInfo> &tracks)
451 // Creating new document
453 QDomElement mlt = doc.createElement("mlt");
454 mlt.setAttribute("LC_NUMERIC", "");
455 doc.appendChild(mlt);
457 // Create black producer
458 // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
459 // the composite transitions with the black track are corrupted.
460 QDomElement blk = doc.createElement("producer");
461 blk.setAttribute("in", 0);
462 blk.setAttribute("out", 500);
463 blk.setAttribute("id", "black");
465 QDomElement property = doc.createElement("property");
466 property.setAttribute("name", "mlt_type");
467 QDomText value = doc.createTextNode("producer");
468 property.appendChild(value);
469 blk.appendChild(property);
471 property = doc.createElement("property");
472 property.setAttribute("name", "aspect_ratio");
473 value = doc.createTextNode(QString::number(0));
474 property.appendChild(value);
475 blk.appendChild(property);
477 property = doc.createElement("property");
478 property.setAttribute("name", "length");
479 value = doc.createTextNode(QString::number(15000));
480 property.appendChild(value);
481 blk.appendChild(property);
483 property = doc.createElement("property");
484 property.setAttribute("name", "eof");
485 value = doc.createTextNode("pause");
486 property.appendChild(value);
487 blk.appendChild(property);
489 property = doc.createElement("property");
490 property.setAttribute("name", "resource");
491 value = doc.createTextNode("black");
492 property.appendChild(value);
493 blk.appendChild(property);
495 property = doc.createElement("property");
496 property.setAttribute("name", "mlt_service");
497 value = doc.createTextNode("colour");
498 property.appendChild(value);
499 blk.appendChild(property);
501 mlt.appendChild(blk);
504 QDomElement tractor = doc.createElement("tractor");
505 tractor.setAttribute("id", "maintractor");
506 //QDomElement multitrack = doc.createElement("multitrack");
507 QDomElement playlist = doc.createElement("playlist");
508 playlist.setAttribute("id", "black_track");
509 mlt.appendChild(playlist);
511 QDomElement blank0 = doc.createElement("entry");
512 blank0.setAttribute("in", "0");
513 blank0.setAttribute("out", "1");
514 blank0.setAttribute("producer", "black");
515 playlist.appendChild(blank0);
518 int total = tracks.count() + 1;
520 for (int i = 1; i < total; ++i) {
521 QDomElement playlist = doc.createElement("playlist");
522 playlist.setAttribute("id", "playlist" + QString::number(i));
523 mlt.appendChild(playlist);
526 QDomElement track0 = doc.createElement("track");
527 track0.setAttribute("producer", "black_track");
528 tractor.appendChild(track0);
530 // create audio and video tracks
531 for (int i = 1; i < total; ++i) {
532 QDomElement track = doc.createElement("track");
533 track.setAttribute("producer", "playlist" + QString::number(i));
534 if (tracks.at(i - 1).type == AudioTrack) {
535 track.setAttribute("hide", "video");
536 } else if (tracks.at(i - 1).isBlind)
537 track.setAttribute("hide", "video");
538 if (tracks.at(i - 1).isMute)
539 track.setAttribute("hide", "audio");
540 tractor.appendChild(track);
543 for (int i = 2; i < total ; ++i) {
544 QDomElement transition = doc.createElement("transition");
545 transition.setAttribute("always_active", "1");
547 QDomElement property = doc.createElement("property");
548 property.setAttribute("name", "a_track");
549 QDomText value = doc.createTextNode(QString::number(1));
550 property.appendChild(value);
551 transition.appendChild(property);
553 property = doc.createElement("property");
554 property.setAttribute("name", "b_track");
555 value = doc.createTextNode(QString::number(i));
556 property.appendChild(value);
557 transition.appendChild(property);
559 property = doc.createElement("property");
560 property.setAttribute("name", "mlt_service");
561 value = doc.createTextNode("mix");
562 property.appendChild(value);
563 transition.appendChild(property);
565 property = doc.createElement("property");
566 property.setAttribute("name", "combine");
567 value = doc.createTextNode("1");
568 property.appendChild(value);
569 transition.appendChild(property);
571 property = doc.createElement("property");
572 property.setAttribute("name", "internal_added");
573 value = doc.createTextNode("237");
574 property.appendChild(value);
575 transition.appendChild(property);
576 tractor.appendChild(transition);
578 mlt.appendChild(tractor);
583 void KdenliveDoc::syncGuides(const QList <Guide *> &guides)
586 QDomElement guideNode = m_guidesXml.createElement("guides");
587 m_guidesXml.appendChild(guideNode);
590 for (int i = 0; i < guides.count(); ++i) {
591 e = m_guidesXml.createElement("guide");
592 e.setAttribute("time", guides.at(i)->position().ms() / 1000);
593 e.setAttribute("comment", guides.at(i)->label());
594 guideNode.appendChild(e);
597 emit guidesUpdated();
600 QDomElement KdenliveDoc::guidesXml() const
602 return m_guidesXml.documentElement();
605 void KdenliveDoc::slotAutoSave()
607 if (m_render && m_autosave) {
608 if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
609 // show error: could not open the autosave file
610 kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
612 kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
613 saveSceneList(m_autosave->fileName(), m_render->sceneList(), QStringList(), true);
617 void KdenliveDoc::setZoom(int horizontal, int vertical)
619 m_documentProperties["zoom"] = QString::number(horizontal);
620 m_documentProperties["verticalzoom"] = QString::number(vertical);
623 QPoint KdenliveDoc::zoom() const
625 return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
628 void KdenliveDoc::setZone(int start, int end)
630 m_documentProperties["zonein"] = QString::number(start);
631 m_documentProperties["zoneout"] = QString::number(end);
634 QPoint KdenliveDoc::zone() const
636 return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
639 QDomDocument KdenliveDoc::xmlSceneList(const QString &scene, const QStringList &expandedFolders)
641 QDomDocument sceneList;
642 sceneList.setContent(scene, true);
643 QDomElement mlt = sceneList.firstChildElement("mlt");
644 if (mlt.isNull() || !mlt.hasChildNodes()) {
645 //scenelist is corrupted
649 // Set playlist audio volume to 100%
650 QDomElement tractor = mlt.firstChildElement("tractor");
651 if (!tractor.isNull()) {
652 QDomNodeList props = tractor.elementsByTagName("property");
653 for (int i = 0; i < props.count(); ++i) {
654 if (props.at(i).toElement().attribute("name") == "meta.volume") {
655 props.at(i).firstChild().setNodeValue("1");
661 QDomElement addedXml = sceneList.createElement("kdenlivedoc");
662 mlt.appendChild(addedXml);
664 // check if project contains custom effects to embed them in project file
665 QDomNodeList effects = mlt.elementsByTagName("filter");
666 int maxEffects = effects.count();
667 kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
668 QMap <QString, QString> effectIds;
669 for (int i = 0; i < maxEffects; ++i) {
670 QDomNode m = effects.at(i);
671 QDomNodeList params = m.childNodes();
674 for (int j = 0; j < params.count(); j++) {
675 QDomElement e = params.item(j).toElement();
676 if (e.attribute("name") == "kdenlive_id") {
677 id = e.firstChild().nodeValue();
679 if (e.attribute("name") == "tag") {
680 tag = e.firstChild().nodeValue();
682 if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
685 QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
686 addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
688 QDomElement markers = sceneList.createElement("markers");
689 addedXml.setAttribute("version", DOCUMENTVERSION);
690 addedXml.setAttribute("kdenliveversion", VERSION);
691 addedXml.setAttribute("profile", profilePath());
692 addedXml.setAttribute("projectfolder", m_projectFolder.path());
694 QDomElement docproperties = sceneList.createElement("documentproperties");
695 QMapIterator<QString, QString> i(m_documentProperties);
696 while (i.hasNext()) {
698 docproperties.setAttribute(i.key(), i.value());
700 docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
701 addedXml.appendChild(docproperties);
703 QDomElement docmetadata = sceneList.createElement("documentmetadata");
704 QMapIterator<QString, QString> j(m_documentMetadata);
705 while (j.hasNext()) {
707 docmetadata.setAttribute(j.key(), j.value());
709 addedXml.appendChild(docmetadata);
711 QDomElement docnotes = sceneList.createElement("documentnotes");
712 QDomText value = sceneList.createTextNode(m_notesWidget->toHtml());
713 docnotes.appendChild(value);
714 addedXml.appendChild(docnotes);
717 QDomElement profileinfo = sceneList.createElement("profileinfo");
718 profileinfo.setAttribute("description", m_profile.description);
719 profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
720 profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
721 profileinfo.setAttribute("width", m_profile.width);
722 profileinfo.setAttribute("height", m_profile.height);
723 profileinfo.setAttribute("progressive", m_profile.progressive);
724 profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
725 profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
726 profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
727 profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
728 addedXml.appendChild(profileinfo);
731 QDomElement tracksinfo = sceneList.createElement("tracksinfo");
732 foreach(const TrackInfo & info, m_tracksList) {
733 QDomElement trackinfo = sceneList.createElement("trackinfo");
734 if (info.type == AudioTrack) trackinfo.setAttribute("type", "audio");
735 trackinfo.setAttribute("mute", info.isMute);
736 trackinfo.setAttribute("blind", info.isBlind);
737 trackinfo.setAttribute("locked", info.isLocked);
738 trackinfo.setAttribute("trackname", info.trackName);
739 tracksinfo.appendChild(trackinfo);
741 addedXml.appendChild(tracksinfo);
743 // save project folders
744 QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
746 QMapIterator<QString, QString> f(folderlist);
747 while (f.hasNext()) {
749 QDomElement folder = sceneList.createElement("folder");
750 folder.setAttribute("id", f.key());
751 folder.setAttribute("name", f.value());
752 if (expandedFolders.contains(f.key())) folder.setAttribute("opened", "1");
753 addedXml.appendChild(folder);
756 // Save project clips
758 QList <DocClipBase*> list = m_clipManager->documentClipList();
759 for (int i = 0; i < list.count(); ++i) {
760 e = list.at(i)->toXML(true);
761 e.setTagName("kdenlive_producer");
762 addedXml.appendChild(sceneList.importNode(e, true));
763 QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
764 for (int j = 0; j < marks.count(); j++) {
765 QDomElement marker = sceneList.createElement("marker");
766 marker.setAttribute("time", marks.at(j).time().ms() / 1000);
767 marker.setAttribute("comment", marks.at(j).comment());
768 marker.setAttribute("id", e.attribute("id"));
769 marker.setAttribute("type", marks.at(j).markerType());
770 markers.appendChild(marker);
773 addedXml.appendChild(markers);
776 if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
779 addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
781 //wes.appendChild(doc.importNode(kdenliveData, true));
785 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene, const QStringList &expandedFolders, bool autosave)
787 QDomDocument sceneList = xmlSceneList(scene, expandedFolders);
788 if (sceneList.isNull()) {
789 //Make sure we don't save if scenelist is corrupted
790 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
794 // Backup current version
795 if (!autosave) backupLastSavedVersion(path);
798 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
799 kWarning() << "////// ERROR writing to file: " << path;
800 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
804 file.write(sceneList.toString().toUtf8());
805 if (file.error() != QFile::NoError) {
806 KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
812 cleanupBackupFiles();
813 QFileInfo info(file);
814 QString fileName = KUrl(path).fileName().section('.', 0, -2);
815 fileName.append('-' + m_documentProperties.value("documentid"));
816 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
817 fileName.append(".kdenlive.png");
818 KUrl backupFile = m_projectFolder;
819 backupFile.addPath(".backup/");
820 backupFile.addPath(fileName);
821 emit saveTimelinePreview(backupFile.path());
826 ClipManager *KdenliveDoc::clipManager()
828 return m_clipManager;
831 KUrl KdenliveDoc::projectFolder() const
833 //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
834 return m_projectFolder;
837 void KdenliveDoc::setProjectFolder(KUrl url)
839 if (url == m_projectFolder) return;
841 KStandardDirs::makeDir(url.path());
842 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
843 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
844 KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "proxy/");
845 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);
846 m_projectFolder = url;
848 updateProjectFolderPlacesEntry();
851 void KdenliveDoc::moveProjectData(const KUrl &url)
853 QList <DocClipBase*> list = m_clipManager->documentClipList();
854 KUrl::List cacheUrls;
855 for (int i = 0; i < list.count(); ++i) {
856 DocClipBase *clip = list.at(i);
857 if (clip->clipType() == Text) {
858 // the image for title clip must be moved
859 KUrl oldUrl = clip->fileURL();
860 KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
861 KIO::Job *job = KIO::copy(oldUrl, newUrl);
862 if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
864 QString hash = clip->getClipHash();
865 KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
866 if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
867 cacheUrls << oldVideoThumbUrl;
869 KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
870 if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
871 cacheUrls << oldAudioThumbUrl;
873 KUrl oldVideoProxyUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "proxy/" + hash + '.' + KdenliveSettings::proxyextension());
874 if (KIO::NetAccess::exists(oldVideoProxyUrl, KIO::NetAccess::SourceSide, 0)) {
875 cacheUrls << oldVideoProxyUrl;
878 if (!cacheUrls.isEmpty()) {
879 KIO::Job *job = KIO::copy(cacheUrls, KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/"));
880 job->ui()->setWindow(kapp->activeWindow());
881 KIO::NetAccess::synchronousRun(job, 0);
885 const QString &KdenliveDoc::profilePath() const
887 return m_profile.path;
890 MltVideoProfile KdenliveDoc::mltProfile() const
895 bool KdenliveDoc::setProfilePath(QString path)
898 path = KdenliveSettings::default_profile();
900 path = QLatin1String("dv_pal");
901 m_profile = ProfilesDialog::getVideoProfile(path);
902 double current_fps = m_fps;
903 if (m_profile.path.isEmpty()) {
904 // Profile not found, use embedded profile
905 QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
906 if (profileInfo.isNull()) {
907 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
908 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
910 m_profile.description = profileInfo.attribute("description");
911 m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
912 m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
913 m_profile.width = profileInfo.attribute("width").toInt();
914 m_profile.height = profileInfo.attribute("height").toInt();
915 m_profile.progressive = profileInfo.attribute("progressive").toInt();
916 m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
917 m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
918 m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
919 m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
920 QString existing = ProfilesDialog::existingProfile(m_profile);
921 if (!existing.isEmpty()) {
922 m_profile = ProfilesDialog::getVideoProfile(existing);
923 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
925 QString newDesc = m_profile.description;
927 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
928 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);
931 // User canceled, use default profile
932 m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
934 if (newDesc != m_profile.description) {
935 // Profile description existed, was replaced by new one
936 m_profile.description = newDesc;
938 KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
940 ProfilesDialog::saveProfile(m_profile);
947 KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
948 m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
949 KdenliveSettings::setProject_fps(m_fps);
950 m_width = m_profile.width;
951 m_height = m_profile.height;
952 kDebug() << "Kdenlive document, init timecode from path: " << path << ", " << m_fps;
953 m_timecode.setFormat(m_fps);
954 KdenliveSettings::setCurrent_profile(m_profile.path);
955 return (current_fps != m_fps);
958 double KdenliveDoc::dar() const
960 return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
963 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
965 emit progressInfo(message, progress);
968 QUndoStack *KdenliveDoc::commandStack()
970 return m_commandStack;
974 void KdenliveDoc::setRenderer(Render *render) {
975 if (m_render) return;
977 emit progressInfo(i18n("Loading playlist..."), 0);
978 //qApp->processEvents();
980 m_render->setSceneList(m_document.toString(), m_startPos);
981 kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
984 emit progressInfo(QString(), -1);
987 void KdenliveDoc::checkProjectClips(bool displayRatioChanged, bool fpsChanged)
989 if (m_render == NULL) return;
990 m_clipManager->resetProducersList(m_render->producersList(), displayRatioChanged, fpsChanged);
993 Render *KdenliveDoc::renderer()
998 void KdenliveDoc::updateClip(const QString &id)
1000 emit updateClipDisplay(id);
1003 int KdenliveDoc::getFramePos(const QString &duration)
1005 return m_timecode.getFrameCount(duration);
1008 QString KdenliveDoc::producerName(const QString &id)
1010 QString result = "unnamed";
1011 QDomNodeList prods = producersList();
1012 int ct = prods.count();
1013 for (int i = 0; i < ct ; ++i) {
1014 QDomElement e = prods.item(i).toElement();
1015 if (e.attribute("id") != "black" && e.attribute("id") == id) {
1016 result = e.attribute("name");
1017 if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
1024 QDomDocument KdenliveDoc::toXml()
1029 Timecode KdenliveDoc::timecode() const
1034 QDomNodeList KdenliveDoc::producersList()
1036 return m_document.elementsByTagName("producer");
1039 double KdenliveDoc::projectDuration() const
1042 return GenTime(m_render->getLength(), m_fps).ms() / 1000;
1047 double KdenliveDoc::fps() const
1052 int KdenliveDoc::width() const
1057 int KdenliveDoc::height() const
1062 KUrl KdenliveDoc::url() const
1067 void KdenliveDoc::setUrl(const KUrl &url)
1072 void KdenliveDoc::setModified(bool mod)
1074 if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
1075 m_autoSaveTimer->start(3000);
1077 if (mod == m_modified) return;
1079 emit docModified(m_modified);
1082 bool KdenliveDoc::isModified() const
1087 const QString KdenliveDoc::description() const
1089 if (m_url.isEmpty())
1090 return i18n("Untitled") + " / " + m_profile.description;
1092 return m_url.fileName() + " / " + m_profile.description;
1095 bool KdenliveDoc::addClip(QDomElement elem, const QString &clipId, bool createClipItem)
1097 const QString producerId = clipId.section('_', 0, 0);
1098 DocClipBase *clip = m_clipManager->getClipById(producerId);
1101 elem.setAttribute("id", producerId);
1102 QString path = elem.attribute("resource");
1104 if (elem.attribute("type").toInt() == SlideShow) {
1105 extension = KUrl(path).fileName();
1106 path = KUrl(path).directory();
1108 if (elem.hasAttribute("_missingsource")) {
1109 // Clip has proxy but missing original source
1111 else if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != Text && !elem.hasAttribute("placeholder")) {
1112 kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1113 const QString size = elem.attribute("file_size");
1114 const QString hash = elem.attribute("file_hash");
1116 int action = KMessageBox::No;
1117 if (!size.isEmpty() && !hash.isEmpty()) {
1118 if (!m_searchFolder.isEmpty())
1119 newpath = searchFileRecursively(m_searchFolder, size, hash);
1121 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")));
1123 if (elem.attribute("type").toInt() == SlideShow) {
1124 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")));
1125 if (res == KMessageBox::Yes)
1126 newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1128 // Abort project loading
1132 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")));
1133 if (res == KMessageBox::Yes)
1134 newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1136 // Abort project loading
1141 if (action == KMessageBox::Yes) {
1142 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1143 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1144 if (!m_searchFolder.isEmpty())
1145 newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1146 } else if (action == KMessageBox::Cancel) {
1148 } else if (action == KMessageBox::No) {
1149 // Keep clip as placeHolder
1150 elem.setAttribute("placeholder", '1');
1152 if (!newpath.isEmpty()) {
1153 kDebug() << "// NEW CLIP PATH FOR CLIP " << clipId << " : " << newpath;
1154 if (elem.attribute("type").toInt() == SlideShow)
1155 newpath.append('/' + extension);
1156 elem.setAttribute("resource", newpath);
1157 setNewClipResource(clipId, newpath);
1161 clip = new DocClipBase(m_clipManager, elem, producerId);
1162 m_clipManager->addClip(clip);
1165 if (createClipItem) {
1166 emit addProjectClip(clip);
1172 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
1174 QDomNodeList prods = m_document.elementsByTagName("producer");
1175 int maxprod = prods.count();
1176 for (int i = 0; i < maxprod; ++i) {
1177 QDomNode m = prods.at(i);
1178 QString prodId = m.toElement().attribute("id");
1179 if (prodId == id || prodId.startsWith(id + '_')) {
1180 QDomNodeList params = m.childNodes();
1181 for (int j = 0; j < params.count(); j++) {
1182 QDomElement e = params.item(j).toElement();
1183 if (e.attribute("name") == "resource") {
1184 e.firstChild().setNodeValue(path);
1192 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1194 QString foundFileName;
1195 QByteArray fileData;
1196 QByteArray fileHash;
1197 QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1198 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); ++i) {
1199 QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1200 if (file.open(QIODevice::ReadOnly)) {
1201 if (QString::number(file.size()) == matchSize) {
1203 * 1 MB = 1 second per 450 files (or faster)
1204 * 10 MB = 9 seconds per 450 files (or faster)
1206 if (file.size() > 1000000 * 2) {
1207 fileData = file.read(1000000);
1208 if (file.seek(file.size() - 1000000))
1209 fileData.append(file.readAll());
1211 fileData = file.readAll();
1213 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1214 if (QString(fileHash.toHex()) == matchHash)
1215 return file.fileName();
1217 kDebug() << filesAndDirs.at(i) << "size match but not hash";
1220 //kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1222 filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1223 for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); ++i) {
1224 foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1225 if (!foundFileName.isEmpty())
1228 return foundFileName;
1231 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, const QString &clipId)
1233 DocClipBase *clip = m_clipManager->getClipById(clipId);
1235 if (!addClip(elem, clipId, false))
1238 QMap <QString, QString> properties;
1239 QDomNamedNodeMap attributes = elem.attributes();
1240 for (int i = 0; i < attributes.count(); ++i) {
1241 QString attrname = attributes.item(i).nodeName();
1242 if (attrname != "resource")
1243 properties.insert(attrname, attributes.item(i).nodeValue());
1244 //kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1246 clip->setProperties(properties);
1247 emit addProjectClip(clip, false);
1249 if (orig != QDomElement()) {
1250 QMap<QString, QString> meta;
1251 for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1252 QString name = m.toElement().attribute("name");
1253 if (name.startsWith("meta.attr")) {
1254 if (name.endsWith(".markup")) name = name.section('.', 0, -2);
1255 meta.insert(name.section('.', 2, -1), m.firstChild().nodeValue());
1258 if (!meta.isEmpty()) {
1260 clip = m_clipManager->getClipById(clipId);
1262 clip->setMetadata(meta);
1269 void KdenliveDoc::deleteClip(const QString &clipId)
1271 emit signalDeleteProjectClip(clipId);
1274 void KdenliveDoc::slotAddClipList(const KUrl::List &urls, const stringMap &data)
1276 m_clipManager->slotAddClipList(urls, data);
1277 //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1282 void KdenliveDoc::slotAddClipFile(const KUrl &url, const stringMap &data)
1284 m_clipManager->slotAddClipFile(url, data);
1285 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1289 const QString KdenliveDoc::getFreeClipId()
1291 return QString::number(m_clipManager->getFreeClipId());
1294 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1296 return m_clipManager->getClipById(clipId);
1299 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement &xml, const QString &group, const QString &groupId)
1301 m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1303 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1306 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, const QString &group, const QString &groupId)
1308 m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1310 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1313 void KdenliveDoc::slotCreateSlideshowClipFile(const QMap <QString, QString> &properties, const QString &group, const QString &groupId)
1315 m_clipManager->slotAddSlideshowClipFile(properties, group, groupId);
1317 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1320 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1322 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1323 KStandardDirs::makeDir(titlesFolder);
1324 QPointer<TitleWidget> dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1325 if (dia_ui->exec() == QDialog::Accepted) {
1326 m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->duration(), dia_ui->xml().toString(), group, groupId);
1328 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1333 void KdenliveDoc::slotCreateTextTemplateClip(const QString &group, const QString &groupId, KUrl path)
1335 QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1336 if (path.isEmpty()) {
1337 path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "application/x-kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1340 if (path.isEmpty()) return;
1342 //TODO: rewrite with new title system (just set resource)
1343 m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1345 emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1348 int KdenliveDoc::tracksCount() const
1350 return m_tracksList.count();
1353 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1355 if (ix < 0 || ix >= m_tracksList.count()) {
1356 kWarning() << "Track INFO outisde of range";
1359 return m_tracksList.at(ix);
1362 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1364 if (ix < 0 || ix >= m_tracksList.count()) {
1365 kWarning() << "SWITCH Track outisde of range";
1368 m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1371 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1373 if (ix < 0 || ix >= m_tracksList.count()) {
1374 kWarning() << "Track Lock outisde of range";
1377 m_tracksList[ix].isLocked = lock;
1380 bool KdenliveDoc::isTrackLocked(int ix) const
1382 if (ix < 0 || ix >= m_tracksList.count()) {
1383 kWarning() << "Track Lock outisde of range";
1386 return m_tracksList.at(ix).isLocked;
1389 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1391 if (ix < 0 || ix >= m_tracksList.count()) {
1392 kWarning() << "SWITCH Track outisde of range";
1395 m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1398 int KdenliveDoc::trackDuration(int ix)
1400 return m_tracksList.at(ix).duration;
1403 void KdenliveDoc::setTrackDuration(int ix, int duration)
1405 m_tracksList[ix].duration = duration;
1408 void KdenliveDoc::insertTrack(int ix, const TrackInfo &type)
1410 if (ix == -1) m_tracksList << type;
1411 else m_tracksList.insert(ix, type);
1414 void KdenliveDoc::deleteTrack(int ix)
1416 if (ix < 0 || ix >= m_tracksList.count()) {
1417 kWarning() << "Delete Track outisde of range";
1420 m_tracksList.removeAt(ix);
1423 void KdenliveDoc::setTrackType(int ix, const TrackInfo &type)
1425 if (ix < 0 || ix >= m_tracksList.count()) {
1426 kWarning() << "SET Track Type outisde of range";
1429 m_tracksList[ix].type = type.type;
1430 m_tracksList[ix].isMute = type.isMute;
1431 m_tracksList[ix].isBlind = type.isBlind;
1432 m_tracksList[ix].isLocked = type.isLocked;
1433 m_tracksList[ix].trackName = type.trackName;
1436 const QList <TrackInfo> KdenliveDoc::tracksList() const
1438 return m_tracksList;
1441 QPoint KdenliveDoc::getTracksCount() const
1445 foreach(const TrackInfo & info, m_tracksList) {
1446 if (info.type == VideoTrack) video++;
1449 return QPoint(video, audio);
1452 void KdenliveDoc::cacheImage(const QString &fileId, const QImage &img) const
1454 img.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1457 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1459 DocumentChecker d(infoproducers, m_document);
1460 return (d.hasErrorInClips() == false);
1466 QList <QDomElement> missingClips;
1467 for (int i = 0; i < infoproducers.count(); ++i) {
1468 e = infoproducers.item(i).toElement();
1469 clipType = e.attribute("type").toInt();
1470 if (clipType == COLOR) continue;
1471 if (clipType == TEXT) {
1472 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1475 id = e.attribute("id");
1476 resource = e.attribute("resource");
1477 if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1478 if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1479 // Missing clip found
1480 missingClips.append(e);
1482 // Check if the clip has changed
1483 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1484 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1485 e.removeAttribute("file_hash");
1489 if (missingClips.isEmpty()) return true;
1490 DocumentChecker d(missingClips, m_document);
1491 return (d.exec() == QDialog::Accepted);*/
1494 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1496 m_documentProperties[name] = value;
1499 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1501 return m_documentProperties.value(name);
1504 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1506 QMap <QString, QString> renderProperties;
1507 QMapIterator<QString, QString> i(m_documentProperties);
1508 while (i.hasNext()) {
1510 if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1512 return renderProperties;
1515 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1517 if (ix < 0 || ix >= m_tracksList.count()) {
1518 kWarning() << "Add Track effect outisde of range";
1521 effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1523 // Init parameter value & keyframes if required
1524 QDomNodeList params = effect.elementsByTagName("parameter");
1525 for (int i = 0; i < params.count(); ++i) {
1526 QDomElement e = params.item(i).toElement();
1528 // Check if this effect has a variable parameter
1529 if (e.attribute("default").contains('%')) {
1530 double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1531 e.setAttribute("default", evaluatedValue);
1532 if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1533 e.setAttribute("value", evaluatedValue);
1537 if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1538 QString def = e.attribute("default");
1539 // Effect has a keyframe type parameter, we need to set the values
1540 if (e.attribute("keyframes").isEmpty()) {
1541 e.setAttribute("keyframes", "0:" + def + ';');
1542 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1547 if (effect.attribute("id") == "crop") {
1548 // default use_profile to 1 for clips with proxies to avoid problems when rendering
1549 if (e.attribute("name") == "use_profile" && getDocumentProperty("enableproxy") == "1")
1550 e.setAttribute("value", "1");
1554 m_tracksList[ix].effectsList.append(effect);
1557 void KdenliveDoc::removeTrackEffect(int ix, const QDomElement &effect)
1559 if (ix < 0 || ix >= m_tracksList.count()) {
1560 kWarning() << "Remove Track effect outisde of range";
1564 int toRemove = effect.attribute("kdenlive_ix").toInt();
1565 for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1566 index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix").toInt();
1567 if (toRemove == index) {
1568 m_tracksList[ix].effectsList.removeAt(toRemove);
1574 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1576 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1577 kWarning() << "Set Track effect outisde of range";
1580 if (effectIndex <= 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count()) || effect.isNull()) {
1581 kDebug() << "Invalid effect index: " << effectIndex;
1584 m_tracksList[trackIndex].effectsList.removeAt(effect.attribute("kdenlive_ix").toInt());
1585 effect.setAttribute("kdenlive_ix", effectIndex);
1586 m_tracksList[trackIndex].effectsList.insert(effect);
1587 //m_tracksList[trackIndex].effectsList.updateEffect(effect);
1590 void KdenliveDoc::enableTrackEffects(int trackIndex, const QList <int> &effectIndexes, bool disable)
1592 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1593 kWarning() << "Set Track effect outisde of range";
1596 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1598 for (int i = 0; i < effectIndexes.count(); ++i) {
1599 effect = list.itemFromIndex(effectIndexes.at(i));
1600 if (!effect.isNull()) effect.setAttribute("disable", (int) disable);
1604 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1606 if (ix < 0 || ix >= m_tracksList.count()) {
1607 kWarning() << "Get Track effects outisde of range";
1608 return EffectsList();
1610 return m_tracksList.at(ix).effectsList;
1613 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1615 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1616 kWarning() << "Get Track effect outisde of range";
1617 return QDomElement();
1619 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1620 if (effectIndex > list.count() || effectIndex < 1 || list.itemFromIndex(effectIndex).isNull()) return QDomElement();
1621 return list.itemFromIndex(effectIndex).cloneNode().toElement();
1624 int KdenliveDoc::hasTrackEffect(int trackIndex, const QString &tag, const QString &id) const
1626 if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1627 kWarning() << "Get Track effect outisde of range";
1630 EffectsList list = m_tracksList.at(trackIndex).effectsList;
1631 return list.hasEffect(tag, id);
1634 bool KdenliveDoc::saveCustomEffects(const QDomNodeList &customeffects)
1637 QStringList importedEffects;
1638 int maxchild = customeffects.count();
1639 for (int i = 0; i < maxchild; ++i) {
1640 e = customeffects.at(i).toElement();
1641 const QString id = e.attribute("id");
1642 const QString tag = e.attribute("tag");
1643 if (!id.isEmpty()) {
1644 // Check if effect exists or save it
1645 if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1647 doc.appendChild(doc.importNode(e, true));
1648 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1649 path += id + ".xml";
1650 if (!QFile::exists(path)) {
1651 importedEffects << id;
1653 if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1654 QTextStream out(&file);
1655 out << doc.toString();
1661 if (!importedEffects.isEmpty())
1662 KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1663 return (!importedEffects.isEmpty());
1666 void KdenliveDoc::updateProjectFolderPlacesEntry()
1669 * For similar and more code have a look at kfileplacesmodel.cpp and the included files:
1670 * http://websvn.kde.org/trunk/KDE/kdelibs/kfile/kfileplacesmodel.cpp?view=markup
1673 const QString file = KStandardDirs::locateLocal("data", "kfileplaces/bookmarks.xml");
1674 KBookmarkManager *bookmarkManager = KBookmarkManager::managerForFile(file, "kfilePlaces");
1675 if (!bookmarkManager) return;
1676 KBookmarkGroup root = bookmarkManager->root();
1678 KBookmark bookmark = root.first();
1680 QString kdenliveName = KGlobal::mainComponent().componentName();
1681 KUrl documentLocation = m_projectFolder;
1683 bool exists = false;
1685 while (!bookmark.isNull()) {
1686 // UDI not empty indicates a device
1687 QString udi = bookmark.metaDataItem("UDI");
1688 QString appName = bookmark.metaDataItem("OnlyInApp");
1690 if (udi.isEmpty() && appName == kdenliveName && bookmark.text() == i18n("Project Folder")) {
1691 if (bookmark.url() != documentLocation) {
1692 bookmark.setUrl(documentLocation);
1693 bookmarkManager->emitChanged(root);
1699 bookmark = root.next(bookmark);
1702 // if entry does not exist yet (was not found), well, create it then
1704 bookmark = root.addBookmark(i18n("Project Folder"), documentLocation, "folder-favorites");
1705 // Make this user selectable ?
1706 bookmark.setMetaDataItem("OnlyInApp", kdenliveName);
1707 bookmarkManager->emitChanged(root);
1711 QStringList KdenliveDoc::getExpandedFolders()
1713 QStringList result = m_documentProperties.value("expandedfolders").split(';');
1714 // this property is only needed once when opening project, so clear it now
1715 m_documentProperties.remove("expandedfolders");
1720 double KdenliveDoc::getDisplayRatio(const QString &path)
1724 if (!file.open(QIODevice::ReadOnly)) {
1725 kWarning() << "ERROR, CANNOT READ: " << path;
1728 if (!doc.setContent(&file)) {
1729 kWarning() << "ERROR, CANNOT READ: " << path;
1734 QDomNodeList list = doc.elementsByTagName("profile");
1735 if (list.isEmpty()) return 0;
1736 QDomElement profile = list.at(0).toElement();
1737 double den = profile.attribute("display_aspect_den").toDouble();
1738 if (den > 0) return profile.attribute("display_aspect_num").toDouble() / den;
1742 void KdenliveDoc::backupLastSavedVersion(const QString &path)
1744 // Ensure backup folder exists
1745 if (path.isEmpty()) return;
1747 KUrl backupFile = m_projectFolder;
1748 backupFile.addPath(".backup/");
1749 KIO::NetAccess::mkdir(backupFile, kapp->activeWindow());
1750 QString fileName = KUrl(path).fileName().section('.', 0, -2);
1751 QFileInfo info(file);
1752 fileName.append('-' + m_documentProperties.value("documentid"));
1753 fileName.append(info.lastModified().toString("-yyyy-MM-dd-hh-mm"));
1754 fileName.append(".kdenlive");
1755 backupFile.addPath(fileName);
1757 if (file.exists()) {
1758 // delete previous backup if it was done less than 60 seconds ago
1759 QFile::remove(backupFile.path());
1760 if (!QFile::copy(path, backupFile.path())) {
1761 KMessageBox::information(kapp->activeWindow(), i18n("Cannot create backup copy:\n%1", backupFile.path()));
1766 void KdenliveDoc::cleanupBackupFiles()
1768 KUrl backupFile = m_projectFolder;
1769 backupFile.addPath(".backup/");
1770 QDir dir(backupFile.path());
1771 QString projectFile = url().fileName().section('.', 0, -2);
1772 projectFile.append('-' + m_documentProperties.value("documentid"));
1773 projectFile.append("-??");
1774 projectFile.append("??");
1775 projectFile.append("-??");
1776 projectFile.append("-??");
1777 projectFile.append("-??");
1778 projectFile.append("-??.kdenlive");
1781 backupFile.addPath(projectFile);
1782 filter << projectFile;
1783 dir.setNameFilters(filter);
1784 QFileInfoList resultList = dir.entryInfoList(QDir::Files, QDir::Time);
1786 QDateTime d = QDateTime::currentDateTime();
1787 QStringList hourList;
1788 QStringList dayList;
1789 QStringList weekList;
1790 QStringList oldList;
1791 for (int i = 0; i < resultList.count(); ++i) {
1792 if (d.secsTo(resultList.at(i).lastModified()) < 3600) {
1793 // files created in the last hour
1794 hourList.append(resultList.at(i).absoluteFilePath());
1796 else if (d.secsTo(resultList.at(i).lastModified()) < 43200) {
1797 // files created in the day
1798 dayList.append(resultList.at(i).absoluteFilePath());
1800 else if (d.daysTo(resultList.at(i).lastModified()) < 8) {
1801 // files created in the week
1802 weekList.append(resultList.at(i).absoluteFilePath());
1806 oldList.append(resultList.at(i).absoluteFilePath());
1809 if (hourList.count() > 20) {
1810 int step = hourList.count() / 10;
1811 for (int i = 0; i < hourList.count(); i += step) {
1812 kDebug()<<"REMOVE AT: "<<i<<", COUNT: "<<hourList.count();
1813 hourList.removeAt(i);
1816 } else hourList.clear();
1817 if (dayList.count() > 20) {
1818 int step = dayList.count() / 10;
1819 for (int i = 0; i < dayList.count(); i += step) {
1820 dayList.removeAt(i);
1823 } else dayList.clear();
1824 if (weekList.count() > 20) {
1825 int step = weekList.count() / 10;
1826 for (int i = 0; i < weekList.count(); i += step) {
1827 weekList.removeAt(i);
1830 } else weekList.clear();
1831 if (oldList.count() > 20) {
1832 int step = oldList.count() / 10;
1833 for (int i = 0; i < oldList.count(); i += step) {
1834 oldList.removeAt(i);
1837 } else oldList.clear();
1840 while (hourList.count() > 0) {
1841 f = hourList.takeFirst();
1843 QFile::remove(f + ".png");
1845 while (dayList.count() > 0) {
1846 f = dayList.takeFirst();
1848 QFile::remove(f + ".png");
1850 while (weekList.count() > 0) {
1851 f = weekList.takeFirst();
1853 QFile::remove(f + ".png");
1855 while (oldList.count() > 0) {
1856 f = oldList.takeFirst();
1858 QFile::remove(f + ".png");
1862 const QMap <QString, QString> KdenliveDoc::metadata() const
1864 return m_documentMetadata;
1867 void KdenliveDoc::setMetadata(const QMap<QString, QString> &meta)
1870 m_documentMetadata = meta;
1873 #include "kdenlivedoc.moc"