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