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