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