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