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