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