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