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