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