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