]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
Working on 358: Resize clip in timeline from clip end causes clip to disappear or...
[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("zoom", m_zoom);
775
776     QDomElement e;
777     QList <DocClipBase*> list = m_clipManager->documentClipList();
778     for (int i = 0; i < list.count(); i++) {
779         e = list.at(i)->toXML();
780         e.setTagName("kdenlive_producer");
781         addedXml.appendChild(sceneList.importNode(e, true));
782         QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
783         for (int j = 0; j < marks.count(); j++) {
784             QDomElement marker = sceneList.createElement("marker");
785             marker.setAttribute("time", marks.at(j).time().ms() / 1000);
786             marker.setAttribute("comment", marks.at(j).comment());
787             marker.setAttribute("id", e.attribute("id"));
788             markers.appendChild(marker);
789         }
790     }
791     addedXml.appendChild(markers);
792     if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml, true));
793
794     wes.appendChild(addedXml);
795     //wes.appendChild(doc.importNode(kdenliveData, true));
796
797     QFile file(path);
798     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
799         kWarning() << "//////  ERROR writing to file: " << path;
800         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
801         return false;
802     }
803     QTextStream out(&file);
804     out << sceneList.toString();
805     file.close();
806     return true;
807 }
808
809 QDomElement KdenliveDoc::documentInfoXml() {
810     QDomDocument doc;
811     QDomElement e;
812     QDomElement addedXml = doc.createElement("kdenlivedoc");
813     QDomElement markers = doc.createElement("markers");
814     addedXml.setAttribute("version", "0.7");
815     addedXml.setAttribute("profile", profilePath());
816     addedXml.setAttribute("position", m_render->seekPosition().frames(m_fps));
817     addedXml.setAttribute("zoom", m_zoom);
818     QList <DocClipBase*> list = m_clipManager->documentClipList();
819     for (int i = 0; i < list.count(); i++) {
820         e = list.at(i)->toXML();
821         e.setTagName("kdenlive_producer");
822         addedXml.appendChild(doc.importNode(e, true));
823         QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
824         for (int j = 0; j < marks.count(); j++) {
825             QDomElement marker = doc.createElement("marker");
826             marker.setAttribute("time", marks.at(j).time().ms() / 1000);
827             marker.setAttribute("comment", marks.at(j).comment());
828             marker.setAttribute("id", e.attribute("id"));
829             markers.appendChild(marker);
830         }
831     }
832     addedXml.appendChild(markers);
833     if (!m_guidesXml.isNull()) addedXml.appendChild(doc.importNode(m_guidesXml, true));
834     //kDebug() << m_document.toString();
835     return addedXml;
836 }
837
838
839 ClipManager *KdenliveDoc::clipManager() {
840     return m_clipManager;
841 }
842
843 KUrl KdenliveDoc::projectFolder() const {
844     if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
845     return m_projectFolder;
846 }
847
848 QString KdenliveDoc::profilePath() const {
849     return m_profile.path;
850 }
851
852 MltVideoProfile KdenliveDoc::mltProfile() const {
853     return m_profile;
854 }
855
856 void KdenliveDoc::setProfilePath(QString path) {
857     if (path.isEmpty()) path = KdenliveSettings::default_profile();
858     if (path.isEmpty()) path = "dv_pal";
859     m_profile = ProfilesDialog::getVideoProfile(path);
860     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
861     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
862     m_width = m_profile.width;
863     m_height = m_profile.height;
864     kDebug() << "KDEnnlive document, init timecode from path: " << path << ",  " << m_fps;
865     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
866     else m_timecode.setFormat((int) m_fps);
867 }
868
869 const double KdenliveDoc::dar() {
870     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
871 }
872
873 void KdenliveDoc::setThumbsProgress(const QString &message, int progress) {
874     emit progressInfo(message, progress);
875 }
876
877 void KdenliveDoc::loadingProgressed() {
878     m_documentLoadingProgress += m_documentLoadingStep;
879     emit progressInfo(QString(), (int) m_documentLoadingProgress);
880 }
881
882 QUndoStack *KdenliveDoc::commandStack() {
883     return m_commandStack;
884 }
885
886 void KdenliveDoc::setRenderer(Render *render) {
887     if (m_render) return;
888     m_render = render;
889     emit progressInfo(i18n("Loading playlist..."), 0);
890     //qApp->processEvents();
891     if (m_render) {
892         m_render->setSceneList(m_document.toString(), m_startPos);
893         checkProjectClips();
894     }
895     emit progressInfo(QString(), -1);
896 }
897
898 void KdenliveDoc::checkProjectClips() {
899     if (m_render == NULL) return;
900     QList <Mlt::Producer *> prods = m_render->producersList();
901     QString id ;
902     QString prodId ;
903     QString prodTrack ;
904     for (int i = 0; i < prods.count(); i++) {
905         id = prods.at(i)->get("id");
906         prodId = id.section('_', 0, 0);
907         prodTrack = id.section('_', 1, 1);
908         kDebug() << "CHECK PRO CLIP, ID: " << id;
909         DocClipBase *clip = m_clipManager->getClipById(prodId);
910         if (clip) clip->setProducer(prods.at(i));
911         kDebug() << "CHECK PRO CLIP, ID: " << id << " DONE";
912         if (clip && clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
913             // regenerate text clip image if required
914             kDebug() << "// TITLE: " << clip->getProperty("titlename") << " Preview file: " << clip->getProperty("resource") << " DOES NOT EXIST";
915             QString titlename = clip->getProperty("titlename");
916             QString titleresource;
917             if (titlename.isEmpty()) {
918                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
919                 titlename = titleInfo.at(0);
920                 titleresource = titleInfo.at(1);
921                 clip->setProperty("titlename", titlename);
922                 kDebug() << "// New title set to: " << titlename;
923             } else {
924                 titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
925             }
926             QString titlepath = projectFolder().path() + "/titles/";
927             TitleWidget *dia_ui = new TitleWidget(KUrl(), titlepath, m_render, kapp->activeWindow());
928             QDomDocument doc;
929             doc.setContent(clip->getProperty("xmldata"));
930             dia_ui->setXml(doc);
931             QPixmap pix = dia_ui->renderedPixmap();
932             pix.save(titleresource);
933             clip->setProperty("resource", titleresource);
934             delete dia_ui;
935             clip->producer()->set("force_reload", 1);
936         }
937     }
938 }
939
940 Render *KdenliveDoc::renderer() {
941     return m_render;
942 }
943
944 void KdenliveDoc::updateClip(const QString &id) {
945     emit updateClipDisplay(id);
946 }
947
948 int KdenliveDoc::getFramePos(QString duration) {
949     return m_timecode.getFrameCount(duration, m_fps);
950 }
951
952 QString KdenliveDoc::producerName(const QString &id) {
953     QString result = "unnamed";
954     QDomNodeList prods = producersList();
955     int ct = prods.count();
956     for (int i = 0; i <  ct ; i++) {
957         QDomElement e = prods.item(i).toElement();
958         if (e.attribute("id") != "black" && e.attribute("id") == id) {
959             result = e.attribute("name");
960             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
961             break;
962         }
963     }
964     return result;
965 }
966
967 void KdenliveDoc::setProducerDuration(const QString &id, int duration) {
968     QDomNodeList prods = producersList();
969     int ct = prods.count();
970     for (int i = 0; i <  ct ; i++) {
971         QDomElement e = prods.item(i).toElement();
972         if (e.attribute("id") != "black" && e.attribute("id") == id) {
973             e.setAttribute("duration", QString::number(duration));
974             break;
975         }
976     }
977 }
978
979 int KdenliveDoc::getProducerDuration(const QString &id) {
980     int result = 0;
981     QDomNodeList prods = producersList();
982     int ct = prods.count();
983     for (int i = 0; i <  ct ; i++) {
984         QDomElement e = prods.item(i).toElement();
985         if (e.attribute("id") != "black" && e.attribute("id") == id) {
986             result = e.attribute("duration").toInt();
987             break;
988         }
989     }
990     return result;
991 }
992
993
994 QDomDocument KdenliveDoc::generateSceneList() {
995     QDomDocument doc;
996     QDomElement westley = doc.createElement("westley");
997     doc.appendChild(westley);
998     QDomElement prod = doc.createElement("producer");
999 }
1000
1001 QDomDocument KdenliveDoc::toXml() const {
1002     return m_document;
1003 }
1004
1005 Timecode KdenliveDoc::timecode() const {
1006     return m_timecode;
1007 }
1008
1009 QDomNodeList KdenliveDoc::producersList() {
1010     return m_document.elementsByTagName("producer");
1011 }
1012
1013 void KdenliveDoc::backupMltPlaylist() {
1014     if (m_render) m_scenelist = m_render->sceneList();
1015 }
1016
1017 double KdenliveDoc::projectDuration() const {
1018     if (m_render) return GenTime(m_render->getLength(), m_fps).ms() / 1000;
1019 }
1020
1021 double KdenliveDoc::fps() const {
1022     return m_fps;
1023 }
1024
1025 int KdenliveDoc::width() const {
1026     return m_width;
1027 }
1028
1029 int KdenliveDoc::height() const {
1030     return m_height;
1031 }
1032
1033 KUrl KdenliveDoc::url() const {
1034     return m_url;
1035 }
1036
1037 void KdenliveDoc::setUrl(KUrl url) {
1038     m_url = url;
1039 }
1040
1041 void KdenliveDoc::setModified(bool mod) {
1042     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
1043         m_autoSaveTimer->start(3000);
1044     }
1045     if (mod == m_modified) return;
1046     m_modified = mod;
1047     emit docModified(m_modified);
1048 }
1049
1050 bool KdenliveDoc::isModified() const {
1051     return m_modified;
1052 }
1053
1054 QString KdenliveDoc::description() const {
1055     if (m_url.isEmpty())
1056         return i18n("Untitled") + " / " + m_profile.description;
1057     else
1058         return m_url.fileName() + " / " + m_profile.description;
1059 }
1060
1061 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem) {
1062     const QString producerId = clipId.section('_', 0, 0);
1063     int subtrack = clipId.section('_', 1, 1).toInt();
1064     DocClipBase *clip = m_clipManager->getClipById(producerId);
1065     if (clip == NULL) {
1066         elem.setAttribute("id", producerId);
1067         QString path = elem.attribute("resource");
1068         QString extension;
1069         if (elem.attribute("type").toInt() == SLIDESHOW) {
1070             extension = KUrl(path).fileName();
1071             path = KUrl(path).directory();
1072         }
1073         if (!path.isEmpty() && !QFile::exists(path)) {
1074             const QString size = elem.attribute("file_size");
1075             const QString hash = elem.attribute("file_hash");
1076             QString newpath;
1077             KMessageBox::ButtonCode action = KMessageBox::No;
1078             if (!size.isEmpty() && !hash.isEmpty()) {
1079                 if (!m_searchFolder.isEmpty()) newpath = searchFileRecursively(m_searchFolder, size, hash);
1080                 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")));
1081             } else {
1082                 if (elem.attribute("type").toInt() == SLIDESHOW) {
1083                     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)
1084                         newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Looking for %1", path));
1085                 } else newpath = KFileDialog::getOpenFileName(KUrl("kfiledialog:///clipfolder"), QString(), kapp->activeWindow(), i18n("Looking for %1", path));
1086             }
1087             if (action == KMessageBox::Yes) {
1088                 kDebug() << "// ASKED FOR SRCH CLIP: " << clipId;
1089                 m_searchFolder = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow());
1090                 if (!m_searchFolder.isEmpty()) {
1091                     newpath = searchFileRecursively(QDir(m_searchFolder), size, hash);
1092                 }
1093             }
1094             if (!newpath.isEmpty()) {
1095                 if (elem.attribute("type").toInt() == SLIDESHOW) newpath.append('/' + extension);
1096                 elem.setAttribute("resource", newpath);
1097                 setNewClipResource(clipId, newpath);
1098                 setModified(true);
1099             }
1100         }
1101         clip = new DocClipBase(m_clipManager, elem, producerId);
1102         m_clipManager->addClip(clip);
1103     }
1104     if (createClipItem) emit addProjectClip(clip);
1105 }
1106
1107 void KdenliveDoc::setNewClipResource(const QString &id, const QString &path) {
1108     QDomNodeList prods = m_document.elementsByTagName("producer");
1109     int maxprod = prods.count();
1110     for (int i = 0; i < maxprod; i++) {
1111         QDomNode m = prods.at(i);
1112         QString prodId = m.toElement().attribute("id");
1113         if (prodId == id || prodId.startsWith(id + "_")) {
1114             QDomNodeList params = m.childNodes();
1115             for (int j = 0; j < params.count(); j++) {
1116                 QDomElement e = params.item(j).toElement();
1117                 if (e.attribute("name") == "resource") {
1118                     e.firstChild().setNodeValue(path);
1119                     break;
1120                 }
1121             }
1122         }
1123     }
1124 }
1125
1126 QString KdenliveDoc::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const {
1127     QString foundFileName;
1128     QByteArray fileData;
1129     QByteArray fileHash;
1130     QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
1131     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1132         QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
1133         if (file.open(QIODevice::ReadOnly)) {
1134             if (QString::number(file.size()) == matchSize) {
1135                 /*
1136                 * 1 MB = 1 second per 450 files (or faster)
1137                 * 10 MB = 9 seconds per 450 files (or faster)
1138                 */
1139                 if (file.size() > 1000000*2) {
1140                     fileData = file.read(1000000);
1141                     if (file.seek(file.size() - 1000000))
1142                         fileData.append(file.readAll());
1143                 } else
1144                     fileData = file.readAll();
1145                 file.close();
1146                 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
1147                 if (QString(fileHash.toHex()) == matchHash)
1148                     return file.fileName();
1149             }
1150         }
1151         kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
1152     }
1153     filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
1154     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
1155         foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
1156         if (!foundFileName.isEmpty())
1157             break;
1158     }
1159     return foundFileName;
1160 }
1161
1162 void KdenliveDoc::addClipInfo(QDomElement elem, QString clipId) {
1163     DocClipBase *clip = m_clipManager->getClipById(clipId);
1164     if (clip == NULL) {
1165         addClip(elem, clipId);
1166     } else {
1167         QMap <QString, QString> properties;
1168         QDomNamedNodeMap attributes = elem.attributes();
1169         QString attrname;
1170         for (unsigned int i = 0; i < attributes.count(); i++) {
1171             attrname = attributes.item(i).nodeName();
1172             if (attrname != "resource")
1173                 properties.insert(attrname, attributes.item(i).nodeValue());
1174             kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1175         }
1176         clip->setProperties(properties);
1177         emit addProjectClip(clip);
1178     }
1179 }
1180
1181 void KdenliveDoc::addFolder(const QString foldername, const QString &clipId, bool edit) {
1182     emit addProjectFolder(foldername, clipId, false, edit);
1183 }
1184
1185 void KdenliveDoc::deleteFolder(const QString foldername, const QString &clipId) {
1186     emit addProjectFolder(foldername, clipId, true);
1187 }
1188
1189 void KdenliveDoc::deleteProjectClip(QList <QString> ids) {
1190     for (int i = 0; i < ids.size(); ++i) {
1191         emit deleteTimelineClip(ids.at(i));
1192         m_clipManager->slotDeleteClip(ids.at(i));
1193     }
1194     setModified(true);
1195 }
1196
1197 void KdenliveDoc::deleteProjectFolder(QMap <QString, QString> map) {
1198     QMapIterator<QString, QString> i(map);
1199     while (i.hasNext()) {
1200         i.next();
1201         slotDeleteFolder(i.key(), i.value());
1202     }
1203     setModified(true);
1204 }
1205
1206 void KdenliveDoc::deleteClip(const QString &clipId) {
1207     emit signalDeleteProjectClip(clipId);
1208     m_clipManager->deleteClip(clipId);
1209 }
1210
1211 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId) {
1212     m_clipManager->slotAddClipList(urls, group, groupId);
1213     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1214     setModified(true);
1215 }
1216
1217
1218 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId) {
1219     kDebug() << "/////////  DOCUM, ADD CLP: " << url;
1220     m_clipManager->slotAddClipFile(url, group, groupId);
1221     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1222     setModified(true);
1223 }
1224
1225 void KdenliveDoc::slotAddFolder(const QString folderName) {
1226     AddFolderCommand *command = new AddFolderCommand(this, folderName, QString::number(m_clipManager->getFreeClipId()), true);
1227     commandStack()->push(command);
1228     setModified(true);
1229 }
1230
1231 void KdenliveDoc::slotDeleteFolder(const QString folderName, const QString &id) {
1232     AddFolderCommand *command = new AddFolderCommand(this, folderName, id, false);
1233     commandStack()->push(command);
1234     setModified(true);
1235 }
1236
1237 void KdenliveDoc::slotEditFolder(const QString newfolderName, const QString oldfolderName, const QString &clipId) {
1238     EditFolderCommand *command = new EditFolderCommand(this, newfolderName, oldfolderName, clipId, false);
1239     commandStack()->push(command);
1240     setModified(true);
1241 }
1242
1243 const QString&KdenliveDoc::getFreeClipId() {
1244     return QString::number(m_clipManager->getFreeClipId());
1245 }
1246
1247 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId) {
1248     return m_clipManager->getClipById(clipId);
1249 }
1250
1251 void KdenliveDoc::slotAddColorClipFile(const QString name, const QString color, QString duration, const QString group, const QString &groupId) {
1252     m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1253     setModified(true);
1254 }
1255
1256 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) {
1257     m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop, fade, luma_duration, luma_file, softness, group, groupId);
1258     setModified(true);
1259 }
1260
1261 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId) {
1262     QString titlesFolder = projectFolder().path() + "/titles/";
1263     KStandardDirs::makeDir(titlesFolder);
1264     TitleWidget *dia_ui = new TitleWidget(KUrl(), titlesFolder, m_render, kapp->activeWindow());
1265     if (dia_ui->exec() == QDialog::Accepted) {
1266         QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1267         QPixmap pix = dia_ui->renderedPixmap();
1268         pix.save(titleInfo.at(1));
1269         //dia_ui->saveTitle(path + ".kdenlivetitle");
1270         m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), QString(), QString());
1271         setModified(true);
1272     }
1273     delete dia_ui;
1274 }
1275
1276
1277
1278 #include "kdenlivedoc.moc"
1279