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