]> git.sesse.net Git - kdenlive/blob - src/documentchecker.cpp
Merge branch 'buildsystem' into next
[kdenlive] / src / documentchecker.cpp
1 /***************************************************************************
2  *   Copyright (C) 2008 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 "documentchecker.h"
22 #include "kthumb.h"
23 #include "docclipbase.h"
24 #include "titlewidget.h"
25 #include "definitions.h"
26 #include "kdenlivesettings.h"
27
28 #include <KDebug>
29 #include <KGlobalSettings>
30 #include <KFileItem>
31 #include <KIO/NetAccess>
32 #include <KFileDialog>
33 #include <KApplication>
34 #include <KUrlRequesterDialog>
35 #include <KMessageBox>
36 #include <KStandardDirs>
37
38 #include <QTreeWidgetItem>
39 #include <QFile>
40 #include <QHeaderView>
41 #include <QIcon>
42 #include <QPixmap>
43 #include <QTimer>
44 #include <QCryptographicHash>
45
46 const int hashRole = Qt::UserRole;
47 const int sizeRole = Qt::UserRole + 1;
48 const int idRole = Qt::UserRole + 2;
49 const int statusRole = Qt::UserRole + 3;
50 const int typeRole = Qt::UserRole + 4;
51 const int typeOriginalResource = Qt::UserRole + 5;
52 const int resetDurationRole = Qt::UserRole + 6;
53
54 const int CLIPMISSING = 0;
55 const int CLIPOK = 1;
56 const int CLIPPLACEHOLDER = 2;
57 const int CLIPWRONGDURATION = 3;
58 const int PROXYMISSING = 4;
59
60 const int LUMAMISSING = 10;
61 const int LUMAOK = 11;
62 const int LUMAPLACEHOLDER = 12;
63
64 enum TITLECLIPTYPE { TITLE_IMAGE_ELEMENT = 20, TITLE_FONT_ELEMENT = 21 };
65
66 DocumentChecker::DocumentChecker(QDomNodeList infoproducers, QDomDocument doc):
67     m_info(infoproducers), m_doc(doc), m_dialog(NULL)
68 {
69
70 }
71
72
73 bool DocumentChecker::hasErrorInClips()
74 {
75     int clipType;
76     QDomElement e;
77     QString resource;
78     int max;
79     QDomNodeList documentProducers = m_doc.elementsByTagName("producer");
80     QList <QDomElement> wrongDurationClips;
81     QList <QDomElement> missingProxies;
82     m_safeImages.clear();
83     m_safeFonts.clear();
84     max = m_info.count();
85     for (int i = 0; i < max; i++) {
86         e = m_info.item(i).toElement();
87         clipType = e.attribute("type").toInt();
88         if (clipType == COLOR) continue;
89         if (clipType != TEXT && clipType != IMAGE && clipType != SLIDESHOW) {
90             QString id = e.attribute("id");
91             int duration = e.attribute("duration").toInt();
92             int mltDuration = -1;
93             QDomElement mltProd;
94             QString prodId;
95             // Check that the duration is in sync between Kdenlive's info and MLT's playlist
96             int prodsCount = documentProducers.count();
97             for (int j = 0; j < prodsCount; j++) {
98                 mltProd = documentProducers.at(j).toElement();
99                 prodId = mltProd.attribute("id");
100                 // Don't check slowmotion clips for now... (TODO?)
101                 if (prodId.startsWith("slowmotion")) continue;
102                 if (prodId.contains("_")) prodId = prodId.section("_", 0, 0);
103                 if (prodId != id) continue;
104                 if (mltDuration > 0 ) {
105                     // We have several MLT producers for the same clip (probably track producers)
106                     int newLength = EffectsList::property(mltProd, "length").toInt();
107                     if (newLength != mltDuration) {
108                         // we have a different duration for the same clip, that is not safe
109                         e.setAttribute("_resetDuration", 1);
110                     }
111                 }
112                 mltDuration = EffectsList::property(mltProd, "length").toInt();
113                 if (mltDuration != duration) {
114                     // Duration mismatch
115                     e.setAttribute("_mismatch", mltDuration);
116                     if (mltDuration == 15000) {
117                         // a length of 15000 might indicate a wrong clip length since it is a default length
118                         e.setAttribute("_resetDuration", 1);
119                     }
120                     if (!wrongDurationClips.contains(e)) wrongDurationClips.append(e);
121                 }
122             }
123         }
124         
125         if (clipType == TEXT) {
126             //TODO: Check is clip template is missing (xmltemplate) or hash changed
127             QStringList images = TitleWidget::extractImageList(e.attribute("xmldata"));
128             QStringList fonts = TitleWidget::extractFontList(e.attribute("xmldata"));
129             checkMissingImagesAndFonts(images, fonts, e.attribute("id"), e.attribute("name"));
130             continue;
131         }
132         resource = e.attribute("resource");
133         if (e.hasAttribute("proxy")) {
134             QString proxyresource = e.attribute("proxy");
135             if (!proxyresource.isEmpty() && proxyresource != "-" && !KIO::NetAccess::exists(KUrl(proxyresource), KIO::NetAccess::SourceSide, 0)) {
136                 // Missing clip found
137                 missingProxies.append(e);
138             }
139         }
140         if (clipType == SLIDESHOW) resource = KUrl(resource).directory();
141         if (!KIO::NetAccess::exists(KUrl(resource), KIO::NetAccess::SourceSide, 0)) {
142             // Missing clip found
143             m_missingClips.append(e);
144         } else {
145             // Check if the clip has changed
146             if (clipType != SLIDESHOW && e.hasAttribute("file_hash")) {
147                 if (e.attribute("file_hash") != DocClipBase::getHash(e.attribute("resource")))
148                     e.removeAttribute("file_hash");
149             }
150         }
151     }
152
153     // Get list of used Luma files
154     QStringList missingLumas;
155     QStringList filesToCheck;
156     QString filePath;
157     QString root = m_doc.documentElement().attribute("root");
158     if (!root.isEmpty()) root = KUrl(root).path(KUrl::AddTrailingSlash);
159     QDomNodeList trans = m_doc.elementsByTagName("transition");
160     max = trans.count();
161     for (int i = 0; i < max; i++) {
162         QString luma = getProperty(trans.at(i).toElement(), "luma");
163         if (!luma.isEmpty() && !filesToCheck.contains(luma))
164             filesToCheck.append(luma);
165     }
166     // Check existence of luma files
167     foreach (const QString lumafile, filesToCheck) {
168         filePath = lumafile;
169         if (!filePath.startsWith('/')) filePath.prepend(root);
170         if (!QFile::exists(filePath)) {
171             missingLumas.append(lumafile);
172         }
173     }
174     
175     
176
177     if (m_missingClips.isEmpty() && missingLumas.isEmpty() && wrongDurationClips.isEmpty() && missingProxies.isEmpty())
178         return false;
179
180     m_dialog = new QDialog();
181     m_dialog->setFont(KGlobalSettings::toolBarFont());
182     m_ui.setupUi(m_dialog);
183
184     foreach(const QString l, missingLumas) {
185         QTreeWidgetItem *item = new QTreeWidgetItem(m_ui.treeWidget, QStringList() << i18n("Luma file") << l);
186         item->setIcon(0, KIcon("dialog-close"));
187         item->setData(0, idRole, l);
188         item->setData(0, statusRole, LUMAMISSING);
189     }
190
191     m_ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
192     max = m_missingClips.count();
193     for (int i = 0; i < max; i++) {
194         e = m_missingClips.at(i).toElement();
195         QString clipType;
196         int t = e.attribute("type").toInt();
197         switch (t) {
198         case AV:
199             clipType = i18n("Video clip");
200             break;
201         case VIDEO:
202             clipType = i18n("Mute video clip");
203             break;
204         case AUDIO:
205             clipType = i18n("Audio clip");
206             break;
207         case PLAYLIST:
208             clipType = i18n("Playlist clip");
209             break;
210         case IMAGE:
211             clipType = i18n("Image clip");
212             break;
213         case SLIDESHOW:
214             clipType = i18n("Slideshow clip");
215             break;
216         case TITLE_IMAGE_ELEMENT:
217             clipType = i18n("Title Image");
218             break;
219         case TITLE_FONT_ELEMENT:
220             clipType = i18n("Title Font");
221             break;
222         default:
223             clipType = i18n("Video clip");
224         }
225         QTreeWidgetItem *item = new QTreeWidgetItem(m_ui.treeWidget, QStringList() << clipType);
226         if (t == TITLE_IMAGE_ELEMENT) {
227             item->setIcon(0, KIcon("dialog-warning"));
228             item->setToolTip(1, e.attribute("name"));
229             item->setText(1, e.attribute("resource"));
230             item->setData(0, statusRole, CLIPPLACEHOLDER);
231             item->setData(0, typeOriginalResource, e.attribute("resource"));
232         } else if (t == TITLE_FONT_ELEMENT) {
233             item->setIcon(0, KIcon("dialog-warning"));
234             item->setToolTip(1, e.attribute("name"));
235             QString ft = e.attribute("resource");
236             QString newft = QFontInfo(QFont(ft)).family();
237             item->setText(1, i18n("%1 will be replaced by %2", ft, newft));
238             item->setData(0, statusRole, CLIPPLACEHOLDER);
239         } else {
240             item->setIcon(0, KIcon("dialog-close"));
241             item->setText(1, e.attribute("resource"));
242             item->setData(0, hashRole, e.attribute("file_hash"));
243             item->setData(0, sizeRole, e.attribute("file_size"));
244             item->setData(0, statusRole, CLIPMISSING);
245         }
246         item->setData(0, typeRole, t);
247         item->setData(0, idRole, e.attribute("id"));
248         item->setToolTip(0, i18n("Missing item"));
249     }
250
251     if (m_missingClips.count() > 0) {
252         if (wrongDurationClips.count() > 0) {
253             m_ui.infoLabel->setText(i18n("The project file contains missing clips or files and clip duration mismatch"));
254         }
255         else {
256             m_ui.infoLabel->setText(i18n("The project file contains missing clips or files"));
257         }
258     }
259     else if (wrongDurationClips.count() > 0) {
260         m_ui.infoLabel->setText(i18n("The project file contains clips with duration mismatch"));
261     }
262     if (missingProxies.count() > 0) {
263         if (!m_ui.infoLabel->text().isEmpty()) m_ui.infoLabel->setText(m_ui.infoLabel->text() + ". ");
264         m_ui.infoLabel->setText(m_ui.infoLabel->text() + i18n("Missing proxies will be recreated after opening."));
265     }
266
267     m_ui.removeSelected->setEnabled(!m_missingClips.isEmpty());
268     m_ui.recursiveSearch->setEnabled(!m_missingClips.isEmpty() || !missingLumas.isEmpty());
269     m_ui.usePlaceholders->setEnabled(!m_missingClips.isEmpty());
270     m_ui.fixDuration->setEnabled(!wrongDurationClips.isEmpty());
271
272     max = wrongDurationClips.count();
273     for (int i = 0; i < max; i++) {
274         e = wrongDurationClips.at(i).toElement();
275         QString clipType;
276         int t = e.attribute("type").toInt();
277         switch (t) {
278         case AV:
279             clipType = i18n("Video clip");
280             break;
281         case VIDEO:
282             clipType = i18n("Mute video clip");
283             break;
284         case AUDIO:
285             clipType = i18n("Audio clip");
286             break;
287         case PLAYLIST:
288             clipType = i18n("Playlist clip");
289             break;
290         case IMAGE:
291             clipType = i18n("Image clip");
292             break;
293         case SLIDESHOW:
294             clipType = i18n("Slideshow clip");
295             break;
296         default:
297             clipType = i18n("Video clip");
298         }
299         QTreeWidgetItem *item = new QTreeWidgetItem(m_ui.treeWidget, QStringList() << clipType);
300         item->setIcon(0, KIcon("timeadjust"));
301         item->setText(1, e.attribute("resource"));
302         item->setData(0, hashRole, e.attribute("file_hash"));
303         item->setData(0, sizeRole, e.attribute("_mismatch"));
304         e.removeAttribute("_mismatch");
305         item->setData(0, resetDurationRole, (int) e.hasAttribute("_resetDuration"));
306         e.removeAttribute("_resetDuration");
307         item->setData(0, statusRole, CLIPWRONGDURATION);
308         item->setData(0, typeRole, t);
309         item->setData(0, idRole, e.attribute("id"));
310         item->setToolTip(0, i18n("Duration mismatch"));
311     }
312
313     if (missingProxies.count() > 0) {
314         QTreeWidgetItem *item = new QTreeWidgetItem(m_ui.treeWidget, QStringList() << i18n("Proxy clip"));
315         item->setIcon(0, KIcon("dialog-warning"));
316         item->setText(1, i18n("%1 missing proxy clips, will be recreated on project opening", missingProxies.count()));
317         item->setData(0, hashRole, e.attribute("file_hash"));
318         item->setData(0, statusRole, PROXYMISSING);
319         item->setToolTip(0, i18n("Missing proxy"));
320     }
321
322     max = missingProxies.count();
323     for (int i = 0; i < max; i++) {
324         e = missingProxies.at(i).toElement();
325         QString clipType;
326         QString realPath = e.attribute("resource");
327         QString id = e.attribute("id");
328         // Replace proxy url with real clip in MLT producers
329         QDomNodeList properties;
330         QDomElement mltProd;
331         QDomElement property;
332         int prodsCount = documentProducers.count();
333         for (int j = 0; j < prodsCount; j++) {
334             mltProd = documentProducers.at(j).toElement();
335             QString prodId = mltProd.attribute("id");
336             bool slowmotion = false;
337             if (prodId.startsWith("slowmotion")) {
338                 slowmotion = true;
339                 prodId = prodId.section(':', 1, 1);
340             }
341             if (prodId.contains('_')) prodId = prodId.section('_', 0, 0);
342             if (prodId == id) {
343                 // Hit, we must replace url
344                 properties = mltProd.childNodes();
345                 for (int k = 0; k < properties.count(); ++k) {
346                     property = properties.item(k).toElement();
347                     if (property.attribute("name") == "resource") {
348                         QString resource = property.firstChild().nodeValue();                    
349                         QString suffix;
350                         if (slowmotion) suffix = "?" + resource.section('?', -1);
351                         property.firstChild().setNodeValue(realPath + suffix);
352                         break;
353                     }
354                 }
355             }
356         }
357     }
358     
359     if (missingProxies.count() > 0) {
360         // original doc was modified
361         QDomElement infoXml = m_doc.elementsByTagName("kdenlivedoc").at(0).toElement();
362         infoXml.setAttribute("modified", "1");
363     }
364     
365     connect(m_ui.recursiveSearch, SIGNAL(pressed()), this, SLOT(slotSearchClips()));
366     connect(m_ui.usePlaceholders, SIGNAL(pressed()), this, SLOT(slotPlaceholders()));
367     connect(m_ui.removeSelected, SIGNAL(pressed()), this, SLOT(slotDeleteSelected()));
368     connect(m_ui.fixDuration, SIGNAL(pressed()), this, SLOT(slotFixDuration()));
369     connect(m_ui.treeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(slotEditItem(QTreeWidgetItem *, int)));
370     connect(m_ui.treeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(slotCheckButtons()));
371     //adjustSize();
372     if (m_ui.treeWidget->topLevelItem(0)) m_ui.treeWidget->setCurrentItem(m_ui.treeWidget->topLevelItem(0));
373     checkStatus();
374     int acceptMissing = m_dialog->exec();
375     if (acceptMissing == QDialog::Accepted) acceptDialog();
376     return (acceptMissing != QDialog::Accepted);
377 }
378
379 DocumentChecker::~DocumentChecker()
380 {
381     if (m_dialog) delete m_dialog;
382 }
383
384
385 QString DocumentChecker::getProperty(QDomElement effect, const QString &name)
386 {
387     QDomNodeList params = effect.elementsByTagName("property");
388     for (int i = 0; i < params.count(); i++) {
389         QDomElement e = params.item(i).toElement();
390         if (e.attribute("name") == name) {
391             return e.firstChild().nodeValue();
392         }
393     }
394     return QString();
395 }
396
397 void DocumentChecker::setProperty(QDomElement effect, const QString &name, const QString value)
398 {
399     QDomNodeList params = effect.elementsByTagName("property");
400     for (int i = 0; i < params.count(); i++) {
401         QDomElement e = params.item(i).toElement();
402         if (e.attribute("name") == name) {
403             e.firstChild().setNodeValue(value);
404         }
405     }
406 }
407
408 void DocumentChecker::slotSearchClips()
409 {
410     QString newpath = KFileDialog::getExistingDirectory(KUrl("kfiledialog:///clipfolder"), kapp->activeWindow(), i18n("Clips folder"));
411     if (newpath.isEmpty()) return;
412     int ix = 0;
413     bool fixed = false;
414     m_ui.recursiveSearch->setEnabled(false);
415     QTreeWidgetItem *child = m_ui.treeWidget->topLevelItem(ix);
416     QDir searchDir(newpath);
417     while (child) {
418         if (child->data(0, statusRole).toInt() == CLIPMISSING) {
419             QString clipPath = searchFileRecursively(searchDir, child->data(0, sizeRole).toString(), child->data(0, hashRole).toString());
420             if (!clipPath.isEmpty()) {
421                 fixed = true;
422                 child->setText(1, clipPath);
423                 child->setIcon(0, KIcon("dialog-ok"));
424                 child->setData(0, statusRole, CLIPOK);
425             }
426         } else if (child->data(0, statusRole).toInt() == LUMAMISSING) {
427             QString fileName = searchLuma(searchDir, child->data(0, idRole).toString());
428             if (!fileName.isEmpty()) {
429                 fixed = true;
430                 child->setText(1, fileName);
431                 child->setIcon(0, KIcon("dialog-ok"));
432                 child->setData(0, statusRole, LUMAOK);
433             }
434         }
435         else if (child->data(0, typeRole).toInt() == TITLE_IMAGE_ELEMENT && child->data(0, statusRole).toInt() == CLIPPLACEHOLDER) {
436             // Search missing title images
437             QString missingFileName = KUrl(child->text(1)).fileName();
438             QString newPath = searchPathRecursively(searchDir, missingFileName);
439             if (!newPath.isEmpty()) {
440                 // File found
441                 fixed = true;
442                 child->setText(1, newPath);
443                 child->setIcon(0, KIcon("dialog-ok"));
444                 child->setData(0, statusRole, CLIPOK);
445             }
446         }
447         ix++;
448         child = m_ui.treeWidget->topLevelItem(ix);
449     }
450     m_ui.recursiveSearch->setEnabled(true);
451     if (fixed) {
452         // original doc was modified
453         QDomElement infoXml = m_doc.elementsByTagName("kdenlivedoc").at(0).toElement();
454         infoXml.setAttribute("modified", "1");
455     }
456     checkStatus();
457 }
458
459
460 QString DocumentChecker::searchLuma(const QDir &dir, const QString &file) const
461 {
462     KUrl searchPath(KdenliveSettings::mltpath());
463     QString fname = KUrl(file).fileName();
464     if (file.contains("PAL"))
465         searchPath.cd("../lumas/PAL");
466     else
467         searchPath.cd("../lumas/NTSC");
468     QString result = searchPath.path(KUrl::AddTrailingSlash) + fname;
469     if (QFile::exists(result))
470         return result;
471     // try to find luma in application path
472     searchPath.clear();
473     searchPath = KUrl(QCoreApplication::applicationDirPath());
474     searchPath.cd("../share/apps/kdenlive/lumas");
475     result = searchPath.path(KUrl::AddTrailingSlash) + fname;
476     if (QFile::exists(result))
477         return result;
478     // Try in Kdenlive's standard KDE path
479     result = KStandardDirs::locate("appdata", "lumas/" + fname);
480     if (!result.isEmpty()) return result;
481     // Try in user's chosen folder 
482     return searchPathRecursively(dir, fname);
483 }
484
485 QString DocumentChecker::searchPathRecursively(const QDir &dir, const QString &fileName) const
486 {
487     QString foundFileName;
488     QStringList filters;
489     filters << fileName;
490     QDir searchDir(dir);
491     searchDir.setNameFilters(filters);
492     QStringList filesAndDirs = searchDir.entryList(QDir::Files | QDir::Readable);
493     if (!filesAndDirs.isEmpty()) return searchDir.absoluteFilePath(filesAndDirs.at(0));
494     searchDir.setNameFilters(QStringList());
495     filesAndDirs = searchDir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
496     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
497         foundFileName = searchPathRecursively(searchDir.absoluteFilePath(filesAndDirs.at(i)), fileName);
498         if (!foundFileName.isEmpty())
499             break;
500     }
501     return foundFileName;
502 }
503
504 QString DocumentChecker::searchFileRecursively(const QDir &dir, const QString &matchSize, const QString &matchHash) const
505 {
506     QString foundFileName;
507     QByteArray fileData;
508     QByteArray fileHash;
509     QStringList filesAndDirs = dir.entryList(QDir::Files | QDir::Readable);
510     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
511         QFile file(dir.absoluteFilePath(filesAndDirs.at(i)));
512         if (QString::number(file.size()) == matchSize) {
513             if (file.open(QIODevice::ReadOnly)) {
514                 /*
515                 * 1 MB = 1 second per 450 files (or faster)
516                 * 10 MB = 9 seconds per 450 files (or faster)
517                 */
518                 if (file.size() > 1000000 * 2) {
519                     fileData = file.read(1000000);
520                     if (file.seek(file.size() - 1000000))
521                         fileData.append(file.readAll());
522                 } else
523                     fileData = file.readAll();
524                 file.close();
525                 fileHash = QCryptographicHash::hash(fileData, QCryptographicHash::Md5);
526                 if (QString(fileHash.toHex()) == matchHash)
527                     return file.fileName();
528             }
529         }
530         //kDebug() << filesAndDirs.at(i) << file.size() << fileHash.toHex();
531     }
532     filesAndDirs = dir.entryList(QDir::Dirs | QDir::Readable | QDir::Executable | QDir::NoDotAndDotDot);
533     for (int i = 0; i < filesAndDirs.size() && foundFileName.isEmpty(); i++) {
534         foundFileName = searchFileRecursively(dir.absoluteFilePath(filesAndDirs.at(i)), matchSize, matchHash);
535         if (!foundFileName.isEmpty())
536             break;
537     }
538     return foundFileName;
539 }
540
541 void DocumentChecker::slotEditItem(QTreeWidgetItem *item, int)
542 {
543     int t = item->data(0, typeRole).toInt();
544     if (t == TITLE_FONT_ELEMENT) return;
545     //|| t == TITLE_IMAGE_ELEMENT) {
546
547     KUrl url = KUrlRequesterDialog::getUrl(item->text(1), m_dialog, i18n("Enter new location for file"));
548     if (url.isEmpty()) return;
549     item->setText(1, url.path());
550     if (KIO::NetAccess::exists(url, KIO::NetAccess::SourceSide, 0)) {
551         item->setIcon(0, KIcon("dialog-ok"));
552         int id = item->data(0, statusRole).toInt();
553         if (id < 10) item->setData(0, statusRole, CLIPOK);
554         else item->setData(0, statusRole, LUMAOK);
555         checkStatus();
556     } else {
557         item->setIcon(0, KIcon("dialog-close"));
558         int id = item->data(0, statusRole).toInt();
559         if (id < 10) item->setData(0, statusRole, CLIPMISSING);
560         else item->setData(0, statusRole, LUMAMISSING);
561         checkStatus();
562     }
563 }
564
565
566 void DocumentChecker::acceptDialog()
567 {
568     QDomElement e, property;
569     QDomNodeList producers = m_doc.elementsByTagName("producer");
570     QDomNodeList infoproducers = m_doc.elementsByTagName("kdenlive_producer");
571     QDomNodeList properties;
572     int ix = 0;
573
574     // prepare transitions
575     QDomNodeList trans = m_doc.elementsByTagName("transition");
576
577     // Mark document as modified
578     m_doc.documentElement().setAttribute("modified", 1);
579
580     QTreeWidgetItem *child = m_ui.treeWidget->topLevelItem(ix);
581     while (child) {
582         int t = child->data(0, typeRole).toInt();
583         if (child->data(0, statusRole).toInt() == CLIPOK) {
584             QString id = child->data(0, idRole).toString();
585             if (t == TITLE_IMAGE_ELEMENT) {
586                 // edit images embedded in titles
587                 for (int i = 0; i < infoproducers.count(); i++) {
588                     e = infoproducers.item(i).toElement();
589                     if (e.attribute("id") == id) {
590                         // Fix clip
591                         QString xml = e.attribute("xmldata");
592                         xml.replace(child->data(0, typeOriginalResource).toString(), child->text(1));
593                         e.setAttribute("xmldata", xml);
594                         break;
595                     }
596                 }
597                 for (int i = 0; i < producers.count(); i++) {
598                     e = producers.item(i).toElement();
599                     if (e.attribute("id").section('_', 0, 0) == id) {
600                         // Fix clip
601                         properties = e.childNodes();
602                         for (int j = 0; j < properties.count(); ++j) {
603                             property = properties.item(j).toElement();
604                             if (property.attribute("name") == "xmldata") {
605                                 QString xml = property.firstChild().nodeValue();
606                                 xml.replace(child->data(0, typeOriginalResource).toString(), child->text(1));
607                                 property.firstChild().setNodeValue(xml);
608                                 break;
609                             }
610                         }
611                     }
612                 }
613             } else {
614                 // edit clip url
615                 for (int i = 0; i < infoproducers.count(); i++) {
616                     e = infoproducers.item(i).toElement();
617                     if (e.attribute("id") == id) {
618                         // Fix clip
619                         e.setAttribute("resource", child->text(1));
620                         e.setAttribute("name", KUrl(child->text(1)).fileName());
621                         break;
622                     }
623                 }
624                 for (int i = 0; i < producers.count(); i++) {
625                     e = producers.item(i).toElement();
626                     if (e.attribute("id").section('_', 0, 0) == id || e.attribute("id").section(':', 1, 1) == id) {
627                         // Fix clip
628                         properties = e.childNodes();
629                         for (int j = 0; j < properties.count(); ++j) {
630                             property = properties.item(j).toElement();
631                             if (property.attribute("name") == "resource") {
632                                 QString resource = property.firstChild().nodeValue();
633                                 if (resource.contains(QRegExp("\\?[0-9]+\\.[0-9]+(&amp;strobe=[0-9]+)?$")))
634                                     property.firstChild().setNodeValue(child->text(1) + '?' + resource.section('?', -1));
635                                 else
636                                     property.firstChild().setNodeValue(child->text(1));
637                                 break;
638                             }
639                         }
640                     }
641                 }
642             }
643         } else if (child->data(0, statusRole).toInt() == CLIPPLACEHOLDER && t != TITLE_FONT_ELEMENT && t != TITLE_IMAGE_ELEMENT) {
644             QString id = child->data(0, idRole).toString();
645             for (int i = 0; i < infoproducers.count(); i++) {
646                 e = infoproducers.item(i).toElement();
647                 if (e.attribute("id") == id) {
648                     // Fix clip
649                     e.setAttribute("placeholder", '1');
650                     break;
651                 }
652             }
653         } else if (child->data(0, statusRole).toInt() == LUMAOK) {
654             for (int i = 0; i < trans.count(); i++) {
655                 QString luma = getProperty(trans.at(i).toElement(), "luma");
656                 
657                 kDebug() << "luma: " << luma;
658                 if (!luma.isEmpty() && luma == child->data(0, idRole).toString()) {
659                     setProperty(trans.at(i).toElement(), "luma", child->text(1));
660                     kDebug() << "replace with; " << child->text(1);
661                 }
662             }
663         } else if (child->data(0, statusRole).toInt() == LUMAMISSING) {
664             for (int i = 0; i < trans.count(); i++) {
665                 QString luma = getProperty(trans.at(i).toElement(), "luma");
666                 if (!luma.isEmpty() && luma == child->data(0, idRole).toString()) {
667                     setProperty(trans.at(i).toElement(), "luma", QString());
668                 }
669             }
670         }
671         ix++;
672         child = m_ui.treeWidget->topLevelItem(ix);
673     }
674     //QDialog::accept();
675 }
676
677 void DocumentChecker::slotPlaceholders()
678 {
679     int ix = 0;
680     QTreeWidgetItem *child = m_ui.treeWidget->topLevelItem(ix);
681     while (child) {
682         if (child->data(0, statusRole).toInt() == CLIPMISSING) {
683             child->setData(0, statusRole, CLIPPLACEHOLDER);
684             child->setIcon(0, KIcon("dialog-ok"));
685         } else if (child->data(0, statusRole).toInt() == LUMAMISSING) {
686             child->setData(0, statusRole, LUMAPLACEHOLDER);
687             child->setIcon(0, KIcon("dialog-ok"));
688         }
689         ix++;
690         child = m_ui.treeWidget->topLevelItem(ix);
691     }
692     checkStatus();
693 }
694
695 void DocumentChecker::slotFixDuration()
696 {
697     int ix = 0;
698     QTreeWidgetItem *child = m_ui.treeWidget->topLevelItem(ix);
699     QDomNodeList documentProducers = m_doc.elementsByTagName("producer");
700     while (child) {
701         if (child->data(0, statusRole).toInt() == CLIPWRONGDURATION) {
702             QString id = child->data(0, idRole).toString();
703             bool resetDuration = child->data(0, resetDurationRole).toInt();
704
705             for (int i = 0; i < m_info.count(); i++) {
706                 QDomElement e = m_info.at(i).toElement();
707                 if (e.attribute("id") == id) {
708                     if (m_missingClips.contains(e)) {
709                         // we cannot fix duration of missing clips
710                         resetDuration = false;
711                     }
712                     else {
713                         if (resetDuration) e.removeAttribute("duration");
714                         else e.setAttribute("duration", child->data(0, sizeRole).toString());
715                         child->setData(0, statusRole, CLIPOK);
716                         child->setIcon(0, KIcon("dialog-ok"));
717                     }
718                     break;
719                 }
720             }
721             if (resetDuration) {
722                 // something is wrong in clip durations, so remove them so mlt fetches them again
723                 for (int j = 0; j < documentProducers.count(); j++) {
724                     QDomElement mltProd = documentProducers.at(j).toElement();
725                     QString prodId = mltProd.attribute("id");
726                     if (prodId == id || prodId.startsWith(id + "_")) {
727                         EffectsList::removeProperty(mltProd, "length");
728                     }
729                 }
730             }
731         }
732         ix++;
733         child = m_ui.treeWidget->topLevelItem(ix);
734     }
735     QDomElement infoXml = m_doc.elementsByTagName("kdenlivedoc").at(0).toElement();
736     infoXml.setAttribute("modified", "1");
737     m_ui.fixDuration->setEnabled(false);
738     checkStatus();
739 }
740
741
742 void DocumentChecker::checkStatus()
743 {
744     bool status = true;
745     int ix = 0;
746     QTreeWidgetItem *child = m_ui.treeWidget->topLevelItem(ix);
747     while (child) {
748         int status = child->data(0, statusRole).toInt();
749         if (status == CLIPMISSING || status == LUMAMISSING || status == CLIPWRONGDURATION) {
750             status = false;
751             break;
752         }
753         ix++;
754         child = m_ui.treeWidget->topLevelItem(ix);
755     }
756     m_ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status);
757 }
758
759
760 void DocumentChecker::slotDeleteSelected()
761 {
762     if (KMessageBox::warningContinueCancel(m_dialog, i18np("This will remove the selected clip from this project", "This will remove the selected clips from this project", m_ui.treeWidget->selectedItems().count()), i18n("Remove clips")) == KMessageBox::Cancel)
763         return;
764     QStringList deletedIds;
765     QStringList deletedLumas;
766     QDomNodeList playlists = m_doc.elementsByTagName("playlist");
767
768     foreach(QTreeWidgetItem *child, m_ui.treeWidget->selectedItems()) {
769         int id = child->data(0, statusRole).toInt();
770         if (id == CLIPMISSING) {
771             deletedIds.append(child->data(0, idRole).toString());
772             delete child;
773         }
774         else if (id == LUMAMISSING) {
775             deletedLumas.append(child->data(0, idRole).toString());
776             delete child;
777         }
778     }
779
780     if (!deletedLumas.isEmpty()) {
781         QDomElement e;
782         QDomNodeList transitions = m_doc.elementsByTagName("transition");
783         foreach (QString lumaPath, deletedLumas) {
784             for (int i = 0; i < transitions.count(); i++) {
785                 e = transitions.item(i).toElement();
786                 QString resource = EffectsList::property(e, "luma");
787                 if (resource == lumaPath) EffectsList::removeProperty(e, "luma");
788             }
789         }
790     }
791
792     if (!deletedIds.isEmpty()) {
793         QDomElement e;
794         QDomNodeList producers = m_doc.elementsByTagName("producer");
795         QDomNodeList infoproducers = m_doc.elementsByTagName("kdenlive_producer");
796
797         QDomNode mlt = m_doc.elementsByTagName("mlt").at(0);
798         QDomNode kdenlivedoc = m_doc.elementsByTagName("kdenlivedoc").at(0);
799
800         for (int i = 0, j = 0; i < infoproducers.count() && j < deletedIds.count(); i++) {
801             e = infoproducers.item(i).toElement();
802             if (deletedIds.contains(e.attribute("id"))) {
803                 // Remove clip
804                 kdenlivedoc.removeChild(e);
805                 i--;
806                 j++;
807             }
808         }
809
810         for (int i = 0; i < producers.count(); i++) {
811             e = producers.item(i).toElement();
812             if (deletedIds.contains(e.attribute("id").section('_', 0, 0)) || deletedIds.contains(e.attribute("id").section(':', 1, 1).section('_', 0, 0))) {
813                 // Remove clip
814                 mlt.removeChild(e);
815                 i--;
816             }
817         }
818
819         for (int i = 0; i < playlists.count(); i++) {
820             QDomNodeList entries = playlists.at(i).toElement().elementsByTagName("entry");
821             for (int j = 0; j < entries.count(); j++) {
822                 e = entries.item(j).toElement();
823                 if (deletedIds.contains(e.attribute("producer").section('_', 0, 0)) || deletedIds.contains(e.attribute("producer").section(':', 1, 1).section('_', 0, 0))) {
824                     // Replace clip with blank
825                     while (e.childNodes().count() > 0)
826                         e.removeChild(e.firstChild());
827                     e.setTagName("blank");
828                     e.removeAttribute("producer");
829                     int length = e.attribute("out").toInt() - e.attribute("in").toInt();
830                     e.setAttribute("length", length);
831                     j--;
832                 }
833             }
834         }
835         QDomElement infoXml = m_doc.elementsByTagName("kdenlivedoc").at(0).toElement();
836         infoXml.setAttribute("modified", "1");
837         checkStatus();
838     }
839 }
840
841 void DocumentChecker::checkMissingImagesAndFonts(QStringList images, QStringList fonts, const QString &id, const QString &baseClip)
842 {
843     QDomDocument doc;
844     foreach(const QString &img, images) {
845         if (m_safeImages.contains(img)) continue;
846         if (!KIO::NetAccess::exists(KUrl(img), KIO::NetAccess::SourceSide, 0)) {
847             QDomElement e = doc.createElement("missingclip");
848             e.setAttribute("type", TITLE_IMAGE_ELEMENT);
849             e.setAttribute("resource", img);
850             e.setAttribute("id", id);
851             e.setAttribute("name", baseClip);
852             m_missingClips.append(e);
853         }
854         else m_safeImages.append(img);
855     }
856     foreach(const QString &fontelement, fonts) {
857         if (m_safeFonts.contains(fontelement)) continue;
858         QFont f(fontelement);
859         //kDebug() << "/ / / CHK FONTS: " << fontelement << " = " << QFontInfo(f).family();
860         if (fontelement != QFontInfo(f).family()) {
861             QDomElement e = doc.createElement("missingclip");
862             e.setAttribute("type", TITLE_FONT_ELEMENT);
863             e.setAttribute("resource", fontelement);
864             e.setAttribute("id", id);
865             e.setAttribute("name", baseClip);
866             m_missingClips.append(e);
867         }
868         else m_safeFonts.append(fontelement);
869     }
870 }
871
872
873 void DocumentChecker::slotCheckButtons()
874 {
875     if (m_ui.treeWidget->currentItem()) {
876         QTreeWidgetItem *item = m_ui.treeWidget->currentItem();
877         int t = item->data(0, typeRole).toInt();
878         int s = item->data(0, statusRole).toInt();
879         if (t == TITLE_FONT_ELEMENT || t == TITLE_IMAGE_ELEMENT || s == PROXYMISSING) {
880             m_ui.removeSelected->setEnabled(false);
881         } else m_ui.removeSelected->setEnabled(true);
882     }
883
884 }
885
886 #include "documentchecker.moc"
887
888