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