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