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