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