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