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