]> git.sesse.net Git - kdenlive/blob - src/kdenlivedoc.cpp
Try to load folders in kdenlive 0.5 files - appears to work
[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     producers = m_document.elementsByTagName("producer");
489     max = producers.count();
490     for (int i = 0; i < max; i++) {
491         QDomElement prod = producers.at(0).toElement();
492         QDomNode m = prod.firstChild();
493         if (!m.isNull()) {
494             if (m.toElement().tagName() == "markers") {
495                 QDomNodeList prodchilds = m.childNodes();
496                 int maxchild = prodchilds.count();
497                 for (int k = 0; k < maxchild; k++) {
498                     QDomElement mark = prodchilds.at(0).toElement();
499                     mark.setAttribute("id", prod.attribute("id"));
500                     markers.insertAfter(mark, QDomNode());
501                 }
502                 prod.removeChild(m);
503             } else if (prod.attribute("type").toInt() == TEXT) {
504                 // convert title clip
505                 if (m.toElement().tagName() == "textclip") {
506                     QDomDocument tdoc;
507                     QDomElement titleclip = m.toElement();
508                     QDomElement title = tdoc.createElement("kdenlivetitle");
509                     tdoc.appendChild(title);
510                     QDomNodeList objects = titleclip.childNodes();
511                     int maxchild = objects.count();
512                     for (int k = 0; k < maxchild; k++) {
513                         QString objectxml;
514                         QDomElement ob = objects.at(k).toElement();
515                         if (ob.attribute("type") == "3") {
516                             // text object
517                             QDomElement item = tdoc.createElement("item");
518                             item.setAttribute("z-index", ob.attribute("z"));
519                             item.setAttribute("type", "QGraphicsTextItem");
520                             QDomElement position = tdoc.createElement("position");
521                             position.setAttribute("x", ob.attribute("x"));
522                             position.setAttribute("y", ob.attribute("y"));
523                             QDomElement content = tdoc.createElement("content");
524                             content.setAttribute("font", ob.attribute("font_family"));
525                             content.setAttribute("font-size", ob.attribute("font_size"));
526                             content.setAttribute("font-bold", ob.attribute("bold"));
527                             content.setAttribute("font-italic", ob.attribute("italic"));
528                             content.setAttribute("font-underline", ob.attribute("underline"));
529                             QString col = ob.attribute("color");
530                             QColor c(col);
531                             content.setAttribute("font-color", colorToString(c));
532                             QDomText conttxt = tdoc.createTextNode(ob.attribute("text"));
533                             content.appendChild(conttxt);
534                             item.appendChild(position);
535                             item.appendChild(content);
536                             title.appendChild(item);
537                         } else if (ob.attribute("type") == "5") {
538                             // rectangle object
539                             QDomElement item = tdoc.createElement("item");
540                             item.setAttribute("z-index", ob.attribute("z"));
541                             item.setAttribute("type", "QGraphicsRectItem");
542                             QDomElement position = tdoc.createElement("position");
543                             position.setAttribute("x", ob.attribute("x"));
544                             position.setAttribute("y", ob.attribute("y"));
545                             QDomElement content = tdoc.createElement("content");
546                             QString col = ob.attribute("color");
547                             QColor c(col);
548                             content.setAttribute("brushcolor", colorToString(c));
549                             QString rect = "0,0,";
550                             rect.append(ob.attribute("width"));
551                             rect.append(",");
552                             rect.append(ob.attribute("height"));
553                             content.setAttribute("rect", rect);
554                             item.appendChild(position);
555                             item.appendChild(content);
556                             title.appendChild(item);
557                         }
558                     }
559                     prod.setAttribute("xmldata", tdoc.toString());
560                     QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
561                     prod.setAttribute("titlename", titleInfo.at(0));
562                     prod.setAttribute("resource", titleInfo.at(1));
563                     //kDebug()<<"TITLE DATA:\n"<<tdoc.toString();
564                     prod.removeChild(m);
565                 }
566
567             } else if (m.isText()) {
568                 QString comment = m.nodeValue();
569                 if (!comment.isEmpty()) {
570                     prod.setAttribute("description", comment);
571                 }
572                 prod.removeChild(m);
573             }
574         }
575         int duration = prod.attribute("duration").toInt();
576         if (duration > 0) prod.setAttribute("out", QString::number(duration));
577         westley.insertBefore(prod, QDomNode());
578
579     }
580
581     QDomNode westley0 = m_document.elementsByTagName("westley").at(0);
582     if (!markers.firstChild().isNull()) westley0.appendChild(markers);
583
584
585     // Convert as much of the kdenlivedoc as possible. Use the producer in westley
586     // First, remove the old stuff from westley, and add a new empty one
587     // Also, track the max id in order to use it for the adding of groups/folders
588     int max_kproducer_id = 0;
589     westley0.removeChild(kdenlivedoc);
590     QDomElement kdenlivedoc_new = m_document.createElement("kdenlivedoc");
591     kdenlivedoc_new.setAttribute("profile", profile);
592     // Add all the producers that has a ressource in westley
593     QDomElement westley_element = westley0.toElement();
594     if (westley_element.isNull()) {
595         kWarning() << "westley0 element in document was not a QDomElement - unable to add producers to new kdenlivedoc";
596     } else {
597         QDomNodeList wproducers = westley_element.elementsByTagName("producer");
598         int kmax = wproducers.count();
599         for (int i = 0; i < kmax; i++) {
600             QDomElement wproducer = wproducers.at(i).toElement();
601             if (wproducer.isNull()) {
602                 kWarning() << "Found producer in westley0, that was not a QDomElement";
603             } else {
604                 QDomElement kproducer = m_document.createElement("kdenlive_producer");
605                 kproducer.setAttribute("id", wproducer.attribute("id"));
606                 kproducer.setAttribute("description", wproducer.attribute("description"));
607                 kproducer.setAttribute("resource", wproducer.attribute("resource"));
608                 kproducer.setAttribute("type", wproducer.attribute("type"));
609                 kdenlivedoc_new.appendChild(kproducer);
610                 if (wproducer.attribute("id").toInt() > max_kproducer_id) {
611                     max_kproducer_id = wproducer.attribute("id").toInt();
612                 }
613             }
614         }
615     }
616 #define LOOKUP_FOLDER 1
617 #ifdef LOOKUP_FOLDER
618     // Look through all the folder elements of the old doc, for each folder, for each producer,
619     // get the id, look it up in the new doc, set the groupname and groupid
620     // Note, this does not work at the moment - at least one folders shows up missing, and clips with no folder
621     // does not show up.
622     //    QDomElement kdenlivedoc_old = kdenlivedoc.toElement();
623     if (!kdenlivedoc_old.isNull()) {
624         QDomNodeList folders = kdenlivedoc_old.elementsByTagName("folder");
625         int fsize = folders.size();
626         int groupId = max_kproducer_id + 1; // Start at +1 of max id of the kdenlive_producers
627         for (int i = 0; i < fsize; ++i) {
628             QDomElement folder = folders.at(i).toElement();
629             if (!folder.isNull()) {
630                 QString groupName = folder.attribute("name");
631                 kDebug() << "groupName: " << groupName << " with groupId: " << groupId;
632                 QDomNodeList fproducers = folder.elementsByTagName("producer");
633                 int psize = fproducers.size();
634                 for (int j = 0; j < psize; ++j) {
635                     QDomElement fproducer = fproducers.at(j).toElement();
636                     if (!fproducer.isNull()) {
637                         QString id = fproducer.attribute("id");
638                         // This is not very effective, but compared to loading the clips, its a breeze
639                         QDomNodeList kdenlive_producers = kdenlivedoc_new.elementsByTagName("kdenlive_producer");
640                         int kpsize = kdenlive_producers.size();
641                         for (int k = 0; k < kpsize; ++k) {
642                             QDomElement kproducer = kdenlive_producers.at(k).toElement(); // Its an element for sure
643                             if (id == kproducer.attribute("id")) {
644                                 // We do not check that it already is part of a folder
645                                 kproducer.setAttribute("groupid", groupId);
646                                 kproducer.setAttribute("groupname", groupName);
647                                 break;
648                             }
649                         }
650                     }
651                 }
652                 ++groupId;
653             }
654         }
655     }
656 #endif
657     westley0.appendChild(kdenlivedoc_new);
658
659     QDomNodeList elements = westley.childNodes();
660     max = elements.count();
661     for (int i = 0; i < max; i++) {
662         QDomElement prod = elements.at(0).toElement();
663         westley0.insertAfter(prod, QDomNode());
664     }
665
666     westley0.removeChild(westley);
667
668     //kDebug() << "/////////////////  CONVERTED DOC:";
669     // kDebug() << m_document.toString();
670     /*
671     QFile file( "converted.kdenlive" );
672     if ( file.open( QIODevice::WriteOnly ) ) {
673       QTextStream stream( &file );
674       stream << m_document.toString();
675       file.close();
676     } else {
677       kDebug() << "Unable to dump file to converted.kdenlive";
678     }
679     */
680     //kDebug() << "/////////////////  END CONVERTED DOC:";
681 }
682
683 QString KdenliveDoc::colorToString(const QColor& c) {
684     QString ret = "%1,%2,%3,%4";
685     ret = ret.arg(c.red()).arg(c.green()).arg(c.blue()).arg(c.alpha());
686     return ret;
687 }
688
689 bool KdenliveDoc::saveSceneList(const QString &path, QDomDocument sceneList) {
690     QDomNode wes = sceneList.elementsByTagName("westley").at(0);
691
692     QDomElement addedXml = sceneList.createElement("kdenlivedoc");
693     QDomElement markers = sceneList.createElement("markers");
694     addedXml.setAttribute("version", "0.8");
695     addedXml.setAttribute("profile", profilePath());
696     addedXml.setAttribute("position", m_render->seekPosition().frames(m_fps));
697     addedXml.setAttribute("zoom", m_zoom);
698
699     QDomElement e;
700     QList <DocClipBase*> list = m_clipManager->documentClipList();
701     for (int i = 0; i < list.count(); i++) {
702         e = list.at(i)->toXML();
703         e.setTagName("kdenlive_producer");
704         addedXml.appendChild(sceneList.importNode(e, true));
705         QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
706         for (int j = 0; j < marks.count(); j++) {
707             QDomElement marker = sceneList.createElement("marker");
708             marker.setAttribute("time", marks.at(j).time().ms() / 1000);
709             marker.setAttribute("comment", marks.at(j).comment());
710             marker.setAttribute("id", e.attribute("id"));
711             markers.appendChild(marker);
712         }
713     }
714     addedXml.appendChild(markers);
715     if (!m_guidesXml.isNull()) addedXml.appendChild(sceneList.importNode(m_guidesXml, true));
716
717     wes.appendChild(addedXml);
718     //wes.appendChild(doc.importNode(kdenliveData, true));
719
720     QFile file(path);
721     if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
722         kWarning() << "//////  ERROR writing to file: " << path;
723         KMessageBox::error(kapp->activeWindow(), i18n("Cannot write to file %1", path));
724         return false;
725     }
726     QTextStream out(&file);
727     out << sceneList.toString();
728     file.close();
729     return true;
730 }
731
732 QDomElement KdenliveDoc::documentInfoXml() {
733     QDomDocument doc;
734     QDomElement e;
735     QDomElement addedXml = doc.createElement("kdenlivedoc");
736     QDomElement markers = doc.createElement("markers");
737     addedXml.setAttribute("version", "0.7");
738     addedXml.setAttribute("profile", profilePath());
739     addedXml.setAttribute("position", m_render->seekPosition().frames(m_fps));
740     addedXml.setAttribute("zoom", m_zoom);
741     QList <DocClipBase*> list = m_clipManager->documentClipList();
742     for (int i = 0; i < list.count(); i++) {
743         e = list.at(i)->toXML();
744         e.setTagName("kdenlive_producer");
745         addedXml.appendChild(doc.importNode(e, true));
746         QList < CommentedTime > marks = list.at(i)->commentedSnapMarkers();
747         for (int j = 0; j < marks.count(); j++) {
748             QDomElement marker = doc.createElement("marker");
749             marker.setAttribute("time", marks.at(j).time().ms() / 1000);
750             marker.setAttribute("comment", marks.at(j).comment());
751             marker.setAttribute("id", e.attribute("id"));
752             markers.appendChild(marker);
753         }
754     }
755     addedXml.appendChild(markers);
756     if (!m_guidesXml.isNull()) addedXml.appendChild(doc.importNode(m_guidesXml, true));
757     //kDebug() << m_document.toString();
758     return addedXml;
759 }
760
761
762 ClipManager *KdenliveDoc::clipManager() {
763     return m_clipManager;
764 }
765
766 KUrl KdenliveDoc::projectFolder() const {
767     if (m_projectFolder.isEmpty()) return KUrl(KStandardDirs::locateLocal("appdata", "/projects/"));
768     return m_projectFolder;
769 }
770
771 QString KdenliveDoc::getDocumentStandard() {
772     //WARNING: this way to tell the video standard is a bit hackish...
773     if (m_profile.description.contains("pal", Qt::CaseInsensitive) || m_profile.description.contains("25", Qt::CaseInsensitive) || m_profile.description.contains("50", Qt::CaseInsensitive)) return "PAL";
774     return "NTSC";
775 }
776
777 QString KdenliveDoc::profilePath() const {
778     return m_profile.path;
779 }
780
781 MltVideoProfile KdenliveDoc::mltProfile() const {
782     return m_profile;
783 }
784
785 void KdenliveDoc::setProfilePath(QString path) {
786     if (path.isEmpty()) path = KdenliveSettings::default_profile();
787     if (path.isEmpty()) path = "dv_pal";
788     m_profile = ProfilesDialog::getVideoProfile(path);
789     KdenliveSettings::setProject_display_ratio((double) m_profile.display_aspect_num / m_profile.display_aspect_den);
790     m_fps = (double) m_profile.frame_rate_num / m_profile.frame_rate_den;
791     m_width = m_profile.width;
792     m_height = m_profile.height;
793     kDebug() << "KDEnnlive document, init timecode from path: " << path << ",  " << m_fps;
794     if (m_fps == 30000.0 / 1001.0) m_timecode.setFormat(30, true);
795     else m_timecode.setFormat((int) m_fps);
796 }
797
798 const double KdenliveDoc::dar() {
799     return (double) m_profile.display_aspect_num / m_profile.display_aspect_den;
800 }
801
802 void KdenliveDoc::setThumbsProgress(const QString &message, int progress) {
803     emit progressInfo(message, progress);
804 }
805
806 void KdenliveDoc::loadingProgressed() {
807     m_documentLoadingProgress += m_documentLoadingStep;
808     emit progressInfo(QString(), (int) m_documentLoadingProgress);
809 }
810
811 QUndoStack *KdenliveDoc::commandStack() {
812     return m_commandStack;
813 }
814
815 void KdenliveDoc::setRenderer(Render *render) {
816     if (m_render) return;
817     m_render = render;
818     emit progressInfo(i18n("Loading playlist..."), 0);
819     //qApp->processEvents();
820     if (m_render) {
821         m_render->setSceneList(m_document.toString(), m_startPos);
822         checkProjectClips();
823     }
824     emit progressInfo(QString(), -1);
825 }
826
827 void KdenliveDoc::checkProjectClips() {
828     if (m_render == NULL) return;
829     QList <Mlt::Producer *> prods = m_render->producersList();
830     QString id ;
831     QString prodId ;
832     QString prodTrack ;
833     for (int i = 0; i < prods.count(); i++) {
834         id = prods.at(i)->get("id");
835         prodId = id.section('_', 0, 0);
836         prodTrack = id.section('_', 1, 1);
837         kDebug() << "CHECK PRO CLIP, ID: " << id;
838         DocClipBase *clip = m_clipManager->getClipById(prodId);
839         if (clip) clip->setProducer(prods.at(i));
840         kDebug() << "CHECK PRO CLIP, ID: " << id << " DONE";
841         if (clip && clip->clipType() == TEXT && !QFile::exists(clip->fileURL().path())) {
842             // regenerate text clip image if required
843             kDebug() << "// TITLE: " << clip->getProperty("titlename") << " Preview file: " << clip->getProperty("resource") << " DOES NOT EXIST";
844             QString titlename = clip->getProperty("titlename");
845             QString titleresource;
846             if (titlename.isEmpty()) {
847                 QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
848                 titlename = titleInfo.at(0);
849                 titleresource = titleInfo.at(1);
850                 clip->setProperty("titlename", titlename);
851                 kDebug() << "// New title set to: " << titlename;
852             } else {
853                 titleresource = TitleWidget::getTitleResourceFromName(projectFolder(), titlename);
854             }
855             QString titlepath = projectFolder().path() + "/titles/";
856             TitleWidget *dia_ui = new TitleWidget(KUrl(), titlepath, m_render, kapp->activeWindow());
857             QDomDocument doc;
858             doc.setContent(clip->getProperty("xmldata"));
859             dia_ui->setXml(doc);
860             QPixmap pix = dia_ui->renderedPixmap();
861             pix.save(titleresource);
862             clip->setProperty("resource", titleresource);
863             delete dia_ui;
864             clip->producer()->set("force_reload", 1);
865         }
866     }
867 }
868
869 Render *KdenliveDoc::renderer() {
870     return m_render;
871 }
872
873 void KdenliveDoc::updateClip(const QString &id) {
874     emit updateClipDisplay(id);
875 }
876
877 int KdenliveDoc::getFramePos(QString duration) {
878     return m_timecode.getFrameCount(duration, m_fps);
879 }
880
881 QString KdenliveDoc::producerName(const QString &id) {
882     QString result = "unnamed";
883     QDomNodeList prods = producersList();
884     int ct = prods.count();
885     for (int i = 0; i <  ct ; i++) {
886         QDomElement e = prods.item(i).toElement();
887         if (e.attribute("id") != "black" && e.attribute("id") == id) {
888             result = e.attribute("name");
889             if (result.isEmpty()) result = KUrl(e.attribute("resource")).fileName();
890             break;
891         }
892     }
893     return result;
894 }
895
896 void KdenliveDoc::setProducerDuration(const QString &id, int duration) {
897     QDomNodeList prods = producersList();
898     int ct = prods.count();
899     for (int i = 0; i <  ct ; i++) {
900         QDomElement e = prods.item(i).toElement();
901         if (e.attribute("id") != "black" && e.attribute("id") == id) {
902             e.setAttribute("duration", QString::number(duration));
903             break;
904         }
905     }
906 }
907
908 int KdenliveDoc::getProducerDuration(const QString &id) {
909     int result = 0;
910     QDomNodeList prods = producersList();
911     int ct = prods.count();
912     for (int i = 0; i <  ct ; i++) {
913         QDomElement e = prods.item(i).toElement();
914         if (e.attribute("id") != "black" && e.attribute("id") == id) {
915             result = e.attribute("duration").toInt();
916             break;
917         }
918     }
919     return result;
920 }
921
922
923 QDomDocument KdenliveDoc::generateSceneList() {
924     QDomDocument doc;
925     QDomElement westley = doc.createElement("westley");
926     doc.appendChild(westley);
927     QDomElement prod = doc.createElement("producer");
928 }
929
930 QDomDocument KdenliveDoc::toXml() const {
931     return m_document;
932 }
933
934 Timecode KdenliveDoc::timecode() const {
935     return m_timecode;
936 }
937
938 QDomNodeList KdenliveDoc::producersList() {
939     return m_document.elementsByTagName("producer");
940 }
941
942 void KdenliveDoc::backupMltPlaylist() {
943     if (m_render) m_scenelist = m_render->sceneList();
944 }
945
946 double KdenliveDoc::projectDuration() const {
947     if (m_render) return GenTime(m_render->getLength(), m_fps).ms() / 1000;
948 }
949
950 double KdenliveDoc::fps() const {
951     return m_fps;
952 }
953
954 int KdenliveDoc::width() const {
955     return m_width;
956 }
957
958 int KdenliveDoc::height() const {
959     return m_height;
960 }
961
962 KUrl KdenliveDoc::url() const {
963     return m_url;
964 }
965
966 void KdenliveDoc::setUrl(KUrl url) {
967     m_url = url;
968 }
969
970 void KdenliveDoc::setModified(bool mod) {
971     if (!m_url.isEmpty() && mod && KdenliveSettings::crashrecovery()) {
972         m_autoSaveTimer->start(3000);
973     }
974     if (mod == m_modified) return;
975     m_modified = mod;
976     emit docModified(m_modified);
977 }
978
979 bool KdenliveDoc::isModified() const {
980     return m_modified;
981 }
982
983 QString KdenliveDoc::description() const {
984     if (m_url.isEmpty())
985         return i18n("Untitled") + " / " + m_profile.description;
986     else
987         return m_url.fileName() + " / " + m_profile.description;
988 }
989
990 void KdenliveDoc::addClip(QDomElement elem, QString clipId, bool createClipItem) {
991     const QString producerId = clipId.section('_', 0, 0);
992     int subtrack = clipId.section('_', 1, 1).toInt();
993     DocClipBase *clip = m_clipManager->getClipById(producerId);
994     if (clip == NULL) {
995         elem.setAttribute("id", producerId);
996         clip = new DocClipBase(m_clipManager, elem, producerId);
997         m_clipManager->addClip(clip);
998     }
999     if (createClipItem) emit addProjectClip(clip);
1000 }
1001
1002 void KdenliveDoc::addClipInfo(QDomElement elem, QString clipId) {
1003     DocClipBase *clip = m_clipManager->getClipById(clipId);
1004     if (clip == NULL) {
1005         addClip(elem, clipId);
1006     } else {
1007         QMap <QString, QString> properties;
1008         QDomNamedNodeMap attributes = elem.attributes();
1009         QString attrname;
1010         for (unsigned int i = 0; i < attributes.count(); i++) {
1011             attrname = attributes.item(i).nodeName();
1012             if (attrname != "resource")
1013                 properties.insert(attrname, attributes.item(i).nodeValue());
1014             kDebug() << attrname << " = " << attributes.item(i).nodeValue();
1015         }
1016         clip->setProperties(properties);
1017         emit addProjectClip(clip);
1018     }
1019 }
1020
1021 void KdenliveDoc::addFolder(const QString foldername, const QString &clipId, bool edit) {
1022     emit addProjectFolder(foldername, clipId, false, edit);
1023 }
1024
1025 void KdenliveDoc::deleteFolder(const QString foldername, const QString &clipId) {
1026     emit addProjectFolder(foldername, clipId, true);
1027 }
1028
1029 void KdenliveDoc::deleteProjectClip(QList <QString> ids) {
1030     for (int i = 0; i < ids.size(); ++i) {
1031         emit deleteTimelineClip(ids.at(i));
1032         m_clipManager->slotDeleteClip(ids.at(i));
1033     }
1034     setModified(true);
1035 }
1036
1037 void KdenliveDoc::deleteProjectFolder(QMap <QString, QString> map) {
1038     QMapIterator<QString, QString> i(map);
1039     while (i.hasNext()) {
1040         i.next();
1041         slotDeleteFolder(i.key(), i.value());
1042     }
1043     setModified(true);
1044 }
1045
1046 void KdenliveDoc::deleteClip(const QString &clipId) {
1047     emit signalDeleteProjectClip(clipId);
1048     m_clipManager->deleteClip(clipId);
1049 }
1050
1051 void KdenliveDoc::slotAddClipList(const KUrl::List urls, const QString group, const QString &groupId) {
1052     m_clipManager->slotAddClipList(urls, group, groupId);
1053     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1054     setModified(true);
1055 }
1056
1057
1058 void KdenliveDoc::slotAddClipFile(const KUrl url, const QString group, const QString &groupId) {
1059     kDebug() << "/////////  DOCUM, ADD CLP: " << url;
1060     m_clipManager->slotAddClipFile(url, group, groupId);
1061     emit selectLastAddedClip(QString::number(m_clipManager->lastClipId()));
1062     setModified(true);
1063 }
1064
1065 void KdenliveDoc::slotAddFolder(const QString folderName) {
1066     AddFolderCommand *command = new AddFolderCommand(this, folderName, QString::number(m_clipManager->getFreeClipId()), true);
1067     commandStack()->push(command);
1068     setModified(true);
1069 }
1070
1071 void KdenliveDoc::slotDeleteFolder(const QString folderName, const QString &id) {
1072     AddFolderCommand *command = new AddFolderCommand(this, folderName, id, false);
1073     commandStack()->push(command);
1074     setModified(true);
1075 }
1076
1077 void KdenliveDoc::slotEditFolder(const QString newfolderName, const QString oldfolderName, const QString &clipId) {
1078     EditFolderCommand *command = new EditFolderCommand(this, newfolderName, oldfolderName, clipId, false);
1079     commandStack()->push(command);
1080     setModified(true);
1081 }
1082
1083 const QString&KdenliveDoc::getFreeClipId() {
1084     return QString::number(m_clipManager->getFreeClipId());
1085 }
1086
1087 DocClipBase *KdenliveDoc::getBaseClip(const QString &clipId) {
1088     return m_clipManager->getClipById(clipId);
1089 }
1090
1091 void KdenliveDoc::slotAddColorClipFile(const QString name, const QString color, QString duration, const QString group, const QString &groupId) {
1092     m_clipManager->slotAddColorClipFile(name, color, duration, group, groupId);
1093     setModified(true);
1094 }
1095
1096 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) {
1097     m_clipManager->slotAddSlideshowClipFile(name, path, count, duration, loop, fade, luma_duration, luma_file, softness, group, groupId);
1098     setModified(true);
1099 }
1100
1101 void KdenliveDoc::slotCreateTextClip(QString group, const QString &groupId) {
1102     QString titlesFolder = projectFolder().path() + "/titles/";
1103     KStandardDirs::makeDir(titlesFolder);
1104     TitleWidget *dia_ui = new TitleWidget(KUrl(), titlesFolder, m_render, kapp->activeWindow());
1105     if (dia_ui->exec() == QDialog::Accepted) {
1106         QStringList titleInfo = TitleWidget::getFreeTitleInfo(projectFolder());
1107         QPixmap pix = dia_ui->renderedPixmap();
1108         pix.save(titleInfo.at(1));
1109         //dia_ui->saveTitle(path + ".kdenlivetitle");
1110         m_clipManager->slotAddTextClipFile(titleInfo.at(0), titleInfo.at(1), dia_ui->xml().toString(), QString(), QString());
1111         setModified(true);
1112     }
1113     delete dia_ui;
1114 }
1115
1116
1117
1118 #include "kdenlivedoc.moc"
1119