]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
c6322e7c0cbf5c432a8c9db03d7aa77664447e11
[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 bool 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         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
596         return false;
597     }
598     QTextStream out(&file);
599     out << sceneList.toString();
600     file.close();
601     return true;
602 }
603
604 QDomElement KdenliveDoc::documentInfoXml() {
605     QDomDocument doc;
606     QDomElement e;
607     QDomElement addedXml = doc.createElement("kdenlivedoc");
608     QDomElement markers = doc.createElement("markers");
609     addedXml.setAttribute("version", "0.7");
610     addedXml.setAttribute("profile", profilePath());
611     addedXml.setAttribute("position", m_render->seekPosition().frames(m_fps));
612     addedXml.setAttribute("zoom", m_zoom);
613     QList <DocClipBase*> list = m_clipManager->documentClipList();
614     for (int i = 0; i < list.count(); i++) {
615         e = list.at(i)->toXML();
616         e.setTagName("kdenlive_producer");
617         addedXml.appendChild(doc.importNode(e, true));
618         QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
619         for (int j = 0; j < marks.count(); j++) {
620             QDomElement marker = doc.createElement("marker");
621             marker.setAttribute("time", marks.at(j).time().ms() / 1000);
622             marker.setAttribute("comment", marks.at(j).comment());
623             marker.setAttribute("id", e.attribute("id"));
624             markers.appendChild(marker);
625         }
626     }
627     addedXml.appendChild(markers);
628     if (!m_guidesXml.isNull()) addedXml.appendChild(doc.importNode(m_guidesXml, true));
629     //kDebug() << m_document.toString();
630     return addedXml;
631 }
632
633
634 ClipManager *KdenliveDoc::clipManager() {
635     return m_clipManager;
636 }
637
638 KUrl KdenliveDoc::projectFolder() const {
639     if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
640     return m_projectFolder;
641 }
642
643 QString KdenliveDoc::getDocumentStandard() {
644     //WARNING: this way to tell the video standard is a bit hackish...
645     if (m_profile.description.contains("pal", Qt::CaseInsensitive) || m_profile.description.contains("25", Qt::CaseInsensitive) || m_profile.description.contains("50", Qt::CaseInsensitive)) return "PAL";
646     return "NTSC";
647 }
648
649 QString KdenliveDoc::profilePath() const {
650     return m_profile.path;
651 }
652
653 MltVideoProfile KdenliveDoc::mltProfile() const {
654     return m_profile;
655 }
656
657 void KdenliveDoc::setProfilePath(QString path) {
658     if (path.isEmpty()) path = KdenliveSettings::default_profile();
659     if (path.isEmpty()) path = "dv_pal";
660     m_profile = ProfilesDialog::getVideoProfile(path);
661     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
662     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
663     m_width = m_profile.width;
664     m_height = m_profile.height;
665     kDebug() << "KDEnnlive document, init timecode from path: " << path << ",  " << m_fps;
666     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
667     else m_timecode.setFormat((int) m_fps);
668 }
669
670 const double KdenliveDoc::dar() {
671     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
672 }
673
674 void KdenliveDoc::setThumbsProgress(const QString &message, int progress) {
675     emit progressInfo(message, progress);
676 }
677
678 void KdenliveDoc::loadingProgressed() {
679     m_documentLoadingProgress += m_documentLoadingStep;
680     emit progressInfo(QString(), (int) m_documentLoadingProgress);
681 }
682
683 QUndoStack *KdenliveDoc::commandStack() {
684     return m_commandStack;
685 }
686
687 void KdenliveDoc::setRenderer(Render *render) {
688     if (m_render) return;
689     m_render = render;
690     emit progressInfo(i18n("Loading playlist..."), 0);
691     //qApp->processEvents();
692     if (m_render) {
693         m_render->setSceneList(m_document.toString(), m_startPos);
694         checkProjectClips();
695     }
696     emit progressInfo(QString(), -1);
697 }
698
699 void KdenliveDoc::checkProjectClips() {
700     if (m_render == NULL) return;
701     QList <Mlt::Producer *> prods = m_render->producersList();
702     QString id ;
703     QString prodId ;
704     QString prodTrack ;
705     for (int i = 0; i < prods.count(); i++) {
706         id = prods.at(i)->get("id");
707         prodId = id.section('_', 0, 0);
708         prodTrack = id.section('_', 1, 1);
709         kDebug() << "CHECK PRO CLIP, ID: " << id;
710         DocClipBase *clip = m_clipManager->getClipById(prodId);
711         if (clip) clip->setProducer(prods.at(i));
712         kDebug() << "CHECK PRO CLIP, ID: " << id << " DONE";
713         if (clip && clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
714             // regenerate text clip image if required
715             kDebug() << "// TITLE: " << clip->getProperty("titlename") << " Preview file: " << clip->getProperty("resource") << " DOES NOT EXIST";
716             QString titlename = clip->getProperty("titlename");
717             QString titleresource;
718             if (titlename.isEmpty()) {
719                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
720                 titlename = titleInfo.at(0);
721                 titleresource = titleInfo.at(1);
722                 clip->setProperty("titlename", titlename);
723                 kDebug() << "// New title set to: " << titlename;
724             } else {
725                 titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
726             }
727             QString titlepath = projectFolder().path() + "/titles/";
728             TitleWidget *dia_ui = new TitleWidget(KUrl(), titlepath, m_render, kapp->activeWindow());
729             QDomDocument doc;
730             doc.setContent(clip->getProperty("xmldata"));
731             dia_ui->setXml(doc);
732             QPixmap pix = dia_ui->renderedPixmap();
733             pix.save(titleresource);
734             clip->setProperty("resource", titleresource);
735             delete dia_ui;
736             clip->producer()->set("force_reload", 1);
737         }
738     }
739 }
740
741 Render *KdenliveDoc::renderer() {
742     return m_render;
743 }
744
745 void KdenliveDoc::updateClip(const QString &id) {
746     emit updateClipDisplay(id);
747 }
748
749 int KdenliveDoc::getFramePos(QString duration) {
750     return m_timecode.getFrameCount(duration, m_fps);
751 }
752
753 QString KdenliveDoc::producerName(const QString &id) {
754     QString result = "unnamed";
755     QDomNodeList prods = producersList();
756     int ct = prods.count();
757     for (int i = 0; i <  ct ; i++) {
758         QDomElement e = prods.item(i).toElement();
759         if (e.attribute("id") != "black" && e.attribute("id") == id) {
760             result = e.attribute("name");
761             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
762             break;
763         }
764     }
765     return result;
766 }
767
768 void KdenliveDoc::setProducerDuration(const QString &id, int duration) {
769     QDomNodeList prods = producersList();
770     int ct = prods.count();
771     for (int i = 0; i <  ct ; i++) {
772         QDomElement e = prods.item(i).toElement();
773         if (e.attribute("id") != "black" && e.attribute("id") == id) {
774             e.setAttribute("duration", QString::number(duration));
775             break;
776         }
777     }
778 }
779
780 int KdenliveDoc::getProducerDuration(const QString &id) {
781     int result = 0;
782     QDomNodeList prods = producersList();
783     int ct = prods.count();
784     for (int i = 0; i <  ct ; i++) {
785         QDomElement e = prods.item(i).toElement();
786         if (e.attribute("id") != "black" && e.attribute("id") == id) {
787             result = e.attribute("duration").toInt();
788             break;
789         }
790     }
791     return result;
792 }
793
794
795 QDomDocument KdenliveDoc::generateSceneList() {
796     QDomDocument doc;
797     QDomElement westley = doc.createElement("westley");
798     doc.appendChild(westley);
799     QDomElement prod = doc.createElement("producer");
800 }
801
802 QDomDocument KdenliveDoc::toXml() const {
803     return m_document;
804 }
805
806 Timecode KdenliveDoc::timecode() const {
807     return m_timecode;
808 }
809
810 QDomNodeList KdenliveDoc::producersList() {
811     return m_document.elementsByTagName("producer");
812 }
813
814 void KdenliveDoc::backupMltPlaylist() {
815     if (m_render) m_scenelist = m_render->sceneList();
816 }
817
818 double KdenliveDoc::projectDuration() const {
819     if (m_render) return GenTime(m_render->getLength(), m_fps).ms() / 1000;
820 }
821
822 double KdenliveDoc::fps() const {
823     return m_fps;
824 }
825
826 int KdenliveDoc::width() const {
827     return m_width;
828 }
829
830 int KdenliveDoc::height() const {
831     return m_height;
832 }
833
834 KUrl KdenliveDoc::url() const {
835     return m_url;
836 }
837
838 void KdenliveDoc::setUrl(KUrl url) {
839     m_url = url;
840 }
841
842 void KdenliveDoc::setModified(bool mod) {
843     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
844         m_autoSaveTimer->start(3000);
845     }
846     if (mod == m_modified) return;
847     m_modified = mod;
848     emit docModified(m_modified);
849 }
850
851 bool KdenliveDoc::isModified() const {
852     return m_modified;
853 }
854
855 QString KdenliveDoc::description() const {
856     if (m_url.isEmpty())
857         return i18n("Untitled") + " / " + m_profile.description;
858     else
859         return m_url.fileName() + " / " + m_profile.description;
860 }
861
862 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem) {
863     const QString producerId = clipId.section('_', 0, 0);
864     int subtrack = clipId.section('_', 1, 1).toInt();
865     DocClipBase *clip = m_clipManager->getClipById(producerId);
866     if (clip == NULL) {
867         elem.setAttribute("id", producerId);
868         clip = new DocClipBase(m_clipManager, elem, producerId);
869         m_clipManager->addClip(clip);
870     }
871     if (createClipItem) emit addProjectClip(clip);
872 }
873
874 void KdenliveDoc::addClipInfo(QDomElement elem, QString clipId) {
875     DocClipBase *clip = m_clipManager->getClipById(clipId);
876     if (clip == NULL) {
877         addClip(elem, clipId);
878     } else {
879         QMap <QString, QString> properties;
880         QDomNamedNodeMap attributes = elem.attributes();
881         QString attrname;
882         for (unsigned int i = 0; i < attributes.count(); i++) {
883             attrname = attributes.item(i).nodeName();
884             if (attrname != "resource")
885                 properties.insert(attrname, attributes.item(i).nodeValue());
886             kDebug() << attrname << " = " << attributes.item(i).nodeValue();
887         }
888         clip->setProperties(properties);
889         emit addProjectClip(clip);
890     }
891 }
892
893 void KdenliveDoc::addFolder(const QString foldername, const QString &clipId, bool edit) {
894     emit addProjectFolder(foldername, clipId, false, edit);
895 }
896
897 void KdenliveDoc::deleteFolder(const QString foldername, const QString &clipId) {
898     emit addProjectFolder(foldername, clipId, true);
899 }
900
901 void KdenliveDoc::deleteProjectClip(QList <QString> ids) {
902     for (int i = 0; i < ids.size(); ++i) {
903         emit deleteTimelineClip(ids.at(i));
904         m_clipManager->slotDeleteClip(ids.at(i));
905     }
906     setModified(true);
907 }
908
909 void KdenliveDoc::deleteProjectFolder(QMap <QString, QString> map) {
910     QMapIterator<QString, QString> i(map);
911     while (i.hasNext()) {
912         i.next();
913         slotDeleteFolder(i.key(), i.value());
914     }
915     setModified(true);
916 }
917
918 void KdenliveDoc::deleteClip(const QString &clipId) {
919     emit signalDeleteProjectClip(clipId);
920     m_clipManager->deleteClip(clipId);
921 }
922
923 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId) {
924     m_clipManager->slotAddClipList(urls, group, groupId);
925     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
926     setModified(true);
927 }
928
929
930 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId) {
931     kDebug() << "/////////  DOCUM, ADD CLP: " << url;
932     m_clipManager->slotAddClipFile(url, group, groupId);
933     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
934     setModified(true);
935 }
936
937 void KdenliveDoc::slotAddFolder(const QString folderName) {
938     AddFolderCommand *command = new AddFolderCommand(this, folderName, QString::number(m_clipManager->getFreeClipId()), true);
939     commandStack()->push(command);
940     setModified(true);
941 }
942
943 void KdenliveDoc::slotDeleteFolder(const QString folderName, const QString &id) {
944     AddFolderCommand *command = new AddFolderCommand(this, folderName, id, false);
945     commandStack()->push(command);
946     setModified(true);
947 }
948
949 void KdenliveDoc::slotEditFolder(const QString newfolderName, const QString oldfolderName, const QString &clipId) {
950     EditFolderCommand *command = new EditFolderCommand(this, newfolderName, oldfolderName, clipId, false);
951     commandStack()->push(command);
952     setModified(true);
953 }
954
955 const QString&KdenliveDoc::getFreeClipId() {
956     return QString::number(m_clipManager->getFreeClipId());
957 }
958
959 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId) {
960     return m_clipManager->getClipById(clipId);
961 }
962
963 void KdenliveDoc::slotAddColorClipFile(const QString name, const QString color, QString duration, const QString group, const QString &groupId) {
964     m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
965     setModified(true);
966 }
967
968 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) {
969     m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop, fade, luma_duration, luma_file, softness, group, groupId);
970     setModified(true);
971 }
972
973 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId) {
974     QString titlesFolder = projectFolder().path() + "/titles/";
975     KStandardDirs::makeDir(titlesFolder);
976     TitleWidget *dia_ui = new TitleWidget(KUrl(), titlesFolder, m_render, kapp->activeWindow());
977     if (dia_ui->exec() == QDialog::Accepted) {
978         QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
979         QPixmap pix = dia_ui->renderedPixmap();
980         pix.save(titleInfo.at(1));
981         //dia_ui->saveTitle(path + ".kdenlivetitle");
982         m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), QString(), QString());
983         setModified(true);
984     }
985     delete dia_ui;
986 }
987
988
989
990 #include "kdenlivedoc.moc"
991