]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
816f7b368425a135d61e69e1b1082d90f47caf06
[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
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 QString KdenliveDoc::profilePath() const {
869     return m_profile.path;
870 }
871
872 MltVideoProfile KdenliveDoc::mltProfile() const {
873     return m_profile;
874 }
875
876 void KdenliveDoc::setProfilePath(QString path) {
877     if (path.isEmpty()) path = KdenliveSettings::default_profile();
878     if (path.isEmpty()) path = "dv_pal";
879     m_profile = ProfilesDialog::getVideoProfile(path);
880     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
881     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
882     m_width = m_profile.width;
883     m_height = m_profile.height;
884     kDebug() << "KDEnnlive document, init timecode from path: " << path << ",  " << m_fps;
885     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
886     else m_timecode.setFormat((int) m_fps);
887 }
888
889 const double KdenliveDoc::dar() {
890     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
891 }
892
893 void KdenliveDoc::setThumbsProgress(const QString &message, int progress) {
894     emit progressInfo(message, progress);
895 }
896
897 void KdenliveDoc::loadingProgressed() {
898     m_documentLoadingProgress += m_documentLoadingStep;
899     emit progressInfo(QString(), (int) m_documentLoadingProgress);
900 }
901
902 QUndoStack *KdenliveDoc::commandStack() {
903     return m_commandStack;
904 }
905
906 void KdenliveDoc::setRenderer(Render *render) {
907     if (m_render) return;
908     m_render = render;
909     emit progressInfo(i18n("Loading playlist..."), 0);
910     //qApp->processEvents();
911     if (m_render) {
912         m_render->setSceneList(m_document.toString(), m_startPos);
913         kDebug() << "// SETTING SCENE LIST:\n\n" << m_document.toString();
914         checkProjectClips();
915     }
916     emit progressInfo(QString(), -1);
917 }
918
919 void KdenliveDoc::checkProjectClips() {
920     if (m_render == NULL) return;
921     QList <Mlt::Producer *> prods = m_render->producersList();
922     QString id ;
923     QString prodId ;
924     QString prodTrack ;
925     for (int i = 0; i < prods.count(); i++) {
926         id = prods.at(i)->get("id");
927         prodId = id.section('_', 0, 0);
928         prodTrack = id.section('_', 1, 1);
929         kDebug() << "CHECK PRO CLIP, ID: " << id;
930         DocClipBase *clip = m_clipManager->getClipById(prodId);
931         if (clip) clip->setProducer(prods.at(i));
932         kDebug() << "CHECK PRO CLIP, ID: " << id << " DONE";
933         if (clip && clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
934             // regenerate text clip image if required
935             kDebug() << "// TITLE: " << clip->getProperty("titlename") << " Preview file: " << clip->getProperty("resource") << " DOES NOT EXIST";
936             QString titlename = clip->getProperty("titlename");
937             QString titleresource;
938             if (titlename.isEmpty()) {
939                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
940                 titlename = titleInfo.at(0);
941                 titleresource = titleInfo.at(1);
942                 clip->setProperty("titlename", titlename);
943                 kDebug() << "// New title set to: " << titlename;
944             } else {
945                 titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
946             }
947             QString titlepath = projectFolder().path() + "/titles/";
948             TitleWidget *dia_ui = new TitleWidget(KUrl(), titlepath, m_render, kapp->activeWindow());
949             QDomDocument doc;
950             doc.setContent(clip->getProperty("xmldata"));
951             dia_ui->setXml(doc);
952             QPixmap pix = dia_ui->renderedPixmap();
953             pix.save(titleresource);
954             clip->setProperty("resource", titleresource);
955             delete dia_ui;
956             clip->producer()->set("force_reload", 1);
957         }
958     }
959 }
960
961 Render *KdenliveDoc::renderer() {
962     return m_render;
963 }
964
965 void KdenliveDoc::updateClip(const QString &id) {
966     emit updateClipDisplay(id);
967 }
968
969 int KdenliveDoc::getFramePos(QString duration) {
970     return m_timecode.getFrameCount(duration, m_fps);
971 }
972
973 QString KdenliveDoc::producerName(const QString &id) {
974     QString result = "unnamed";
975     QDomNodeList prods = producersList();
976     int ct = prods.count();
977     for (int i = 0; i <  ct ; i++) {
978         QDomElement e = prods.item(i).toElement();
979         if (e.attribute("id") != "black" && e.attribute("id") == id) {
980             result = e.attribute("name");
981             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
982             break;
983         }
984     }
985     return result;
986 }
987
988 void KdenliveDoc::setProducerDuration(const QString &id, int duration) {
989     QDomNodeList prods = producersList();
990     int ct = prods.count();
991     for (int i = 0; i <  ct ; i++) {
992         QDomElement e = prods.item(i).toElement();
993         if (e.attribute("id") != "black" && e.attribute("id") == id) {
994             e.setAttribute("duration", QString::number(duration));
995             break;
996         }
997     }
998 }
999
1000 int KdenliveDoc::getProducerDuration(const QString &id) {
1001     int result = 0;
1002     QDomNodeList prods = producersList();
1003     int ct = prods.count();
1004     for (int i = 0; i <  ct ; i++) {
1005         QDomElement e = prods.item(i).toElement();
1006         if (e.attribute("id") != "black" && e.attribute("id") == id) {
1007             result = e.attribute("duration").toInt();
1008             break;
1009         }
1010     }
1011     return result;
1012 }
1013
1014
1015 QDomDocument KdenliveDoc::generateSceneList() {
1016     QDomDocument doc;
1017     QDomElement westley = doc.createElement("westley");
1018     doc.appendChild(westley);
1019     QDomElement prod = doc.createElement("producer");
1020 }
1021
1022 QDomDocument KdenliveDoc::toXml() const {
1023     return m_document;
1024 }
1025
1026 Timecode KdenliveDoc::timecode() const {
1027     return m_timecode;
1028 }
1029
1030 QDomNodeList KdenliveDoc::producersList() {
1031     return m_document.elementsByTagName("producer");
1032 }
1033
1034 void KdenliveDoc::backupMltPlaylist() {
1035     if (m_render) m_scenelist = m_render->sceneList();
1036 }
1037
1038 double KdenliveDoc::projectDuration() const {
1039     if (m_render) return GenTime(m_render->getLength(), m_fps).ms() / 1000;
1040 }
1041
1042 double KdenliveDoc::fps() const {
1043     return m_fps;
1044 }
1045
1046 int KdenliveDoc::width() const {
1047     return m_width;
1048 }
1049
1050 int KdenliveDoc::height() const {
1051     return m_height;
1052 }
1053
1054 KUrl KdenliveDoc::url() const {
1055     return m_url;
1056 }
1057
1058 void KdenliveDoc::setUrl(KUrl url) {
1059     m_url = url;
1060 }
1061
1062 void KdenliveDoc::setModified(bool mod) {
1063     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
1064         m_autoSaveTimer->start(3000);
1065     }
1066     if (mod == m_modified) return;
1067     m_modified = mod;
1068     emit docModified(m_modified);
1069 }
1070
1071 bool KdenliveDoc::isModified() const {
1072     return m_modified;
1073 }
1074
1075 QString KdenliveDoc::description() const {
1076     if (m_url.isEmpty())
1077         return i18n("Untitled") + " / " + m_profile.description;
1078     else
1079         return m_url.fileName() + " / " + m_profile.description;
1080 }
1081
1082 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem) {
1083     const QString producerId = clipId.section('_', 0, 0);
1084     int subtrack = clipId.section('_', 1, 1).toInt();
1085     DocClipBase *clip = m_clipManager->getClipById(producerId);
1086     if (clip == NULL) {
1087         elem.setAttribute("id", producerId);
1088         QString path = elem.attribute("resource");
1089         QString extension;
1090         if (elem.attribute("type").toInt() == SLIDESHOW) {
1091             extension = KUrl(path).fileName();
1092             path = KUrl(path).directory();
1093         }
1094         if (!path.isEmpty() && !QFile::exists(path)) {
1095             const QString size = elem.attribute("file_size");
1096             const QString hash = elem.attribute("file_hash");
1097             QString newpath;
1098             KMessageBox::ButtonCode action = KMessageBox::No;
1099             if (!size.isEmpty() && !hash.isEmpty()) {
1100                 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
1101                 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")));
1102             } else {
1103                 if (elem.attribute("type").toInt() == SLIDESHOW) {
1104                     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)
1105                         newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1106                 } else newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1107             }
1108             if (action == KMessageBox::Yes) {
1109                 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1110                 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1111                 if (!m_searchFolder.isEmpty()) {
1112                     newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1113                 }
1114             }
1115             if (!newpath.isEmpty()) {
1116                 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
1117                 elem.setAttribute("resource", newpath);
1118                 setNewClipResource(clipId, newpath);
1119                 setModified(true);
1120             }
1121         }
1122         clip = new DocClipBase(m_clipManager, elem, producerId);
1123         m_clipManager->addClip(clip);
1124     }
1125     if (createClipItem) emit addProjectClip(clip);
1126 }
1127
1128 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path) {
1129     QDomNodeList prods = m_document.elementsByTagName("producer");
1130     int maxprod = prods.count();
1131     for (int i = 0; i < maxprod; i++) {
1132         QDomNode m = prods.at(i);
1133         QString prodId = m.toElement().attribute("id");
1134         if (prodId == id || prodId.startsWith(id + "_")) {
1135             QDomNodeList params = m.childNodes();
1136             for (int j = 0; j < params.count(); j++) {
1137                 QDomElement e = params.item(j).toElement();
1138                 if (e.attribute("name") == "resource") {
1139                     e.firstChild().setNodeValue(path);
1140                     break;
1141                 }
1142             }
1143         }
1144     }
1145 }
1146
1147 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const {
1148     QString foundFileName;
1149     QByteArray fileData;
1150     QByteArray fileHash;
1151     QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1152     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1153         QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1154         if (file.open(QIODevice::ReadOnly)) {
1155             if (QString::number(file.size()) == matchSize) {
1156                 /*
1157                 * 1 MB = 1 second per 450 files (or faster)
1158                 * 10 MB = 9 seconds per 450 files (or faster)
1159                 */
1160                 if (file.size() > 1000000*2) {
1161                     fileData = file.read(1000000);
1162                     if (file.seek(file.size() - 1000000))
1163                         fileData.append(file.readAll());
1164                 } else
1165                     fileData = file.readAll();
1166                 file.close();
1167                 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1168                 if (QString(fileHash.toHex()) == matchHash)
1169                     return file.fileName();
1170             }
1171         }
1172         kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1173     }
1174     filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1175     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1176         foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1177         if (!foundFileName.isEmpty())
1178             break;
1179     }
1180     return foundFileName;
1181 }
1182
1183 void KdenliveDoc::addClipInfo(QDomElement elem, QString clipId) {
1184     DocClipBase *clip = m_clipManager->getClipById(clipId);
1185     if (clip == NULL) {
1186         addClip(elem, clipId);
1187     } else {
1188         QMap <QString, QString> properties;
1189         QDomNamedNodeMap attributes = elem.attributes();
1190         QString attrname;
1191         for (unsigned int i = 0; i < attributes.count(); i++) {
1192             attrname = attributes.item(i).nodeName();
1193             if (attrname != "resource")
1194                 properties.insert(attrname, attributes.item(i).nodeValue());
1195             kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1196         }
1197         clip->setProperties(properties);
1198         emit addProjectClip(clip);
1199     }
1200 }
1201
1202 void KdenliveDoc::addFolder(const QString foldername, const QString &clipId, bool edit) {
1203     emit addProjectFolder(foldername, clipId, false, edit);
1204 }
1205
1206 void KdenliveDoc::deleteFolder(const QString foldername, const QString &clipId) {
1207     emit addProjectFolder(foldername, clipId, true);
1208 }
1209
1210 void KdenliveDoc::deleteProjectClip(QList <QString> ids) {
1211     for (int i = 0; i < ids.size(); ++i) {
1212         emit deleteTimelineClip(ids.at(i));
1213         m_clipManager->slotDeleteClip(ids.at(i));
1214     }
1215     setModified(true);
1216 }
1217
1218 void KdenliveDoc::deleteProjectFolder(QMap <QString, QString> map) {
1219     QMapIterator<QString, QString> i(map);
1220     while (i.hasNext()) {
1221         i.next();
1222         slotDeleteFolder(i.key(), i.value());
1223     }
1224     setModified(true);
1225 }
1226
1227 void KdenliveDoc::deleteClip(const QString &clipId) {
1228     emit signalDeleteProjectClip(clipId);
1229     m_clipManager->deleteClip(clipId);
1230 }
1231
1232 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId) {
1233     m_clipManager->slotAddClipList(urls, group, groupId);
1234     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1235     setModified(true);
1236 }
1237
1238
1239 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId) {
1240     kDebug() << "/////////  DOCUM, ADD CLP: " << url;
1241     m_clipManager->slotAddClipFile(url, group, groupId);
1242     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1243     setModified(true);
1244 }
1245
1246 void KdenliveDoc::slotAddFolder(const QString folderName) {
1247     AddFolderCommand *command = new AddFolderCommand(this, folderName, QString::number(m_clipManager->getFreeClipId()), true);
1248     commandStack()->push(command);
1249     setModified(true);
1250 }
1251
1252 void KdenliveDoc::slotDeleteFolder(const QString folderName, const QString &id) {
1253     AddFolderCommand *command = new AddFolderCommand(this, folderName, id, false);
1254     commandStack()->push(command);
1255     setModified(true);
1256 }
1257
1258 void KdenliveDoc::slotEditFolder(const QString newfolderName, const QString oldfolderName, const QString &clipId) {
1259     EditFolderCommand *command = new EditFolderCommand(this, newfolderName, oldfolderName, clipId, false);
1260     commandStack()->push(command);
1261     setModified(true);
1262 }
1263
1264 const QString&KdenliveDoc::getFreeClipId() {
1265     return QString::number(m_clipManager->getFreeClipId());
1266 }
1267
1268 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId) {
1269     return m_clipManager->getClipById(clipId);
1270 }
1271
1272 void KdenliveDoc::slotAddColorClipFile(const QString name, const QString color, QString duration, const QString group, const QString &groupId) {
1273     m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1274     setModified(true);
1275 }
1276
1277 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) {
1278     m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop, fade, luma_duration, luma_file, softness, group, groupId);
1279     setModified(true);
1280 }
1281
1282 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId) {
1283     QString titlesFolder = projectFolder().path() + "/titles/";
1284     KStandardDirs::makeDir(titlesFolder);
1285     TitleWidget *dia_ui = new TitleWidget(KUrl(), titlesFolder, m_render, kapp->activeWindow());
1286     if (dia_ui->exec() == QDialog::Accepted) {
1287         QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1288         QPixmap pix = dia_ui->renderedPixmap();
1289         pix.save(titleInfo.at(1));
1290         //dia_ui->saveTitle(path + ".kdenlivetitle");
1291         m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), QString(), QString());
1292         setModified(true);
1293     }
1294     delete dia_ui;
1295 }
1296
1297 int KdenliveDoc::tracksCount() const {
1298     return m_tracksList.count();
1299 }
1300
1301 TrackInfo KdenliveDoc::trackInfoAt(int ix) const {
1302     return m_tracksList.at(ix);
1303 }
1304
1305 void KdenliveDoc::switchTrackAudio(int ix, bool hide) {
1306     m_tracksList[ix].isMute = hide; // !m_tracksList.at(ix).isMute;
1307 }
1308
1309 void KdenliveDoc::switchTrackVideo(int ix, bool hide) {
1310     m_tracksList[ix].isBlind = hide; // !m_tracksList.at(ix).isBlind;
1311 }
1312
1313 void KdenliveDoc::insertTrack(int ix, TrackInfo type) {
1314     if (ix == -1) m_tracksList << type;
1315     else m_tracksList.insert(ix, type);
1316 }
1317
1318 void KdenliveDoc::deleteTrack(int ix) {
1319     m_tracksList.removeAt(ix);
1320 }
1321
1322 void KdenliveDoc::setTrackType(int ix, TrackInfo type) {
1323     m_tracksList[ix].type = type.type;
1324     m_tracksList[ix].isMute = type.isMute;
1325     m_tracksList[ix].isBlind = type.isBlind;
1326 }
1327
1328 const QList <TrackInfo> KdenliveDoc::tracksList() const {
1329     return m_tracksList;
1330 }
1331
1332 QPoint KdenliveDoc::getTracksCount() const {
1333     int audio = 0;
1334     int video = 0;
1335     foreach(const TrackInfo &info, m_tracksList) {
1336         if (info.type == VIDEOTRACK) video++;
1337         else audio++;
1338     }
1339     return QPoint(video, audio);
1340 }
1341
1342 QString KdenliveDoc::getTracksInfo() const {
1343     QString result;
1344     foreach(const TrackInfo &info, m_tracksList) {
1345         if (info.type == VIDEOTRACK) result.append('v');
1346         else result.append('a');
1347     }
1348     return result;
1349 }
1350
1351 #include "kdenlivedoc.moc"
1352