]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
35c81324b04c857e2b3ce95e51adad9f21557553
[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 #include <QCryptographicHash>
21 #include <QFile>
22
23 #include <KDebug>
24 #include <KStandardDirs>
25 #include <KMessageBox>
26 #include <KLocale>
27 #include <KFileDialog>
28 #include <KIO/NetAccess>
29 #include <KIO/CopyJob>
30 #include <KApplication>
31
32
33 #include <mlt++/Mlt.h>
34
35 #include "kdenlivedoc.h"
36 #include "docclipbase.h"
37 #include "profilesdialog.h"
38 #include "kdenlivesettings.h"
39 #include "renderer.h"
40 #include "clipmanager.h"
41 #include "titlewidget.h"
42 #include "mainwindow.h"
43
44 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, const QString &profileName, const QPoint tracks, Render *render, MainWindow *parent): QObject(parent), m_render(render), m_url(url), m_projectFolder(projectFolder), m_commandStack(new QUndoStack(undoGroup)), m_modified(false), m_documentLoadingProgress(0), m_documentLoadingStep(0.0), m_startPos(0), m_zoom(7), m_autosave(NULL), m_zoneStart(0), m_zoneEnd(100), m_abortLoading(false) {
45     m_clipManager = new ClipManager(this);
46     m_autoSaveTimer = new QTimer(this);
47     m_autoSaveTimer->setSingleShot(true);
48     if (!url.isEmpty()) {
49         QString tmpFile;
50         if (KIO::NetAccess::download(url.path(), tmpFile, parent)) {
51             QFile file(tmpFile);
52             m_document.setContent(&file, false);
53             file.close();
54             QDomNode infoXmlNode = m_document.elementsByTagName("kdenlivedoc").at(0);
55             QDomNode westley = m_document.elementsByTagName("westley").at(0);
56             if (!infoXmlNode.isNull()) {
57                 QDomElement infoXml = infoXmlNode.toElement();
58                 double version = infoXml.attribute("version").toDouble();
59
60                 // Upgrade old Kdenlive documents to current version
61                 if (!convertDocument(version)) {
62                     KMessageBox::sorry(parent, i18n("This project type is unsupported and can't be loaded."), i18n("Unable to open project"));
63                     m_document = createEmptyDocument(tracks.x(), tracks.y());
64                     setProfilePath(profileName);
65                 } else {
66                     /*
67                      * read again <kdenlivedoc> and <westley> to get all the new
68                      * stuff (convertDocument() can now do anything without breaking
69                      * document loading)
70                      */
71                     infoXmlNode = m_document.elementsByTagName("kdenlivedoc").at(0);
72                     infoXml = infoXmlNode.toElement();
73                     version = infoXml.attribute("version").toDouble();
74                     westley = m_document.elementsByTagName("westley").at(0);
75
76                     QString profilePath = infoXml.attribute("profile");
77                     QString projectFolderPath = infoXml.attribute("projectfolder");
78                     if (!projectFolderPath.isEmpty()) m_projectFolder = KUrl(projectFolderPath);
79
80                     if (m_projectFolder.isEmpty() || !KIO::NetAccess::exists(m_projectFolder.path(), KIO::NetAccess::DestinationSide, parent)) {
81                         // Make sure the project folder is usable
82                         KMessageBox::information(parent, i18n("Document project folder is invalid, setting it to the default one: %1", KdenliveSettings::defaultprojectfolder()));
83                         m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
84                     }
85                     m_startPos = infoXml.attribute("position").toInt();
86                     m_zoom = infoXml.attribute("zoom", "7").toInt();
87
88
89
90
91                     m_zoneEnd = infoXml.attribute("zoneout", "100").toInt();
92                     setProfilePath(profilePath);
93
94                     // Build tracks
95                     QString xmltracks = infoXml.attribute("tracks");
96                     TrackInfo videoTrack;
97                     videoTrack.type = VIDEOTRACK;
98                     videoTrack.isMute = false;
99                     videoTrack.isBlind = false;
100                     videoTrack.isLocked = false;
101
102                     TrackInfo audioTrack;
103                     audioTrack.type = AUDIOTRACK;
104                     audioTrack.isMute = false;
105                     audioTrack.isBlind = true;
106                     audioTrack.isLocked = false;
107
108                     for (int i = 0; i < xmltracks.size(); i++) {
109                         if (xmltracks.data()[i] == 'v') m_tracksList.append(videoTrack);
110                         else m_tracksList.append(audioTrack);
111                     }
112
113
114                     QDomElement e;
115                     QDomElement orig;
116                     QDomNodeList producers = m_document.elementsByTagName("producer");
117                     QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
118                     const int max = producers.count();
119                     const int infomax = infoproducers.count();
120
121                     QDomNodeList folders = m_document.elementsByTagName("folder");
122                     for (int i = 0; i < folders.count(); i++) {
123                         e = folders.item(i).cloneNode().toElement();
124                         m_clipManager->addFolder(e.attribute("id"), e.attribute("name"));
125                     }
126
127                     if (max > 0) {
128                         m_documentLoadingStep = 100.0 / (max + infomax + m_document.elementsByTagName("entry").count());
129                         parent->slotGotProgressInfo(i18n("Loading project clips"), (int) m_documentLoadingProgress);
130                     }
131
132
133                     for (int i = 0; i < infomax && !m_abortLoading; i++) {
134                         e = infoproducers.item(i).cloneNode().toElement();
135                         if (m_documentLoadingStep > 0) {
136                             m_documentLoadingProgress += m_documentLoadingStep;
137                             parent->slotGotProgressInfo(QString(), (int) m_documentLoadingProgress);
138                             //qApp->processEvents();
139                         }
140                         QString prodId = e.attribute("id");
141                         if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion") && !m_abortLoading) {
142                             e.setTagName("producer");
143                             // Get MLT's original producer properties
144
145                             for (int j = 0; j < max; j++) {
146                                 QDomElement o = producers.item(j).cloneNode().toElement();
147                                 QString origId = o.attribute("id").section('_', 0, 0);
148                                 if (origId == prodId) {
149                                     orig = o;
150                                     break;
151                                 }
152                             }
153                             addClipInfo(e, orig, prodId);
154                             kDebug() << "// NLIVE PROD: " << prodId;
155                         }
156                     }
157                     if (m_abortLoading) {
158                         //parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
159                         emit resetProjectList();
160                         m_startPos = 0;
161                         m_url = KUrl();
162                         m_tracksList.clear();
163                         kWarning() << "Aborted loading of: " << url.path();
164                         m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
165                         setProfilePath(KdenliveSettings::default_profile());
166                         m_clipManager->clear();
167                     } else {
168                         QDomNode markers = m_document.elementsByTagName("markers").at(0);
169                         if (!markers.isNull()) {
170                             QDomNodeList markerslist = markers.childNodes();
171                             int maxchild = markerslist.count();
172                             for (int k = 0; k < maxchild; k++) {
173                                 e = markerslist.at(k).toElement();
174                                 if (e.tagName() == "marker") {
175                                     m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
176                                 }
177                             }
178                             westley.removeChild(markers);
179                         }
180                         m_document.removeChild(infoXmlNode);
181                         kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
182                     }
183                 }
184             } else {
185                 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
186                 kWarning() << "  NO KDENLIVE INFO FOUND IN FILE: " << url.path();
187                 m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
188                 m_url = KUrl();
189                 setProfilePath(KdenliveSettings::default_profile());
190             }
191             KIO::NetAccess::removeTempFile(tmpFile);
192         } else {
193             KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
194             parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
195             m_url = KUrl();
196             m_document = createEmptyDocument(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
197             setProfilePath(KdenliveSettings::default_profile());
198         }
199     } else {
200         m_document = createEmptyDocument(tracks.x(), tracks.y());
201         setProfilePath(profileName);
202     }
203     if (m_projectFolder.isEmpty()) m_projectFolder = KUrl(KdenliveSettings::defaultprojectfolder());
204
205     // make sure that the necessary folders exist
206     KStandardDirs::makeDir(m_projectFolder.path() + "/titles/");
207     KStandardDirs::makeDir(m_projectFolder.path() + "/thumbs/");
208     KStandardDirs::makeDir(m_projectFolder.path() + "/ladspa/");
209
210     kDebug() << "KDEnlive document, init timecode: " << m_fps;
211     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
212     else m_timecode.setFormat((int) m_fps);
213
214     //kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
215     connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
216
217 }
218
219 KdenliveDoc::~KdenliveDoc() {
220     delete m_commandStack;
221     delete m_clipManager;
222     delete m_autoSaveTimer;
223     if (m_autosave) {
224         m_autosave->remove();
225         delete m_autosave;
226     }
227 }
228
229 void KdenliveDoc::setSceneList() {
230     m_render->setSceneList(m_document.toString(), m_startPos);
231     checkProjectClips();
232 }
233
234 QDomDocument KdenliveDoc::createEmptyDocument(const int videotracks, const int audiotracks) {
235     // Creating new document
236     QDomDocument doc;
237     QDomElement westley = doc.createElement("westley");
238     doc.appendChild(westley);
239
240
241     TrackInfo videoTrack;
242     videoTrack.type = VIDEOTRACK;
243     videoTrack.isMute = false;
244     videoTrack.isBlind = false;
245     videoTrack.isLocked = false;
246
247     TrackInfo audioTrack;
248     audioTrack.type = AUDIOTRACK;
249     audioTrack.isMute = false;
250     audioTrack.isBlind = true;
251     audioTrack.isLocked = false;
252
253     QDomElement tractor = doc.createElement("tractor");
254     tractor.setAttribute("id", "maintractor");
255     QDomElement multitrack = doc.createElement("multitrack");
256     QDomElement playlist = doc.createElement("playlist");
257     playlist.setAttribute("id", "black_track");
258     westley.appendChild(playlist);
259
260
261     // create playlists
262     int total = audiotracks + videotracks + 1;
263
264     for (int i = 1; i < total; i++) {
265         QDomElement playlist = doc.createElement("playlist");
266         playlist.setAttribute("id", "playlist" + QString::number(i));
267         westley.appendChild(playlist);
268     }
269
270     QDomElement track0 = doc.createElement("track");
271     track0.setAttribute("producer", "black_track");
272     tractor.appendChild(track0);
273
274     // create audio tracks
275     for (int i = 1; i < audiotracks + 1; i++) {
276         QDomElement track = doc.createElement("track");
277         track.setAttribute("producer", "playlist" + QString::number(i));
278         track.setAttribute("hide", "video");
279         tractor.appendChild(track);
280         m_tracksList.append(audioTrack);
281     }
282
283     // create video tracks
284     for (int i = audiotracks + 1; i < total; i++) {
285         QDomElement track = doc.createElement("track");
286         track.setAttribute("producer", "playlist" + QString::number(i));
287         tractor.appendChild(track);
288         m_tracksList.append(videoTrack);
289     }
290
291     for (uint i = 2; i < total ; i++) {
292         QDomElement transition = doc.createElement("transition");
293         transition.setAttribute("always_active", "1");
294
295         QDomElement property = doc.createElement("property");
296         property.setAttribute("name", "a_track");
297         QDomText value = doc.createTextNode(QString::number(1));
298         property.appendChild(value);
299         transition.appendChild(property);
300
301         property = doc.createElement("property");
302         property.setAttribute("name", "b_track");
303         value = doc.createTextNode(QString::number(i));
304         property.appendChild(value);
305         transition.appendChild(property);
306
307         property = doc.createElement("property");
308         property.setAttribute("name", "mlt_service");
309         value = doc.createTextNode("mix");
310         property.appendChild(value);
311         transition.appendChild(property);
312
313         property = doc.createElement("property");
314         property.setAttribute("name", "combine");
315         value = doc.createTextNode("1");
316         property.appendChild(value);
317         transition.appendChild(property);
318
319         property = doc.createElement("property");
320         property.setAttribute("name", "internal_added");
321         value = doc.createTextNode("237");
322         property.appendChild(value);
323         transition.appendChild(property);
324         tractor.appendChild(transition);
325     }
326     westley.appendChild(tractor);
327     return doc;
328 }
329
330
331 void KdenliveDoc::syncGuides(QList <Guide *> guides) {
332     QDomDocument doc;
333     QDomElement e;
334     m_guidesXml.clear();
335     m_guidesXml = doc.createElement("guides");
336
337     for (int i = 0; i < guides.count(); i++) {
338         e = doc.createElement("guide");
339         e.setAttribute("time", guides.at(i)->position().ms() / 1000);
340         e.setAttribute("comment", guides.at(i)->label());
341         m_guidesXml.appendChild(e);
342     }
343     emit guidesUpdated();
344 }
345
346 QDomElement KdenliveDoc::guidesXml() const {
347     return m_guidesXml;
348 }
349
350 void KdenliveDoc::slotAutoSave() {
351     if (m_render && m_autosave) {
352         if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
353             // show error: could not open the autosave file
354             kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
355         }
356         kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
357         QDomDocument doc;
358         if (KdenliveSettings::dropbframes()) {
359             KdenliveSettings::setDropbframes(false);
360             m_clipManager->updatePreviewSettings();
361             doc.setContent(m_render->sceneList());
362             KdenliveSettings::setDropbframes(true);
363             m_clipManager->updatePreviewSettings();
364         } else doc.setContent(m_render->sceneList());
365         saveSceneList(m_autosave->fileName(), doc);
366     }
367 }
368
369 void KdenliveDoc::setZoom(int factor) {
370     m_zoom = factor;
371 }
372
373 int KdenliveDoc::zoom() const {
374     return m_zoom;
375 }
376
377 bool KdenliveDoc::convertDocument(double version) {
378     kDebug() << "Opening a document with version " << version;
379
380     if (version == 0.81) return true;
381
382     // Opening a old Kdenlive document
383     if (version == 0.5 || version == 0.7 || version > 0.81) {
384         kDebug() << "Unable to open document with version " << version;
385         // TODO: convert 0.7 (0.5?) files to the new document format.
386         return FALSE;
387     }
388
389     if (version == 0.8) {
390         // Add the tracks information
391         QString tracksOrder;
392         QDomNodeList tracks = m_document.elementsByTagName("track");
393         int max = tracks.count();
394         for (int i = 0; i < max; i++) {
395             QDomElement t = tracks.at(i).toElement();
396             if (t.attribute("hide") == "video")
397                 tracksOrder.append('a');
398             else if (t.attribute("producer") != "black_track")
399                 tracksOrder.append('v');
400         }
401         QDomNode kdenlivedoc = m_document.elementsByTagName("kdenlivedoc").at(0);
402         QDomElement infoXml = kdenlivedoc.toElement();
403         QString currentTrackOrder = infoXml.attribute("tracks");
404         if (currentTrackOrder.isEmpty()) infoXml.setAttribute("tracks", tracksOrder);
405
406         return TRUE;
407     }
408
409     QDomNode westley = m_document.elementsByTagName("westley").at(1);
410     QDomNode tractor = m_document.elementsByTagName("tractor").at(0);
411     QDomNode kdenlivedoc = m_document.elementsByTagName("kdenlivedoc").at(0);
412     QDomElement kdenlivedoc_old = kdenlivedoc.cloneNode(true).toElement(); // Needed for folders
413     QDomNode multitrack = m_document.elementsByTagName("multitrack").at(0);
414     QDomNodeList playlists = m_document.elementsByTagName("playlist");
415
416     QDomNode props = m_document.elementsByTagName("properties").at(0).toElement();
417     QString profile = props.toElement().attribute("videoprofile");
418     m_startPos = props.toElement().attribute("timeline_position").toInt();
419     if (profile == "dv_wide") profile = "dv_pal_wide";
420
421     // move playlists outside of tractor and add the tracks instead
422     int max = playlists.count();
423     for (int i = 0; i < max; i++) {
424         QDomNode n = playlists.at(i);
425         westley.insertBefore(n, QDomNode());
426         QDomElement pl = n.toElement();
427         QDomElement track = m_document.createElement("track");
428         QString trackType = pl.attribute("hide");
429         if (!trackType.isEmpty())
430             track.setAttribute("hide", trackType);
431         QString playlist_id =  pl.attribute("id");
432         if (playlist_id.isEmpty()) {
433             playlist_id = "black_track";
434             pl.setAttribute("id", playlist_id);
435         }
436         track.setAttribute("producer", playlist_id);
437         //tractor.appendChild(track);
438 #define KEEP_TRACK_ORDER 1
439 #ifdef KEEP_TRACK_ORDER
440         tractor.insertAfter(track, QDomNode());
441 #else
442         // Insert the new track in an order that hopefully matches the 3 video, then 2 audio tracks of Kdenlive 0.7.0
443         // insertion sort - O( tracks*tracks )
444         // Note, this breaks _all_ transitions - but you can move them up and down afterwards.
445         QDomElement tractor_elem = tractor.toElement();
446         if (! tractor_elem.isNull()) {
447             QDomNodeList tracks = tractor_elem.elementsByTagName("track");
448             int size = tracks.size();
449             if (size == 0) {
450                 tractor.insertAfter(track, QDomNode());
451             } else {
452                 bool inserted = false;
453                 for (int i = 0; i < size; ++i) {
454                     QDomElement track_elem = tracks.at(i).toElement();
455                     if (track_elem.isNull()) {
456                         tractor.insertAfter(track, QDomNode());
457                         inserted = true;
458                         break;
459                     } else {
460                         kDebug() << "playlist_id: " << playlist_id << " producer:" << track_elem.attribute("producer");
461                         if (playlist_id < track_elem.attribute("producer")) {
462                             tractor.insertBefore(track, track_elem);
463                             inserted = true;
464                             break;
465                         }
466                     }
467                 }
468                 // Reach here, no insertion, insert last
469                 if (!inserted) {
470                     tractor.insertAfter(track, QDomNode());
471                 }
472             }
473         } else {
474             kWarning() << "tractor was not a QDomElement";
475             tractor.insertAfter(track, QDomNode());
476         }
477 #endif
478     }
479     tractor.removeChild(multitrack);
480
481     // write tracks order now that they've been sorted
482     QString tracksOrder;
483     QDomNodeList tracks = m_document.elementsByTagName("track");
484     for (int i = 0; i < tracks.count(); ++i) {
485         QDomElement track = tracks.at(i).toElement();
486         if (track.attribute("hide") == "video")
487             tracksOrder.append('a');
488         else if (track.attribute("producer") != "black_track")
489             tracksOrder.append('v');
490     }
491
492     // audio track mixing transitions should not be added to track view, so add required attribute
493     QDomNodeList transitions = m_document.elementsByTagName("transition");
494     max = transitions.count();
495     for (int i = 0; i < max; i++) {
496         QDomElement tr = transitions.at(i).toElement();
497         if (tr.attribute("combine") == "1" && tr.attribute("mlt_service") == "mix") {
498             QDomElement property = m_document.createElement("property");
499             property.setAttribute("name", "internal_added");
500             QDomText value = m_document.createTextNode("237");
501             property.appendChild(value);
502             tr.appendChild(property);
503         } else {
504             // convert transition
505             QDomNamedNodeMap attrs = tr.attributes();
506             for (unsigned int j = 0; j < attrs.count(); j++) {
507                 QString attrName = attrs.item(j).nodeName();
508                 if (attrName != "in" && attrName != "out" && attrName != "id") {
509                     QDomElement property = m_document.createElement("property");
510                     property.setAttribute("name", attrName);
511                     QDomText value = m_document.createTextNode(attrs.item(j).nodeValue());
512                     property.appendChild(value);
513                     tr.appendChild(property);
514                 }
515             }
516         }
517     }
518
519     // move transitions after tracks
520     for (int i = 0; i < max; i++) {
521         tractor.insertAfter(transitions.at(0), QDomNode());
522     }
523
524     // Fix filters format
525     QDomNodeList entries = m_document.elementsByTagName("entry");
526     max = entries.count();
527     for (int i = 0; i < max; i++) {
528         QString last_id;
529         int effectix = 0;
530         QDomNode m = entries.at(i).firstChild();
531         while (!m.isNull()) {
532             if (m.toElement().tagName() == "filter") {
533                 QDomElement filt = m.toElement();
534                 QDomNamedNodeMap attrs = filt.attributes();
535                 QString current_id = filt.attribute("kdenlive_id");
536                 if (current_id != last_id) {
537                     effectix++;
538                     last_id = current_id;
539                 }
540                 QDomElement e = m_document.createElement("property");
541                 e.setAttribute("name", "kdenlive_ix");
542                 QDomText value = m_document.createTextNode(QString::number(effectix));
543                 e.appendChild(value);
544                 filt.appendChild(e);
545                 for (int j = 0; j < attrs.count(); j++) {
546                     QDomAttr a = attrs.item(j).toAttr();
547                     if (!a.isNull()) {
548                         kDebug() << " FILTER; adding :" << a.name() << ":" << a.value();
549                         QDomElement e = m_document.createElement("property");
550                         e.setAttribute("name", a.name());
551                         QDomText value = m_document.createTextNode(a.value());
552                         e.appendChild(value);
553                         filt.appendChild(e);
554
555                     }
556                 }
557             }
558             m = m.nextSibling();
559         }
560     }
561
562     /*
563         QDomNodeList filters = m_document.elementsByTagName("filter");
564         max = filters.count();
565         QString last_id;
566         int effectix = 0;
567         for (int i = 0; i < max; i++) {
568             QDomElement filt = filters.at(i).toElement();
569             QDomNamedNodeMap attrs = filt.attributes();
570      QString current_id = filt.attribute("kdenlive_id");
571      if (current_id != last_id) {
572          effectix++;
573          last_id = current_id;
574      }
575      QDomElement e = m_document.createElement("property");
576             e.setAttribute("name", "kdenlive_ix");
577             QDomText value = m_document.createTextNode(QString::number(1));
578             e.appendChild(value);
579             filt.appendChild(e);
580             for (int j = 0; j < attrs.count(); j++) {
581                 QDomAttr a = attrs.item(j).toAttr();
582                 if (!a.isNull()) {
583                     kDebug() << " FILTER; adding :" << a.name() << ":" << a.value();
584                     QDomElement e = m_document.createElement("property");
585                     e.setAttribute("name", a.name());
586                     QDomText value = m_document.createTextNode(a.value());
587                     e.appendChild(value);
588                     filt.appendChild(e);
589                 }
590             }
591         }*/
592
593     // fix slowmotion
594     QDomNodeList producers = westley.toElement().elementsByTagName("producer");
595     max = producers.count();
596     for (int i = 0; i < max; i++) {
597         QDomElement prod = producers.at(i).toElement();
598         if (prod.attribute("mlt_service") == "framebuffer") {
599             QString slowmotionprod = prod.attribute("resource");
600             slowmotionprod.replace(':', '?');
601             kDebug() << "// FOUND WRONG SLOWMO, new: " << slowmotionprod;
602             prod.setAttribute("resource", slowmotionprod);
603         }
604     }
605     // move producers to correct place, markers to a global list, fix clip descriptions
606     QDomElement markers = m_document.createElement("markers");
607     // This will get the westley producers:
608     producers = m_document.elementsByTagName("producer");
609     max = producers.count();
610     for (int i = 0; i < max; i++) {
611         QDomElement prod = producers.at(0).toElement();
612         // add resource also as a property (to allow path correction in setNewResource())
613         // TODO: will it work with slowmotion? needs testing
614         if (!prod.attribute("resource").isEmpty()) {
615             QDomElement prop_resource = m_document.createElement("property");
616             prop_resource.setAttribute("name", "resource");
617             QDomText resource = m_document.createTextNode(prod.attribute("resource"));
618             prop_resource.appendChild(resource);
619             prod.appendChild(prop_resource);
620         }
621         QDomNode m = prod.firstChild();
622         if (!m.isNull()) {
623             if (m.toElement().tagName() == "markers") {
624                 QDomNodeList prodchilds = m.childNodes();
625                 int maxchild = prodchilds.count();
626                 for (int k = 0; k < maxchild; k++) {
627                     QDomElement mark = prodchilds.at(0).toElement();
628                     mark.setAttribute("id", prod.attribute("id"));
629                     markers.insertAfter(mark, QDomNode());
630                 }
631                 prod.removeChild(m);
632             } else if (prod.attribute("type").toInt() == TEXT) {
633                 // convert title clip
634                 if (m.toElement().tagName() == "textclip") {
635                     QDomDocument tdoc;
636                     QDomElement titleclip = m.toElement();
637                     QDomElement title = tdoc.createElement("kdenlivetitle");
638                     tdoc.appendChild(title);
639                     QDomNodeList objects = titleclip.childNodes();
640                     int maxchild = objects.count();
641                     for (int k = 0; k < maxchild; k++) {
642                         QString objectxml;
643                         QDomElement ob = objects.at(k).toElement();
644                         if (ob.attribute("type") == "3") {
645                             // text object - all of this goes into "xmldata"...
646                             QDomElement item = tdoc.createElement("item");
647                             item.setAttribute("z-index", ob.attribute("z"));
648                             item.setAttribute("type", "QGraphicsTextItem");
649                             QDomElement position = tdoc.createElement("position");
650                             position.setAttribute("x", ob.attribute("x"));
651                             position.setAttribute("y", ob.attribute("y"));
652                             QDomElement content = tdoc.createElement("content");
653                             content.setAttribute("font", ob.attribute("font_family"));
654                             content.setAttribute("font-size", ob.attribute("font_size"));
655                             content.setAttribute("font-bold", ob.attribute("bold"));
656                             content.setAttribute("font-italic", ob.attribute("italic"));
657                             content.setAttribute("font-underline", ob.attribute("underline"));
658                             QString col = ob.attribute("color");
659                             QColor c(col);
660                             content.setAttribute("font-color", colorToString(c));
661                             // todo: These fields are missing from the newly generated xmldata:
662                             // transform, startviewport, endviewport, background
663
664                             QDomText conttxt = tdoc.createTextNode(ob.attribute("text"));
665                             content.appendChild(conttxt);
666                             item.appendChild(position);
667                             item.appendChild(content);
668                             title.appendChild(item);
669                         } else if (ob.attribute("type") == "5") {
670                             // rectangle object
671                             QDomElement item = tdoc.createElement("item");
672                             item.setAttribute("z-index", ob.attribute("z"));
673                             item.setAttribute("type", "QGraphicsRectItem");
674                             QDomElement position = tdoc.createElement("position");
675                             position.setAttribute("x", ob.attribute("x"));
676                             position.setAttribute("y", ob.attribute("y"));
677                             QDomElement content = tdoc.createElement("content");
678                             QString col = ob.attribute("color");
679                             QColor c(col);
680                             content.setAttribute("brushcolor", colorToString(c));
681                             QString rect = "0,0,";
682                             rect.append(ob.attribute("width"));
683                             rect.append(",");
684                             rect.append(ob.attribute("height"));
685                             content.setAttribute("rect", rect);
686                             item.appendChild(position);
687                             item.appendChild(content);
688                             title.appendChild(item);
689                         }
690                     }
691                     prod.setAttribute("xmldata", tdoc.toString());
692                     // mbd todo: This clearly does not work, as every title gets the same name - trying to leave it empty
693                     // QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
694                     // prod.setAttribute("titlename", titleInfo.at(0));
695                     // prod.setAttribute("resource", titleInfo.at(1));
696                     //kDebug()<<"TITLE DATA:\n"<<tdoc.toString();
697                     prod.removeChild(m);
698                 } // End conversion of title clips.
699
700             } else if (m.isText()) {
701                 QString comment = m.nodeValue();
702                 if (!comment.isEmpty()) {
703                     prod.setAttribute("description", comment);
704                 }
705                 prod.removeChild(m);
706             }
707         }
708         int duration = prod.attribute("duration").toInt();
709         if (duration > 0) prod.setAttribute("out", QString::number(duration));
710         // The clip goes back in, but text clips should not go back in, at least not modified
711         westley.insertBefore(prod, QDomNode());
712
713     }
714
715     QDomNode westley0 = m_document.elementsByTagName("westley").at(0);
716     if (!markers.firstChild().isNull()) westley0.appendChild(markers);
717
718
719     // Convert as much of the kdenlivedoc as possible. Use the producer in westley
720     // First, remove the old stuff from westley, and add a new empty one
721     // Also, track the max id in order to use it for the adding of groups/folders
722     int max_kproducer_id = 0;
723     westley0.removeChild(kdenlivedoc);
724     QDomElement kdenlivedoc_new = m_document.createElement("kdenlivedoc");
725     kdenlivedoc_new.setAttribute("profile", profile);
726     kdenlivedoc_new.setAttribute("tracks", tracksOrder);
727     // Add all the producers that has a ressource in westley
728     QDomElement westley_element = westley0.toElement();
729     if (westley_element.isNull()) {
730         kWarning() << "westley0 element in document was not a QDomElement - unable to add producers to new kdenlivedoc";
731     } else {
732         QDomNodeList wproducers = westley_element.elementsByTagName("producer");
733         int kmax = wproducers.count();
734         for (int i = 0; i < kmax; i++) {
735             QDomElement wproducer = wproducers.at(i).toElement();
736             if (wproducer.isNull()) {
737                 kWarning() << "Found producer in westley0, that was not a QDomElement";
738             } else {
739                 // We have to do slightly different things, depending on the type
740                 kDebug() << "Converting producer element with type" << wproducer.attribute("type");
741                 if (wproducer.attribute("type").toInt() == TEXT) {
742                     kDebug() << "Found TEXT element in producer" << endl;
743                     QDomElement kproducer = wproducer.cloneNode(true).toElement();
744                     kproducer.setTagName("kdenlive_producer");
745                     kdenlivedoc_new.appendChild(kproducer);
746                     // TODO: Perhaps needs some more changes here to "frequency", aspect ratio as a float, frame_size, channels, and later, ressource and title name
747                 } else {
748                     QDomElement kproducer = m_document.createElement("kdenlive_producer");
749                     kproducer.setAttribute("id", wproducer.attribute("id"));
750                     if (!wproducer.attribute("description").isEmpty())
751                         kproducer.setAttribute("description", wproducer.attribute("description"));
752                     kproducer.setAttribute("resource", wproducer.attribute("resource"));
753                     kproducer.setAttribute("type", wproducer.attribute("type"));
754                     // Testing fix for 358
755                     if (!wproducer.attribute("aspect_ratio").isEmpty()) {
756                         kproducer.setAttribute("aspect_ratio", wproducer.attribute("aspect_ratio"));
757                     }
758                     if (!wproducer.attribute("source_fps").isEmpty()) {
759                         kproducer.setAttribute("fps", wproducer.attribute("source_fps"));
760                     }
761                     if (!wproducer.attribute("length").isEmpty()) {
762                         kproducer.setAttribute("duration", wproducer.attribute("length"));
763                     }
764                     kdenlivedoc_new.appendChild(kproducer);
765                 }
766                 if (wproducer.attribute("id").toInt() > max_kproducer_id) {
767                     max_kproducer_id = wproducer.attribute("id").toInt();
768                 }
769             }
770         }
771     }
772 #define LOOKUP_FOLDER 1
773 #ifdef LOOKUP_FOLDER
774     // Look through all the folder elements of the old doc, for each folder, for each producer,
775     // get the id, look it up in the new doc, set the groupname and groupid
776     // Note, this does not work at the moment - at least one folders shows up missing, and clips with no folder
777     // does not show up.
778     //    QDomElement kdenlivedoc_old = kdenlivedoc.toElement();
779     if (!kdenlivedoc_old.isNull()) {
780         QDomNodeList folders = kdenlivedoc_old.elementsByTagName("folder");
781         int fsize = folders.size();
782         int groupId = max_kproducer_id + 1; // Start at +1 of max id of the kdenlive_producers
783         for (int i = 0; i < fsize; ++i) {
784             QDomElement folder = folders.at(i).toElement();
785             if (!folder.isNull()) {
786                 QString groupName = folder.attribute("name");
787                 kDebug() << "groupName: " << groupName << " with groupId: " << groupId;
788                 QDomNodeList fproducers = folder.elementsByTagName("producer");
789                 int psize = fproducers.size();
790                 for (int j = 0; j < psize; ++j) {
791                     QDomElement fproducer = fproducers.at(j).toElement();
792                     if (!fproducer.isNull()) {
793                         QString id = fproducer.attribute("id");
794                         // This is not very effective, but compared to loading the clips, its a breeze
795                         QDomNodeList kdenlive_producers = kdenlivedoc_new.elementsByTagName("kdenlive_producer");
796                         int kpsize = kdenlive_producers.size();
797                         for (int k = 0; k < kpsize; ++k) {
798                             QDomElement kproducer = kdenlive_producers.at(k).toElement(); // Its an element for sure
799                             if (id == kproducer.attribute("id")) {
800                                 // We do not check that it already is part of a folder
801                                 kproducer.setAttribute("groupid", groupId);
802                                 kproducer.setAttribute("groupname", groupName);
803                                 break;
804                             }
805                         }
806                     }
807                 }
808                 ++groupId;
809             }
810         }
811     }
812 #endif
813     westley0.appendChild(kdenlivedoc_new);
814
815     QDomNodeList elements = westley.childNodes();
816     max = elements.count();
817     for (int i = 0; i < max; i++) {
818         QDomElement prod = elements.at(0).toElement();
819         westley0.insertAfter(prod, QDomNode());
820     }
821
822     westley0.removeChild(westley);
823
824     // experimental and probably slow
825     // adds <avfile /> information to <kdenlive_producer />
826     QDomNodeList kproducers = m_document.elementsByTagName("kdenlive_producer");
827     QDomNodeList avfiles = kdenlivedoc_old.elementsByTagName("avfile");
828     kDebug() << "found" << avfiles.count() << "<avfile />s and" << kproducers.count() << "<kdenlive_producer />s";
829     for (int i = 0; i < avfiles.count(); ++i) {
830         QDomElement avfile = avfiles.at(i).toElement();
831         QDomElement kproducer = QDomElement();
832         if (avfile.isNull())
833             kWarning() << "found an <avfile /> that is not a QDomElement";
834         else {
835             QString id = avfile.attribute("id");
836             // this is horrible, must be rewritten, it's just for test
837             for (int j = 0; j < kproducers.count(); ++j) {
838                 //kDebug() << "checking <kdenlive_producer /> with id" << kproducers.at(j).toElement().attribute("id");
839                 if (kproducers.at(j).toElement().attribute("id") == id) {
840                     kproducer = kproducers.at(j).toElement();
841                     break;
842                 }
843             }
844             if (kproducer == QDomElement())
845                 kWarning() << "no match for <avfile /> with id =" << id;
846             else {
847                 //kDebug() << "ready to set additional <avfile />'s attributes (id =" << id << ")";
848                 kproducer.setAttribute("channels", avfile.attribute("channels"));
849                 kproducer.setAttribute("duration", avfile.attribute("duration"));
850                 kproducer.setAttribute("frame_size", avfile.attribute("width") + "x" + avfile.attribute("height"));
851                 kproducer.setAttribute("frequency", avfile.attribute("frequency"));
852                 if (kproducer.attribute("description").isEmpty() && !avfile.attribute("description").isEmpty())
853                     kproducer.setAttribute("description", avfile.attribute("description"));
854             }
855         }
856     }
857
858     //kDebug() << "/////////////////  CONVERTED DOC:";
859     //kDebug() << m_document.toString();
860     /*
861     QFile file( "converted.kdenlive" );
862     if ( file.open( QIODevice::WriteOnly ) ) {
863       QTextStream stream( &file );
864       stream << m_document.toString();
865       file.close();
866     } else {
867       kDebug() << "Unable to dump file to converted.kdenlive";
868     }
869     */
870     //kDebug() << "/////////////////  END CONVERTED DOC:";
871
872     return TRUE;
873 }
874
875 QString KdenliveDoc::colorToString(const QColor& c) {
876     QString ret = "%1,%2,%3,%4";
877     ret = ret.arg(c.red()).arg(c.green()).arg(c.blue()).arg(c.alpha());
878     return ret;
879 }
880
881 void KdenliveDoc::setZone(int start, int end) {
882     m_zoneStart = start;
883     m_zoneEnd = end;
884 }
885
886 QPoint KdenliveDoc::zone() const {
887     return QPoint(m_zoneStart, m_zoneEnd);
888 }
889
890 bool KdenliveDoc::saveSceneList(const QString &path, QDomDocument sceneList) {
891     QDomNode wes = sceneList.elementsByTagName("westley").at(0);
892
893     QDomElement addedXml = sceneList.createElement("kdenlivedoc");
894     QDomElement markers = sceneList.createElement("markers");
895     addedXml.setAttribute("version", "0.81");
896     addedXml.setAttribute("profile", profilePath());
897     addedXml.setAttribute("position", m_render->seekPosition().frames(m_fps));
898     addedXml.setAttribute("zonein", m_zoneStart);
899     addedXml.setAttribute("zoneout", m_zoneEnd);
900     addedXml.setAttribute("projectfolder", m_projectFolder.path());
901     addedXml.setAttribute("tracks", getTracksInfo());
902     addedXml.setAttribute("zoom", m_zoom);
903
904     // save project folders
905     QMap <QString, QString> folderlist = m_clipManager->documentFolderList();
906
907     QMapIterator<QString, QString> f(folderlist);
908     while (f.hasNext()) {
909         f.next();
910         QDomElement folder = sceneList.createElement("folder");
911         folder.setAttribute("id", f.key());
912         folder.setAttribute("name", f.value());
913         addedXml.appendChild(folder);
914     }
915
916     // Save project clips
917     QDomElement e;
918     QList <DocClipBase*> list = m_clipManager->documentClipList();
919     for (int i = 0; i < list.count(); i++) {
920         e = list.at(i)->toXML();
921         e.setTagName("kdenlive_producer");
922         addedXml.appendChild(sceneList.importNode(e, true));
923         QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
924         for (int j = 0; j < marks.count(); j++) {
925             QDomElement marker = sceneList.createElement("marker");
926             marker.setAttribute("time", marks.at(j).time().ms() / 1000);
927             marker.setAttribute("comment", marks.at(j).comment());
928             marker.setAttribute("id", e.attribute("id"));
929             markers.appendChild(marker);
930         }
931     }
932     addedXml.appendChild(markers);
933     if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml, true));
934
935     wes.appendChild(addedXml);
936     //wes.appendChild(doc.importNode(kdenliveData, true));
937
938     QFile file(path);
939     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
940         kWarning() << "//////  ERROR writing to file: " << path;
941         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
942         return false;
943     }
944     QTextStream out(&file);
945     out << sceneList.toString();
946     file.close();
947     return true;
948 }
949
950 ClipManager *KdenliveDoc::clipManager() {
951     return m_clipManager;
952 }
953
954 KUrl KdenliveDoc::projectFolder() const {
955     //if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
956     return m_projectFolder;
957 }
958
959 void KdenliveDoc::setProjectFolder(KUrl url) {
960     if (url == m_projectFolder) return;
961     setModified(true);
962     KStandardDirs::makeDir(url.path());
963     KStandardDirs::makeDir(url.path() + "/titles/");
964     KStandardDirs::makeDir(url.path() + "/thumbs/");
965     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);
966     m_projectFolder = url;
967 }
968
969 void KdenliveDoc::moveProjectData(KUrl url) {
970     QList <DocClipBase*> list = m_clipManager->documentClipList();
971     //TODO: Also move ladspa effects files
972     for (int i = 0; i < list.count(); i++) {
973         DocClipBase *clip = list.at(i);
974         if (clip->clipType() == TEXT) {
975             // the image for title clip must be moved
976             KUrl oldUrl = clip->fileURL();
977             KUrl newUrl = KUrl(url.path() + "/titles/" + oldUrl.fileName());
978             KIO::Job *job = KIO::copy(oldUrl, newUrl);
979             if (KIO::NetAccess::synchronousRun(job, 0)) clip->setProperty("resource", newUrl.path());
980         }
981         QString hash = clip->getClipHash();
982         KUrl oldVideoThumbUrl = KUrl(m_projectFolder.path() + "/thumbs/" + hash + ".png");
983         KUrl oldAudioThumbUrl = KUrl(m_projectFolder.path() + "/thumbs/" + hash + ".thumb");
984         if (KIO::NetAccess::exists(oldVideoThumbUrl, KIO::NetAccess::SourceSide, 0)) {
985             KUrl newUrl = KUrl(url.path() + "/thumbs/" + hash + ".png");
986             KIO::Job *job = KIO::copy(oldVideoThumbUrl, newUrl);
987             KIO::NetAccess::synchronousRun(job, 0);
988         }
989         if (KIO::NetAccess::exists(oldAudioThumbUrl, KIO::NetAccess::SourceSide, 0)) {
990             KUrl newUrl = KUrl(url.path() + "/thumbs/" + hash + ".thumb");
991             KIO::Job *job = KIO::copy(oldAudioThumbUrl, newUrl);
992             if (KIO::NetAccess::synchronousRun(job, 0)) clip->refreshThumbUrl();
993         }
994     }
995 }
996
997 QString KdenliveDoc::profilePath() const {
998     return m_profile.path;
999 }
1000
1001 MltVideoProfile KdenliveDoc::mltProfile() const {
1002     return m_profile;
1003 }
1004
1005 void KdenliveDoc::setProfilePath(QString path) {
1006     if (path.isEmpty()) path = KdenliveSettings::default_profile();
1007     if (path.isEmpty()) path = "dv_pal";
1008     m_profile = ProfilesDialog::getVideoProfile(path);
1009     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
1010     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
1011     m_width = m_profile.width;
1012     m_height = m_profile.height;
1013     kDebug() << "KDEnnlive document, init timecode from path: " << path << ",  " << m_fps;
1014     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
1015     else m_timecode.setFormat((int) m_fps);
1016 }
1017
1018 const double KdenliveDoc::dar() {
1019     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
1020 }
1021
1022 void KdenliveDoc::setThumbsProgress(const QString &message, int progress) {
1023     emit progressInfo(message, progress);
1024 }
1025
1026 void KdenliveDoc::loadingProgressed() {
1027     m_documentLoadingProgress += m_documentLoadingStep;
1028     emit progressInfo(QString(), (int) m_documentLoadingProgress);
1029 }
1030
1031 QUndoStack *KdenliveDoc::commandStack() {
1032     return m_commandStack;
1033 }
1034
1035 /*
1036 void KdenliveDoc::setRenderer(Render *render) {
1037     if (m_render) return;
1038     m_render = render;
1039     emit progressInfo(i18n("Loading playlist..."), 0);
1040     //qApp->processEvents();
1041     if (m_render) {
1042         m_render->setSceneList(m_document.toString(), m_startPos);
1043         kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
1044         checkProjectClips();
1045     }
1046     emit progressInfo(QString(), -1);
1047 }*/
1048
1049 void KdenliveDoc::checkProjectClips() {
1050     if (m_render == NULL) return;
1051     QList <Mlt::Producer *> prods = m_render->producersList();
1052     QString id ;
1053     QString prodId ;
1054     QString prodTrack ;
1055     for (int i = 0; i < prods.count(); i++) {
1056         id = prods.at(i)->get("id");
1057         prodId = id.section('_', 0, 0);
1058         prodTrack = id.section('_', 1, 1);
1059         DocClipBase *clip = m_clipManager->getClipById(prodId);
1060         if (clip) clip->setProducer(prods.at(i));
1061         if (clip && clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
1062             // regenerate text clip image if required
1063             kDebug() << "// TITLE: " << clip->getProperty("titlename") << " Preview file: " << clip->getProperty("resource") << " DOES NOT EXIST";
1064             QString titlename = clip->getProperty("titlename");
1065             QString titleresource;
1066             if (titlename.isEmpty()) {
1067                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1068                 titlename = titleInfo.at(0);
1069                 titleresource = titleInfo.at(1);
1070                 clip->setProperty("titlename", titlename);
1071                 kDebug() << "// New title set to: " << titlename;
1072             } else {
1073                 titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
1074             }
1075             QString titlepath = projectFolder().path() + "/titles/";
1076             TitleWidget *dia_ui = new TitleWidget(KUrl(), titlepath, m_render, kapp->activeWindow());
1077             QDomDocument doc;
1078             doc.setContent(clip->getProperty("xmldata"));
1079             dia_ui->setXml(doc);
1080             QImage pix = dia_ui->renderedPixmap();
1081             pix.save(titleresource);
1082             clip->setProperty("resource", titleresource);
1083             delete dia_ui;
1084             clip->producer()->set("force_reload", 1);
1085         }
1086     }
1087 }
1088
1089 void KdenliveDoc::updatePreviewSettings() {
1090     m_clipManager->updatePreviewSettings();
1091     m_render->updatePreviewSettings();
1092     m_clipManager->resetProducersList(m_render->producersList());
1093
1094 }
1095
1096 Render *KdenliveDoc::renderer() {
1097     return m_render;
1098 }
1099
1100 void KdenliveDoc::updateClip(const QString &id) {
1101     emit updateClipDisplay(id);
1102 }
1103
1104 int KdenliveDoc::getFramePos(QString duration) {
1105     return m_timecode.getFrameCount(duration, m_fps);
1106 }
1107
1108 QString KdenliveDoc::producerName(const QString &id) {
1109     QString result = "unnamed";
1110     QDomNodeList prods = producersList();
1111     int ct = prods.count();
1112     for (int i = 0; i <  ct ; i++) {
1113         QDomElement e = prods.item(i).toElement();
1114         if (e.attribute("id") != "black" && e.attribute("id") == id) {
1115             result = e.attribute("name");
1116             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
1117             break;
1118         }
1119     }
1120     return result;
1121 }
1122
1123 void KdenliveDoc::setProducerDuration(const QString &id, int duration) {
1124     QDomNodeList prods = producersList();
1125     int ct = prods.count();
1126     for (int i = 0; i <  ct ; i++) {
1127         QDomElement e = prods.item(i).toElement();
1128         if (e.attribute("id") != "black" && e.attribute("id") == id) {
1129             e.setAttribute("duration", QString::number(duration));
1130             break;
1131         }
1132     }
1133 }
1134
1135 int KdenliveDoc::getProducerDuration(const QString &id) {
1136     int result = 0;
1137     QDomNodeList prods = producersList();
1138     int ct = prods.count();
1139     for (int i = 0; i <  ct ; i++) {
1140         QDomElement e = prods.item(i).toElement();
1141         if (e.attribute("id") != "black" && e.attribute("id") == id) {
1142             result = e.attribute("duration").toInt();
1143             break;
1144         }
1145     }
1146     return result;
1147 }
1148
1149
1150 QDomDocument KdenliveDoc::generateSceneList() {
1151     QDomDocument doc;
1152     QDomElement westley = doc.createElement("westley");
1153     doc.appendChild(westley);
1154     QDomElement prod = doc.createElement("producer");
1155 }
1156
1157 QDomDocument KdenliveDoc::toXml() {
1158     return m_document;
1159 }
1160
1161 Timecode KdenliveDoc::timecode() const {
1162     return m_timecode;
1163 }
1164
1165 QDomNodeList KdenliveDoc::producersList() {
1166     return m_document.elementsByTagName("producer");
1167 }
1168
1169 double KdenliveDoc::projectDuration() const {
1170     if (m_render) return GenTime(m_render->getLength(), m_fps).ms() / 1000;
1171 }
1172
1173 double KdenliveDoc::fps() const {
1174     return m_fps;
1175 }
1176
1177 int KdenliveDoc::width() const {
1178     return m_width;
1179 }
1180
1181 int KdenliveDoc::height() const {
1182     return m_height;
1183 }
1184
1185 KUrl KdenliveDoc::url() const {
1186     return m_url;
1187 }
1188
1189 void KdenliveDoc::setUrl(KUrl url) {
1190     m_url = url;
1191 }
1192
1193 void KdenliveDoc::setModified(bool mod) {
1194     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
1195         m_autoSaveTimer->start(3000);
1196     }
1197     if (mod == m_modified) return;
1198     m_modified = mod;
1199     emit docModified(m_modified);
1200 }
1201
1202 bool KdenliveDoc::isModified() const {
1203     return m_modified;
1204 }
1205
1206 QString KdenliveDoc::description() const {
1207     if (m_url.isEmpty())
1208         return i18n("Untitled") + " / " + m_profile.description;
1209     else
1210         return m_url.fileName() + " / " + m_profile.description;
1211 }
1212
1213 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem) {
1214     const QString producerId = clipId.section('_', 0, 0);
1215     int subtrack = clipId.section('_', 1, 1).toInt();
1216     DocClipBase *clip = m_clipManager->getClipById(producerId);
1217     if (clip == NULL) {
1218         /*kDebug()<<"// CLIP "<<clipId<<" NOT OFUND in LIST, CREATING";
1219         QDomDocument doc;
1220         doc.appendChild(doc.importNode(elem, true));
1221         kDebug() << "IMPORTED CLIP: \n" << doc.toString()<<"\n";*/
1222         elem.setAttribute("id", producerId);
1223         QString path = elem.attribute("resource");
1224         QString extension;
1225         if (elem.attribute("type").toInt() == SLIDESHOW) {
1226             extension = KUrl(path).fileName();
1227             path = KUrl(path).directory();
1228         }
1229         if (!QFile::exists(path) && elem.attribute("type").toInt() == TEXT) {
1230             kDebug() << "// TITLE: " << elem.attribute("titlename") << " Preview file: " << elem.attribute("resource") << " DOES NOT EXIST";
1231             QString titlename = elem.attribute("titlename");
1232             QString titleresource;
1233             if (titlename.isEmpty()) {
1234                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1235                 titlename = titleInfo.at(0);
1236                 titleresource = titleInfo.at(1);
1237                 elem.setAttribute("titlename", titlename);
1238                 kDebug() << "// New title set to: " << titlename;
1239             } else {
1240                 titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
1241             }
1242             QString titlepath = projectFolder().path() + "/titles/";
1243             TitleWidget *dia_ui = new TitleWidget(KUrl(), titlepath, m_render, kapp->activeWindow());
1244             QDomDocument doc;
1245             doc.setContent(elem.attribute("xmldata"));
1246             dia_ui->setXml(doc);
1247             QImage pix = dia_ui->renderedPixmap();
1248             pix.save(titleresource);
1249             elem.setAttribute("resource", titleresource);
1250             delete dia_ui;
1251         } else if (!path.isEmpty() && !QFile::exists(path) && elem.attribute("type").toInt() != TEXT) {
1252             kDebug() << "// FOUND MISSING CLIP: " << path << ", TYPE: " << elem.attribute("type").toInt();
1253             const QString size = elem.attribute("file_size");
1254             const QString hash = elem.attribute("file_hash");
1255             QString newpath;
1256             int action = KMessageBox::No;
1257             if (!size.isEmpty() && !hash.isEmpty()) {
1258                 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
1259                 else 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")));
1260             } else {
1261                 if (elem.attribute("type").toInt() == SLIDESHOW) {
1262                     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")));
1263                     if (res == KMessageBox::Yes)
1264                         newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1265                     else if (res == KMessageBox::Cancel) {
1266                         // Abort project loading
1267                         action = KMessageBox::Cancel;
1268                     }
1269                 } else {
1270                     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")));
1271                     if (res == KMessageBox::Yes)
1272                         newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1273                     else if (res == KMessageBox::Cancel) {
1274                         // Abort project loading
1275                         action = KMessageBox::Cancel;
1276                     }
1277                 }
1278             }
1279             if (action == KMessageBox::Yes) {
1280                 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1281                 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1282                 if (!m_searchFolder.isEmpty()) {
1283                     newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1284                 }
1285             } else if (action == KMessageBox::Cancel) {
1286                 m_abortLoading = true;
1287                 return;
1288             }
1289             if (!newpath.isEmpty()) {
1290                 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
1291                 elem.setAttribute("resource", newpath);
1292                 setNewClipResource(clipId, newpath);
1293                 setModified(true);
1294             }
1295         }
1296         clip = new DocClipBase(m_clipManager, elem, producerId);
1297         m_clipManager->addClip(clip);
1298     }
1299     if (createClipItem) {
1300         emit addProjectClip(clip);
1301         qApp->processEvents();
1302         m_render->getFileProperties(clip->toXML(), clip->getId());
1303     }
1304 }
1305
1306
1307 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path) {
1308     QDomNodeList prods = m_document.elementsByTagName("producer");
1309     int maxprod = prods.count();
1310     for (int i = 0; i < maxprod; i++) {
1311         QDomNode m = prods.at(i);
1312         QString prodId = m.toElement().attribute("id");
1313         if (prodId == id || prodId.startsWith(id + "_")) {
1314             QDomNodeList params = m.childNodes();
1315             for (int j = 0; j < params.count(); j++) {
1316                 QDomElement e = params.item(j).toElement();
1317                 if (e.attribute("name") == "resource") {
1318                     e.firstChild().setNodeValue(path);
1319                     break;
1320                 }
1321             }
1322         }
1323     }
1324 }
1325
1326 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const {
1327     QString foundFileName;
1328     QByteArray fileData;
1329     QByteArray fileHash;
1330     QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1331     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1332         QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1333         if (file.open(QIODevice::ReadOnly)) {
1334             if (QString::number(file.size()) == matchSize) {
1335                 /*
1336                 * 1 MB = 1 second per 450 files (or faster)
1337                 * 10 MB = 9 seconds per 450 files (or faster)
1338                 */
1339                 if (file.size() > 1000000*2) {
1340                     fileData = file.read(1000000);
1341                     if (file.seek(file.size() - 1000000))
1342                         fileData.append(file.readAll());
1343                 } else
1344                     fileData = file.readAll();
1345                 file.close();
1346                 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1347                 if (QString(fileHash.toHex()) == matchHash)
1348                     return file.fileName();
1349             }
1350         }
1351         kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1352     }
1353     filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1354     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1355         foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1356         if (!foundFileName.isEmpty())
1357             break;
1358     }
1359     return foundFileName;
1360 }
1361
1362 void KdenliveDoc::addClipInfo(QDomElement elem, QDomElement orig, QString clipId) {
1363     DocClipBase *clip = m_clipManager->getClipById(clipId);
1364     if (clip == NULL) {
1365         addClip(elem, clipId, false);
1366     } else {
1367         QMap <QString, QString> properties;
1368         QDomNamedNodeMap attributes = elem.attributes();
1369         QString attrname;
1370         for (unsigned int i = 0; i < attributes.count(); i++) {
1371             attrname = attributes.item(i).nodeName();
1372             if (attrname != "resource")
1373                 properties.insert(attrname, attributes.item(i).nodeValue());
1374             kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1375         }
1376         clip->setProperties(properties);
1377         emit addProjectClip(clip, false);
1378     }
1379     if (orig != QDomElement()) {
1380         QMap<QString, QString> meta;
1381         QDomNode m = orig.firstChild();
1382         while (!m.isNull()) {
1383             QString name = m.toElement().attribute("name");
1384             if (name.startsWith("meta.attr")) {
1385                 meta.insert(name.section('.', 2, 3), m.firstChild().nodeValue());
1386             }
1387             m = m.nextSibling();
1388         }
1389         if (!meta.isEmpty()) {
1390             clip = m_clipManager->getClipById(clipId);
1391             if (clip) clip->setMetadata(meta);
1392         }
1393     }
1394 }
1395
1396 void KdenliveDoc::deleteProjectClip(QList <QString> ids) {
1397     for (int i = 0; i < ids.size(); ++i) {
1398         emit deleteTimelineClip(ids.at(i));
1399         m_clipManager->slotDeleteClip(ids.at(i));
1400     }
1401     setModified(true);
1402 }
1403
1404 void KdenliveDoc::deleteClip(const QString &clipId) {
1405     emit signalDeleteProjectClip(clipId);
1406     m_clipManager->deleteClip(clipId);
1407 }
1408
1409 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId) {
1410     m_clipManager->slotAddClipList(urls, group, groupId);
1411     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1412     setModified(true);
1413 }
1414
1415
1416 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId) {
1417     kDebug() << "/////////  DOCUM, ADD CLP: " << url;
1418     m_clipManager->slotAddClipFile(url, group, groupId);
1419     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1420     setModified(true);
1421 }
1422
1423 const QString&KdenliveDoc::getFreeClipId() {
1424     return QString::number(m_clipManager->getFreeClipId());
1425 }
1426
1427 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId) {
1428     return m_clipManager->getClipById(clipId);
1429 }
1430
1431 void KdenliveDoc::slotAddColorClipFile(const QString name, const QString color, QString duration, const QString group, const QString &groupId) {
1432     m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1433     setModified(true);
1434 }
1435
1436 void KdenliveDoc::slotAddSlideshowClipFile(const QString name, const QString path, int count, const QString duration, const bool loop, const bool fade, const QString &luma_duration, const QString &luma_file, const int softness, const QString group, const QString &groupId) {
1437     m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop, fade, luma_duration, luma_file, softness, group, groupId);
1438     setModified(true);
1439 }
1440
1441 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId) {
1442     QString titlesFolder = projectFolder().path() + "/titles/";
1443     KStandardDirs::makeDir(titlesFolder);
1444     TitleWidget *dia_ui = new TitleWidget(KUrl(), titlesFolder, m_render, kapp->activeWindow());
1445     if (dia_ui->exec() == QDialog::Accepted) {
1446         QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1447         QImage pix = dia_ui->renderedPixmap();
1448         pix.save(titleInfo.at(1));
1449         //dia_ui->saveTitle(path + ".kdenlivetitle");
1450         m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), QString(), QString());
1451         setModified(true);
1452     }
1453     delete dia_ui;
1454 }
1455
1456 int KdenliveDoc::tracksCount() const {
1457     return m_tracksList.count();
1458 }
1459
1460 TrackInfo KdenliveDoc::trackInfoAt(int ix) const {
1461     return m_tracksList.at(ix);
1462 }
1463
1464 void KdenliveDoc::switchTrackAudio(int ix, bool hide) {
1465     m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1466 }
1467
1468 void KdenliveDoc::switchTrackLock(int ix, bool lock) {
1469     m_tracksList[ix].isLocked = lock;
1470 }
1471
1472 void KdenliveDoc::switchTrackVideo(int ix, bool hide) {
1473     m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1474 }
1475
1476 void KdenliveDoc::insertTrack(int ix, TrackInfo type) {
1477     if (ix == -1) m_tracksList << type;
1478     else m_tracksList.insert(ix, type);
1479 }
1480
1481 void KdenliveDoc::deleteTrack(int ix) {
1482     m_tracksList.removeAt(ix);
1483 }
1484
1485 void KdenliveDoc::setTrackType(int ix, TrackInfo type) {
1486     m_tracksList[ix].type = type.type;
1487     m_tracksList[ix].isMute = type.isMute;
1488     m_tracksList[ix].isBlind = type.isBlind;
1489     m_tracksList[ix].isLocked = type.isLocked;
1490 }
1491
1492 const QList <TrackInfo> KdenliveDoc::tracksList() const {
1493     return m_tracksList;
1494 }
1495
1496 QPoint KdenliveDoc::getTracksCount() const {
1497     int audio = 0;
1498     int video = 0;
1499     foreach(const TrackInfo &info, m_tracksList) {
1500         if (info.type == VIDEOTRACK) video++;
1501         else audio++;
1502     }
1503     return QPoint(video, audio);
1504 }
1505
1506 QString KdenliveDoc::getTracksInfo() const {
1507     QString result;
1508     foreach(const TrackInfo &info, m_tracksList) {
1509         if (info.type == VIDEOTRACK) result.append('v');
1510         else result.append('a');
1511     }
1512     return result;
1513 }
1514
1515 void KdenliveDoc::cachePixmap(const QString &fileId, const QPixmap &pix) const {
1516     pix.save(m_projectFolder.path() + "/thumbs/" + fileId + ".png");
1517 }
1518
1519 QString KdenliveDoc::getLadspaFile() const {
1520     int ct = 0;
1521     QString counter = QString::number(ct).rightJustified(5, '0', false);
1522     while (QFile::exists(m_projectFolder.path() + "/ladspa/" + counter + ".ladspa")) {
1523         ct++;
1524         counter = QString::number(ct).rightJustified(5, '0', false);
1525     }
1526     return m_projectFolder.path() + "/ladspa/" + counter + ".ladspa";
1527 }
1528
1529 #include "kdenlivedoc.moc"
1530