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