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