]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
Try to fix audio mixing bug ( http://www.kdenlive.org:80/mantis/view.php?id=228 )
[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 <KDebug>
21 #include <KStandardDirs>
22 #include <KMessageBox>
23 #include <KLocale>
24 #include <KFileDialog>
25 #include <KIO/NetAccess>
26 #include <KApplication>
27
28 #include <mlt++/Mlt.h>
29
30 #include "kdenlivedoc.h"
31 #include "docclipbase.h"
32 #include "profilesdialog.h"
33 #include "kdenlivesettings.h"
34 #include "renderer.h"
35 #include "clipmanager.h"
36 #include "addfoldercommand.h"
37 #include "editfoldercommand.h"
38 #include "titlewidget.h"
39 #include "mainwindow.h"
40
41
42 KdenliveDoc::KdenliveDoc(const KUrl &url, const KUrl &projectFolder, QUndoGroup *undoGroup, const QString &profileName, const QPoint tracks, MainWindow *parent): QObject(parent), m_render(NULL), 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) {
43     m_clipManager = new ClipManager(this);
44     if (!url.isEmpty()) {
45         QString tmpFile;
46         if (KIO::NetAccess::download(url.path(), tmpFile, parent)) {
47             QFile file(tmpFile);
48             m_document.setContent(&file, false);
49             file.close();
50             QDomNode infoXmlNode = m_document.elementsByTagName("kdenlivedoc").at(0);
51             QDomNode westley = m_document.elementsByTagName("westley").at(0);
52             if (!infoXmlNode.isNull()) {
53                 QDomElement infoXml = infoXmlNode.toElement();
54                 QString profilePath = infoXml.attribute("profile");
55                 m_startPos = infoXml.attribute("position").toInt();
56                 m_zoom = infoXml.attribute("zoom", "7").toInt();
57                 setProfilePath(profilePath);
58                 double version = infoXml.attribute("version").toDouble();
59                 if (version < 0.8) convertDocument(version);
60                 else {
61                     //delete all mlt producers and instead, use Kdenlive saved producers
62                     /*QDomNodeList prods = m_document.elementsByTagName("producer");
63                     int maxprod = prods.count();
64                     int pos = 0;
65                     for (int i = 0; i < maxprod; i++) {
66                         QDomNode m = prods.at(pos);
67                         QString prodId = m.toElement().attribute("id");
68                         if (prodId == "black" || prodId.startsWith("slowmotion"))
69                             pos++;
70                         else westley.removeChild(m);
71                     }*/
72                     /*prods = m_document.elementsByTagName("kdenlive_producer");
73                     maxprod = prods.count();
74                     for (int i = 0; i < maxprod; i++) {
75                         prods.at(0).toElement().setTagName("producer");
76                         westley.insertBefore(prods.at(0), QDomNode());
77                     }*/
78                 }
79                 QDomElement e;
80                 QDomNodeList producers = m_document.elementsByTagName("producer");
81                 QDomNodeList infoproducers = m_document.elementsByTagName("kdenlive_producer");
82                 const int max = producers.count();
83                 const int infomax = infoproducers.count();
84
85                 if (max > 0) {
86                     m_documentLoadingStep = 100.0 / (max + infomax + m_document.elementsByTagName("entry").count());
87                     parent->slotGotProgressInfo(i18n("Loading project clips"), (int) m_documentLoadingProgress);
88                 }
89
90                 for (int i = 0; i < max; i++) {
91                     e = producers.item(i).cloneNode().toElement();
92                     if (m_documentLoadingStep > 0) {
93                         m_documentLoadingProgress += m_documentLoadingStep;
94                         parent->slotGotProgressInfo(QString(), (int) m_documentLoadingProgress);
95                         //qApp->processEvents();
96                     }
97                     QString prodId = e.attribute("id");
98                     if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")/*&& prodId.toInt() > 0*/) {
99                         // addClip(e, prodId, false);
100                         kDebug() << "// PROD: " << prodId;
101                     }
102                 }
103
104                 for (int i = 0; i < infomax; i++) {
105                     e = infoproducers.item(i).cloneNode().toElement();
106                     if (m_documentLoadingStep > 0) {
107                         m_documentLoadingProgress += m_documentLoadingStep;
108                         parent->slotGotProgressInfo(QString(), (int) m_documentLoadingProgress);
109                         //qApp->processEvents();
110                     }
111                     QString prodId = e.attribute("id");
112                     if (!e.isNull() && prodId != "black" && !prodId.startsWith("slowmotion")) {
113                         e.setTagName("producer");
114                         addClipInfo(e, prodId);
115                         kDebug() << "// NLIVE PROD: " << prodId;
116                     }
117                 }
118
119                 QDomNode markers = m_document.elementsByTagName("markers").at(0);
120                 if (!markers.isNull()) {
121                     QDomNodeList markerslist = markers.childNodes();
122                     int maxchild = markerslist.count();
123                     for (int k = 0; k < maxchild; k++) {
124                         e = markerslist.at(k).toElement();
125                         if (e.tagName() == "marker") {
126                             m_clipManager->getClipById(e.attribute("id"))->addSnapMarker(GenTime(e.attribute("time").toDouble()), e.attribute("comment"));
127                         }
128                     }
129                     westley.removeChild(markers);
130                 }
131                 m_document.removeChild(infoXmlNode);
132
133                 kDebug() << "Reading file: " << url.path() << ", found clips: " << producers.count();
134             } else {
135                 parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
136                 kWarning() << "  NO KDENLIVE INFO FOUND IN FILE: " << url.path();
137                 m_document = createEmptyDocument(tracks.x(), tracks.y());
138                 setProfilePath(profileName);
139             }
140             KIO::NetAccess::removeTempFile(tmpFile);
141         } else {
142             KMessageBox::error(parent, KIO::NetAccess::lastErrorString());
143             parent->slotGotProgressInfo(i18n("File %1 is not a Kdenlive project file."), 100);
144             m_document = createEmptyDocument(tracks.x(), tracks.y());
145             setProfilePath(profileName);
146         }
147     } else {
148         m_document = createEmptyDocument(tracks.x(), tracks.y());
149         setProfilePath(profileName);
150     }
151     m_scenelist = m_document.toString();
152     kDebug() << "KDEnnlive document, init timecode: " << m_fps;
153     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
154     else m_timecode.setFormat((int) m_fps);
155
156     m_autoSaveTimer = new QTimer(this);
157     m_autoSaveTimer->setSingleShot(true);
158     connect(m_autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
159 }
160
161 KdenliveDoc::~KdenliveDoc() {
162     delete m_commandStack;
163     delete m_clipManager;
164     delete m_autoSaveTimer;
165     m_autosave->remove();
166 }
167
168 QDomDocument KdenliveDoc::createEmptyDocument(const int videotracks, const int audiotracks) {
169     // Creating new document
170     QDomDocument doc;
171     QDomElement westley = doc.createElement("westley");
172     doc.appendChild(westley);
173
174     QDomElement tractor = doc.createElement("tractor");
175     tractor.setAttribute("id", "maintractor");
176     QDomElement multitrack = doc.createElement("multitrack");
177     QDomElement playlist = doc.createElement("playlist");
178     playlist.setAttribute("id", "black_track");
179     westley.appendChild(playlist);
180
181
182     // create playlists
183     int total = audiotracks + videotracks + 1;
184
185     for (int i = 1; i < total; i++) {
186         QDomElement playlist = doc.createElement("playlist");
187         playlist.setAttribute("id", "playlist" + QString::number(i));
188         westley.appendChild(playlist);
189     }
190
191     QDomElement track0 = doc.createElement("track");
192     track0.setAttribute("producer", "black_track");
193     tractor.appendChild(track0);
194
195     // create audio tracks
196     for (int i = 1; i < audiotracks + 1; i++) {
197         QDomElement track = doc.createElement("track");
198         track.setAttribute("producer", "playlist" + QString::number(i));
199         track.setAttribute("hide", "video");
200         tractor.appendChild(track);
201     }
202
203     // create video tracks
204     for (int i = audiotracks + 1; i < total; i++) {
205         QDomElement track = doc.createElement("track");
206         track.setAttribute("producer", "playlist" + QString::number(i));
207         tractor.appendChild(track);
208     }
209
210     for (uint i = 2; i < total ; i++) {
211         QDomElement transition = doc.createElement("transition");
212         transition.setAttribute("always_active", "1");
213
214         QDomElement property = doc.createElement("property");
215         property.setAttribute("name", "a_track");
216         QDomText value = doc.createTextNode(QString::number(1));
217         property.appendChild(value);
218         transition.appendChild(property);
219
220         property = doc.createElement("property");
221         property.setAttribute("name", "b_track");
222         value = doc.createTextNode(QString::number(i));
223         property.appendChild(value);
224         transition.appendChild(property);
225
226         property = doc.createElement("property");
227         property.setAttribute("name", "mlt_service");
228         value = doc.createTextNode("mix");
229         property.appendChild(value);
230         transition.appendChild(property);
231
232         property = doc.createElement("property");
233         property.setAttribute("name", "combine");
234         value = doc.createTextNode("1");
235         property.appendChild(value);
236         transition.appendChild(property);
237
238         property = doc.createElement("property");
239         property.setAttribute("name", "internal_added");
240         value = doc.createTextNode("237");
241         property.appendChild(value);
242         transition.appendChild(property);
243         tractor.appendChild(transition);
244     }
245     westley.appendChild(tractor);
246     return doc;
247 }
248
249
250 void KdenliveDoc::syncGuides(QList <Guide *> guides) {
251     QDomDocument doc;
252     QDomElement e;
253     m_guidesXml.clear();
254     m_guidesXml = doc.createElement("guides");
255
256     for (int i = 0; i < guides.count(); i++) {
257         e = doc.createElement("guide");
258         e.setAttribute("time", guides.at(i)->position().ms() / 1000);
259         e.setAttribute("comment", guides.at(i)->label());
260         m_guidesXml.appendChild(e);
261     }
262     emit guidesUpdated();
263 }
264
265 QDomElement KdenliveDoc::guidesXml() const {
266     return m_guidesXml;
267 }
268
269 void KdenliveDoc::slotAutoSave() {
270     if (m_render) {
271         if (!m_autosave->isOpen() && !m_autosave->open(QIODevice::ReadWrite)) {
272             // show error: could not open the autosave file
273             kDebug() << "ERROR; CANNOT CREATE AUTOSAVE FILE";
274         }
275         kDebug() << "// AUTOSAVE FILE: " << m_autosave->fileName();
276         QDomDocument doc;
277         doc.setContent(m_render->sceneList());
278         saveSceneList(m_autosave->fileName(), doc);
279     }
280 }
281
282 void KdenliveDoc::setZoom(int factor) {
283     m_zoom = factor;
284 }
285
286 int KdenliveDoc::zoom() const {
287     return m_zoom;
288 }
289
290 void KdenliveDoc::convertDocument(double version) {
291     // Opening a old Kdenlive document
292     if (version == 0.7) {
293         // TODO: convert 0.7 files to the new document format.
294         return;
295     }
296     QDomNode westley = m_document.elementsByTagName("westley").at(1);
297     QDomNode tractor = m_document.elementsByTagName("tractor").at(0);
298     QDomNode kdenlivedoc = m_document.elementsByTagName("kdenlivedoc").at(0);
299     QDomNode multitrack = m_document.elementsByTagName("multitrack").at(0);
300     QDomNodeList playlists = m_document.elementsByTagName("playlist");
301
302     m_startPos = kdenlivedoc.toElement().attribute("timeline_position").toInt();
303
304     QDomNode props = m_document.elementsByTagName("properties").at(0).toElement();
305     QString profile = props.toElement().attribute("videoprofile");
306     if (profile == "dv_wide") profile = "dv_pal_wide";
307     setProfilePath(profile);
308
309     // move playlists outside of tractor and add the tracks instead
310     int max = playlists.count();
311     for (int i = 0; i < max; i++) {
312         QDomNode n = playlists.at(i);
313         westley.insertBefore(n, QDomNode());
314         QDomElement pl = n.toElement();
315         QDomElement track = m_document.createElement("track");
316         QString trackType = pl.attribute("hide");
317         if (!trackType.isEmpty()) track.setAttribute("hide", trackType);
318         QString playlist_id =  pl.attribute("id");
319         if (playlist_id.isEmpty()) {
320             playlist_id = "black_track";
321             pl.setAttribute("id", playlist_id);
322         }
323         track.setAttribute("producer", playlist_id);
324         //tractor.appendChild(track);
325         tractor.insertAfter(track, QDomNode());
326     }
327     tractor.removeChild(multitrack);
328
329     // audio track mixing transitions should not be added to track view, so add required attribute
330     QDomNodeList transitions = m_document.elementsByTagName("transition");
331     max = transitions.count();
332     for (int i = 0; i < max; i++) {
333         QDomElement tr = transitions.at(i).toElement();
334         if (tr.attribute("combine") == "1" && tr.attribute("mlt_service") == "mix") {
335             QDomElement property = m_document.createElement("property");
336             property.setAttribute("name", "internal_added");
337             QDomText value = m_document.createTextNode("237");
338             property.appendChild(value);
339             tr.appendChild(property);
340         } else {
341             // convert transition
342             QDomNamedNodeMap attrs = tr.attributes();
343             for (unsigned int j = 0; j < attrs.count(); j++) {
344                 QString attrName = attrs.item(j).nodeName();
345                 if (attrName != "in" && attrName != "out" && attrName != "id") {
346                     QDomElement property = m_document.createElement("property");
347                     property.setAttribute("name", attrName);
348                     QDomText value = m_document.createTextNode(attrs.item(j).nodeValue());
349                     property.appendChild(value);
350                     tr.appendChild(property);
351                 }
352             }
353         }
354     }
355
356     // move transitions after tracks
357     for (int i = 0; i < max; i++) {
358         tractor.insertAfter(transitions.at(0), QDomNode());
359     }
360
361     // Fix filters format
362     QDomNodeList entries = m_document.elementsByTagName("entry");
363     max = entries.count();
364     for (int i = 0; i < max; i++) {
365         QString last_id;
366         int effectix = 0;
367         QDomNode m = entries.at(i).firstChild();
368         while (!m.isNull()) {
369             if (m.toElement().tagName() == "filter") {
370                 QDomElement filt = m.toElement();
371                 QDomNamedNodeMap attrs = filt.attributes();
372                 QString current_id = filt.attribute("kdenlive_id");
373                 if (current_id != last_id) {
374                     effectix++;
375                     last_id = current_id;
376                 }
377                 QDomElement e = m_document.createElement("property");
378                 e.setAttribute("name", "kdenlive_ix");
379                 QDomText value = m_document.createTextNode(QString::number(effectix));
380                 e.appendChild(value);
381                 filt.appendChild(e);
382                 for (int j = 0; j < attrs.count(); j++) {
383                     QDomAttr a = attrs.item(j).toAttr();
384                     if (!a.isNull()) {
385                         kDebug() << " FILTER; adding :" << a.name() << ":" << a.value();
386                         QDomElement e = m_document.createElement("property");
387                         e.setAttribute("name", a.name());
388                         QDomText value = m_document.createTextNode(a.value());
389                         e.appendChild(value);
390                         filt.appendChild(e);
391
392                     }
393                 }
394             }
395             m = m.nextSibling();
396         }
397     }
398
399     /*
400         QDomNodeList filters = m_document.elementsByTagName("filter");
401         max = filters.count();
402         QString last_id;
403         int effectix = 0;
404         for (int i = 0; i < max; i++) {
405             QDomElement filt = filters.at(i).toElement();
406             QDomNamedNodeMap attrs = filt.attributes();
407      QString current_id = filt.attribute("kdenlive_id");
408      if (current_id != last_id) {
409          effectix++;
410          last_id = current_id;
411      }
412      QDomElement e = m_document.createElement("property");
413             e.setAttribute("name", "kdenlive_ix");
414             QDomText value = m_document.createTextNode(QString::number(1));
415             e.appendChild(value);
416             filt.appendChild(e);
417             for (int j = 0; j < attrs.count(); j++) {
418                 QDomAttr a = attrs.item(j).toAttr();
419                 if (!a.isNull()) {
420                     kDebug() << " FILTER; adding :" << a.name() << ":" << a.value();
421                     QDomElement e = m_document.createElement("property");
422                     e.setAttribute("name", a.name());
423                     QDomText value = m_document.createTextNode(a.value());
424                     e.appendChild(value);
425                     filt.appendChild(e);
426                 }
427             }
428         }*/
429
430     // fix slowmotion
431     QDomNodeList producers = westley.toElement().elementsByTagName("producer");
432     max = producers.count();
433     for (int i = 0; i < max; i++) {
434         QDomElement prod = producers.at(i).toElement();
435         if (prod.attribute("mlt_service") == "framebuffer") {
436             QString slowmotionprod = prod.attribute("resource");
437             slowmotionprod.replace(':', '?');
438             kDebug() << "// FOUND WRONG SLOWMO, new: " << slowmotionprod;
439             prod.setAttribute("resource", slowmotionprod);
440         }
441     }
442     // move producers to correct place, markers to a global list, fix clip descriptions
443     QDomElement markers = m_document.createElement("markers");
444     producers = m_document.elementsByTagName("producer");
445     max = producers.count();
446     for (int i = 0; i < max; i++) {
447         QDomElement prod = producers.at(0).toElement();
448         QDomNode m = prod.firstChild();
449         if (!m.isNull()) {
450             if (m.toElement().tagName() == "markers") {
451                 QDomNodeList prodchilds = m.childNodes();
452                 int maxchild = prodchilds.count();
453                 for (int k = 0; k < maxchild; k++) {
454                     QDomElement mark = prodchilds.at(0).toElement();
455                     mark.setAttribute("id", prod.attribute("id"));
456                     markers.insertAfter(mark, QDomNode());
457                 }
458                 prod.removeChild(m);
459             } else if (prod.attribute("type").toInt() == TEXT) {
460                 // convert title clip
461                 if (m.toElement().tagName() == "textclip") {
462                     QDomDocument tdoc;
463                     QDomElement titleclip = m.toElement();
464                     QDomElement title = tdoc.createElement("kdenlivetitle");
465                     tdoc.appendChild(title);
466                     QDomNodeList objects = titleclip.childNodes();
467                     int maxchild = objects.count();
468                     for (int k = 0; k < maxchild; k++) {
469                         QString objectxml;
470                         QDomElement ob = objects.at(k).toElement();
471                         if (ob.attribute("type") == "3") {
472                             // text object
473                             QDomElement item = tdoc.createElement("item");
474                             item.setAttribute("z-index", ob.attribute("z"));
475                             item.setAttribute("type", "QGraphicsTextItem");
476                             QDomElement position = tdoc.createElement("position");
477                             position.setAttribute("x", ob.attribute("x"));
478                             position.setAttribute("y", ob.attribute("y"));
479                             QDomElement content = tdoc.createElement("content");
480                             content.setAttribute("font", ob.attribute("font_family"));
481                             content.setAttribute("font-size", ob.attribute("font_size"));
482                             content.setAttribute("font-bold", ob.attribute("bold"));
483                             content.setAttribute("font-italic", ob.attribute("italic"));
484                             content.setAttribute("font-underline", ob.attribute("underline"));
485                             QString col = ob.attribute("color");
486                             QColor c(col);
487                             content.setAttribute("font-color", colorToString(c));
488                             QDomText conttxt = tdoc.createTextNode(ob.attribute("text"));
489                             content.appendChild(conttxt);
490                             item.appendChild(position);
491                             item.appendChild(content);
492                             title.appendChild(item);
493                         } else if (ob.attribute("type") == "5") {
494                             // rectangle object
495                             QDomElement item = tdoc.createElement("item");
496                             item.setAttribute("z-index", ob.attribute("z"));
497                             item.setAttribute("type", "QGraphicsRectItem");
498                             QDomElement position = tdoc.createElement("position");
499                             position.setAttribute("x", ob.attribute("x"));
500                             position.setAttribute("y", ob.attribute("y"));
501                             QDomElement content = tdoc.createElement("content");
502                             QString col = ob.attribute("color");
503                             QColor c(col);
504                             content.setAttribute("brushcolor", colorToString(c));
505                             QString rect = "0,0,";
506                             rect.append(ob.attribute("width"));
507                             rect.append(",");
508                             rect.append(ob.attribute("height"));
509                             content.setAttribute("rect", rect);
510                             item.appendChild(position);
511                             item.appendChild(content);
512                             title.appendChild(item);
513                         }
514                     }
515                     prod.setAttribute("xmldata", tdoc.toString());
516                     QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
517                     prod.setAttribute("titlename", titleInfo.at(0));
518                     prod.setAttribute("resource", titleInfo.at(1));
519                     //kDebug()<<"TITLE DATA:\n"<<tdoc.toString();
520                     prod.removeChild(m);
521                 }
522
523             } else if (m.isText()) {
524                 QString comment = m.nodeValue();
525                 if (!comment.isEmpty()) {
526                     prod.setAttribute("description", comment);
527                 }
528                 prod.removeChild(m);
529             }
530         }
531         int duration = prod.attribute("duration").toInt();
532         if (duration > 0) prod.setAttribute("out", QString::number(duration));
533         westley.insertBefore(prod, QDomNode());
534
535     }
536
537     QDomNode westley0 = m_document.elementsByTagName("westley").at(0);
538     if (!markers.firstChild().isNull()) westley0.appendChild(markers);
539     westley0.removeChild(kdenlivedoc);
540
541     QDomNodeList elements = westley.childNodes();
542     max = elements.count();
543     for (int i = 0; i < max; i++) {
544         QDomElement prod = elements.at(0).toElement();
545         westley0.insertAfter(prod, QDomNode());
546     }
547
548     westley0.removeChild(westley);
549
550     //kDebug() << "/////////////////  CONVERTED DOC:";
551     //kDebug() << m_document.toString();
552     //kDebug() << "/////////////////  END CONVERTED DOC:";
553 }
554
555 QString KdenliveDoc::colorToString(const QColor& c) {
556     QString ret = "%1,%2,%3,%4";
557     ret = ret.arg(c.red()).arg(c.green()).arg(c.blue()).arg(c.alpha());
558     return ret;
559 }
560
561 void KdenliveDoc::saveSceneList(const QString &path, QDomDocument sceneList) {
562     QDomNode wes = sceneList.elementsByTagName("westley").at(0);
563
564     QDomElement addedXml = sceneList.createElement("kdenlivedoc");
565     QDomElement markers = sceneList.createElement("markers");
566     addedXml.setAttribute("version", "0.8");
567     addedXml.setAttribute("profile", profilePath());
568     addedXml.setAttribute("position", m_render->seekPosition().frames(m_fps));
569     addedXml.setAttribute("zoom", m_zoom);
570
571     QDomElement e;
572     QList <DocClipBase*> list = m_clipManager->documentClipList();
573     for (int i = 0; i < list.count(); i++) {
574         e = list.at(i)->toXML();
575         e.setTagName("kdenlive_producer");
576         addedXml.appendChild(sceneList.importNode(e, true));
577         QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
578         for (int j = 0; j < marks.count(); j++) {
579             QDomElement marker = sceneList.createElement("marker");
580             marker.setAttribute("time", marks.at(j).time().ms() / 1000);
581             marker.setAttribute("comment", marks.at(j).comment());
582             marker.setAttribute("id", e.attribute("id"));
583             markers.appendChild(marker);
584         }
585     }
586     addedXml.appendChild(markers);
587     if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml, true));
588
589     wes.appendChild(addedXml);
590     //wes.appendChild(doc.importNode(kdenliveData, true));
591
592     QFile file(path);
593     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
594         kWarning() << "//////  ERROR writing to file: " << path;
595         return;
596     }
597     QTextStream out(&file);
598     out << sceneList.toString();
599     file.close();
600
601 }
602
603 QDomElement KdenliveDoc::documentInfoXml() {
604     QDomDocument doc;
605     QDomElement e;
606     QDomElement addedXml = doc.createElement("kdenlivedoc");
607     QDomElement markers = doc.createElement("markers");
608     addedXml.setAttribute("version", "0.7");
609     addedXml.setAttribute("profile", profilePath());
610     addedXml.setAttribute("position", m_render->seekPosition().frames(m_fps));
611     addedXml.setAttribute("zoom", m_zoom);
612     QList <DocClipBase*> list = m_clipManager->documentClipList();
613     for (int i = 0; i < list.count(); i++) {
614         e = list.at(i)->toXML();
615         e.setTagName("kdenlive_producer");
616         addedXml.appendChild(doc.importNode(e, true));
617         QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
618         for (int j = 0; j < marks.count(); j++) {
619             QDomElement marker = doc.createElement("marker");
620             marker.setAttribute("time", marks.at(j).time().ms() / 1000);
621             marker.setAttribute("comment", marks.at(j).comment());
622             marker.setAttribute("id", e.attribute("id"));
623             markers.appendChild(marker);
624         }
625     }
626     addedXml.appendChild(markers);
627     if (!m_guidesXml.isNull()) addedXml.appendChild(doc.importNode(m_guidesXml, true));
628     //kDebug() << m_document.toString();
629     return addedXml;
630 }
631
632
633 ClipManager *KdenliveDoc::clipManager() {
634     return m_clipManager;
635 }
636
637 KUrl KdenliveDoc::projectFolder() const {
638     if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
639     return m_projectFolder;
640 }
641
642 QString KdenliveDoc::getDocumentStandard() {
643     //WARNING: this way to tell the video standard is a bit hackish...
644     if (m_profile.description.contains("pal", Qt::CaseInsensitive) || m_profile.description.contains("25", Qt::CaseInsensitive) || m_profile.description.contains("50", Qt::CaseInsensitive)) return "PAL";
645     return "NTSC";
646 }
647
648 QString KdenliveDoc::profilePath() const {
649     return m_profile.path;
650 }
651
652 MltVideoProfile KdenliveDoc::mltProfile() const {
653     return m_profile;
654 }
655
656 void KdenliveDoc::setProfilePath(QString path) {
657     if (path.isEmpty()) path = KdenliveSettings::default_profile();
658     if (path.isEmpty()) path = "dv_pal";
659     m_profile = ProfilesDialog::getVideoProfile(path);
660     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
661     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
662     m_width = m_profile.width;
663     m_height = m_profile.height;
664     kDebug() << "KDEnnlive document, init timecode from path: " << path << ",  " << m_fps;
665     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
666     else m_timecode.setFormat((int) m_fps);
667 }
668
669 const double KdenliveDoc::dar() {
670     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
671 }
672
673 void KdenliveDoc::setThumbsProgress(const QString &message, int progress) {
674     emit progressInfo(message, progress);
675 }
676
677 void KdenliveDoc::loadingProgressed() {
678     m_documentLoadingProgress += m_documentLoadingStep;
679     emit progressInfo(QString(), (int) m_documentLoadingProgress);
680 }
681
682 QUndoStack *KdenliveDoc::commandStack() {
683     return m_commandStack;
684 }
685
686 void KdenliveDoc::setRenderer(Render *render) {
687     if (m_render) return;
688     m_render = render;
689     emit progressInfo(i18n("Loading playlist..."), 0);
690     //qApp->processEvents();
691     if (m_render) {
692         m_render->setSceneList(m_document.toString(), m_startPos);
693         checkProjectClips();
694     }
695     emit progressInfo(QString(), -1);
696 }
697
698 void KdenliveDoc::checkProjectClips() {
699     if (m_render == NULL) return;
700     QList <Mlt::Producer *> prods = m_render->producersList();
701     QString id ;
702     QString prodId ;
703     QString prodTrack ;
704     for (int i = 0; i < prods.count(); i++) {
705         id = prods.at(i)->get("id");
706         prodId = id.section('_', 0, 0);
707         prodTrack = id.section('_', 1, 1);
708         kDebug() << "CHECK PRO CLIP, ID: " << id;
709         DocClipBase *clip = m_clipManager->getClipById(prodId);
710         if (clip) clip->setProducer(prods.at(i));
711         kDebug() << "CHECK PRO CLIP, ID: " << id << " DONE";
712         if (clip && clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
713             // regenerate text clip image if required
714             kDebug() << "// TITLE: " << clip->getProperty("titlename") << " Preview file: " << clip->getProperty("resource") << " DOES NOT EXIST";
715             QString titlename = clip->getProperty("titlename");
716             QString titleresource;
717             if (titlename.isEmpty()) {
718                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
719                 titlename = titleInfo.at(0);
720                 titleresource = titleInfo.at(1);
721                 clip->setProperty("titlename", titlename);
722                 kDebug() << "// New title set to: " << titlename;
723             } else {
724                 titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
725             }
726             QString titlepath = projectFolder().path() + "/titles/";
727             TitleWidget *dia_ui = new TitleWidget(KUrl(), titlepath, m_render, kapp->activeWindow());
728             QDomDocument doc;
729             doc.setContent(clip->getProperty("xmldata"));
730             dia_ui->setXml(doc);
731             QPixmap pix = dia_ui->renderedPixmap();
732             pix.save(titleresource);
733             clip->setProperty("resource", titleresource);
734             delete dia_ui;
735             clip->producer()->set("force_reload", 1);
736         }
737     }
738 }
739
740 Render *KdenliveDoc::renderer() {
741     return m_render;
742 }
743
744 void KdenliveDoc::updateClip(const QString &id) {
745     emit updateClipDisplay(id);
746 }
747
748 int KdenliveDoc::getFramePos(QString duration) {
749     return m_timecode.getFrameCount(duration, m_fps);
750 }
751
752 QString KdenliveDoc::producerName(const QString &id) {
753     QString result = "unnamed";
754     QDomNodeList prods = producersList();
755     int ct = prods.count();
756     for (int i = 0; i <  ct ; i++) {
757         QDomElement e = prods.item(i).toElement();
758         if (e.attribute("id") != "black" && e.attribute("id") == id) {
759             result = e.attribute("name");
760             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
761             break;
762         }
763     }
764     return result;
765 }
766
767 void KdenliveDoc::setProducerDuration(const QString &id, int duration) {
768     QDomNodeList prods = producersList();
769     int ct = prods.count();
770     for (int i = 0; i <  ct ; i++) {
771         QDomElement e = prods.item(i).toElement();
772         if (e.attribute("id") != "black" && e.attribute("id") == id) {
773             e.setAttribute("duration", QString::number(duration));
774             break;
775         }
776     }
777 }
778
779 int KdenliveDoc::getProducerDuration(const QString &id) {
780     int result = 0;
781     QDomNodeList prods = producersList();
782     int ct = prods.count();
783     for (int i = 0; i <  ct ; i++) {
784         QDomElement e = prods.item(i).toElement();
785         if (e.attribute("id") != "black" && e.attribute("id") == id) {
786             result = e.attribute("duration").toInt();
787             break;
788         }
789     }
790     return result;
791 }
792
793
794 QDomDocument KdenliveDoc::generateSceneList() {
795     QDomDocument doc;
796     QDomElement westley = doc.createElement("westley");
797     doc.appendChild(westley);
798     QDomElement prod = doc.createElement("producer");
799 }
800
801 QDomDocument KdenliveDoc::toXml() const {
802     return m_document;
803 }
804
805 Timecode KdenliveDoc::timecode() const {
806     return m_timecode;
807 }
808
809 QDomNodeList KdenliveDoc::producersList() {
810     return m_document.elementsByTagName("producer");
811 }
812
813 void KdenliveDoc::backupMltPlaylist() {
814     if (m_render) m_scenelist = m_render->sceneList();
815 }
816
817 double KdenliveDoc::projectDuration() const {
818     if (m_render) return GenTime(m_render->getLength(), m_fps).ms() / 1000;
819 }
820
821 double KdenliveDoc::fps() const {
822     return m_fps;
823 }
824
825 int KdenliveDoc::width() const {
826     return m_width;
827 }
828
829 int KdenliveDoc::height() const {
830     return m_height;
831 }
832
833 KUrl KdenliveDoc::url() const {
834     return m_url;
835 }
836
837 void KdenliveDoc::setUrl(KUrl url) {
838     m_url = url;
839 }
840
841 void KdenliveDoc::setModified(bool mod) {
842     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
843         m_autoSaveTimer->start(3000);
844     }
845     if (mod == m_modified) return;
846     m_modified = mod;
847     emit docModified(m_modified);
848 }
849
850 bool KdenliveDoc::isModified() const {
851     return m_modified;
852 }
853
854 QString KdenliveDoc::description() const {
855     if (m_url.isEmpty())
856         return i18n("Untitled") + " / " + m_profile.description;
857     else
858         return m_url.fileName() + " / " + m_profile.description;
859 }
860
861 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem) {
862     const QString producerId = clipId.section('_', 0, 0);
863     int subtrack = clipId.section('_', 1, 1).toInt();
864     DocClipBase *clip = m_clipManager->getClipById(producerId);
865     if (clip == NULL) {
866         elem.setAttribute("id", producerId);
867         clip = new DocClipBase(m_clipManager, elem, producerId);
868         m_clipManager->addClip(clip);
869     }
870     if (createClipItem) emit addProjectClip(clip);
871 }
872
873 void KdenliveDoc::addClipInfo(QDomElement elem, QString clipId) {
874     DocClipBase *clip = m_clipManager->getClipById(clipId);
875     if (clip == NULL) {
876         addClip(elem, clipId);
877     } else {
878         QMap <QString, QString> properties;
879         QDomNamedNodeMap attributes = elem.attributes();
880         QString attrname;
881         for (unsigned int i = 0; i < attributes.count(); i++) {
882             attrname = attributes.item(i).nodeName();
883             if (attrname != "resource")
884                 properties.insert(attrname, attributes.item(i).nodeValue());
885             kDebug() << attrname << " = " << attributes.item(i).nodeValue();
886         }
887         clip->setProperties(properties);
888         emit addProjectClip(clip);
889     }
890 }
891
892 void KdenliveDoc::addFolder(const QString foldername, const QString &clipId, bool edit) {
893     emit addProjectFolder(foldername, clipId, false, edit);
894 }
895
896 void KdenliveDoc::deleteFolder(const QString foldername, const QString &clipId) {
897     emit addProjectFolder(foldername, clipId, true);
898 }
899
900 void KdenliveDoc::deleteProjectClip(QList <QString> ids) {
901     for (int i = 0; i < ids.size(); ++i) {
902         emit deleteTimelineClip(ids.at(i));
903         m_clipManager->slotDeleteClip(ids.at(i));
904     }
905     setModified(true);
906 }
907
908 void KdenliveDoc::deleteProjectFolder(QMap <QString, QString> map) {
909     QMapIterator<QString, QString> i(map);
910     while (i.hasNext()) {
911         i.next();
912         slotDeleteFolder(i.key(), i.value());
913     }
914     setModified(true);
915 }
916
917 void KdenliveDoc::deleteClip(const QString &clipId) {
918     emit signalDeleteProjectClip(clipId);
919     m_clipManager->deleteClip(clipId);
920 }
921
922 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId) {
923     m_clipManager->slotAddClipList(urls, group, groupId);
924     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
925     setModified(true);
926 }
927
928
929 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId) {
930     kDebug() << "/////////  DOCUM, ADD CLP: " << url;
931     m_clipManager->slotAddClipFile(url, group, groupId);
932     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
933     setModified(true);
934 }
935
936 void KdenliveDoc::slotAddFolder(const QString folderName) {
937     AddFolderCommand *command = new AddFolderCommand(this, folderName, QString::number(m_clipManager->getFreeClipId()), true);
938     commandStack()->push(command);
939     setModified(true);
940 }
941
942 void KdenliveDoc::slotDeleteFolder(const QString folderName, const QString &id) {
943     AddFolderCommand *command = new AddFolderCommand(this, folderName, id, false);
944     commandStack()->push(command);
945     setModified(true);
946 }
947
948 void KdenliveDoc::slotEditFolder(const QString newfolderName, const QString oldfolderName, const QString &clipId) {
949     EditFolderCommand *command = new EditFolderCommand(this, newfolderName, oldfolderName, clipId, false);
950     commandStack()->push(command);
951     setModified(true);
952 }
953
954 const QString&KdenliveDoc::getFreeClipId() {
955     return QString::number(m_clipManager->getFreeClipId());
956 }
957
958 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId) {
959     return m_clipManager->getClipById(clipId);
960 }
961
962 void KdenliveDoc::slotAddColorClipFile(const QString name, const QString color, QString duration, const QString group, const QString &groupId) {
963     m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
964     setModified(true);
965 }
966
967 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) {
968     m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop, fade, luma_duration, luma_file, softness, group, groupId);
969     setModified(true);
970 }
971
972 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId) {
973     QString titlesFolder = projectFolder().path() + "/titles/";
974     KStandardDirs::makeDir(titlesFolder);
975     TitleWidget *dia_ui = new TitleWidget(KUrl(), titlesFolder, m_render, kapp->activeWindow());
976     if (dia_ui->exec() == QDialog::Accepted) {
977         QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
978         QPixmap pix = dia_ui->renderedPixmap();
979         pix.save(titleInfo.at(1));
980         //dia_ui->saveTitle(path + ".kdenlivetitle");
981         m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), QString(), QString());
982         setModified(true);
983     }
984     delete dia_ui;
985 }
986
987
988
989 #include "kdenlivedoc.moc"
990