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