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