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