]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
36e3188a6c00aeec5ce5d0d15b1dc103f819658f
[kdenlive] / src / kdenlivedoc.cpp
1 /***************************************************************************
2  *   Copyright (C) 2007 by Jean-Baptiste Mardelle (jb@kdenlive.org)        *
3  *                                                                         *
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.                                   *
8  *                                                                         *
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.                          *
13  *                                                                         *
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  ***************************************************************************/
19
20
21 #include "kdenlivedoc.h"
22 #include "docclipbase.h"
23 #include "profilesdialog.h"
24 #include "kdenlivesettings.h"
25 #include "renderer.h"
26 #include "clipmanager.h"
27 #include "titlewidget.h"
28 #include "mainwindow.h"
29 #include "documentchecker.h"
30 #include "documentvalidator.h"
31 #include "kdenlive-config.h"
32 #include "initeffects.h"
33
34 #include <KDebug>
35 #include <KStandardDirs>
36 #include <KMessageBox>
37 #include <KProgressDialog>
38 #include <KLocale>
39 #include <KFileDialog>
40 #include <KIO/NetAccess>
41 #include <KIO/CopyJob>
42 #include <KApplication>
43
44 #include <QCryptographicHash>
45 #include <QFile>
46 #include <QInputDialog>
47 #include <QDomImplementation>
48
49 #include <mlt++/Mlt.h>
50
51 const double DOCUMENTVERSION = 0.85;
52
53 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, QString profileName, const QPoint tracks, Render *render, KTextEdit *notes, MainWindow *parent) :
54     QObject(parent),
55     m_autosave(NULL),
56     m_url(url),
57     m_render(render),
58     m_notesWidget(notes),
59     m_commandStack(new QUndoStack(undoGroup)),
60     m_modified(false),
61     m_projectFolder(projectFolder)
62 {
63     m_clipManager = new ClipManager(this);
64     m_autoSaveTimer = new QTimer(this);
65     m_autoSaveTimer->setSingleShot(true);
66     bool success = false;
67
68     // init default document properties
69     m_documentProperties["zoom"] = "7";
70     m_documentProperties["verticalzoom"] = "1";
71     m_documentProperties["zonein"] = "0";
72     m_documentProperties["zoneout"] = "100";
73
74     if (!url.isEmpty()) {
75         QString tmpFile;
76         success = KIO::NetAccess::download(url.path(), tmpFile, parent);
77         if (!success) // The file cannot be opened
78             KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
79         else {
80             QFile file(tmpFile);
81             QString errorMsg;
82             QDomImplementation impl;
83             impl.setInvalidDataPolicy(QDomImplementation::DropInvalidChars);
84             success = m_document.setContent(&file, false, &errorMsg);
85             file.close();
86             KIO::NetAccess::removeTempFile(tmpFile);
87
88             if (!success) // It is corrupted
89                 KMessageBox::error(parent, errorMsg);
90             else {
91                 parent->slotGotProgressInfo(i18n("Validating"), 0);
92                 DocumentValidator validator(m_document);
93                 success = validator.isProject();
94                 if (!success) {
95                     // It is not a project file
96                     parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file", m_url.path()), 100);
97                 } else {
98                     /*
99                      * Validate the file against the current version (upgrade
100                      * and recover it if needed). It is NOT a passive operation
101                      */
102                     // TODO: backup the document or alert the user?
103                     success = validator.validate(DOCUMENTVERSION);
104                     if (success) { // Let the validator handle error messages
105                         parent->slotGotProgressInfo(i18n("Check missing clips"), 0);
106                         QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
107                         success = checkDocumentClips(infoproducers);
108                         if (success) {
109                             parent->slotGotProgressInfo(i18n("Loading"), 0);
110                             QDomElement mlt = m_document.firstChildElement("mlt");
111                             QDomElement infoXml = mlt.firstChildElement("kdenlivedoc");
112
113                             // Check embedded effects
114                             QDomElement customeffects = infoXml.firstChildElement("customeffects");
115                             if (!customeffects.isNull() && customeffects.hasChildNodes()) {
116                                 parent->slotGotProgressInfo(i18n("Importing project effects"), 0);
117                                 if (saveCustomEffects(customeffects.childNodes())) parent->slotReloadEffects();
118                             }
119
120                             QDomElement e;
121                             // Read notes
122                             QDomElement notesxml = infoXml.firstChildElement("documentnotes");
123                             if (!notesxml.isNull()) m_notesWidget->setText(notesxml.firstChild().nodeValue());
124
125                             // Build tracks
126                             QDomElement tracksinfo = infoXml.firstChildElement("tracksinfo");
127                             if (!tracksinfo.isNull()) {
128                                 QDomNodeList trackslist = tracksinfo.childNodes();
129                                 int maxchild = trackslist.count();
130                                 for (int k = 0; k < maxchild; k++) {
131                                     e = trackslist.at(k).toElement();
132                                     if (e.tagName() == "trackinfo") {
133                                         TrackInfo projectTrack;
134                                         if (e.attribute("type") == "audio")
135                                             projectTrack.type = AUDIOTRACK;
136                                         else
137                                             projectTrack.type = VIDEOTRACK;
138                                         projectTrack.isMute = e.attribute("mute").toInt();
139                                         projectTrack.isBlind = e.attribute("blind").toInt();
140                                         projectTrack.isLocked = e.attribute("locked").toInt();
141                                         projectTrack.trackName = e.attribute("trackname");
142                                         m_tracksList.append(projectTrack);
143                                     }
144                                 }
145                                 mlt.removeChild(tracksinfo);
146                             }
147
148                             QDomNodeList                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    folders = m_document.elementsByTagName("folder");
149                             for (int i = 0; i < folders.count(); i++) {
150                                 e = folders.item(i).cloneNode().toElement();
151                                 m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
152                             }
153
154                             const int infomax = infoproducers.count();
155                             QDomNodeList producers = m_document.elementsByTagName("producer");
156                             const int max = producers.count();
157
158                             KProgressDialog progressDialog(parent, i18n("Loading project"), i18n("Loading project"));
159                             progressDialog.setAllowCancel(false);
160                             progressDialog.progressBar()->setMaximum(infomax - 1);
161                             progressDialog.show();
162
163                             for (int i = 0; i < infomax; i++) {
164                                 e = infoproducers.item(i).cloneNode().toElement();
165                                 QString prodId = e.attribute("id");
166                                 if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
167                                     e.setTagName("producer");
168                                     // Get MLT's original producer properties
169                                     QDomElement orig;
170                                     for (int j = 0; j < max; j++) {
171                                         QDomNode o = producers.item(j);
172                                         QString origId = o.attributes().namedItem("id").nodeValue().section('_', 0, 0);
173                                         if (origId == prodId) {
174                                             orig = o.cloneNode().toElement();
175                                             break;
176                                         }
177                                     }
178
179                                     if (!addClipInfo(e, orig, prodId)) {
180                                         // The user manually aborted the loading.
181                                         success = false;
182                                         emit resetProjectList();
183                                         m_tracksList.clear();
184                                         m_clipManager->clear();
185                                         break;
186                                     }
187                                 }
188                                 progressDialog.progressBar()->setValue(i);
189                             }
190
191                             if (success) {
192                                 QDomElement markers = infoXml.firstChildElement("markers");
193                                 if (!markers.isNull()) {
194                                     QDomNodeList markerslist = markers.childNodes();
195                                     int maxchild = markerslist.count();
196                                     for (int k = 0; k < maxchild; k++) {
197                                         e = markerslist.at(k).toElement();
198                                         if (e.tagName() == "marker")
199                                             m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
200                                     }
201                                     infoXml.removeChild(markers);
202                                 }
203
204                                 m_projectFolder = KUrl(infoXml.attribute("projectfolder"));
205                                 QDomElement docproperties = infoXml.firstChildElement("documentproperties");
206                                 QDomNamedNodeMap props = docproperties.attributes();
207                                 for (int i = 0; i < props.count(); i++)
208                                     m_documentProperties.insert(props.item(i).nodeName(), props.item(i).nodeValue());
209                                 setProfilePath(infoXml.attribute("profile"));
210                                 setModified(validator.isModified());
211                                 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
212                             }
213                         }
214                     }
215                 }
216             }
217         }
218     }
219
220     // Something went wrong, or a new file was requested: create a new project
221     if (!success) {
222         m_url = KUrl();
223         setProfilePath(profileName);
224         m_document = createEmptyDocument(tracks.x(), tracks.y());
225     }
226
227     // Set the video profile (empty == default)
228     KdenliveSettings::setCurrent_profile(profilePath());
229
230     // Ask to create the project directory if it does not exist
231     if (!QFile::exists(m_projectFolder.path())) {
232         int create = KMessageBox::questionYesNo(parent, i18n("Project directory %1 does not exist. Create it?", m_projectFolder.path()));
233         if (create == KMessageBox::Yes) {
234             QDir projectDir(m_projectFolder.path());
235             bool ok = projectDir.mkpath(m_projectFolder.path());
236             if (!ok) {
237                 KMessageBox::sorry(parent, i18n("The directory %1, could not be created.\nPlease make sure you have the required permissions.", m_projectFolder.path()));
238             }
239         }
240     }
241
242     // Make sure the project folder is usable
243     if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
244         KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
245         m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
246     }
247
248     // Make sure that the necessary folders exist
249     KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "titles/");
250     KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/");
251     KStandardDirs::makeDir(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/");
252
253     //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
254     connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
255 }
256
257 KdenliveDoc::~KdenliveDoc()
258 {
259     m_autoSaveTimer->stop();
260     delete m_commandStack;
261     kDebug() << "// DEL CLP MAN";
262     delete m_clipManager;
263     kDebug() << "// DEL CLP MAN done";
264     delete m_autoSaveTimer;
265     if (m_autosave) {
266         if (!m_autosave->fileName().isEmpty()) m_autosave->remove();
267         delete m_autosave;
268     }
269 }
270
271 int KdenliveDoc::setSceneList()
272 {
273     m_render->resetProfile(KdenliveSettings::current_profile());
274     if (m_render->setSceneList(m_document.toString(), m_documentProperties.value("position").toInt()) == -1) {
275         // INVALID MLT Consumer, something is wrong
276         return -1;
277     }
278     m_documentProperties.remove("position");
279     // m_document xml is now useless, clear it
280     m_document.clear();
281     return 0;
282 }
283
284 QDomDocument KdenliveDoc::createEmptyDocument(int videotracks, int audiotracks)
285 {
286     m_tracksList.clear();
287
288     // Tracks are added Â«backwards», so we need to reverse the track numbering
289     // mbt 331: http://www.kdenlive.org/mantis/view.php?id=331
290     // Better default names for tracks: Audio 1 etc. instead of blank numbers
291     for (int i = 0; i < audiotracks; i++) {
292         TrackInfo audioTrack;
293         audioTrack.type = AUDIOTRACK;
294         audioTrack.isMute = false;
295         audioTrack.isBlind = true;
296         audioTrack.isLocked = false;
297         audioTrack.trackName = QString("Audio ") + QString::number(audiotracks - i);
298         m_tracksList.append(audioTrack);
299
300     }
301     for (int i = 0; i < videotracks; i++) {
302         TrackInfo videoTrack;
303         videoTrack.type = VIDEOTRACK;
304         videoTrack.isMute = false;
305         videoTrack.isBlind = false;
306         videoTrack.isLocked = false;
307         videoTrack.trackName = QString("Video ") + QString::number(videotracks - i);
308         m_tracksList.append(videoTrack);
309     }
310     return createEmptyDocument(m_tracksList);
311 }
312
313 QDomDocument KdenliveDoc::createEmptyDocument(QList <TrackInfo> tracks)
314 {
315     // Creating new document
316     QDomDocument doc;
317     QDomElement mlt = doc.createElement("mlt");
318     doc.appendChild(mlt);
319
320
321     // Create black producer
322     // For some unknown reason, we have to build the black producer here and not in renderer.cpp, otherwise
323     // the composite transitions with the black track are corrupted.
324     QDomElement blk = doc.createElement("producer");
325     blk.setAttribute("in", 0);
326     blk.setAttribute("out", 500);
327     blk.setAttribute("id", "black");
328
329     QDomElement property = doc.createElement("property");
330     property.setAttribute("name", "mlt_type");
331     QDomText value = doc.createTextNode("producer");
332     property.appendChild(value);
333     blk.appendChild(property);
334
335     property = doc.createElement("property");
336     property.setAttribute("name", "aspect_ratio");
337     value = doc.createTextNode(QString::number(0.0));
338     property.appendChild(value);
339     blk.appendChild(property);
340
341     property = doc.createElement("property");
342     property.setAttribute("name", "length");
343     value = doc.createTextNode(QString::number(15000));
344     property.appendChild(value);
345     blk.appendChild(property);
346
347     property = doc.createElement("property");
348     property.setAttribute("name", "eof");
349     value = doc.createTextNode("pause");
350     property.appendChild(value);
351     blk.appendChild(property);
352
353     property = doc.createElement("property");
354     property.setAttribute("name", "resource");
355     value = doc.createTextNode("black");
356     property.appendChild(value);
357     blk.appendChild(property);
358
359     property = doc.createElement("property");
360     property.setAttribute("name", "mlt_service");
361     value = doc.createTextNode("colour");
362     property.appendChild(value);
363     blk.appendChild(property);
364
365     mlt.appendChild(blk);
366
367
368     QDomElement tractor = doc.createElement("tractor");
369     tractor.setAttribute("id", "maintractor");
370     QDomElement multitrack = doc.createElement("multitrack");
371     QDomElement playlist = doc.createElement("playlist");
372     playlist.setAttribute("id", "black_track");
373     mlt.appendChild(playlist);
374
375     QDomElement blank0 = doc.createElement("entry");
376     blank0.setAttribute("in", "0");
377     blank0.setAttribute("out", "1");
378     blank0.setAttribute("producer", "black");
379     playlist.appendChild(blank0);
380
381     // create playlists
382     int total = tracks.count() + 1;
383
384     for (int i = 1; i < total; i++) {
385         QDomElement playlist = doc.createElement("playlist");
386         playlist.setAttribute("id", "playlist" + QString::number(i));
387         mlt.appendChild(playlist);
388     }
389
390     QDomElement track0 = doc.createElement("track");
391     track0.setAttribute("producer", "black_track");
392     tractor.appendChild(track0);
393
394     // create audio and video tracks
395     for (int i = 1; i < total; i++) {
396         QDomElement track = doc.createElement("track");
397         track.setAttribute("producer", "playlist" + QString::number(i));
398         if (tracks.at(i - 1).type == AUDIOTRACK) {
399             track.setAttribute("hide", "video");
400         } else if (tracks.at(i - 1).isBlind)
401             track.setAttribute("hide", "video");
402         if (tracks.at(i - 1).isMute)
403             track.setAttribute("hide", "audio");
404         tractor.appendChild(track);
405     }
406
407     for (int i = 2; i < total ; i++) {
408         QDomElement transition = doc.createElement("transition");
409         transition.setAttribute("always_active", "1");
410
411         QDomElement property = doc.createElement("property");
412         property.setAttribute("name", "a_track");
413         QDomText value = doc.createTextNode(QString::number(1));
414         property.appendChild(value);
415         transition.appendChild(property);
416
417         property = doc.createElement("property");
418         property.setAttribute("name", "b_track");
419         value = doc.createTextNode(QString::number(i));
420         property.appendChild(value);
421         transition.appendChild(property);
422
423         property = doc.createElement("property");
424         property.setAttribute("name", "mlt_service");
425         value = doc.createTextNode("mix");
426         property.appendChild(value);
427         transition.appendChild(property);
428
429         property = doc.createElement("property");
430         property.setAttribute("name", "combine");
431         value = doc.createTextNode("1");
432         property.appendChild(value);
433         transition.appendChild(property);
434
435         property = doc.createElement("property");
436         property.setAttribute("name", "internal_added");
437         value = doc.createTextNode("237");
438         property.appendChild(value);
439         transition.appendChild(property);
440         tractor.appendChild(transition);
441     }
442     mlt.appendChild(tractor);
443     return doc;
444 }
445
446
447 void KdenliveDoc::syncGuides(QList <Guide *> guides)
448 {
449     m_guidesXml.clear();
450     QDomElement guideNode = m_guidesXml.createElement("guides");
451     m_guidesXml.appendChild(guideNode);
452     QDomElement e;
453
454     for (int i = 0; i < guides.count(); i++) {
455         e = m_guidesXml.createElement("guide");
456         e.setAttribute("time", guides.at(i)->position().ms() / 1000);
457         e.setAttribute("comment", guides.at(i)->label());
458         guideNode.appendChild(e);
459     }
460     setModified(true);
461     emit guidesUpdated();
462 }
463
464 QDomElement KdenliveDoc::guidesXml() const
465 {
466     return m_guidesXml.documentElement();
467 }
468
469 void KdenliveDoc::slotAutoSave()
470 {
471     if (m_render && m_autosave) {
472         if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
473             // show error: could not open the autosave file
474             kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
475         }
476         kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
477         QString doc;
478         if (KdenliveSettings::dropbframes()) {
479             KdenliveSettings::setDropbframes(false);
480             m_clipManager->updatePreviewSettings();
481             doc = m_render->sceneList();
482             KdenliveSettings::setDropbframes(true);
483             m_clipManager->updatePreviewSettings();
484         } else doc = m_render->sceneList();
485         saveSceneList(m_autosave->fileName(), doc);
486     }
487 }
488
489 void KdenliveDoc::setZoom(int horizontal, int vertical)
490 {
491     m_documentProperties["zoom"] = QString::number(horizontal);
492     m_documentProperties["verticalzoom"] = QString::number(vertical);
493 }
494
495 QPoint KdenliveDoc::zoom() const
496 {
497     return QPoint(m_documentProperties.value("zoom").toInt(), m_documentProperties.value("verticalzoom").toInt());
498 }
499
500 void KdenliveDoc::setZone(int start, int end)
501 {
502     m_documentProperties["zonein"] = QString::number(start);
503     m_documentProperties["zoneout"] = QString::number(end);
504 }
505
506 QPoint KdenliveDoc::zone() const
507 {
508     return QPoint(m_documentProperties.value("zonein").toInt(), m_documentProperties.value("zoneout").toInt());
509 }
510
511 bool KdenliveDoc::saveSceneList(const QString &path, const QString &scene)
512 {
513     QDomDocument sceneList;
514     sceneList.setContent(scene, true);
515     QDomElement mlt = sceneList.firstChildElement("mlt");
516     if (mlt.isNull() || !mlt.hasChildNodes()) {
517         //Make sure we don't save if scenelist is corrupted
518         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1, scene list is corrupted.", path));
519         return false;
520     }
521
522     QDomElement addedXml = sceneList.createElement("kdenlivedoc");
523     mlt.appendChild(addedXml);
524
525     // check if project contains custom effects to embed them in project file
526     QDomNodeList effects = mlt.elementsByTagName("filter");
527     int maxEffects = effects.count();
528     kDebug() << "// FOUD " << maxEffects << " EFFECTS+++++++++++++++++++++";
529     QMap <QString, QString> effectIds;
530     for (int i = 0; i < maxEffects; i++) {
531         QDomNode m = effects.at(i);
532         QDomNodeList params = m.childNodes();
533         QString id;
534         QString tag;
535         for (int j = 0; j < params.count(); j++) {
536             QDomElement e = params.item(j).toElement();
537             if (e.attribute("name") == "kdenlive_id") {
538                 id = e.firstChild().nodeValue();
539             }
540             if (e.attribute("name") == "tag") {
541                 tag = e.firstChild().nodeValue();
542             }
543             if (!id.isEmpty() && !tag.isEmpty()) effectIds.insert(id, tag);
544         }
545     }
546     QDomDocument customeffects = initEffects::getUsedCustomEffects(effectIds);
547     addedXml.appendChild(sceneList.importNode(customeffects.documentElement(), true));
548
549     QDomElement markers = sceneList.createElement("markers");
550     addedXml.setAttribute("version", DOCUMENTVERSION);
551     addedXml.setAttribute("kdenliveversion", VERSION);
552     addedXml.setAttribute("profile", profilePath());
553     addedXml.setAttribute("projectfolder", m_projectFolder.path());
554
555     QDomElement docproperties = sceneList.createElement("documentproperties");
556     QMapIterator<QString, QString> i(m_documentProperties);
557     while (i.hasNext()) {
558         i.next();
559         docproperties.setAttribute(i.key(), i.value());
560     }
561     docproperties.setAttribute("position", m_render->seekPosition().frames(m_fps));
562     addedXml.appendChild(docproperties);
563
564     QDomElement docnotes = sceneList.createElement("documentnotes");
565     QDomText value = sceneList.createTextNode(m_notesWidget->toPlainText());
566     docnotes.appendChild(value);
567     addedXml.appendChild(docnotes);
568
569     // Add profile info
570     QDomElement profileinfo = sceneList.createElement("profileinfo");
571     profileinfo.setAttribute("description", m_profile.description);
572     profileinfo.setAttribute("frame_rate_num", m_profile.frame_rate_num);
573     profileinfo.setAttribute("frame_rate_den", m_profile.frame_rate_den);
574     profileinfo.setAttribute("width", m_profile.width);
575     profileinfo.setAttribute("height", m_profile.height);
576     profileinfo.setAttribute("progressive", m_profile.progressive);
577     profileinfo.setAttribute("sample_aspect_num", m_profile.sample_aspect_num);
578     profileinfo.setAttribute("sample_aspect_den", m_profile.sample_aspect_den);
579     profileinfo.setAttribute("display_aspect_num", m_profile.display_aspect_num);
580     profileinfo.setAttribute("display_aspect_den", m_profile.display_aspect_den);
581     addedXml.appendChild(profileinfo);
582
583     // tracks info
584     QDomElement tracksinfo = sceneList.createElement("tracksinfo");
585     foreach(const TrackInfo & info, m_tracksList) {
586         QDomElement trackinfo = sceneList.createElement("trackinfo");
587         if (info.type == AUDIOTRACK) trackinfo.setAttribute("type", "audio");
588         trackinfo.setAttribute("mute", info.isMute);
589         trackinfo.setAttribute("blind", info.isBlind);
590         trackinfo.setAttribute("locked", info.isLocked);
591         trackinfo.setAttribute("trackname", info.trackName);
592         tracksinfo.appendChild(trackinfo);
593     }
594     addedXml.appendChild(tracksinfo);
595
596     // save project folders
597     QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
598
599     QMapIterator<QString, QString> f(folderlist);
600     while (f.hasNext()) {
601         f.next();
602         QDomElement folder = sceneList.createElement("folder");
603         folder.setAttribute("id", f.key());
604         folder.setAttribute("name", f.value());
605         addedXml.appendChild(folder);
606     }
607
608     // Save project clips
609     QDomElement e;
610     QList <DocClipBase*> list = m_clipManager->documentClipList();
611     for (int i = 0; i < list.count(); i++) {
612         e = list.at(i)->toXML();
613         e.setTagName("kdenlive_producer");
614         addedXml.appendChild(sceneList.importNode(e, true));
615         QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
616         for (int j = 0; j < marks.count(); j++) {
617             QDomElement marker = sceneList.createElement("marker");
618             marker.setAttribute("time", marks.at(j).time().ms() / 1000);
619             marker.setAttribute("comment", marks.at(j).comment());
620             marker.setAttribute("id", e.attribute("id"));
621             markers.appendChild(marker);
622         }
623     }
624     addedXml.appendChild(markers);
625
626     // Add guides
627     if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml.documentElement(), true));
628
629     // Add clip groups
630     addedXml.appendChild(sceneList.importNode(m_clipManager->groupsXml(), true));
631
632     //wes.appendChild(doc.importNode(kdenliveData, true));
633
634     QFile file(path);
635     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
636         kWarning() << "//////  ERROR writing to file: " << path;
637         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
638         return false;
639     }
640
641     file.write(sceneList.toString().toUtf8());
642     if (file.error() != QFile::NoError) {
643         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
644         file.close();
645         return false;
646     }
647     file.close();
648     return true;
649 }
650
651 ClipManager *KdenliveDoc::clipManager()
652 {
653     return m_clipManager;
654 }
655
656 KUrl KdenliveDoc::projectFolder() const
657 {
658     //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
659     return m_projectFolder;
660 }
661
662 void KdenliveDoc::setProjectFolder(KUrl url)
663 {
664     if (url == m_projectFolder) return;
665     setModified(true);
666     KStandardDirs::makeDir(url.path());
667     KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "titles/");
668     KStandardDirs::makeDir(url.path(KUrl::AddTrailingSlash) + "thumbs/");
669     if (KMessageBox::questionYesNo(kapp->activeWindow(), i18n("You have changed the project folder. Do you want to copy the cached data from %1 to the new folder %2?").arg(m_projectFolder.path(), url.path())) == KMessageBox::Yes) moveProjectData(url);
670     m_projectFolder = url;
671 }
672
673 void KdenliveDoc::moveProjectData(KUrl url)
674 {
675     QList <DocClipBase*> list = m_clipManager->documentClipList();
676     //TODO: Also move ladspa effects files
677     for (int i = 0; i < list.count(); i++) {
678         DocClipBase *clip = list.at(i);
679         if (clip->clipType() == TEXT) {
680             // the image for title clip must be moved
681             KUrl oldUrl = clip->fileURL();
682             KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "titles/" + oldUrl.fileName());
683             KIO::Job *job = KIO::copy(oldUrl, newUrl);
684             if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
685         }
686         QString hash = clip->getClipHash();
687         KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
688         KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
689         if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
690             KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".png");
691             KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
692             KIO::NetAccess::synchronousRun(job, 0);
693         }
694         if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
695             KUrl newUrl = KUrl(url.path(KUrl::AddTrailingSlash) + "thumbs/" + hash + ".thumb");
696             KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
697             if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
698         }
699     }
700 }
701
702 const QString &KdenliveDoc::profilePath() const
703 {
704     return m_profile.path;
705 }
706
707 MltVideoProfile KdenliveDoc::mltProfile() const
708 {
709     return m_profile;
710 }
711
712 bool KdenliveDoc::setProfilePath(QString path)
713 {
714     if (path.isEmpty()) path = KdenliveSettings::default_profile();
715     if (path.isEmpty()) path = "dv_pal";
716     m_profile = ProfilesDialog::getVideoProfile(path);
717     bool current_fps = m_fps;
718     if (m_profile.path.isEmpty()) {
719         // Profile not found, use embedded profile
720         QDomElement profileInfo = m_document.elementsByTagName("profileinfo").at(0).toElement();
721         if (profileInfo.isNull()) {
722             KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, using default profile."), i18n("Missing Profile"));
723             m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
724         } else {
725             m_profile.description = profileInfo.attribute("description");
726             m_profile.frame_rate_num = profileInfo.attribute("frame_rate_num").toInt();
727             m_profile.frame_rate_den = profileInfo.attribute("frame_rate_den").toInt();
728             m_profile.width = profileInfo.attribute("width").toInt();
729             m_profile.height = profileInfo.attribute("height").toInt();
730             m_profile.progressive = profileInfo.attribute("progressive").toInt();
731             m_profile.sample_aspect_num = profileInfo.attribute("sample_aspect_num").toInt();
732             m_profile.sample_aspect_den = profileInfo.attribute("sample_aspect_den").toInt();
733             m_profile.display_aspect_num = profileInfo.attribute("display_aspect_num").toInt();
734             m_profile.display_aspect_den = profileInfo.attribute("display_aspect_den").toInt();
735             QString existing = ProfilesDialog::existingProfile(m_profile);
736             if (!existing.isEmpty()) {
737                 m_profile = ProfilesDialog::getVideoProfile(existing);
738                 KMessageBox::information(kapp->activeWindow(), i18n("Project profile not found, replacing with existing one: %1", m_profile.description), i18n("Missing Profile"));
739             } else {
740                 QString newDesc = m_profile.description;
741                 bool ok = true;
742                 while (ok && (newDesc.isEmpty() || ProfilesDialog::existingProfileDescription(newDesc))) {
743                     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);
744                 }
745                 if (ok == false) {
746                     // User canceled, use default profile
747                     m_profile = ProfilesDialog::getVideoProfile(KdenliveSettings::default_profile());
748                 } else {
749                     if (newDesc != m_profile.description) {
750                         // Profile description existed, was replaced by new one
751                         m_profile.description = newDesc;
752                     } else {
753                         KMessageBox::information(kapp->activeWindow(), i18n("Project profile was not found, it will be added to your system now."), i18n("Missing Profile"));
754                     }
755                     ProfilesDialog::saveProfile(m_profile);
756                 }
757             }
758             setModified(true);
759         }
760     }
761
762     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
763     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
764     KdenliveSettings::setProject_fps(m_fps);
765     m_width = m_profile.width;
766     m_height = m_profile.height;
767     kDebug() << "Kdenlive document, init timecode from path: " << path << ",  " << m_fps;
768     m_timecode.setFormat(m_fps);
769     return (current_fps != m_fps);
770 }
771
772 double KdenliveDoc::dar() const
773 {
774     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
775 }
776
777 void KdenliveDoc::setThumbsProgress(const QString &message, int progress)
778 {
779     emit progressInfo(message, progress);
780 }
781
782 QUndoStack *KdenliveDoc::commandStack()
783 {
784     return m_commandStack;
785 }
786
787 /*
788 void KdenliveDoc::setRenderer(Render *render) {
789     if (m_render) return;
790     m_render = render;
791     emit progressInfo(i18n("Loading playlist..."), 0);
792     //qApp->processEvents();
793     if (m_render) {
794         m_render->setSceneList(m_document.toString(), m_startPos);
795         kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
796         checkProjectClips();
797     }
798     emit progressInfo(QString(), -1);
799 }*/
800
801 void KdenliveDoc::checkProjectClips()
802 {
803     if (m_render == NULL) return;
804     m_clipManager->resetProducersList(m_render->producersList());
805 }
806
807 void KdenliveDoc::updatePreviewSettings()
808 {
809     m_clipManager->updatePreviewSettings();
810     m_render->updatePreviewSettings();
811     QList <Mlt::Producer *> prods = m_render->producersList();
812     m_clipManager->resetProducersList(m_render->producersList());
813     qDeleteAll(prods);
814     prods.clear();
815 }
816
817 Render *KdenliveDoc::renderer()
818 {
819     return m_render;
820 }
821
822 void KdenliveDoc::updateClip(const QString id)
823 {
824     emit updateClipDisplay(id);
825 }
826
827 int KdenliveDoc::getFramePos(QString duration)
828 {
829     return m_timecode.getFrameCount(duration);
830 }
831
832 QString KdenliveDoc::producerName(const QString &id)
833 {
834     QString result = "unnamed";
835     QDomNodeList prods = producersList();
836     int ct = prods.count();
837     for (int i = 0; i <  ct ; i++) {
838         QDomElement e = prods.item(i).toElement();
839         if (e.attribute("id") != "black" && e.attribute("id") == id) {
840             result = e.attribute("name");
841             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
842             break;
843         }
844     }
845     return result;
846 }
847
848 QDomDocument KdenliveDoc::toXml()
849 {
850     return m_document;
851 }
852
853 Timecode KdenliveDoc::timecode() const
854 {
855     return m_timecode;
856 }
857
858 QDomNodeList KdenliveDoc::producersList()
859 {
860     return m_document.elementsByTagName("producer");
861 }
862
863 double KdenliveDoc::projectDuration() const
864 {
865     if (m_render)
866         return GenTime(m_render->getLength(), m_fps).ms() / 1000;
867     else
868         return 0;
869 }
870
871 double KdenliveDoc::fps() const
872 {
873     return m_fps;
874 }
875
876 int KdenliveDoc::width() const
877 {
878     return m_width;
879 }
880
881 int KdenliveDoc::height() const
882 {
883     return m_height;
884 }
885
886 KUrl KdenliveDoc::url() const
887 {
888     return m_url;
889 }
890
891 void KdenliveDoc::setUrl(KUrl url)
892 {
893     m_url = url;
894 }
895
896 void KdenliveDoc::setModified(bool mod)
897 {
898     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
899         m_autoSaveTimer->start(3000);
900     }
901     if (mod == m_modified) return;
902     m_modified = mod;
903     emit docModified(m_modified);
904 }
905
906 bool KdenliveDoc::isModified() const
907 {
908     return m_modified;
909 }
910
911 const QString KdenliveDoc::description() const
912 {
913     if (m_url.isEmpty())
914         return i18n("Untitled") + " / " + m_profile.description;
915     else
916         return m_url.fileName() + " / " + m_profile.description;
917 }
918
919 bool KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem)
920 {
921     const QString producerId = clipId.section('_', 0, 0);
922     DocClipBase *clip = m_clipManager->getClipById(producerId);
923
924     if (clip == NULL) {
925         elem.setAttribute("id", producerId);
926         QString path = elem.attribute("resource");
927         QString extension;
928         if (elem.attribute("type").toInt() == SLIDESHOW) {
929             extension = KUrl(path).fileName();
930             path = KUrl(path).directory();
931         }
932
933         if (path.isEmpty() == false && QFile::exists(path) == false && elem.attribute("type").toInt() != TEXT && !elem.hasAttribute("placeholder")) {
934             kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
935             const QString size = elem.attribute("file_size");
936             const QString hash = elem.attribute("file_hash");
937             QString newpath;
938             int action = KMessageBox::No;
939             if (!size.isEmpty() && !hash.isEmpty()) {
940                 if (!m_searchFolder.isEmpty())
941                     newpath = searchFileRecursively(m_searchFolder, size, hash);
942                 else
943                     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")));
944             } else {
945                 if (elem.attribute("type").toInt() == SLIDESHOW) {
946                     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")));
947                     if (res == KMessageBox::Yes)
948                         newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
949                     else {
950                         // Abort project loading
951                         action = res;
952                     }
953                 } else {
954                     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")));
955                     if (res == KMessageBox::Yes)
956                         newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
957                     else {
958                         // Abort project loading
959                         action = res;
960                     }
961                 }
962             }
963             if (action == KMessageBox::Yes) {
964                 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
965                 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
966                 if (!m_searchFolder.isEmpty())
967                     newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
968             } else if (action == KMessageBox::Cancel) {
969                 return false;
970             } else if (action == KMessageBox::No) {
971                 // Keep clip as placeHolder
972                 elem.setAttribute("placeholder", '1');
973             }
974             if (!newpath.isEmpty()) {
975                 if (elem.attribute("type").toInt() == SLIDESHOW)
976                     newpath.append('/' + extension);
977                 elem.setAttribute("resource", newpath);
978                 setNewClipResource(clipId, newpath);
979                 setModified(true);
980             }
981         }
982         clip = new DocClipBase(m_clipManager, elem, producerId);
983         m_clipManager->addClip(clip);
984     }
985
986     if (createClipItem) {
987         emit addProjectClip(clip);
988         //qApp->processEvents();
989     }
990
991     return true;
992 }
993
994 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path)
995 {
996     QDomNodeList prods = m_document.elementsByTagName("producer");
997     int maxprod = prods.count();
998     for (int i = 0; i < maxprod; i++) {
999         QDomNode m = prods.at(i);
1000         QString prodId = m.toElement().attribute("id");
1001         if (prodId == id || prodId.startsWith(id + '_')) {
1002             QDomNodeList params = m.childNodes();
1003             for (int j = 0; j < params.count(); j++) {
1004                 QDomElement e = params.item(j).toElement();
1005                 if (e.attribute("name") == "resource") {
1006                     e.firstChild().setNodeValue(path);
1007                     break;
1008                 }
1009             }
1010         }
1011     }
1012 }
1013
1014 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
1015 {
1016     QString foundFileName;
1017     QByteArray fileData;
1018     QByteArray fileHash;
1019     QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1020     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1021         QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1022         if (file.open(QIODevice::ReadOnly)) {
1023             if (QString::number(file.size()) == matchSize) {
1024                 /*
1025                 * 1 MB = 1 second per 450 files (or faster)
1026                 * 10 MB = 9 seconds per 450 files (or faster)
1027                 */
1028                 if (file.size() > 1000000 * 2) {
1029                     fileData = file.read(1000000);
1030                     if (file.seek(file.size() - 1000000))
1031                         fileData.append(file.readAll());
1032                 } else
1033                     fileData = file.readAll();
1034                 file.close();
1035                 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1036                 if (QString(fileHash.toHex()) == matchHash)
1037                     return file.fileName();
1038             }
1039         }
1040         kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1041     }
1042     filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1043     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1044         foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1045         if (!foundFileName.isEmpty())
1046             break;
1047     }
1048     return foundFileName;
1049 }
1050
1051 bool KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId)
1052 {
1053     DocClipBase *clip = m_clipManager->getClipById(clipId);
1054     if (clip == NULL) {
1055         if (!addClip(elem, clipId, false))
1056             return false;
1057     } else {
1058         QMap <QString, QString> properties;
1059         QDomNamedNodeMap attributes = elem.attributes();
1060         for (int i = 0; i < attributes.count(); i++) {
1061             QString attrname = attributes.item(i).nodeName();
1062             if (attrname != "resource")
1063                 properties.insert(attrname, attributes.item(i).nodeValue());
1064             kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1065         }
1066         clip->setProperties(properties);
1067         emit addProjectClip(clip, false);
1068     }
1069     if (orig != QDomElement()) {
1070         QMap<QString, QString> meta;
1071         for (QDomNode m = orig.firstChild(); !m.isNull(); m = m.nextSibling()) {
1072             QString name = m.toElement().attribute("name");
1073             if (name.startsWith("meta.attr"))
1074                 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1075         }
1076         if (!meta.isEmpty()) {
1077             if (clip == NULL)
1078                 clip = m_clipManager->getClipById(clipId);
1079             if (clip)
1080                 clip->setMetadata(meta);
1081         }
1082     }
1083     return true;
1084 }
1085
1086
1087 void KdenliveDoc::deleteClip(const QString &clipId)
1088 {
1089     emit signalDeleteProjectClip(clipId);
1090 }
1091
1092 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId)
1093 {
1094     m_clipManager->slotAddClipList(urls, group, groupId);
1095     //emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1096     setModified(true);
1097 }
1098
1099
1100 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId)
1101 {
1102     m_clipManager->slotAddClipFile(url, group, groupId);
1103     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1104     setModified(true);
1105 }
1106
1107 const QString KdenliveDoc::getFreeClipId()
1108 {
1109     return QString::number(m_clipManager->getFreeClipId());
1110 }
1111
1112 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId)
1113 {
1114     return m_clipManager->getClipById(clipId);
1115 }
1116
1117 void KdenliveDoc::slotCreateXmlClip(const QString &name, const QDomElement xml, QString group, const QString &groupId)
1118 {
1119     m_clipManager->slotAddXmlClipFile(name, xml, group, groupId);
1120     setModified(true);
1121     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1122 }
1123
1124 void KdenliveDoc::slotCreateColorClip(const QString &name, const QString &color, const QString &duration, QString group, const QString &groupId)
1125 {
1126     m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1127     setModified(true);
1128     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1129 }
1130
1131 void KdenliveDoc::slotCreateSlideshowClipFile(const QString name, const QString path, int count, const QString duration,
1132         const bool loop, const bool crop, const bool fade,
1133         const QString &luma_duration, const QString &luma_file, const int softness,
1134         const QString &animation, QString group, const QString &groupId)
1135 {
1136     m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop,
1137                                             crop, fade, luma_duration,
1138                                             luma_file, softness,
1139                                             animation, group, groupId);
1140     setModified(true);
1141     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1142 }
1143
1144 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId, const QString &templatePath)
1145 {
1146     QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1147     KStandardDirs::makeDir(titlesFolder);
1148     TitleWidget *dia_ui = new TitleWidget(templatePath, m_timecode, titlesFolder, m_render, kapp->activeWindow());
1149     if (dia_ui->exec() == QDialog::Accepted) {
1150         m_clipManager->slotAddTextClipFile(i18n("Title clip"), dia_ui->outPoint(), dia_ui->xml().toString(), group, groupId);
1151         setModified(true);
1152         emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1153     }
1154     delete dia_ui;
1155 }
1156
1157 void KdenliveDoc::slotCreateTextTemplateClip(QString group, const QString &groupId, KUrl path)
1158 {
1159     QString titlesFolder = projectFolder().path(KUrl::AddTrailingSlash) + "titles/";
1160     if (path.isEmpty()) {
1161         path = KFileDialog::getOpenUrl(KUrl(titlesFolder), "*.kdenlivetitle", kapp->activeWindow(), i18n("Enter Template Path"));
1162     }
1163
1164     if (path.isEmpty()) return;
1165
1166     //TODO: rewrite with new title system (just set resource)
1167     m_clipManager->slotAddTextTemplateClip(i18n("Template title clip"), path, group, groupId);
1168     setModified(true);
1169     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1170 }
1171
1172 int KdenliveDoc::tracksCount() const
1173 {
1174     return m_tracksList.count();
1175 }
1176
1177 TrackInfo KdenliveDoc::trackInfoAt(int ix) const
1178 {
1179     if (ix < 0 || ix >= m_tracksList.count()) {
1180         kWarning() << "Track INFO outisde of range";
1181         return TrackInfo();
1182     }
1183     return m_tracksList.at(ix);
1184 }
1185
1186 void KdenliveDoc::switchTrackAudio(int ix, bool hide)
1187 {
1188     if (ix < 0 || ix >= m_tracksList.count()) {
1189         kWarning() << "SWITCH Track outisde of range";
1190         return;
1191     }
1192     m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1193 }
1194
1195 void KdenliveDoc::switchTrackLock(int ix, bool lock)
1196 {
1197     if (ix < 0 || ix >= m_tracksList.count()) {
1198         kWarning() << "Track Lock outisde of range";
1199         return;
1200     }
1201     m_tracksList[ix].isLocked = lock;
1202 }
1203
1204 bool KdenliveDoc::isTrackLocked(int ix) const
1205 {
1206     if (ix < 0 || ix >= m_tracksList.count()) {
1207         kWarning() << "Track Lock outisde of range";
1208         return true;
1209     }
1210     return m_tracksList.at(ix).isLocked;
1211 }
1212
1213 void KdenliveDoc::switchTrackVideo(int ix, bool hide)
1214 {
1215     if (ix < 0 || ix >= m_tracksList.count()) {
1216         kWarning() << "SWITCH Track outisde of range";
1217         return;
1218     }
1219     m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1220 }
1221
1222 void KdenliveDoc::insertTrack(int ix, TrackInfo type)
1223 {
1224     if (ix == -1) m_tracksList << type;
1225     else m_tracksList.insert(ix, type);
1226 }
1227
1228 void KdenliveDoc::deleteTrack(int ix)
1229 {
1230     if (ix < 0 || ix >= m_tracksList.count()) {
1231         kWarning() << "Delete Track outisde of range";
1232         return;
1233     }
1234     m_tracksList.removeAt(ix);
1235 }
1236
1237 void KdenliveDoc::setTrackType(int ix, TrackInfo type)
1238 {
1239     if (ix < 0 || ix >= m_tracksList.count()) {
1240         kWarning() << "SET Track Type outisde of range";
1241         return;
1242     }
1243     m_tracksList[ix].type = type.type;
1244     m_tracksList[ix].isMute = type.isMute;
1245     m_tracksList[ix].isBlind = type.isBlind;
1246     m_tracksList[ix].isLocked = type.isLocked;
1247     m_tracksList[ix].trackName = type.trackName;
1248 }
1249
1250 const QList <TrackInfo> KdenliveDoc::tracksList() const
1251 {
1252     return m_tracksList;
1253 }
1254
1255 QPoint KdenliveDoc::getTracksCount() const
1256 {
1257     int audio = 0;
1258     int video = 0;
1259     foreach(const TrackInfo & info, m_tracksList) {
1260         if (info.type == VIDEOTRACK) video++;
1261         else audio++;
1262     }
1263     return QPoint(video, audio);
1264 }
1265
1266 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const
1267 {
1268     pix.save(m_projectFolder.path(KUrl::AddTrailingSlash) + "thumbs/" + fileId + ".png");
1269 }
1270
1271 QString KdenliveDoc::getLadspaFile() const
1272 {
1273     int ct = 0;
1274     QString counter = QString::number(ct).rightJustified(5, '0', false);
1275     while (QFile::exists(m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa")) {
1276         ct++;
1277         counter = QString::number(ct).rightJustified(5, '0', false);
1278     }
1279     return m_projectFolder.path(KUrl::AddTrailingSlash) + "ladspa/" + counter + ".ladspa";
1280 }
1281
1282 bool KdenliveDoc::checkDocumentClips(QDomNodeList infoproducers)
1283 {
1284     DocumentChecker d(infoproducers, m_document);
1285     return (d.hasMissingClips() == false);
1286
1287     /*    int clipType;
1288         QDomElement e;
1289         QString id;
1290         QString resource;
1291         QList <QDomElement> missingClips;
1292         for (int i = 0; i < infoproducers.count(); i++) {
1293             e = infoproducers.item(i).toElement();
1294             clipType = e.attribute("type").toInt();
1295             if (clipType == COLOR) continue;
1296             if (clipType == TEXT) {
1297                 //TODO: Check is clip template is missing (xmltemplate) or hash changed
1298                 continue;
1299             }
1300             id = e.attribute("id");
1301             resource = e.attribute("resource");
1302             if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
1303             if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
1304                 // Missing clip found
1305                 missingClips.append(e);
1306             } else {
1307                 // Check if the clip has changed
1308                 if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
1309                     if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
1310                         e.removeAttribute("file_hash");
1311                 }
1312             }
1313         }
1314         if (missingClips.isEmpty()) return true;
1315         DocumentChecker d(missingClips, m_document);
1316         return (d.exec() == QDialog::Accepted);*/
1317 }
1318
1319 void KdenliveDoc::setDocumentProperty(const QString &name, const QString &value)
1320 {
1321     m_documentProperties[name] = value;
1322 }
1323
1324 const QString KdenliveDoc::getDocumentProperty(const QString &name) const
1325 {
1326     return m_documentProperties.value(name);
1327 }
1328
1329 QMap <QString, QString> KdenliveDoc::getRenderProperties() const
1330 {
1331     QMap <QString, QString> renderProperties;
1332     QMapIterator<QString, QString> i(m_documentProperties);
1333     while (i.hasNext()) {
1334         i.next();
1335         if (i.key().startsWith("render")) renderProperties.insert(i.key(), i.value());
1336     }
1337     return renderProperties;
1338 }
1339
1340 void KdenliveDoc::addTrackEffect(int ix, QDomElement effect)
1341 {
1342     if (ix < 0 || ix >= m_tracksList.count()) {
1343         kWarning() << "Add Track effect outisde of range";
1344         return;
1345     }
1346     effect.setAttribute("kdenlive_ix", m_tracksList.at(ix).effectsList.count() + 1);
1347
1348     // Init parameter value & keyframes if required
1349     QDomNodeList params = effect.elementsByTagName("parameter");
1350     for (int i = 0; i < params.count(); i++) {
1351         QDomElement e = params.item(i).toElement();
1352
1353         // Check if this effect has a variable parameter
1354         if (e.attribute("default").startsWith('%')) {
1355             double evaluatedValue = ProfilesDialog::getStringEval(m_profile, e.attribute("default"));
1356             e.setAttribute("default", evaluatedValue);
1357             if (e.hasAttribute("value") && e.attribute("value").startsWith('%')) {
1358                 e.setAttribute("value", evaluatedValue);
1359             }
1360         }
1361
1362         if (!e.isNull() && (e.attribute("type") == "keyframe" || e.attribute("type") == "simplekeyframe")) {
1363             QString def = e.attribute("default");
1364             // Effect has a keyframe type parameter, we need to set the values
1365             if (e.attribute("keyframes").isEmpty()) {
1366                 e.setAttribute("keyframes", "0:" + def + ';');
1367                 kDebug() << "///// EFFECT KEYFRAMES INITED: " << e.attribute("keyframes");
1368                 //break;
1369             }
1370         }
1371     }
1372
1373     m_tracksList[ix].effectsList.append(effect);
1374 }
1375
1376 void KdenliveDoc::removeTrackEffect(int ix, QDomElement effect)
1377 {
1378     if (ix < 0 || ix >= m_tracksList.count()) {
1379         kWarning() << "Remove Track effect outisde of range";
1380         return;
1381     }
1382     QString index;
1383     QString toRemove = effect.attribute("kdenlive_ix");
1384     for (int i = 0; i < m_tracksList.at(ix).effectsList.count(); ++i) {
1385         index = m_tracksList.at(ix).effectsList.at(i).attribute("kdenlive_ix");
1386         if (toRemove == index) {
1387             m_tracksList[ix].effectsList.removeAt(i);
1388             i--;
1389         } else if (index.toInt() > toRemove.toInt()) {
1390             m_tracksList[ix].effectsList.item(i).setAttribute("kdenlive_ix", index.toInt() - 1);
1391         }
1392     }
1393 }
1394
1395 void KdenliveDoc::setTrackEffect(int trackIndex, int effectIndex, QDomElement effect)
1396 {
1397     if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1398         kWarning() << "Set Track effect outisde of range";
1399         return;
1400     }
1401     if (effectIndex < 0 || effectIndex > (m_tracksList.at(trackIndex).effectsList.count() - 1) || effect.isNull()) {
1402         kDebug() << "Invalid effect index: " << effectIndex;
1403         return;
1404     }
1405     effect.setAttribute("kdenlive_ix", effectIndex + 1);
1406     m_tracksList[trackIndex].effectsList.replace(effectIndex, effect);
1407 }
1408
1409 const EffectsList KdenliveDoc::getTrackEffects(int ix)
1410 {
1411     if (ix < 0 || ix >= m_tracksList.count()) {
1412         kWarning() << "Get Track effects outisde of range";
1413         return EffectsList();
1414     }
1415     return m_tracksList.at(ix).effectsList;
1416 }
1417
1418 QDomElement KdenliveDoc::getTrackEffect(int trackIndex, int effectIndex) const
1419 {
1420     if (trackIndex < 0 || trackIndex >= m_tracksList.count()) {
1421         kWarning() << "Get Track effect outisde of range";
1422         return QDomElement();
1423     }
1424     EffectsList list = m_tracksList.at(trackIndex).effectsList;
1425     if (effectIndex > list.count() - 1 || effectIndex < 0 || list.at(effectIndex).isNull()) return QDomElement();
1426     return list.at(effectIndex).cloneNode().toElement();
1427 }
1428
1429 bool KdenliveDoc::saveCustomEffects(QDomNodeList customeffects)
1430 {
1431     QDomElement e;
1432     QStringList importedEffects;
1433     int maxchild = customeffects.count();
1434     for (int i = 0; i < maxchild; i++) {
1435         e = customeffects.at(i).toElement();
1436         QString id = e.attribute("id");
1437         QString tag = e.attribute("tag");
1438         if (!id.isEmpty()) {
1439             // Check if effect exists or save it
1440             if (MainWindow::customEffects.hasEffect(tag, id) == -1) {
1441                 QDomDocument doc;
1442                 doc.appendChild(doc.importNode(e, true));
1443                 QString path = KStandardDirs::locateLocal("appdata", "effects/", true);
1444                 path += id + ".xml";
1445                 if (!QFile::exists(path)) {
1446                     importedEffects << id;
1447                     QFile file(path);
1448                     if (file.open(QFile::WriteOnly | QFile::Truncate)) {
1449                         QTextStream out(&file);
1450                         out << doc.toString();
1451                     }
1452                 }
1453             }
1454         }
1455     }
1456     if (!importedEffects.isEmpty()) KMessageBox::informationList(kapp->activeWindow(), i18n("The following effects were imported from the project:"), importedEffects);
1457     return (!importedEffects.isEmpty());
1458 }
1459
1460 #include "kdenlivedoc.moc"
1461