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