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